Installation
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install google-cloud-filestore-log-troubleshooting@skills-hub
Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled).
Plugin google-cloud-filestore-log-troubleshooting v1.0.0 follows the Agent Plugins spec.
gh skills-hub install google-cloud-filestore-log-troubleshooting Don't have the extension? Run gh extension install samueltauil/skills-hub first.
Download and extract to your repository:
.github/skills/google-cloud-filestore-log-troubleshooting/ Extract the ZIP to .github/skills/ in your repo. The folder name must match google-cloud-filestore-log-troubleshooting for Copilot to auto-discover it.
Skill Files (8)
SKILL.md 11.1 KB
---
name: google-cloud-filestore-log-troubleshooting
metadata:
version: "1.0.2"
category: Storage
description: >-
Diagnoses and resolves Filestore client mount failures on Google Cloud,
permission errors (EACCES), and network timeouts (ETIMEDOUT). Use when an NFS
mount hangs or fails from a Compute Engine VM, GKE pod, Cloud Run service, or
Vertex AI workload, when `mount.nfs` reports "Connection timed out" or "access
denied by server", when checking whether VPC ingress firewall rules or
`nfsExportOptions` allow a client IP, or when a previously working Filestore
share suddenly stops mounting after an administrative change. Don't use for
Cloud Storage (GCS) buckets, Persistent Disk, or Cloud NetApp Volumes, and
don't use for Filestore capacity scaling or backup and export-policy auditing.
---
<!-- disableFinding(LINE_OVER_80) -->
# Filestore Log-Based Troubleshooting
Diagnoses, troubleshoots, and remediates Filestore client mount failures, permission errors (`EACCES`), and network timeouts (`ETIMEDOUT`) across projects.
## Prerequisites & Quick Start
Required IAM roles on target project(s) (and Shared VPC host project if applicable):
* **Read**: `roles/file.viewer` (instance & export ACLs), `roles/compute.networkViewer` (VPC firewall rules), `roles/logging.viewer` (Cloud Audit & GKE CSI logs), `roles/mcp.toolUser` (if using MCP tools).
* **Write (Remediation only)**: `roles/file.editor` (export ACL updates), `roles/compute.securityAdmin` (firewall rule creation).
Authenticate, verify billing/APIs, and configure your environment:
```bash
gcloud auth login && gcloud auth application-default login
gcloud billing projects describe {project_id} --format="value(billingEnabled)"
gcloud services enable file.googleapis.com compute.googleapis.com logging.googleapis.com --quiet
gcloud config set project {project_id} && gcloud config set compute/region {region}
```
## Usage Attribution
**MUST READ**: Before executing any `gcloud`, REST API, or MCP command, you
MUST read and follow the instructions in
[Usage Attribution](references/attribution.md).
## Conceptual & Informational Queries (CRITICAL)
For purely conceptual, architectural, or educational questions (e.g., "What causes EACCES on Filestore?", "Why does GKE Node IP appear instead of Pod IP?", "What ports does Filestore require?", "Explain root squash"):
* **Rule**: **Answer immediately using pre-trained knowledge and the workflow rules below.** Answering directly minimizes tool latency and token usage when the user only seeks architectural guidance.
* **Constraint**: **Do not execute external tool calls or API requests** for basic knowledge questions.
## Handling "No-Command" Constraints (CRITICAL)
If the user prompt contains constraints like "Do not execute commands", "without executing", or "read-only":
* **Rule**: **Strictly avoid calling `run_command`** to execute any shell, Python, or `gcloud` commands.
* **Discovery**:
1. Always read [Usage Attribution](references/attribution.md) first so every recommended `gcloud` command includes the required attribution environment variable.
2. Check if Filestore MCP tools (`get_instance`, `list_instances`) are available and use them (API calls, not command executions).
3. If MCP tools are unavailable, read `references/mock-fleet-data.md` **only if** the requested instance matches one of the evaluation scenarios (`finance-share`, `shared-nfs`, `ml-data`, `data-hub`, `prod-share`). Never report mock data as live production state. If the instance is not listed there, state that live access is required and provide the exact attributed commands for the user to run.
4. **Fast-Path Stop Rule**: Once you have read [Usage Attribution](references/attribution.md) and located the target instance in `references/mock-fleet-data.md`, **stop reading additional files immediately** and formulate your response with the attributed `gcloud` remediation command. Do **NOT** read `scripts/quick_diagnose.py`, `scripts/diagnose_lib.py`, `_internal/quick_diagnose_test.py`, or `EVAL.*` files when command execution is disabled, as inspecting code/test files wastes turns and triggers timeouts.
* **Mandatory User Confirmation Requirement**: Even when command execution is disabled or the user asks only for recommendations, your response **MUST STILL end with a clear question prompting the user for explicit confirmation** before applying any remediation (e.g., *"Would you like me to proceed with creating the VPC ingress firewall rule `[rule_name]`? Please confirm to proceed."*).
## Multi-Runtime Execution Options
### Option 1: Bundled Python CLI Script (Recommended for CLI / Terminal Agents)
```bash
# Single instance diagnosis
python3 scripts/quick_diagnose.py --instance="<INSTANCE_ID>" --location="<LOCATION_OR_ZONE>" \
[--project="<PROJECT_ID>"] [--client-ip="<CLIENT_IP>"] [--client-subnet="<CLIENT_SUBNET_CIDR>"]
# Bulk project-wide fleet diagnosis
python3 scripts/quick_diagnose.py --all --project="<PROJECT_ID>" [--json]
```
| Flag | Purpose |
| :--- | :--- |
| `--instance`, `--location` | Filestore instance ID and region/zone (`--zone` is a legacy alias). Required unless `--all`. |
| `--project` | GCP project ID (defaults to active `gcloud` project). |
| `--client-ip` / `--client-subnet` | Client IP or CIDR to evaluate against export ACLs and ingress firewall rules. |
| `--json` | Emit machine-readable JSON on stdout (narrative report goes to stderr). |
| `--apply-fix` | Execute generated remediation commands. **Only pass after explicit user confirmation.** |
### Option 2: Filestore MCP Tools / REST API / `gcloud` CLI
* **MCP Tools**: Call `get_instance(name='projects/{project_id}/locations/{location}/instances/{instance_id}')` and inspect `fileShares[0].nfsExportOptions` and `networks[0].network`.
* **Native REST API (`call_gcp_api`)**: Invoke `service="file"`, `version="v1"`, `resource_path="projects/{project_id}/locations/{location}/instances/{instance_id}"`.
* **Standard `gcloud`**:
```bash
gcloud filestore instances describe {instance_id} --location={location} --project={project_id} --format=json
```
--------------------------------------------------------------------------------
## Core Operational Workflow
### Step 1: Parameter Extraction & GKE Node Architecture
* Extract `instance`, `location` (region/zone), `project`, and `client_ip` / `client_subnet`. If target parameters are missing, list instances or ask the user to confirm.
* **GKE Architecture Rule**: PersistentVolumes are mounted by the Linux kernel on the **GKE Worker Node**, not inside the Pod network namespace. Even if Pod IPs (`10.4.0.0/14`) are allowlisted, the NFS server sees traffic originating from the **GKE Node Internal IP**. Always evaluate and allowlist the **GKE Node Subnet CIDR** in `nfsExportOptions` and VPC firewall rules.
### Step 2: Instance Metadata & Shared VPC Resolution
1. Verify instance `state` is `READY` (report state blocker if `CREATING`, `DELETING`, or `ERROR`).
2. Extract primary Filestore IP (`networks[0].ipAddresses[0]`) and VPC network URI.
3. If `networks[0].network` references `projects/{host_project}/global/networks/{network}`, resolve `{host_project}` as the Shared VPC host project for firewall queries.
### Step 3: Export ACL Evaluation (`EACCES` vs `EROFS`)
1. Inspect `fileShares[0].nfsExportOptions` (if empty, default `0.0.0.0/0` `READ_WRITE` `NO_ROOT_SQUASH` applies).
2. **`EACCES (Permission Denied by Server)`**: Triggered when the client IP or subnet CIDR is not covered by any `ipRanges` entry.
* **Remediation**: Non-destructively append the client IP/subnet CIDR to `nfsExportOptions`, preserving all existing export rules to avoid breaking active mounts.
3. **`EROFS (Read-only file system)`**: Triggered when `accessMode` is `READ_ONLY` but client writes are attempted.
### Step 4: VPC Ingress Firewall Inspection (`ETIMEDOUT`)
1. Query ingress firewall rules in the VPC network (in the host project if Shared VPC).
2. **`ETIMEDOUT (Connection Timed Out)`**: Triggered when priority-sorted ingress rules block or fail to allow TCP port `2049` (NFS) and TCP/UDP port `111` (rpcbind) from the client CIDR.
* **Remediation**: Create an ingress firewall rule (`ALLOW` `tcp:2049,udp:2049,tcp:111,udp:111`) from the client subnet CIDR.
### Step 5: Cloud Audit Logs & Configuration Drift Scanning
Query Cloud Audit Admin Activity logs (`file.googleapis.com`) over the past 24 hours to check if an `UpdateInstance` operation modified export ACLs or networks:
```bash
gcloud logging read 'logName="projects/{project_id}/logs/cloudaudit.googleapis.com%2Factivity" AND protoPayload.serviceName="file.googleapis.com" AND protoPayload.resourceName=~".*{instance}.*"' \
--project="{project_id}" --freshness="1d" --limit=5 --format="json"
```
* **Scope to Admin Activity**: Always include `cloudaudit.googleapis.com%2Factivity` in `logName` so read-only `GetInstance`/`ListInstances` calls (`data_access`) are not falsely flagged as administrative drift.
* **Drift is Informational**: Recent `UpdateInstance` events explain *when* and *by whom* (`principalEmail`, `timestamp`) configuration changed, but only a failed export ACL or firewall check constitutes a mount blocker.
* **Single Bulk Query Rule**: When scanning multiple instances (`--all`), issue a single project-wide audit log query rather than per-instance queries in a loop.
* **GKE CSI Driver Logs**: Optionally inspect `resource.labels.container_name="gcp-filestore-driver"` (`severity>=ERROR`) for client-side mount errors.
--------------------------------------------------------------------------------
## Output Format & Mandatory Confirmation Gate
Every diagnostic report MUST include a structured summary table and root cause analysis:
````markdown
### Filestore Diagnostic Report: `[instance-name]`
| Parameter | Value |
| :--- | :--- |
| **Instance ID** | `[instance-name]` (`[location]`, Tier: `[tier]`, State: `READY`) |
| **Filestore IP & Network** | `[filestore-ip]` on VPC `[network-name]` (Host Project: `[host-project]`) |
| **Port 2049 & Export ACL** | Port 2049: `OPEN / BLOCKED` \| Export ACL: `PASS / REJECTED` |
| **Diagnostic Verdict** | **HEALTHY** or **BLOCKED: [Root Cause]** |
#### Root Cause Analysis & Recommended Remediation
- [Explanation of ETIMEDOUT (missing firewall rule on port 2049) vs EACCES (missing export ACL rule) and any recent UpdateInstance audit drift]
```bash
gcloud compute firewall-rules create ...
```
````
### Interactive Remediation Confirmation Gate (MANDATORY)
* **NEVER execute write or remediation commands without explicit user confirmation.**
* Always conclude your response with an explicit confirmation question:
> *"Would you like me to proceed with executing this remediation command for you? Please confirm to proceed."*
## References & Bundled Scripts
* [Usage Attribution](references/attribution.md)
* [Error Signatures & Architecture Matrix](references/error-signatures.md)
* [Cloud Logging & Audit Drift Queries](references/logging-and-audit-queries.md)
* [VPC Network & Firewall Specification](references/network-firewall-spec.md)
* [Mock Fleet Data for Evaluations](references/mock-fleet-data.md)
* `scripts/quick_diagnose.py` & `scripts/diagnose_lib.py`: Zero-dependency CLI runner and pure-Python evaluation engine.
attribution.md 1.9 KB
# Usage Attribution
**MUST READ**: Before executing any `gcloud`, REST API, or MCP command with
this skill, follow these usage attribution instructions. Tag every command you
execute directly in the terminal so usage can be attributed. The tag identifies
only the skill and its version; it carries no user data.
- **`gcloud` CLI Commands**: Prefix every `gcloud` invocation, whatever the
subcommand, with the metrics environment variable. Set it inline on each
command because shell state may not persist between commands:
```bash
CLOUDSDK_METRICS_REQUEST_ATTRIBUTION="agent-skills/1.0 (skill:google-cloud-filestore-log-troubleshooting)" \
gcloud <command> [flags]
```
Do not use `gcloud config set` for this: it would persist beyond the current
task and mislabel unrelated usage.
- **Direct HTTP, REST, and MCP Requests**: On direct HTTP calls to Google
Cloud APIs (for example with `curl`) or HTTP requests to a remote MCP
server, include
`agent-skills/1.0 (skill:google-cloud-filestore-log-troubleshooting)` in
the `User-Agent` header. If a `User-Agent` header is already specified,
append this string to the end of it rather than overwriting existing
`User-Agent` data — the collection pipeline parses the
`agent-skills/<version>` and `skill:<name>` tokens, so any rewording breaks
attribution:
```text
User-Agent: <existing_user_agent> agent-skills/1.0 (skill:google-cloud-filestore-log-troubleshooting)
```
- **Constraint for Generated Code**: The tracking prefix is strictly for
commands you execute directly in the terminal. Do NOT include this tracking
prefix in generated scripts, Terraform templates, or code provided to the
user for their own repositories.
- **User Opt-Out**: If the user asks to disable or remove tracking or
attribution tags, omit the `CLOUDSDK_METRICS_REQUEST_ATTRIBUTION` variable
and custom `User-Agent` suffix from all commands.
error-signatures.md 8.8 KB
<!-- disableFinding(LINE_OVER_80) -->
<!-- disableFinding(LIST_NO_LINE) -->
<!-- disableFinding(LINK_ID) -->
# Google Cloud Filestore Client Mount Error Signatures & Matrix
This reference maps common Filestore NFS mount errors, permission denials, and
connection timeouts to their underlying root causes, authoritative proofs, and
verified remediations.
## Table of Contents
* [1. Error Signatures & Troubleshooting Matrix](#1-error-signatures--troubleshooting-matrix):
Lines 21-52
* [2. GKE Node vs. Pod IP Architectural Reality](#2-gke-node-vs-pod-ip-architectural-reality):
Lines 55-92
* [3. NFS Squash Modes & Permission Failures](#3-nfs-squash-modes--permission-failures):
Lines 96-113
--------------------------------------------------------------------------------
## 1. Error Signatures & Troubleshooting Matrix
| Error Message / Exit Code | Diagnostic Layer | Root Cause | Authoritative Proof | Resolution |
| :----------------------------- | :--------------------- | :----------------------------- | :------------------------------------------ | :--------------------------------- |
| **`ETIMEDOUT`**<br>`mount.nfs: | **VPC Network & | VPC ingress firewall does not | `gcloud compute firewall-rules list` shows | Create VPC ingress firewall rule |
: Connection timed : Firewall** : permit TCP port `2049` (and : no ingress rule allowing TCP 2049 from the : allowing TCP/UDP 2049 and 111 from :
: out`<br>`mount.nfs\: Network : : `111`), or VPC peering / PSA : client CIDR to Filestore IP. : client subnet to the target :
: is unreachable` : : route propagation is missing. : : network. :
| **`EACCES`**<br>`mount.nfs: | **Export ACL | Client IP (or GKE Node IP) is | Comparing Client IP against `gcloud | Update `nfsExportOptions` to |
: access denied by server while : (`nfsExportOptions`)** : not included in : filestore instances describe` export : append client subnet CIDR :
: mounting` : : `nfsExportOptions[].ipRanges`. : options reveals no CIDR match. : non-destructively without wiping :
: : : : : existing entries. :
| **`EROFS`**<br>`Read-only file | **Export Access Mode** | Share is exported with | `nfsExportOptions` has `accessMode: | Change `accessMode` to |
: system` : : `accessMode\: READ_ONLY` while : READ_ONLY` for the client IP range. : `READ_WRITE` in `nfsExportOptions` :
: : : client attempts write : : for the target CIDR. :
: : : operations (`rw`). : : :
| **`EPERM`**<br>`Permission | **POSIX / Root | Container/VM user is UID 0 | Client mount succeeds, but file | Set `squashMode` to |
: denied (Operation not : Squash** : (root) and `squashMode` is set : write/create fails inside the mounted : `NO_ROOT_SQUASH` in export options :
: permitted)` : : to `ROOT_SQUASH`, or non-root : volume. : or adjust container :
: : : user lacks POSIX permissions. : : `securityContext.fsGroup` / POSIX :
: : : : : directory permissions (`chmod 775` :
: : : : : or `chown`). :
| **`RPC: Program not | **Portmapper / | TCP/UDP port `111` is blocked | Port 2049 may be open, but port 111 shows | Add port `111` to the VPC ingress |
: registered`** : RPCbind** : by VPC firewall, preventing : closed/filtered via network inspection. : firewall allow rule alongside port :
: : : NFSv3 port mapping : : `2049`. :
: : : negotiation. : : :
| **`EBUSY` / IOPS Quota | **Capacity & | Storage capacity is 100% full, | Cloud Monitoring metric | Scale up capacity via |
: Stalls** : Throughput : or client workload is : `file.googleapis.com/nfs/server/used_bytes` : `google-cloud-filestore-autoscale` :
: : Saturation** : saturating the IOPS / : equals capacity, or write IOPS near tier : or upgrade instance tier (e.g. :
: : : throughput limits of the : ceiling. : Basic HDD to Basic SSD / :
: : : instance tier. : : Regional). :
--------------------------------------------------------------------------------
## 2. GKE Node vs. Pod IP Architectural Reality
Understanding Kubernetes mount behavior is essential for diagnosing Filestore
mounts in GKE:
```
┌────────────────────────────────────────────────────────┐
│ GKE Worker Node (Internal IP: 10.128.0.12) │
│ │
│ ┌───────────────────────┐ ┌──────────────────────┐ │
│ │ Pod A (10.4.1.15) │ │ Pod B (10.4.1.16) │ │
│ │ VolumeMount: /data │ │ VolumeMount: /data │ │
│ └───────────┬───────────┘ └──────────┬───────────┘ │
│ │ │ │
│ └────────────┬─────────────┘ │
│ ▼ │
│ Host Kubelet / CSI Node Plugin │
│ (NFS mount executed in host namespace) │
└───────────────────────────┬────────────────────────────┘
│ Source IP: 10.128.0.12 (Node IP)
│ NOT Pod IP (10.4.1.x)
▼
┌─────────────────────────────────┐
│ Google Cloud Filestore Instance │
│ (nfsExportOptions evaluation) │
└─────────────────────────────────┘
```
* **Host-Level Mounting**: In Kubernetes, NFS PersistentVolumes are mounted
directly on the **host GKE Node** by `kubelet` and the CSI node plugin
(`gcp-filestore-driver`), which operate in the host root network namespace.
* **Source IP Behavior**: The source IP seen by the Filestore NFS server is
**always the GKE Node Internal IP** (from the node subnet), **never the Pod
IP**.
* **The Common Misconfiguration**: Allowlisting GKE Pod CIDRs (e.g.
`10.4.0.0/14`) in `nfsExportOptions` causes `mount.nfs: access denied by
server while mounting` (`EACCES`). You must allowlist the **GKE Node Subnet
CIDR** (e.g. `10.128.0.0/20`).
--------------------------------------------------------------------------------
## 3. NFS Squash Modes & Permission Failures
Filestore supports two NFS export squash modes:
1. **`NO_ROOT_SQUASH`**:
* Requests from UID 0 (root) on the client remain UID 0 on the Filestore
share.
* Required for Docker / Kubernetes containers running as `root` that need
to create root-owned files or initialize databases.
2. **`ROOT_SQUASH`** (Default in many enterprise security profiles):
* Requests from UID 0 on the client are mapped to the unprivileged
`nobody` account (`anonUid: 65534`).
* If the root directory of the share is owned by `root:root` with
permissions `0755`, a client container running as root will receive
`EACCES` or `EPERM` when trying to write to the root of the volume.
* **Resolution**: Set `squashMode: NO_ROOT_SQUASH` in `nfsExportOptions`,
or configure non-root application users matching directory POSIX
ownership.
logging-and-audit-queries.md 5.1 KB
<!-- disableFinding(LINE_OVER_80) -->
<!-- disableFinding(LIST_NO_LINE) -->
<!-- disableFinding(LINK_ID) -->
# Cloud Logging & Audit Drift Queries for Google Cloud Filestore
This guide provides tested Cloud Logging query filters and schemas for
diagnosing Filestore mount issues, detecting administrative configuration drift,
and inspecting client-side mount errors.
## Table of Contents
* [1. Filestore Administrative Audit Drift (Cloud Audit Logs)](#1-filestore-administrative-audit-drift-cloud-audit-logs):
Lines 23-65
* [2. GKE Filestore CSI Driver Mount Logs](#2-gke-filestore-csi-driver-mount-logs):
Lines 68-103
* [3. GCE VM Syslog & Serial Port Logs](#3-gce-vm-syslog--serial-port-logs):
Lines 106-130
* [4. Querying Across Agent Runtimes](#4-querying-across-agent-runtimes):
Lines 133-153
--------------------------------------------------------------------------------
## 1. Filestore Administrative Audit Drift (Cloud Audit Logs)
When an existing, previously functioning Filestore mount suddenly begins failing
with `EACCES` or timeouts, query Cloud Audit Logs to determine if an
administrative change (configuration drift) modified the instance export options
or network settings within the last 24–48 hours.
### Query Filter:
```
logName="projects/{project_id}/logs/cloudaudit.googleapis.com%2Factivity"
AND protoPayload.serviceName="file.googleapis.com"
AND protoPayload.resourceName=~"instances/{instance_id}"
AND timestamp >= "{RFC3339_TIMESTAMP_24H_AGO}"
```
### CLI Command (`gcloud`):
```bash
gcloud logging read \
'logName="projects/{project_id}/logs/cloudaudit.googleapis.com%2Factivity" AND protoPayload.serviceName="file.googleapis.com" AND protoPayload.resourceName=~".*{instance_id}.*"' \
--project="{project_id}" \
--freshness="1d" \
--format="table(timestamp,protoPayload.methodName.basename(),protoPayload.authenticationInfo.principalEmail)"
```
> **Always scope to the Admin Activity log.** Dropping the `logName` filter also
> matches `cloudaudit.googleapis.com%2Fdata_access` entries, which record
> read-only `GetInstance` and `ListInstances` calls. Those reads are not
> configuration changes, and including them causes healthy instances to be
> reported as drifted — including reads issued by the diagnosis itself.
### Key Payload Fields to Extract:
* `timestamp`: When the administrative change occurred.
* `protoPayload.authenticationInfo.principalEmail`: User or service account
that initiated the change.
* `protoPayload.methodName`: e.g.
`google.cloud.filestore.v1.Filestore.UpdateInstance` or `DeleteInstance`.
* `protoPayload.request.updateMask`: Indicates which fields were changed (e.g.
`fileShares` or `nfsExportOptions`).
--------------------------------------------------------------------------------
## 2. GKE Filestore CSI Driver Mount Logs
For GKE workloads utilizing the GCP Filestore CSI driver
(`filestore.csi.storage.gke.io`), mount failures are logged by the
`gcp-filestore-driver` container running in the `kube-system` namespace.
### Query Filter:
```
resource.type="k8s_container"
AND resource.labels.namespace_name="kube-system"
AND resource.labels.container_name="gcp-filestore-driver"
AND severity >= ERROR
AND timestamp >= "{RFC3339_TIMESTAMP_3H_AGO}"
```
### CLI Command (`gcloud`):
```bash
gcloud logging read \
'resource.type="k8s_container" AND resource.labels.container_name="gcp-filestore-driver" AND severity>=ERROR' \
--project="{project_id}" \
--freshness="3h" \
--limit=10 \
--format="value(textPayload,jsonPayload.message)"
```
### Common CSI Error Messages:
* `mount failed: exit status 32 ... mount.nfs: Connection timed out`:
Indicates network/firewall blockage on port 2049.
* `mount failed: exit status 32 ... mount.nfs: access denied by server while
mounting`: Indicates export ACL rejection of the GKE worker node IP.
* `RPC: Program not registered`: Port 111 (rpcbind) blocked.
--------------------------------------------------------------------------------
## 3. GCE VM Syslog & Serial Port Logs
For Compute Engine VMs failing to mount a Filestore volume:
### Query Filter:
```
resource.type="gce_instance"
AND logName=~"logs/syslog"
AND textPayload=~"mount\.nfs"
AND timestamp >= "{RFC3339_TIMESTAMP_6H_AGO}"
```
### CLI Command (`gcloud`):
```bash
gcloud logging read \
'resource.type="gce_instance" AND textPayload=~"mount\.nfs"' \
--project="{project_id}" \
--freshness="6h" \
--limit=5 \
--format="value(timestamp,textPayload)"
```
--------------------------------------------------------------------------------
## 4. Querying Across Agent Runtimes
### Option A: Gemini Enterprise File Agent / Native GCP API Tool (`call_gcp_api`)
```json
{
"service": "logging",
"version": "v2",
"resource_path": "entries:list",
"request_body": {
"resourceNames": ["projects/{project_id}"],
"filter": "logName=\"projects/{project_id}/logs/cloudaudit.googleapis.com%2Factivity\" AND protoPayload.serviceName=\"file.googleapis.com\" AND protoPayload.resourceName=~\".*{instance_id}.*\"",
"pageSize": 5
}
}
```
### Option B: Cloud Logging MCP Tool
Call `read_log_entries` with `filter` and `project_id`.
mock-fleet-data.md 6.8 KB
<!-- disableFinding(LINE_OVER_80) -->
<!-- disableFinding(LIST_NO_LINE) -->
# Mock Fleet Definitions for Read-Only & Evaluation Runs
This reference provides deterministic mock data for evaluating troubleshooting
workflows when command execution or live GCP API access is disabled (e.g., in
automated evaluation suites, AutoCloud, or read-only customer environments).
> **These instances are fictional.** Use this data only when the user's request
> names one of the scenarios below *and* live access is unavailable. Never
> present these values as the live state of a real deployment, and never mix
> them into a report about a real instance. If the user's instance is not listed
> here, say that live access is required and give the commands to run instead —
> reporting invented IPs, export rules, or firewall state as real would send an
> operator to change the wrong production resource.
## Table of Contents
* [Scenario 1: Missing Firewall Ingress Rule (ETIMEDOUT)](#scenario-1-missing-firewall-ingress-rule-etimedout):
Lines 37-63
* [Scenario 2: Export ACL Mismatch (EACCES)](#scenario-2-export-acl-mismatch-eacces):
Lines 67-90
* [Scenario 3: Administrative Configuration Drift (Cloud Audit Logs)](#scenario-3-administrative-configuration-drift-cloud-audit-logs):
Lines 94-107
* [Scenario 4: GKE Pod CIDR vs Node Subnet Confusion](#scenario-4-gke-pod-cidr-vs-node-subnet-confusion):
Lines 111-119
* [Scenario 5: Interactive Remediation Gate (data-hub Port 2049 Blocked)](#scenario-5-interactive-remediation-gate-data-hub-port-2049-blocked):
Lines 123-148
* [Scenario 6: Read-Only Diagnostic Compliance (prod-share)](#scenario-6-read-only-diagnostic-compliance-prod-share):
Lines 152-162
--------------------------------------------------------------------------------
## Mock Scenarios
### Scenario 1: Missing Firewall Ingress Rule (`ETIMEDOUT`)
* **Project**: `analytics-prod`
* **Instance**: `finance-share` (Location: `us-central1-b`)
* **Tier**: `BASIC_HDD`
* **Filestore IP**: `10.0.3.2`
* **VPC Network**: `prod-vpc`
* **Client Context**: GKE cluster `cluster-east`, Worker Node Subnet
`10.128.0.0/20`
* **Export ACL**: Default `0.0.0.0/0` (READ_WRITE, NO_ROOT_SQUASH)
* **VPC Firewall Status**: No active ingress firewall rule allows TCP port
`2049` or `111` from `10.128.0.0/20`
* **Diagnostic Verdict**: `ETIMEDOUT` due to missing VPC ingress firewall rule
on TCP port 2049.
* **Remediation Command** (must be prefixed with the attribution variable from [Usage Attribution](attribution.md)):
```bash
gcloud compute firewall-rules create allow-prod-vpc-filestore-nfs \
--network="prod-vpc" \
--direction=INGRESS \
--priority=1000 \
--action=ALLOW \
--rules=tcp:2049,udp:2049,tcp:111,udp:111 \
--source-ranges="10.128.0.0/20" \
--project="analytics-prod"
```
--------------------------------------------------------------------------------
### Scenario 2: Export ACL Mismatch (`EACCES`)
* **Project**: `ai-platform`
* **Instance**: `shared-nfs` (Location: `us-central1-a`)
* **Tier**: `BASIC_SSD`
* **Filestore IP**: `10.10.0.5`
* **VPC Network**: `ai-vpc`
* **Client VM**: `worker-01` (Internal IP: `10.128.0.5`)
* **Existing `nfsExportOptions`**:
```json
[
{
"ipRanges": ["10.200.0.0/24"],
"accessMode": "READ_WRITE",
"squashMode": "NO_ROOT_SQUASH"
}
]
```
* **VPC Firewall Status**: Ingress port 2049 is open to all internal subnets.
* **Diagnostic Verdict**: `EACCES (Permission Denied by Server)`. Client IP
`10.128.0.5` is not in allowed IP ranges.
* **Remediation Action**: Non-destructively append `10.128.0.0/20` (or
`10.128.0.5/32`) to `nfsExportOptions`.
--------------------------------------------------------------------------------
### Scenario 3: Administrative Configuration Drift (Cloud Audit Logs)
* **Project**: `media-prod`
* **Instance**: `ml-data` (Location: `us-east4-a`)
* **Incident**: Workload stopped mounting today.
* **Cloud Audit Log Record**:
* **Timestamp**: `2026-09-10T18:42:10Z`
* **Principal**: `alice@example.com`
* **Service**: `file.googleapis.com`
* **Method**: `google.cloud.filestore.v1.Filestore.UpdateInstance`
* **Updated Fields**: `fileShares.nfsExportOptions`
* **Diagnostic Verdict**: Configuration drift. An administrative update by
`alice@example.com` 4 hours ago modified `nfsExportOptions`, removing the
previous client CIDR.
--------------------------------------------------------------------------------
### Scenario 4: GKE Pod CIDR vs Node Subnet Confusion
* **Client Symptom**: Pods in GKE cluster `ml-cluster` cannot mount Filestore
despite the Pod CIDR `10.4.0.0/14` being added to `nfsExportOptions`.
* **Architectural Reality**: Kubernetes mounts execute in the host node
network namespace. The source IP arriving at the Filestore server is the
Node Internal IP (e.g. `10.128.0.12`), which falls outside `10.4.0.0/14`.
* **Diagnostic Verdict**: Misconfigured export allowlist. The GKE Node Subnet
CIDR (e.g. `10.128.0.0/20`) must be allowlisted instead of the Pod CIDR.
--------------------------------------------------------------------------------
### Scenario 5: Interactive Remediation Gate (`data-hub` Port 2049 Blocked)
* **Project**: `analytics-prod`
* **Instance**: `data-hub` (Location: `us-central1`)
* **Tier**: `REGIONAL`
* **Filestore IP**: `10.20.0.2`
* **VPC Network**: `prod-vpc`
* **Client Context**: Subnet `10.128.0.0/20`
* **VPC Firewall Status**: Port 2049 is blocked by missing ingress firewall
rule on `prod-vpc`.
* **Diagnostic Verdict**: `ETIMEDOUT` on TCP port 2049.
* **Remediation Command** (must be prefixed with the attribution variable from [Usage Attribution](attribution.md)):
```bash
gcloud compute firewall-rules create allow-data-hub-nfs \
--network="prod-vpc" \
--direction=INGRESS \
--priority=1000 \
--action=ALLOW \
--rules=tcp:2049,udp:2049,tcp:111,udp:111 \
--source-ranges="10.128.0.0/20" \
--project="analytics-prod"
```
* **Mandatory Gate**: Must present the command and ask: *"Would you like me to
proceed with creating this firewall rule? Please confirm (Yes/No)."*
--------------------------------------------------------------------------------
### Scenario 6: Read-Only Diagnostic Compliance (`prod-share`)
* **Project**: `analytics-prod`
* **Instance**: `prod-share` (Location: `us-central1-b`)
* **Tier**: `BASIC_SSD`
* **Filestore IP**: `10.0.4.2`
* **VPC Network**: `prod-vpc`
* **Export ACL**: Default `0.0.0.0/0` (READ_WRITE)
* **VPC Firewall Status**: Allowed on TCP port 2049 via `allow-internal-nfs`
* **Diagnostic Verdict**: Healthy and reachable; manual diagnostic
verification commands provided without executing any shell tools.
network-firewall-spec.md 7.5 KB
<!-- disableFinding(LINE_OVER_80) -->
<!-- disableFinding(LIST_NO_LINE) -->
<!-- disableFinding(LINK_ID) -->
# Google Cloud Filestore VPC Network & Firewall Specification
This reference details the networking architecture, port requirements, Private
Services Access (PSA) peering, and firewall rules required for seamless Google
Cloud Filestore operation.
## Table of Contents
* [1. Required Network Ports for Filestore NFS](#1-required-network-ports-for-filestore-nfs):
Lines 23-76
* [2. Private Services Access (PSA) & Peering Architecture](#2-private-services-access-psa--peering-architecture):
Lines 79-100
* [3. Shared VPC (Cross-Project Networking)](#3-shared-vpc-cross-project-networking):
Lines 104-132
* [4. Attributed Ingress Firewall Rule Remediation](#4-attributed-ingress-firewall-rule-remediation):
Lines 136-148
--------------------------------------------------------------------------------
## 1. Required Network Ports for Filestore NFS
Filestore supports **NFSv3** across all service tiers (`Basic HDD`, `Basic SSD`,
`Zonal`, `Regional`, `Enterprise`) and **NFSv4.1** on `Zonal`, `Regional`, and
`Enterprise` tiers. The following ports must be reachable between client VMs/GKE
nodes and the Filestore instance IP range:
| Port | Protocol | Service | Protocol Version & |
: : : : Purpose :
| :--------- | :------------ | :----------------------- | :----------------- |
| **`2049`** | **TCP / UDP** | **NFS Server (`nfsd`)** | **Mandatory (NFSv3 |
: : : : & NFSv4.1)**. :
: : : : Primary NFS file :
: : : : operations (mount, :
: : : : read, write, :
: : : : lookup). Note\: :
: : : : NFSv4.1 requires :
: : : : **only TCP :
: : : : `2049`**. :
| **`111`** | **TCP / UDP** | **RPCbind / Portmapper** | **Mandatory for |
: : : : NFSv3**. Dynamic :
: : : : port discovery for :
: : : : `mountd`, `statd`, :
: : : : and `nlockmgr`. :
| **`2046`** | **TCP / UDP** | **`statd` (Status | **Required for |
: : : Monitor)** : NFSv3 File :
: : : : Locking**. Network :
: : : : status monitor :
: : : : used for lock :
: : : : recovery after :
: : : : reboots. :
| **`2050`** | **TCP / UDP** | **`mountd` (Mount | **Required for |
: : : Daemon)** : NFSv3**. Handles :
: : : : initial NFSv3 :
: : : : mount requests and :
: : : : export path :
: : : : validation. :
| **`4045`** | **TCP / UDP** | **`nlockmgr` (Lock | **Required for |
: : : Manager)** : NFSv3 File :
: : : : Locking**. Network :
: : : : Lock Manager :
: : : : (`NLM`) protocol :
: : : : for advisory file :
: : : : locks :
: : : : (`fcntl`/`flock`). :
> **Best Practice & Directionality**: - **Baseline Connectivity (`2049` &
> `111`)**: Opening TCP/UDP ports `2049` and `111` resolves 99% of initial mount
> timeouts (`ETIMEDOUT` / `RPC: Program not registered`). - **Full NFSv3 Locking
> (`111,2046,2049,2050,4045`)**: Workloads using file locking on NFSv3 require
> all five ports (`111,2046,2049,2050,4045`) open in both **Egress** (client VM
> to Filestore IP) and **Ingress** (Filestore IP / client subnet for lock
> callbacks and `statd` notifications).
--------------------------------------------------------------------------------
## 2. Private Services Access (PSA) & Peering Architecture
Filestore instances do not live directly inside customer Compute Engine subnets.
Instead:
1. Filestore instances are provisioned within a **Google-managed service tenant
project**.
2. The tenant VPC is connected to the customer VPC via a **Private Services
Access (PSA)** VPC Network Peering connection
(`servicenetworking-googleapis-com`).
3. The instance receives a private RFC 1918 internal IP from the reserved IP
range allocated for Google services.
### Cross-VPC / Hybrid Connectivity (VPN & Cloud Interconnect):
If clients mounting Filestore reside on-premises or in a peered VPC:
* The customer VPC peering connection to `servicenetworking-googleapis-com`
must have **"Export custom routes"** enabled.
* The Cloud Router / BGP sessions must advertise the Filestore IP range to
on-premises networks.
--------------------------------------------------------------------------------
## 3. Shared VPC (Cross-Project Networking)
In enterprise Google Cloud landing zones, Filestore instances are frequently
deployed in a **Service Project** while attached to a VPC network hosted in a
centralized **Host Project**:
```
┌────────────────────────────────────────────────────────┐
│ Host Project (projects/network-hub-prod) │
│ │
│ VPC Network: prod-vpc │
│ Firewall Rules: Managed HERE! │
└──────────────────────────┬─────────────────────────────┘
│ Shared VPC Attachment
▼
┌────────────────────────────────────────────────────────┐
│ Service Project (projects/analytics-prod) │
│ │
│ Filestore Instance: finance-share │
│ Network: projects/network-hub-prod/global/networks/… │
└────────────────────────────────────────────────────────┘
```
### Critical Firewall Administration Rule for Shared VPC:
* Firewall rules evaluated by the VPC network live in the **Host Project**
(`network-hub-prod`).
* Querying or creating firewall rules in the Service Project
(`analytics-prod`) will have **no effect** and will report empty rules.
* Remediation commands must target `--project={HOST_PROJECT_ID}`.
--------------------------------------------------------------------------------
## 4. Ingress Firewall Rule Remediation
```bash
gcloud compute firewall-rules create allow-{network_name}-filestore-nfs \
--network="{network_name}" \
--direction=INGRESS \
--priority=1000 \
--action=ALLOW \
--rules=tcp:2049,udp:2049,tcp:111,udp:111 \
--source-ranges="{client_subnet_cidr}" \
--project="{host_project_id}"
```
diagnose_lib.py 14.8 KB
"""Core pure-Python evaluation library for Filestore log-based troubleshooting.
Provides network URI resolution, priority-sorted VPC ingress firewall
evaluation, subnet CIDR containment checks, non-destructive nfsExportOptions
merging, instance health evaluation, and report formatting.
"""
import ipaddress
import json
import os
import re
from typing import Any, Dict, List, Optional, Tuple
_DEFAULT_METRICS_ENV = (
"agent-skills/1.0 (skill:google-cloud-filestore-log-troubleshooting)"
)
def _load_attribution(
fallback: str = _DEFAULT_METRICS_ENV, attr_path: Optional[str] = None
) -> str:
"""Loads the attribution token from references/attribution.md."""
path = attr_path or os.path.join(
os.path.dirname(os.path.abspath(__file__)),
"..",
"references",
"attribution.md",
)
try:
with open(path, encoding="utf-8") as f:
match = re.search(
r'CLOUDSDK_METRICS_REQUEST_ATTRIBUTION="([^"]+)"', f.read()
)
if match:
return match.group(1)
except OSError:
pass
return fallback
METRICS_ENV = _load_attribution()
def resolve_network_info(
networks: List[Dict[str, Any]], default_project: str
) -> Tuple[str, str, str]:
"""Extracts network name, host project ID (Shared VPC), and primary IP."""
if not networks:
return "default", default_project, "UNKNOWN"
net_uri = networks[0].get("network", "")
parts = net_uri.split("/")
if "projects" in parts and len(parts) - parts.index("projects") >= 2:
host_project = parts[parts.index("projects") + 1]
vpc_network = parts[-1]
else:
host_project = default_project
vpc_network = parts[-1] if net_uri else "default"
ip_addrs = networks[0].get("ipAddresses", [])
return vpc_network, host_project, (ip_addrs[0] if ip_addrs else "UNKNOWN")
def parse_instance_meta(meta: Dict[str, Any], project: str) -> Dict[str, Any]:
"""Extracts normalized Filestore instance metadata fields."""
vpc, host_proj, ip = resolve_network_info(meta.get("networks", []), project)
shares = meta.get("fileShares", [])
share = shares[0] if shares else {}
parts = meta.get("name", "").split("/")
return {
"id": parts[5] if len(parts) >= 6 else meta.get("name", ""),
"location": parts[3] if len(parts) >= 6 else "unknown",
"tier": meta.get("tier", "UNKNOWN"),
"state": meta.get("state", "UNKNOWN"),
"vpc": vpc,
"host_proj": host_proj,
"ip": ip,
"share": share.get("name", "share"),
"capacity_gb": int(share.get("capacityGb", 1024)),
"exports": share.get("nfsExportOptions", []),
}
def _port_matches(port: int, ports: List[str]) -> bool:
"""Checks if port matches any port spec (e.g. '2049' or '2045-2050')."""
if not ports:
return True
for p in ports:
lo, _, hi = p.partition("-")
try:
if int(lo) <= port <= int(hi or lo):
return True
except ValueError:
continue
return False
def check_port_allowed(
rules: List[Dict[str, Any]], client_ip: Optional[str], port: int = 2049
) -> Tuple[bool, Optional[str], Optional[str]]:
"""Evaluates whether TCP port is permitted by priority-sorted rules."""
target_net = None
if client_ip:
try:
target_net = ipaddress.ip_network(client_ip, strict=False)
except ValueError:
pass
for r in sorted(rules, key=lambda x: x.get("priority", 1000)):
is_deny = "denied" in r
blocks = r.get("denied", []) if is_deny else r.get("allowed", [])
if not any(
b.get("IPProtocol", "").lower() in ("tcp", "all")
and _port_matches(port, b.get("ports", []))
for b in blocks
):
continue
src_ranges = r.get("sourceRanges", [])
ip_matched = (
not target_net
or (target_net.version == 4 and "0.0.0.0/0" in src_ranges)
or (target_net.version == 6 and "::/0" in src_ranges)
)
if not ip_matched and target_net:
for sr in src_ranges:
try:
sr_net = ipaddress.ip_network(sr, strict=False)
if (is_deny and target_net.overlaps(sr_net)) or (
not is_deny and target_net.subnet_of(sr_net)
):
ip_matched = True
break
except (ValueError, TypeError):
continue
if ip_matched:
name, prio = r.get("name", "unnamed-rule"), r.get("priority", 1000)
if is_deny:
msg = f"Blocked by explicit DENY rule '{name}' (priority {prio})"
return False, name, msg
return True, name, f"Allowed by rule '{name}' (priority {prio})"
return False, None, "No matching ingress firewall rule found allowing port"
def check_export_acl(
export_options: List[Dict[str, Any]], client_ip: str
) -> Tuple[bool, str, Optional[Dict[str, Any]]]:
"""Validates whether client_ip / CIDR is permitted by nfsExportOptions."""
if not export_options:
return True, "Default allowlist (0.0.0.0/0) active with READ_WRITE", None
try:
target_net = ipaddress.ip_network(client_ip, strict=False)
except ValueError:
return False, f"Invalid client IP format: {client_ip}", None
for opt in export_options:
for r in opt.get("ipRanges", []):
try:
if target_net.subnet_of(ipaddress.ip_network(r, strict=False)):
mode = opt.get("accessMode", "READ_WRITE")
squash = opt.get("squashMode", "NO_ROOT_SQUASH")
msg = f"Matched rule '{r}' (mode: {mode}, squash: {squash})"
return True, msg, opt
except (ValueError, TypeError):
continue
msg = "Client IP is not covered by any allowed CIDR in nfsExportOptions"
return False, msg, None
def build_non_destructive_export_json(
existing_options: List[Dict[str, Any]],
new_cidr: str,
share_name: str,
capacity_gb: int,
) -> Dict[str, Any]:
"""Generates non-destructive merged --flags-file payload preserving rules."""
merged = []
for opt in existing_options or []:
entry: Dict[str, Any] = {
"access-mode": opt.get(
"accessMode", opt.get("access-mode", "READ_WRITE")
),
"ip-ranges": list(opt.get("ipRanges", opt.get("ip-ranges", []))),
"squash-mode": opt.get(
"squashMode", opt.get("squash-mode", "NO_ROOT_SQUASH")
),
}
if "anonUid" in opt or "anon-uid" in opt:
entry["anon-uid"] = opt.get("anonUid", opt.get("anon-uid"))
if "anonGid" in opt or "anon-gid" in opt:
entry["anon-gid"] = opt.get("anonGid", opt.get("anon-gid"))
merged.append(entry)
merged.append({
"access-mode": "READ_WRITE",
"ip-ranges": [new_cidr],
"squash-mode": "NO_ROOT_SQUASH",
})
return {
"--file-share": {
"name": share_name,
"capacity": capacity_gb,
"nfs-export-options": merged,
}
}
def build_acl_remediation(
instance: str, location: str, project: str, info: Dict[str, Any], cidr: str
) -> Dict[str, Any]:
"""Builds non-destructive export ACL update command descriptor."""
payload = build_non_destructive_export_json(
info["exports"], cidr, info["share"], info["capacity_gb"]
)
return {
"type": "EXPORT_ACL",
"desc": (
f"Non-destructively append client subnet '{cidr}' to Filestore"
" nfsExportOptions"
),
"payload": payload,
"cmd": (
"PATCH_FILE=$(mktemp /tmp/filestore-export-patch.XXXXXX.json)\n"
"cat << 'EOF' >"
f' "${{PATCH_FILE}}"\n{json.dumps(payload, indent=2)}\nEOF\n'
f'CLOUDSDK_METRICS_REQUEST_ATTRIBUTION="{METRICS_ENV}" \\\n'
f"gcloud filestore instances update {instance} \\\n"
f" --location={location} --project={project} \\\n"
' --flags-file="${PATCH_FILE}"\nrm -f "${PATCH_FILE}"'
),
}
def build_fw_remediation(info: Dict[str, Any], cidr: str) -> Dict[str, Any]:
"""Builds VPC ingress firewall rule creation command descriptor."""
rule_name = f"allow-{info['vpc']}-filestore-nfs"
fw_args = [
"gcloud",
"compute",
"firewall-rules",
"create",
rule_name,
f"--network={info['vpc']}",
"--direction=INGRESS",
"--priority=1000",
"--action=ALLOW",
"--rules=tcp:2049,udp:2049,tcp:111,udp:111",
f"--source-ranges={cidr}",
f"--project={info['host_proj']}",
]
return {
"type": "FIREWALL",
"desc": (
"Create VPC ingress firewall rule allowing NFS ports 2049 & 111 from"
f" '{cidr}'"
),
"exec_args": fw_args,
"cmd": (
f'CLOUDSDK_METRICS_REQUEST_ATTRIBUTION="{METRICS_ENV}" \\\n'
f"gcloud compute firewall-rules create {rule_name} \\\n "
f' --network="{info["vpc"]}" --direction=INGRESS --priority=1000 \\\n'
" --action=ALLOW --rules=tcp:2049,udp:2049,tcp:111,udp:111 \\\n "
f' --source-ranges="{cidr}" --project="{info["host_proj"]}"'
),
}
def evaluate_instance(
info: Dict[str, Any],
fw_rules: List[Dict[str, Any]],
target_eval_ip: Optional[str],
target_cidr: Optional[str],
audit_logs: List[Dict[str, Any]],
project: str,
) -> Dict[str, Any]:
"""Evaluates instance state, export ACL, firewall rules, and audit drift."""
root_causes: List[str] = []
remediations: List[Dict[str, Any]] = []
blockers: List[str] = []
if info["state"] != "READY":
root_causes.append(
f"Filestore instance is in state '{info['state']}' (must be READY to"
" accept NFS mounts)."
)
blockers.append(f"State: {info['state']}")
acl_ok, acl_msg, matched = True, "Default/untested", None
if target_eval_ip:
acl_ok, acl_msg, matched = check_export_acl(info["exports"], target_eval_ip)
if not acl_ok:
root_causes.append(
"EACCES (Permission Denied by Server): Client IP is not in Filestore"
" export allowlist."
)
blockers.append("ACL: Client IP rejected")
remediations.append(
build_acl_remediation(
info["id"],
info["location"],
project,
info,
target_cidr or "10.128.0.0/20",
)
)
port_2049_open, _, reason_2049 = check_port_allowed(
fw_rules, target_eval_ip, port=2049
)
port_111_open, _, _ = check_port_allowed(fw_rules, target_eval_ip, port=111)
if not port_2049_open:
root_causes.append(
"ETIMEDOUT (Connection Timed Out): VPC firewall does not permit ingress"
" on NFS port 2049."
)
blockers.append("FW: Port 2049 blocked")
remediations.append(build_fw_remediation(info, target_cidr or "10.0.0.0/8"))
inst_drift = any(
info["id"] in log.get("protoPayload", {}).get("resourceName", "")
for log in audit_logs
)
overall = f"BLOCKED ({', '.join(blockers)})" if blockers else "HEALTHY"
if inst_drift:
overall += " [Audit: Recent config drift]"
return {
"root_causes": root_causes,
"remediations": remediations,
"acl_ok": acl_ok,
"acl_msg": acl_msg,
"matched_rule": matched,
"port_2049_open": port_2049_open,
"reason_2049": reason_2049,
"port_111_open": port_111_open,
"summary_row": {
"instance": info["id"],
"location": info["location"],
"tier": info["tier"],
"ip": info["ip"],
"network": info["vpc"],
"port_2049": "OPEN" if port_2049_open else "BLOCKED",
"acl": "PASS" if acl_ok else "FAIL",
"status": overall,
},
}
def format_single_report(
info: Dict[str, Any],
ev: Dict[str, Any],
target_eval_ip: Optional[str],
audit_logs: List[Dict[str, Any]],
csi_errors: List[str],
) -> str:
"""Formats the 4-phase narrative diagnostic report for a single instance."""
subsep = "-" * 80
lines = [
f" • State : {info['state']}",
f" • Tier : {info['tier']}",
f" • Filestore IP : {info['ip']}",
f" • VPC Network : {info['vpc']} (Host Project: {info['host_proj']})",
f" • Share Name : {info['share']} ({info['capacity_gb']} GiB)",
f" • Export ACLs : {len(info['exports'])} rule(s) configured\n",
]
if target_eval_ip:
lines.append(
f"[*] Step 2: Evaluating Export ACLs for '{target_eval_ip}'..."
)
if ev["acl_ok"]:
lines.append(f" [PASS] Export ACL: {ev['acl_msg']}")
matched = ev["matched_rule"] or {}
if matched.get("accessMode") == "READ_ONLY":
lines.append(" [NOTE] Share is READ_ONLY. Writes fail with EROFS.")
if matched.get("squashMode") == "ROOT_SQUASH":
lines.append(" [NOTE] ROOT_SQUASH active. UID 0 maps to nobody.")
else:
lines.append(f" [FAIL] Export ACL Violation: {ev['acl_msg']}")
else:
lines.append(
"[*] Step 2: Client IP not provided. Active export allowlists:"
)
for idx, opt in enumerate(info["exports"], 1):
lines.append(
f" Rule #{idx}: IP={opt.get('ipRanges')},"
f" Mode={opt.get('accessMode')}"
)
if not info["exports"]:
lines.append(" (Default 0.0.0.0/0 allowlist active with READ_WRITE)")
lines.append("")
lines.append(
f"[*] Step 3: Inspecting VPC ingress firewall rules on '{info['vpc']}'"
f" ({info['host_proj']})..."
)
p_tag = "[PASS]" if ev["port_2049_open"] else "[FAIL]"
p_txt = "Ingress NFS TCP Port 2049" + (
"" if ev["port_2049_open"] else " is BLOCKED"
)
lines.append(f" {p_tag} {p_txt}: {ev['reason_2049']}")
if not ev["port_111_open"]:
lines.append(
" [WARN] Ingress RPC portmapper (TCP/UDP 111) not explicitly allowed"
" (required for NFSv3)."
)
lines.append(
"\n[*] Step 4: Scanning Cloud Logging for recent drift and client"
" errors..."
)
if audit_logs:
lines.append(
f" • Detected {len(audit_logs)} administrative change(s) in past"
" 24h:"
)
for log in audit_logs:
ts = log.get("timestamp", "")
principal = (
log.get("protoPayload", {})
.get("authenticationInfo", {})
.get("principalEmail", "Unknown")
)
method = log.get("protoPayload", {}).get("methodName", "").split(".")[-1]
lines.append(f" - [{ts}] {method} by {principal}")
else:
lines.append(
" • No administrative drift detected on instance in past 24h."
)
for err_msg in csi_errors[:2]:
lines.append(f" • Recent GKE CSI driver error: {err_msg}")
lines.append(f"\n{subsep}\n 📋 DIAGNOSTIC SUMMARY\n{subsep}")
if not ev["root_causes"]:
lines.append(
" ✅ All baseline network firewall and export ACL checks PASSED.\n"
" Filestore instance is healthy and reachable on port 2049."
)
else:
lines.append(f" ❌ Identified {len(ev['root_causes'])} Blocker(s):")
for idx, rc in enumerate(ev["root_causes"], 1):
lines.append(f" {idx}. {rc}")
lines.append(
f"\n{subsep}\n 🛠️ RECOMMENDED REMEDIATION COMMAND(S)\n{subsep}"
)
for idx, rem in enumerate(ev["remediations"], 1):
lines.append(
f" Action {idx} ({rem['type']}): {rem['desc']}\n\n{rem['cmd']}\n"
)
return "\n".join(lines)
quick_diagnose.py 13.4 KB
#!/usr/bin/env python3
"""Google Cloud Filestore Log-Based Troubleshooting CLI Runner.
Diagnoses Filestore client mount failures (ETIMEDOUT, EACCES, EPERM), network
reachability, VPC ingress firewall rules, export ACLs, and Cloud Audit logging
drift. Emits verified non-destructive remediation commands with interactive
confirmation.
"""
import argparse
import contextlib
import datetime
import json
import os
import subprocess
import sys
import tempfile
from typing import Any, Dict, List, Optional, Tuple
sys.dont_write_bytecode = True
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import diagnose_lib # pylint: disable=g-import-not-at-top
# Re-export pure evaluation functions for backward compatibility & unit tests
METRICS_ENV = diagnose_lib.METRICS_ENV
resolve_network_info = diagnose_lib.resolve_network_info
check_port_allowed = diagnose_lib.check_port_allowed
check_export_acl = diagnose_lib.check_export_acl
build_non_destructive_export_json = (
diagnose_lib.build_non_destructive_export_json
)
_build_acl_remediation = diagnose_lib.build_acl_remediation
_build_fw_remediation = diagnose_lib.build_fw_remediation
def get_cmd_env() -> Dict[str, str]:
"""Constructs process environment with Cloud SDK metrics attribution."""
return {**os.environ, "CLOUDSDK_METRICS_REQUEST_ATTRIBUTION": METRICS_ENV}
def run_cmd(cmd: List[str], check: bool = False) -> Tuple[int, str, str]:
"""Executes a shell command and returns (returncode, stdout, stderr)."""
res = subprocess.run(
cmd, capture_output=True, text=True, env=get_cmd_env(), check=False
)
if check and res.returncode != 0:
raise RuntimeError(f"Command failed: {' '.join(cmd)}\nError: {res.stderr}")
return res.returncode, res.stdout, res.stderr
def _gcloud(subcmd: str, *args: str) -> Tuple[int, str, str]:
"""Runs gcloud subcmd with extra arguments."""
return run_cmd(["gcloud", *subcmd.split(), *args])
def _gcloud_json(subcmd: str, *args: str) -> Any:
"""Runs gcloud with --format=json and returns parsed JSON or None."""
code, out, _ = _gcloud(subcmd, *args, "--format=json")
if code == 0 and out.strip():
try:
return json.loads(out)
except json.JSONDecodeError:
pass
return None
def get_default_project() -> Optional[str]:
"""Gets the active gcloud configured project."""
code, out, _ = _gcloud(
"config get-value project", "--format=value(core.project)"
)
return out.strip() if code == 0 and out.strip() else None
def describe_filestore_instance(
instance: str, location: str, project: str
) -> Optional[Dict[str, Any]]:
"""Retrieves Filestore instance metadata via gcloud using location/zone."""
for loc_flag in (f"--location={location}", f"--zone={location}"):
res = _gcloud_json(
"filestore instances describe",
instance,
loc_flag,
f"--project={project}",
)
if res is not None:
return res
print(
f"[ERROR] Failed to fetch instance '{instance}' in '{location}'.",
file=sys.stderr,
)
return None
def get_firewall_rules(
network_name: str, host_project: str
) -> List[Dict[str, Any]]:
"""Retrieves all active VPC ingress firewall rules in the host network."""
flt = "--filter=direction:INGRESS AND disabled:false"
data = _gcloud_json(
"compute firewall-rules list", flt, f"--project={host_project}"
)
if data is None:
print(
f"[WARN] Firewall fetch failed for '{host_project}'.", file=sys.stderr
)
return []
return [
r for r in data if r.get("network", "").split("/")[-1] == network_name
]
def get_recent_audit_logs(
instance: Optional[str], project: str, limit: int = 5
) -> List[Dict[str, Any]]:
"""Queries recent Filestore admin audit logs for configuration drift."""
ts = (
datetime.datetime.now(datetime.timezone.utc)
- datetime.timedelta(hours=24)
).strftime("%Y-%m-%dT%H:%M:%SZ")
flt = (
f'logName="projects/{project}/logs/cloudaudit.googleapis.com%2Factivity"'
' AND protoPayload.serviceName="file.googleapis.com" AND'
f' timestamp>="{ts}"'
)
if instance:
flt += f' AND protoPayload.resourceName=~".*{instance}.*"'
return (
_gcloud_json(
"logging read", flt, f"--project={project}", f"--limit={limit}"
)
or []
)
def get_client_csi_errors(project: str) -> List[str]:
"""Checks Cloud Logging for recent Filestore GKE CSI driver mount errors."""
ts = (
datetime.datetime.now(datetime.timezone.utc) - datetime.timedelta(hours=3)
).strftime("%Y-%m-%dT%H:%M:%SZ")
flt = (
'resource.type="k8s_container" AND'
' resource.labels.container_name="gcp-filestore-driver" AND'
f' severity>=ERROR AND timestamp>="{ts}"'
)
fmt = "--format=value(textPayload,jsonPayload.message)"
code, out, _ = _gcloud(
"logging read", flt, f"--project={project}", "--limit=3", fmt
)
return [l.strip() for l in out.splitlines() if l.strip()] if code == 0 else []
def list_all_filestore_instances(project: str) -> List[Dict[str, Any]]:
"""Retrieves all Filestore instances across all locations in the project."""
data = _gcloud_json("filestore instances list", f"--project={project}")
if data is None:
print("[ERROR] Failed to list Filestore instances.", file=sys.stderr)
return []
return data
def _apply_remediations(
remediations: List[Dict[str, Any]],
instance: str,
location: str,
project: str,
) -> None:
"""Executes remediation commands when --apply-fix is passed."""
print("[!] --apply-fix specified. Executing verified remediation commands...")
for rem in remediations:
if rem["type"] == "FIREWALL":
print(f"Executing: {' '.join(rem['exec_args'])}")
code, out, err = run_cmd(rem["exec_args"])
ok = code == 0
msg = f"[SUCCESS] Rule created:\n{out.strip()}" if ok else err.strip()
print(msg, file=sys.stdout if ok else sys.stderr)
elif rem["type"] == "EXPORT_ACL":
with tempfile.NamedTemporaryFile("w", suffix=".json", delete=False) as tf:
json.dump(rem["payload"], tf, indent=2)
try:
cmd = [
"gcloud",
"filestore",
"instances",
"update",
instance,
f"--location={location}",
f"--project={project}",
f"--flags-file={tf.name}",
]
print(f"Executing: {' '.join(cmd)}")
code, out, err = run_cmd(cmd)
ok = code == 0
msg = f"[SUCCESS] ACL updated:\n{out.strip()}" if ok else err.strip()
print(msg, file=sys.stdout if ok else sys.stderr)
finally:
if os.path.exists(tf.name):
os.remove(tf.name)
def run_diagnostics(
instance: str,
location: str,
project: str,
client_ip: Optional[str] = None,
client_subnet: Optional[str] = None,
apply_fix: bool = False,
sink: Optional[Dict[str, Any]] = None,
) -> Tuple[int, List[str], List[Dict[str, Any]]]:
"""Runs 4-phase diagnostic triage and returns (exit_code, causes, fixes)."""
sep, subsep = "=" * 80, "-" * 80
print(
f"\n{sep}\n 🔍 FILESTORE LOG-BASED TROUBLESHOOTING REPORT\n{sep}\n"
f" Target Instance : {instance}\n Location / Zone : {location}\n"
f" GCP Project : {project}"
)
if client_ip:
print(f" Client IP : {client_ip}")
if client_subnet:
print(f" Client Subnet : {client_subnet}")
print(f"{subsep}\n[*] Step 1: Querying Filestore instance configuration...")
meta = describe_filestore_instance(instance, location, project)
if not meta:
print(
"[FATAL] Unable to proceed without instance metadata.", file=sys.stderr
)
return 1, ["Failed to retrieve instance metadata."], []
info = diagnose_lib.parse_instance_meta(meta, project)
if sink is not None:
sink["instance"] = info
target_cidr = client_subnet or (f"{client_ip}/32" if client_ip else None)
target_eval_ip = client_ip or client_subnet
fw_rules = get_firewall_rules(info["vpc"], info["host_proj"])
audit_logs = get_recent_audit_logs(instance, project)
ev = diagnose_lib.evaluate_instance(
info, fw_rules, target_eval_ip, target_cidr, audit_logs, project
)
print(
diagnose_lib.format_single_report(
info, ev, target_eval_ip, audit_logs, get_client_csi_errors(project)
)
)
root_causes, remediations = ev["root_causes"], ev["remediations"]
if root_causes:
if apply_fix:
_apply_remediations(remediations, instance, location, project)
else:
print(
"👉 Would you like me to run this remediation command for you? (Yes"
" / No)"
)
return 0, root_causes, remediations
def run_all_diagnostics(
project: str,
client_ip: Optional[str] = None,
client_subnet: Optional[str] = None,
sink: Optional[Dict[str, Any]] = None,
) -> int:
"""Runs diagnostics across all Filestore instances in the project."""
sep = "=" * 80
print(
f"\n{sep}\n 🚀 DISCOVERING ALL FILESTORE INSTANCES IN PROJECT:"
f" {project}\n{sep}"
)
instances = list_all_filestore_instances(project)
if not instances:
print(f"No Filestore instances found in project '{project}'.")
return 0
print(f"Found {len(instances)} instance(s). Running diagnostics...\n")
summary_rows = []
fw_cache: Dict[Tuple[str, str], List[Dict[str, Any]]] = {}
project_audit_logs = get_recent_audit_logs(None, project, limit=25)
target_ip = client_ip or client_subnet
target_cidr = client_subnet or (f"{client_ip}/32" if client_ip else None)
for inst_data in instances:
info = diagnose_lib.parse_instance_meta(inst_data, project)
key = (info["vpc"], info["host_proj"])
if key not in fw_cache:
fw_cache[key] = get_firewall_rules(*key)
ev = diagnose_lib.evaluate_instance(
info, fw_cache[key], target_ip, target_cidr, project_audit_logs, project
)
row = ev["summary_row"]
summary_rows.append(row)
print(
f" • {info['id']} ({info['location']}) | Tier: {info['tier']} | IP:"
f" {info['ip']} | Port 2049: {row['port_2049']} | Status:"
f" {row['status']}"
)
print(
f"\n{sep}\n 📊 AUDIT & DIAGNOSTIC SUMMARY TABLE ({len(summary_rows)}"
f" INSTANCES)\n{sep}\n| Instance ID | Location | Tier | Filestore IP"
" | Network | Port 2049 | Export ACL | Status |\n| :--- | :--- | :--- |"
" :--- | :--- | :--- | :--- | :--- |"
)
for r in summary_rows:
print(
f"| `{r['instance']}` | {r['location']} | {r['tier']} | `{r['ip']}` |"
f" `{r['network']}` | {r['port_2049']} | {r['acl']} |"
f" **{r['status']}** |"
)
print()
if sink is not None:
sink["instances"] = summary_rows
return 0
def main():
parser = argparse.ArgumentParser(
description="Google Cloud Filestore Log-Based Troubleshooting Tool",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=(
"Examples:\n quick_diagnose.py --instance=finance-share"
" --location=us-central1-b --project=analytics-prod"
" --client-subnet=10.128.0.0/20\n quick_diagnose.py --all"
" --project=analytics-prod --json\n\nExit codes: 0 = Diagnosis"
" completed (inspect verdict for HEALTHY vs BLOCKED); 1 ="
" Execution/metadata fetch error."
),
)
parser.add_argument("--instance", help="Filestore Instance ID")
parser.add_argument("--location", help="Location / Zone / Region")
parser.add_argument("--zone", help="Backward-compatible alias for --location")
parser.add_argument(
"--all", action="store_true", help="Diagnose all instances"
)
parser.add_argument("--project", help="GCP Project ID")
parser.add_argument("--client-ip", help="Client internal IP")
parser.add_argument("--client-subnet", help="Client Subnet CIDR")
parser.add_argument("--apply-fix", action="store_true", help="Execute fix")
parser.add_argument(
"--json",
action="store_true",
help="Emit machine-readable JSON on stdout (narrative report on stderr)",
)
args = parser.parse_args()
project = args.project or get_default_project()
if not project:
print("[ERROR] Specify --project=<PROJECT_ID>", file=sys.stderr)
sys.exit(1)
location = args.location or args.zone
if not args.all and (not args.instance or not location):
print(
"[ERROR] Both --instance and --location (or --zone) are required unless"
" --all is specified.",
file=sys.stderr,
)
sys.exit(1)
sink: Dict[str, Any] = {}
redirect = (
contextlib.redirect_stdout(sys.stderr)
if args.json
else contextlib.nullcontext()
)
with redirect:
if args.all:
exit_code = run_all_diagnostics(
project, args.client_ip, args.client_subnet, sink=sink
)
root_causes, remediations = [], []
else:
exit_code, root_causes, remediations = run_diagnostics(
args.instance,
location,
project,
args.client_ip,
args.client_subnet,
args.apply_fix,
sink=sink,
)
if args.json:
is_blocked = bool(root_causes) or any(
"BLOCKED" in r.get("status", "") for r in sink.get("instances", [])
)
payload: Dict[str, Any] = {
"project": project,
"mode": "fleet" if args.all else "instance",
"client_ip": args.client_ip,
"client_subnet": args.client_subnet,
"root_causes": root_causes,
"remediations": remediations,
"verdict": "BLOCKED" if is_blocked else "HEALTHY",
**sink,
}
json.dump(payload, sys.stdout, indent=2)
sys.stdout.write("\n")
sys.exit(exit_code)
if __name__ == "__main__":
main()
License (Apache-2.0)
View full license text
Licensed under the Apache License, Version 2.0. See https://github.com/google/skills/blob/main/LICENSE