Installation
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install cloud-trace-querying@skills-hub
Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled).
Plugin cloud-trace-querying v1.0.0 follows the Agent Plugins spec.
gh skills-hub install cloud-trace-querying Don't have the extension? Run gh extension install samueltauil/skills-hub first.
Download and extract to your repository:
.github/skills/cloud-trace-querying/ Extract the ZIP to .github/skills/ in your repo. The folder name must match cloud-trace-querying for Copilot to auto-discover it.
Skill Files (90)
SKILL.md 7.2 KB
---
name: cloud-trace-querying
metadata:
version: "1.0.3"
category: CloudObservabilityAndMonitoring
description: >-
Query Cloud Trace spans, filter by latency thresholds or error status,
correlate distributed traces with Cloud Logging, and diagnose latency bottlenecks
across Google Cloud services. Use when investigating slow requests, analyzing trace
hierarchies, or resolving latency regressions. Do NOT use for querying non-GCP
telemetry or database query optimization outside Cloud Trace.
---
# Cloud Trace Querying Skill (`cloud-trace-querying`)
This skill equips the agent to interact with Cloud Trace by providing standard query patterns, diagnostic workflows for latency and errors, and tools to fetch and inspect trace hierarchies.
> [!IMPORTANT]
> **AUTONOMOUS TOOL EXECUTION MANDATE**:
> You MUST execute the tool scripts directly in bash to query telemetry.
> Do NOT just describe query strings or write Python scripts. Run the provided bash tools directly and report the exact results.
## Attribution
**MUST READ**: Before executing any `gcloud`, REST API, or MCP command, you
MUST read [Usage Attribution](references/attribution.md). For commands executed
directly in the terminal (never in generated scripts, Terraform, or user code),
prefix `gcloud` with
`CLOUDSDK_METRICS_REQUEST_ATTRIBUTION="agent-skills/1.0 (skill:cloud-trace-querying)"`
and append `agent-skills/1.0 (skill:cloud-trace-querying)` to `User-Agent` headers.
## Prerequisites & Setup
1. **Google Cloud SDK**: Verify `gcloud` is installed ([Installation Guide](https://docs.cloud.google.com/sdk/docs/install-sdk)).
2. **Authentication**: Authenticate CLI and application default credentials:
```bash
gcloud auth login && gcloud auth application-default login
```
3. **Project & Billing**: Identify the target `<PROJECT_ID>` (from the user's prompt or via `bash scripts/get_trace_project/run.sh`), ensure an active billing account is attached, and configure the project if not already set:
```bash
gcloud config set project <PROJECT_ID>
```
4. **API Enablement**: Verify Cloud Trace and Cloud Logging APIs are enabled:
```bash
gcloud services enable cloudtrace.googleapis.com logging.googleapis.com
```
## Quickstart Workflows
### 1. Identify Google Cloud Project ID
If the user specified a Google Cloud project ID in their prompt, use it.
If they did not, ALWAYS determine the Google Cloud project ID by running:
```bash
bash scripts/get_trace_project/run.sh
```
### 2. Search Traces (Latency & Errors)
To find traces matching specific criteria, such as a root span of `/v1/booking/book` with a duration of at least 1.5s:
```bash
bash scripts/search_traces/run.sh --filter 'root:/v1/booking/book latency:1.5s' --projects '<PROJECT_ID>'
```
*Note: `--filter` is required. To list traces without specific filtering, pass `--filter ''` or `--filter 'root:'`.*
*Filter syntax: The Cloud Trace API uses `latency:<duration>` (such as `latency:1.5s` for duration >= 1.5s), which corresponds to "Span duration" in Trace Explorer.*
*The script outputs JSON where each cluster's `examples` array contains sample trace objects with `trace_id`, `duration_seconds`, span count, and error status.*
### 3. Fetch Entire Trace Hierarchy
To view all spans and status codes/labels within a trace:
```bash
bash scripts/fetch_entire_trace/run.sh --trace-id '<TRACE_ID>' --project '<PROJECT_ID>'
```
### 4. Fetch Correlated Application Logs
To retrieve application log entries correlated with a trace ID:
```bash
bash scripts/fetch_related_logs/run.sh --trace-id '<TRACE_ID>' --trace-projects '<PROJECT_ID>'
```
*Application log entries are useful when inspecting stack traces, exception messages, and log events emitted during span execution. When diagnosing errors or service crashes, inspect the returned log entries for `severity: "ERROR"` to confirm root causes or uncover unhandled exceptions.*
*Note: `fetch_related_logs` queries the default log scope (`_Default`), searching across configured log views in the target project. An empty response can occur if: (1) no log entries match the criteria, (2) the caller lacks IAM permissions to view the matching entries, or (3) matching entries reside in log views outside the searched log scope.*
### 5. Fetch Specific Trace Span
To inspect attributes and metadata of a single span within a trace:
```bash
bash scripts/fetch_trace_span/run.sh --trace-id '<TRACE_ID>' --span-id '<SPAN_ID>' --project '<PROJECT_ID>'
```
### 6. Generate Cloud Console Deep Links
To generate direct Cloud Console URLs for browser inspection of traces or correlated logs:
```bash
bash scripts/generate_links/run.sh --trace-id '<TRACE_ID>' --project '<PROJECT_ID>' [--span-id '<SPAN_ID>']
```
### 7. Format Output
- **Terminal / CLI**: Render span trees as indented ASCII timelines using `|--`.
- **UI Presentation**: Render as A2UI JSON graph structures when requested for UI.
### 8. Upstream Service Error Handling
If the Cloud Trace API or Cloud Logging API returns an upstream HTTP service error (such as `500 Internal Server Error`, `503 Service Unavailable`, or `GoogleAPICallError`), report the upstream service outage directly to the user. Do not attempt to inspect virtual environments, modify internal scripts, or debug local libraries.
## Reference Documentation
- **Master Index**: [Reference Documentation Index](./references/index.md)
### Operational Workflows
- [Troubleshoot Latency Workflow](./references/troubleshoot-latency.md)
- [Correlated Logs Workflow](./references/correlated-logs.md)
- [Trace Querying Decision Tree](./references/decision-tree.md)
- [Console Deep Links](./references/console-deep-links.md)
- [Workflows Overview](./references/workflows-overview.md)
### Query Syntax & Tools
- [Filter Syntax](./references/filter-syntax.md) (`root:`, `latency:`, `+span:`, `error:true`)
- [API Limits and Constraints](./references/api-limits.md)
- [Observability Analytics (BigQuery SQL)](./references/querying-observability-analytics.md)
- [Cloud Trace MCP Tools](./references/querying-mcp.md)
### Semantic Conventions
- [Conventions Overview](./references/conventions.md)
- [OpenTelemetry Core](./references/conventions-otel.md)
- [OpenTelemetry HTTP](./references/conventions-otel-http.md)
- [OpenTelemetry gRPC & RPC](./references/conventions-otel-grpc.md)
- [OpenTelemetry GenAI](./references/conventions-otel-genai.md)
- [GCP App Hub & Service Conventions](./references/conventions-gcp.md)
- [GCP Legacy Labels](./references/conventions-gcp-legacy.md)
### Concepts & Architecture
- [Observability Scopes](./references/observability-scopes.md)
- [Distributed Traces Concept](./references/concepts-trace.md)
- [Spans Concept](./references/concepts-span.md)
- [Logs-to-Trace Correlation](./references/logs-trace-correlation.md)
- [Knowledge Overview](./references/knowledge-overview.md)
### Templates & Assets
- [ASCII Formatting Templates](./assets/formatting/ascii)
- [A2UI Formatting Templates](./assets/formatting/a2ui)
- [Query Scenarios](./assets/queries)
## Official Documentation Links
- [Cloud Trace Documentation](https://docs.cloud.google.com/trace/docs)
- [Finding and Viewing Traces](https://docs.cloud.google.com/trace/docs/finding-traces)
- [OpenTelemetry Semantic Conventions](https://opentelemetry.io/docs/specs/semconv/)
display.a2ui.json 1.1 KB
[
{
"createSurface": {
"id": "span-surface-4a2b3c",
"title": "Span: /db.Query",
"components": [
{
"id": "span-metadata-table",
"component": "Table",
"headers": ["Metadata Property", "Value"],
"rows": [
["Trace ID", "7b2c0199e4f5a3e10c55a29811d0bb3e"],
["Span ID", "4a2b3c4d5e6f7a8b"],
["Parent Span ID", "1a2b3c4d5e6f7a8b"],
["Start Time", "2026-07-14T15:00:00.100Z"],
["End Time", "2026-07-14T15:00:00.250Z"],
["Duration", "150ms"],
["Status", "OK"]
]
},
{
"id": "span-attributes-table",
"component": "Table",
"headers": ["Attribute Key", "Value"],
"rows": [
["db.system.name", "mysql"],
["db.operation.name", "SELECT"],
["db.namespace", "orders"],
["db.query.text", "SELECT * FROM orders WHERE order_id = ?"],
["server.address", "db-primary.internal"],
["server.port", 3306]
]
}
]
}
}
]
display.a2ui.json 1.1 KB
[
{
"createSurface": {
"id": "trace-surface-7b2c01",
"title": "Trace: /v1/orders/submit",
"components": [
{
"id": "trace-summary-card",
"component": "Card",
"title": "Trace Summary",
"children": [
{
"component": "Table",
"headers": ["Property", "Value"],
"rows": [
["Trace ID", "7b2c0199e4f5a3e10c55a29811d0bb3e"],
["Total Duration", "1000ms"],
["Spans", "4"]
]
}
]
},
{
"id": "trace-spans-table",
"component": "Table",
"headers": ["Span Name", "Start Offset", "Duration", "Timeline", "Status"],
"rows": [
["/v1/orders/submit", "0ms", "1000ms", "[====================]", "OK"],
["/auth/verify", "0ms", "200ms", "[====................]", "OK"],
["/db.Query", "200ms", "700ms", "[....==============..]", "OK"],
["/notify/queue", "900ms", "100ms", "[..................==]", "OK"]
]
}
]
}
}
]
display.a2ui.json 0.7 KB
[
{
"createSurface": {
"id": "trace-flow-surface",
"title": "Trace Flow: /v2/items/batch_get",
"components": [
{
"id": "trace-flow-graph",
"component": "Graph",
"nodes": [
{"id": "n1", "label": "/v2/items/batch_get (800ms)"},
{"id": "n2", "label": "/cache/read (350ms)"},
{"id": "n3", "label": "/service/fetch (400ms)"},
{"id": "n4", "label": "/db.Query (300ms)"},
{"id": "n5", "label": "/render/json (50ms)"}
],
"edges": [
{"from": "n1", "to": "n2"},
{"from": "n1", "to": "n3"},
{"from": "n3", "to": "n4"},
{"from": "n1", "to": "n5"}
]
}
]
}
}
]
display.a2ui.json 1.8 KB
[
{
"createSurface": {
"id": "traces-heatmap-surface",
"title": "Traces Heat Map",
"components": [
{
"id": "traces-heatmap-chart",
"component": "ScatterPlot",
"xAxis": {"label": "Time", "type": "time"},
"yAxis": {"label": "Latency (ms)", "type": "linear"},
"series": [
{
"name": "Success",
"color": "green",
"data": [
["2026-07-14T12:00:00Z", 2200, "Trace 1"],
["2026-07-14T12:05:00Z", 2500, "Trace 2"],
["2026-07-14T12:10:00Z", 2100, "Trace 4"],
["2026-07-14T12:00:00Z", 1100, "Trace 5"],
["2026-07-14T12:15:00Z", 1000, "Trace 7"]
]
},
{
"name": "Error",
"color": "red",
"data": [
["2026-07-14T12:10:00Z", 3200, "Trace 3"],
["2026-07-14T12:05:00Z", 1200, "Trace 6"]
]
}
]
},
{
"id": "traces-heatmap-key",
"component": "Table",
"title": "Trace Key",
"headers": ["Label", "Trace ID", "Latency", "Status"],
"rows": [
["Trace 1", "7b2c0199e4f5a3e10c55a29811d0bb3e", "2.2s", "OK"],
["Trace 2", "a1d38200f73c6821e90b8f411aa509de", "2.5s", "OK"],
["Trace 3", "ee901a88b502c31049ddc784f1a233b2", "3.2s", "ERROR"],
["Trace 4", "9b8c7d6e5f4e3d2c1b0a9f8e7d6c5b4a", "2.1s", "OK"],
["Trace 5", "3f2e1d0c9b8a7f6e5d4c3b2a1e0d9c8b", "1.1s", "OK"],
["Trace 6", "5c4b3a210f9e8d7c6b5a4f3e2d1c0b9a", "1.2s", "ERROR"],
["Trace 7", "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d", "1.0s", "OK"]
]
}
]
}
}
]
display.txt 0.4 KB
Span ID: 4a2b3c4d5e6f7a8b
Name: /db.Query
Parent Span ID: 1a2b3c4d5e6f7a8b
Start Time: 2026-07-14T15:00:00.100Z
End Time: 2026-07-14T15:00:00.250Z
Duration: 150ms
Status: OK
Attributes:
db.system.name: mysql
db.operation.name: SELECT
db.namespace: orders
db.query.text: SELECT * FROM orders WHERE order_id = ?
server.address: db-primary.internal
server.port: 3306
display.txt 0.5 KB
Trace ID: ee901a88b502c31049ddc784f1a233b2
Root Span: /v1/payment/charge
Total Latency: 1500ms
[1500ms] /v1/payment/charge [=========================================]
[ 100ms] |-- /gateway/auth [=== ] (OK)
[ 400ms] |-- /gateway/post [ ========== ] (ERROR - timeout)
[ 950ms] |-- /gateway/retry [ ============================] (OK - fallback)
[ 50ms] |-- /db.Write [ ] (OK)
display.txt 0.4 KB
Trace ID: a1d38200f73c6821e90b8f411aa509de
[ /v2/items/batch_get ] (ID: a1b2c3d4e5f6a7b8, 800ms, ERROR)
│
├───> [ /cache/read ] (ID: b2c3d4e5f6a7b8c9, 350ms, OK)
│
├───> [ /service/fetch ] (ID: c3d4e5f6a7b8c9d0, 400ms, ERROR)
│ │
│ └───> [ /db.Query ] (ID: d4e5f6a7b8c9d0e1, 300ms, ERROR)
│
└───> [ /render/json ] (ID: e5f6a7b8c9d0e1f2, 50ms, OK)
display.txt 0.9 KB
Filter: root:/v1/checkout/process
Latency
^
| <3>
3s|
| [2]
2s| [1] | [4]
| | | |
1s| [5] <6> [7]
+-------------------------------------> Time
12:00 12:05 12:10 12:15
Legend:
[N] : Successful Trace (ID: N)
<N> : Failed Trace (ID: N)
Trace Key:
1: Trace ID 7b2c0199e4f5a3e10c55a29811d0bb3e (Latency: 2.2s, Status: OK)
2: Trace ID a1d38200f73c6821e90b8f411aa509de (Latency: 2.5s, Status: OK)
3: Trace ID ee901a88b502c31049ddc784f1a233b2 (Latency: 3.2s, Status: ERROR)
4: Trace ID 9b8c7d6e5f4e3d2c1b0a9f8e7d6c5b4a (Latency: 2.1s, Status: OK)
5: Trace ID 3f2e1d0c9b8a7f6e5d4c3b2a1e0d9c8b (Latency: 1.1s, Status: OK)
6: Trace ID 5c4b3a210f9e8d7c6b5a4f3e2d1c0b9a (Latency: 1.2s, Status: ERROR)
7: Trace ID 1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d (Latency: 1.0s, Status: OK)
SCENARIO.md 1.4 KB
# Scenario: Errors in Billing Service
Find traces where a call to the gRPC service `billing.PaymentService` method `Charge` failed with any error.
This helps identify billing failures regardless of the specific error type or status code.
This query leverages:
* `rpc.method`: Span label matching the fully-qualified RPC method name semantic convention.
* `label:rpc.response.status_code`: Filters for traces where the `rpc.response.status_code` label is present.
### Important Query Limitations & Post-Filtering Requirements:
1. **Independent Span Matching (False Positives)**:
Predicates are evaluated at the trace level. The query `+rpc.method:billing.PaymentService/Charge label:rpc.response.status_code` will match a trace if **any** span matches the method and **any** span (even a completely unrelated database call) has a status code label.
* *Requirement*: The agent must programmatically inspect the matched trace to verify that the `billing.PaymentService/Charge` span itself contains the error.
2. **Explicit OK Statuses**:
While conforming instrumentations omit `rpc.response.status_code` for successful calls, it is legally valid for a library to explicitly set it to `"ok"`.
* *Requirement*: The agent must post-filter the results to verify that the value of `rpc.response.status_code` is not `"ok"` (or `0` numeric) before flagging it as a failure.
query.txt 0.1 KB
+rpc.method:billing.PaymentService/Charge label:rpc.response.status_code
SCENARIO.md 0.4 KB
# Scenario: Latency Bottleneck in Checkout Service
Find all traces starting at the HTTP route `/v1/checkout/process` with a total latency of 1.5 seconds or more.
This helps isolate performance issues specifically impacting the checkout flow.
This query leverages:
* `^http.route`: Root span label matching the HTTP route semantic convention.
* `latency`: Filtering for traces exceeding the specified duration.
query.txt 0.0 KB
+^http.route:/v1/checkout/process latency:1.5s
SCENARIO.md 0.3 KB
# Scenario: Identify Traces for Specific Customer Group
Find traces containing spans associated with customer IDs prefixed with `cust_99`.
This helps debug issues reported by specific customers or accounts.
This query leverages:
* `app.customer_id`: Custom application-specific span label prefix match.
query.txt 0.0 KB
app.customer_id:cust_99
SCENARIO.md 1.0 KB
# Scenario: Production Latency Outliers
Find traces in the production environment that have a latency of 2 seconds or longer.
This helps identify slow requests affecting real users in production.
This query leverages:
* `deployment.environment.name`: Standard OpenTelemetry Resource attribute to identify the deployment environment (e.g., `production`).
* `latency`: Filtering for traces with high overall duration.
### Alternative Environment Attributes:
Depending on your environment's instrumentation and cloud provider integrations, the environment might be tracked using different resource attributes.
If your services are integrated with Google Cloud App Hub, they will be annotated using GCP App Hub semantic conventions (which use uppercase enum values):
* **App Hub Service Environment**:
`+gcp.apphub.service.environment_type:PRODUCTION latency:2s`
* **App Hub Workload Environment**:
`+gcp.apphub.workload.environment_type:PRODUCTION latency:2s`
query.txt 0.0 KB
+deployment.environment.name:production latency:2s
SCENARIO.md 0.4 KB
# Scenario: Slow Database Queries
Find traces that contain any database span (marked with `db.system.name` attribute) taking 500 milliseconds or more.
This helps isolate database performance issues from overall application latency.
This query leverages:
* `db.system.name`: Span label matching the database system name semantic convention.
* `latency`: Filtering for traces that have at least one span meeting the duration threshold.
query.txt 0.0 KB
db.system.name:mysql latency:500ms
api-limits.md 1.6 KB
# API Limits and Constraints
This reference details the limits, quotas, and constraints when querying Cloud
Trace and Cloud Logging APIs. Note that limits are endpoint-specific and vary
between the v1 and v2 API versions.
## Cloud Trace API (v1) Quotas & Limits
1. **Query Page Size / List Limits**:
* The v1 `projects.traces.list` API endpoint caps the maximum number of
traces returned in a single request at 1000.
2. **Rate Limits**:
* API v1 has standard rate-limiting quotas (e.g. read requests per minute
per project). Consult the GCP Quotas page for your current project
limits.
3. **Data Retention**:
* Trace data is stored for 30 days. Queries looking back further than 30
days will return empty results.
4. **Filter Formatting Constraints**:
* Latency filters must be formatted as an integer value followed
immediately by a unit suffix (`ms`, `s`, `m`). No spaces are allowed
(e.g. `800ms`, not `800 ms`).
## Cloud Logging API Limits
1. **Log Entry Retention**:
* Default retention is 30 days, but custom log buckets can be configured
for longer retention periods (up to 3650 days).
2. **Log Query Page Size**:
* Maximum page size for list log entries is 1000 entries.
## See Also
* [Cloud Trace Quotas and Limits - Google Cloud docs](https://cloud.google.com/trace/docs/quotas)
* [Cloud Logging Quotas and Limits - Google Cloud docs](https://cloud.google.com/logging/quotas)
* [Cloud Observability Pricing - Google Cloud docs](https://cloud.google.com/stackdriver/pricing)
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:cloud-trace-querying)" \
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:cloud-trace-querying)` 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:
```
User-Agent: <existing_user_agent> agent-skills/1.0 (skill:cloud-trace-querying)
```
- **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.
concepts-span.md 0.8 KB
# Concept: Spans
A span represents a single unit of work or timed operation within a distributed
trace (e.g., an HTTP request, a database query, or a function execution). Spans
form a parent-child hierarchy to map execution flow and dependency relationships
across distributed service networks.
## See Also
* [Traces and Spans Concept - Google Cloud docs](https://docs.cloud.google.com/trace/docs/traces-and-spans)
* [Spans Concept - OpenTelemetry docs](https://opentelemetry.io/docs/concepts/signals/traces/#spans)
* [Span API Reference - Google Cloud docs](https://cloud.google.com/trace/docs/reference)
* [REST API Spans Reference - Google Cloud docs](https://docs.cloud.google.com/trace/docs/reference/v2/rest/v2/projects.traces.spans.md.txt)
* [Tracing API Specification - OpenTelemetry docs](https://opentelemetry.io/docs/specs/otel/trace/api/#span)
concepts-trace.md 1.3 KB
# Concept: Distributed Traces
A distributed trace represents the end-to-end execution path of a transaction or
request as it flows through multiple microservices, hosts, or cloud services.
## Key Fields
* **Trace ID**: A globally unique 32-character hexadecimal string representing
the transaction (conforming to the
[W3C Trace Context Specification](https://www.w3.org/TR/trace-context/)).
All spans within a single transaction share the same Trace ID.
* **Span Collection**: A trace is formed by a directed acyclic graph (DAG) of
[spans](./concepts-span.md) representing individual operations.
* **Cross-Boundary Analysis**: Traces allow engineers to track RPC boundaries,
measure latency across hops, and isolate failures (see
[Troubleshoot Slow Requests Workflow](./troubleshoot-latency.md)).
## See Also
* [Traces and Spans Concept - Google Cloud docs](https://docs.cloud.google.com/trace/docs/traces-and-spans)
* [Cloud Trace Documentation - Google Cloud docs](https://cloud.google.com/trace/docs)
* [Traces Concept - OpenTelemetry docs](https://opentelemetry.io/docs/concepts/signals/traces/)
* [W3C Trace Context Specification - W3C spec](https://www.w3.org/TR/trace-context/)
* [Trace API Reference - Google Cloud docs](https://cloud.google.com/trace/docs/reference)
console-deep-links.md 1.1 KB
# Workflow: Generate Console Deep Links
Instead of constructing Console deep links manually, you should use the `generate_links` helper script to generate deep links for Cloud Trace and Cloud Logging.
## Usage
```bash
# Location: scripts/generate_links/
./run.sh --project PROJECT_ID --trace-id TRACE_ID [--span-id SPAN_ID]
```
This script will output formatted, URL-encoded console deep links to inspect:
1. **Cloud Trace**: Displays details of the specific trace (and optional span) in the Cloud Console.
2. **Cloud Logging**: Filtered view showing logs associated with the specified trace (and optional span).
## See Also
* [Cloud Trace Documentation - Google Cloud docs](https://cloud.google.com/trace/docs)
* [Cloud Logging Documentation - Google Cloud docs](https://cloud.google.com/logging/docs)
* [Traces Concept - OpenTelemetry docs](https://opentelemetry.io/docs/concepts/signals/traces/)
* [Viewing Trace Details - Google Cloud docs](https://cloud.google.com/trace/docs/viewing-details)
* [Logging Query Library - Google Cloud docs](https://cloud.google.com/logging/docs/view/query-library)
conventions-gcp-legacy.md 3.4 KB
# GCP Legacy Span Labels
This document details legacy span label keys used in older Google Cloud Trace
systems. These labels typically start with a forward slash (`/`) or `g.co/` and
are commonly found in GCP-generated telemetry from App Engine, Cloud Functions, and Cloud Run OR from telemetry running on GCP using legacy exporters or instrumentation solutions.
## Legacy slash-prefixed Labels
The following keys are often found in older Google Cloud APIs, legacy App Engine
applications, or pre-OTel Stackdriver instrumentation:
Label Key | Description | OTel Equivalent | Example
:------------------ | :--------------------------------- | :-------------------------- | :------
`/http/method` | HTTP request method. | `http.request.method` | `GET`
`/http/status_code` | HTTP response status code. | `http.response.status_code` | `200`
`/http/path` | Request path portion of URL. | `url.path` | `/index.html`
`/http/host` | HTTP host header. | `server.address` | `example.com`
`/http/url` | Complete requested URL. | `url.full` | `http://example.com/`
`/http/user_agent` | Value of the User-Agent header. | `user_agent.original` | `Mozilla/5.0...`
`/http/client_ip` | Remote IP address of the client. | `client.address` | `203.0.113.195`
`/rpc/method` | RPC method name. | `rpc.method` | `GetItem`
`/rpc/status_code` | RPC response status code. | `rpc.grpc.status_code` | `0`
`/error/name` | Class name of the error/exception. | `error.type` | `NullReferenceException`
## GCP Exporter `g.co/` Attributes
Legacy GCP exporters inject specialized attributes prefixed with `g.co/` to
trace exporter metadata and compute resource context:
Attribute Key | Category | Description | Example
:---------------------------- | :------- | :-------------------------------------------- | :------
`g.co/agent` | Exporter | Identifies the exporter agent or SDK wrapper. | `opentelemetry-go`
`g.co/r/container_name` | GKE | Canonical GKE container name. | `auth-api`
`g.co/r/pod_name` | GKE | Canonical GKE pod name. | `auth-api-559d87-abc`
`g.co/r/namespace_name` | GKE | GKE namespace name. | `production`
`g.co/r/cluster_name` | GKE | GKE cluster name. | `prod-cluster`
`g.co/gae/app/version` | GAE | App Engine application version. | `v2`
`g.co/gae/app/module` | GAE | App Engine module/service name. | `default`
`g.co/gae/app/module_version` | GAE | App Engine module version string. | `v2.44101882`
`g.co/gce/hostname` | GCE | Compute Engine hostname. | `prod-vm-01.c.my-proj.internal`
`g.co/gce/instanceid` | GCE | Compute Engine VM instance ID. | `1234567890123456789`
## Querying Examples
To query using legacy HTTP status code label:
```filter
/http/status_code:500
```
To search for a specific legacy HTTP method:
```filter
/http/method:POST
```
## See Also
* [Legacy Stackdriver Trace Labels - Google Cloud docs](https://cloud.google.com/trace/docs/reference)
conventions-gcp.md 2.7 KB
# GCP App Hub and Service Conventions
This document details modern Google Cloud Platform (GCP) specific semantic
conventions used in App Hub mappings and service mesh proxy tracing.
## GCP Service Context Attributes
The following attributes identify the client and server logical service contexts
when querying GCP APIs and service endpoints:
| Attribute Key | Description | Example |
| :--- | :--- | :--- |
| `gcp.client.service` | Used by GCP client libraries (which may be used by code belonging to GCP users running on or outside of GCP) to denote which GCP service the library interacts with. | `firestore`, `storage`, `run`, `spanner`, `datastore`, `bigquery` |
| `gcp.server.service` | Used by GCP server-side service components to identify the service emitting the telemetry. | `firestore.googleapis.com`, `spanner.googleapis.com`, `storage.googleapis.com`, `run.googleapis.com` |
## GCP App Hub Attributes
[GCP App Hub](https://cloud.google.com/app-hub/docs) groups resources together
to represent application systems. Spans are stamped with App Hub identifiers
mapping the source container:
| Attribute Key | Description | Example |
| :-------------------------- | :------------------- | :-------------------- |
| `gcp.apphub.application.id` | The registered App | `ecommerce-app` |
: : Hub Application ID. : :
| `gcp.apphub.service.id` | Logical Service ID | `checkout-api` |
: : within App Hub. : :
| `gcp.apphub.workload.id` | Workload identifier | `checkout-deployment` |
: : backing the service. : :
## GCP App Hub Destination Attributes
For egress or cross-application boundaries, destination App Hub tags are
recorded:
| Attribute Key | Description | Example |
| :-------------------------------------- | :----------- | :------------------ |
| `gcp.apphub_destination.application.id` | Destination | `payment-app` |
: : App Hub : :
: : Application : :
: : ID. : :
| `gcp.apphub_destination.service.id` | Destination | `stripe-processor` |
: : Service ID. : :
| `gcp.apphub_destination.workload.id` | Destination | `stripe-deployment` |
: : Workload ID. : :
## See Also
* [Google Cloud App Hub Documentation - Google Cloud docs](https://cloud.google.com/app-hub/docs)
conventions-otel-genai.md 6.9 KB
# OpenTelemetry GenAI Semantic Conventions
This document details semantic conventions for Generative AI (GenAI) models,
agentic workflows, and Model Context Protocol (MCP) interactions.
## GenAI Semantic Conventions
The table below lists canonical GenAI semantic attributes and maps them to
deprecated or legacy aliases (noting Vertex/Gemini values where applicable):
Attribute Key | Aliases / Deprecated Keys | Description | Example
:------------------------------- | :------------------------------- | :------------------------------------------------------------------------------- | :------
`gen_ai.provider.name` | `gen_ai.system` | Generative AI system/provider name. For Google Cloud, canonical values are `gcp.vertex_ai` (for Vertex AI API), `gcp.gemini` (for Gemini / AI Studio API), or `gcp.gen_ai`. | `gcp.vertex_ai`
`gen_ai.request.model` | | The requested LLM model name. | `gemini-1.5-pro`
`gen_ai.response.model` | | The actual model name generating the response. | `gemini-1.5-pro-001`
`gen_ai.request.temperature` | | Temperature configuration parameter. | `0.7`
`gen_ai.request.max_tokens` | | Maximum number of tokens to generate. | `2048`
`gen_ai.request.top_p` | | Top-p (nucleus) sampling configuration. | `0.9`
`gen_ai.response.id` | | The unique identifier of the response. | `chatcmpl-12345`
`gen_ai.response.finish_reasons` | | Finish reasons for generation. | `["stop"]`, `["length"]`
`gen_ai.usage.input_tokens` | `gen_ai.usage.prompt_tokens` | Count of prompt (input) tokens. | `1024`
`gen_ai.usage.output_tokens` | `gen_ai.usage.completion_tokens` | Count of completion (output) tokens. | `256`
## GenAI Agent & Span Conventions
When querying trace data for agentic frameworks and multi-agent systems, look for these standard OTel GenAI attributes:
| Attribute Key | Description | Example |
| :--------------------------- | :------------------- | :-------------------- |
| `gen_ai.agent.name` | Human-readable name | `Codebase Researcher` |
: : of the agent. : :
| `gen_ai.system_instructions` | The system prompt or | `You are a helpful |
: : instructions sent to : coding assistant...` :
: : the model. : :
| `gen_ai.input.messages` | Serialized input | `[{"role": "user", |
: : messages list (JSON : "content"\: "..."}]` :
: : array). : :
| `gen_ai.output.messages` | Serialized output | `[{"role": |
: : messages list (JSON : "assistant", :
: : array). : "content"\: "..."}]` :
| `gen_ai.tool.name` | The name of the tool | `read_file` |
: : called by the agent. : :
| `gen_ai.tool.status` | Completion status of | `success` |
: : the tool execution. : :
| `gen_ai.memory.id` | The unique ID of the | `session_abc_123` |
: : conversation memory : :
: : scope. : :
## Model Context Protocol (MCP) Semantic Conventions
Attributes used for Model Context Protocol (MCP) client-server interactions:
| Attribute Key | Aliases / | Description | Example |
: : Deprecated : : :
: : Keys : : :
| :--------------------- | :----------- | :---------- | :--------------------- |
| `mcp.method.name` | `mcp.method` | The MCP | `tools/call` |
: : : method : :
: : : being : :
: : : called. : :
| `mcp.protocol.version` | | The version | `2024-11-05` |
: : : of the MCP : :
: : : protocol. : :
| `mcp.session.id` | | Session | `session_xyz_789` |
: : : identifier : :
: : : correlating : :
: : : requests. : :
| `mcp.resource.uri` | | Resource | `file:///path/to/file` |
: : : URI : :
: : : accessed. : :
## Non-Standard Attributes for GenAI
Some older or alternative frameworks use different prefixes, but these are not
canonical OTel keys:
* **`llm.` Prefixes**: Attributes like `llm.tool.name` or `llm.request.model`
are injected by older versions of tools such as OpenInference.
## Correlated Log Conventions
For large prompt payloads, model responses, or instructions that do not fit
inside span attributes, applications write structured log events with reference
indicators:
* **`gen_ai.client.inference.operation.details` Event**: Logged when executing
inference operations.
* **Key Fields**:
* `gen_ai.input.messages_ref`: Reference/URI pointing to the prompt input
payload.
* `gen_ai.output.messages_ref`: Reference/URI pointing to the response
output payload.
* `gen_ai.system_instructions_ref`: Reference/URI pointing to the system
instructions payload.
## See Also
* [OpenTelemetry GenAI Semantic Conventions - GitHub Specification](https://github.com/open-telemetry/semantic-conventions-genai)
* [Collect and View Multimodal Prompts & Responses - Google Cloud docs](https://docs.cloud.google.com/trace/docs/collect-view-multimodal-prompts-responses)
conventions-otel-grpc.md 2.4 KB
# OpenTelemetry gRPC & RPC Semantic Conventions
This document details current and legacy semantic conventions for RPC and gRPC
client and server spans.
## RPC & gRPC Attributes
The table below maps canonical RPC semantic conventions to older legacy and
non-OTel formats:
Attribute Key | Aliases / Deprecated Keys | Description | Example
:------------------------------ | :-------------------------------------- | :------------------------------------------------------------------------------- | :------
`rpc.system.name` | `rpc.system` | The RPC system name. | `grpc`
`rpc.service` | | Fully qualified name of the RPC service. | `google.pubsub.v1.Publisher`
`rpc.method` | | Name of the RPC method called. | `Publish`
`rpc.response.status_code` | `rpc.grpc.status_code` (legacy numeric) | Canonical textual status code representation (or legacy numeric representation). | `unavailable`, `ok` (textual) or `14`, `0` (numeric)
`rpc.message.type` | | Type of message (e.g. `SENT`, `RECEIVED`). | `SENT`
`rpc.message.id` | | Message identifier. | `1`
`rpc.message.uncompressed_size` | | Uncompressed message size in bytes. | `512`
`grpc.status` | | **Non-OTel** textual status value used in some non-OTel gRPC instrumentations. | `UNAVAILABLE`
> [!NOTE] Connection-related attributes (`client.address`, `server.address`, and
> `server.port`) are documented under [OpenTelemetry Core](./conventions-otel.md).
## See Also
* [OpenTelemetry RPC Semantic Conventions - OpenTelemetry specs](https://opentelemetry.io/docs/specs/semconv/rpc/)
* [gRPC Semantic Conventions - OpenTelemetry specs](https://opentelemetry.io/docs/specs/semconv/rpc/grpc/)
conventions-otel-http.md 1.9 KB
# OpenTelemetry HTTP Semantic Conventions
This document details semantic conventions for HTTP client and server spans.
## HTTP Attributes
The table below lists some current or past HTTP semantic conventions and maps them to
deprecated aliases:
Attribute Key | Aliases / Deprecated Keys | Description | Example
:-------------------------- | :------------------------ | :----------------------------------------------- | :------
`http.request.method` | `http.method` | HTTP request method. | `GET`
`http.response.status_code` | `http.status_code` | HTTP response status code. | `200`
`url.path` | `http.target` | Path portion of the URL. | `/v1/checkout`
`url.query` | | Query portion of the URL. | `id=123`
`url.scheme` | `http.scheme` | URI scheme. | `https`
`url.full` | `http.url` | Absolute URL. | `https://example.com/v1/checkout`
`user_agent.original` | `http.user_agent` | Value of HTTP `User-Agent` header. | `Mozilla/5.0...`
`http.route` | | The matched route template. | `/v1/checkout/:id`
`url.template` | | Alternative name for the matched route template. | `/v1/checkout/{id}`
> [!NOTE] Connection-related attributes (`client.address`, `server.address`, and
> `server.port`) are documented under [OpenTelemetry Core](./conventions-otel.md).
## See Also
* [OpenTelemetry HTTP Semantic Conventions - OpenTelemetry specs](https://opentelemetry.io/docs/specs/semconv/http/http-spans/)
conventions-otel.md 4.2 KB
# OpenTelemetry Core Semantic Conventions
This document details general, resource-related, and network-related semantic
conventions defined by OpenTelemetry (OTel).
## Core Attributes
These attributes provide general context about the execution environment,
service context, and errors:
| Attribute Key | Description | Example |
| :--------------------- | :------------------------------------------- | :------------------- |
| `service.name` | Logical name of the service. | `payment-service` |
| `service.namespace` | A namespace grouping multiple services. | `billing` |
| `service.version` | Service version string. | `1.4.2` |
| `service.instance.id` | Unique ID identifying a running instance. | `a4f21b77-d1a1-4fe1` |
| `error.type` | Category/type of error (e.g. exception). | `ValueError` |
| `error.message` | Legacy error message. | `Division by zero` |
| `exception.message` | Exception error message. | `Division by zero` |
| `exception.stacktrace` | Raw stack trace. | `Traceback (most recent...)` |
| `process.id` | Process identifier. | `12345` |
## Cloud Resource Attributes
These resource attributes identify the cloud infrastructure environment:
| Attribute Key | Aliases / Deprecated Keys | Description | Example |
| :------------------------ | :------------------------ | :------------------------------------------------------- | :------ |
| `cloud.provider` | | The cloud provider name. MUST be `gcp` for Google Cloud. | `gcp` |
| `cloud.account.id` | | GCP Project ID (only when `cloud.provider` is `gcp`). | `my-prod-project` |
| `cloud.platform` | | The specific platform type. | `gcp_kubernetes_engine`, `gcp_compute_engine` |
| `cloud.region` | | GCP geographical region. | `us-central1` |
| `cloud.availability_zone` | | GCP availability zone (zone suffix). | `us-central1-a` |
| `cloud.resource.id` | `cloud.resource_id` | Canonical unique resource ID. Starts with `//` prefix. | `//compute.googleapis.com/projects/my-project/zones/...` |
## Common Network & Connection Attributes
These network connection details are applicable to multiple protocol spans
(HTTP, RPC, etc.):
| Attribute Key | Aliases / Deprecated Keys | Description | Example |
| :--------------------- | :------------------------ | :---------- | :------ |
| `client.address` | | Client IP address or hostname. | `192.0.2.1` |
| `server.address` | `net.host.name` (deprecated) | Server host address or IP. | `api.example.com` |
| `server.port` | `net.host.port` (deprecated) | Port number of the server. | `443` |
| `network.peer.address` | `net.peer.name` (deprecated), `net.sock.peer.addr` (deprecated) | Peer IP address. | `192.0.2.5` |
| `network.peer.port` | `net.peer.port` (deprecated), `net.sock.peer.port` (deprecated) | Peer port number. | `8080` |
## See Also
* [OpenTelemetry General Semantic Conventions - OpenTelemetry specs](https://opentelemetry.io/docs/specs/semconv/general/trace/)
* [Resource Semantic Conventions - OpenTelemetry specs](https://opentelemetry.io/docs/specs/semconv/resource/)
* [OTel Network Semantic Conventions](https://opentelemetry.io/docs/specs/semconv/registry/attributes/network/)
* [OTel Cloud Semantic Conventions](https://opentelemetry.io/docs/specs/semconv/registry/attributes/cloud/)
* [OTel HTTP Semantic Conventions](https://opentelemetry.io/docs/specs/semconv/registry/attributes/http/)
* [OTel URL Semantic Conventions](https://opentelemetry.io/docs/specs/semconv/registry/attributes/url/)
* [OTel RPC Semantic Conventions](https://opentelemetry.io/docs/specs/semconv/registry/attributes/rpc/)
conventions.md 2.5 KB
# Trace Span Conventions
Understanding trace span semantic conventions is critical for formulating
correct trace search queries and accurately interpreting telemetry results.
Because microservices in a single GCP project may use different instrumentation
frameworks, multiple distinct conventions can appear simultaneously.
## Querying and Interpretation Guidelines
* **Diverse Frameworks**: Production environments often mix OpenTelemetry
(OTel), legacy Stackdriver instrumentation, and specialized framework
conventions (such as App Hub, OpenInference, or gRPC).
* **Formulating Filters**: When querying traces, look for both current OTel
keys (e.g. `http.request.method`) and their legacy or alternative
counterparts (e.g. `/http/method`) to ensure complete results.
## Convention Categories
### 1. [OpenTelemetry Core](./conventions-otel.md)
Common OTel attributes for general service context, errors, and cloud resource
metadata.
* `service.name`: Logical service name.
* `error.type`: Category or type of error.
* `cloud.provider`: Cloud provider name (e.g. `gcp`).
### 2. [OpenTelemetry HTTP](./conventions-otel-http.md)
Semantic conventions for HTTP server and client requests.
* `http.request.method`: The HTTP method (e.g. `GET`, `POST`).
* `http.response.status_code`: The response status code.
### 3. [OpenTelemetry gRPC & RPC](./conventions-otel-grpc.md)
Conventions for gRPC/RPC protocols.
* `rpc.system.name`: The RPC protocol name (e.g. `grpc`).
* `rpc.response.status_code`: Textual response status (e.g. `unavailable`).
### 4. [OpenTelemetry GenAI & AI Frameworks](./conventions-otel-genai.md)
Conventions for Large Language Models (LLM), agentic tools, and Model Context
Protocol (MCP) server executions.
* `gen_ai.request.model`: The LLM requested.
* `gen_ai.usage.input_tokens`: Number of input tokens.
* `gen_ai.usage.output_tokens`: Number of output tokens.
### 5. [GCP App Hub and Service Conventions](./conventions-gcp.md)
Modern GCP-specific resource mappings, service identifiers, and App Hub
application conventions.
* `gcp.client.service`: The GCP service that the client library interacts with.
* `gcp.apphub.application.id`: App Hub application ID.
### 6. [GCP Legacy Labels](./conventions-gcp-legacy.md)
Legacy Stackdriver labels prefixed with a forward slash (`/`) and others.
* `/http/method`: Legacy HTTP method.
* `/http/status_code`: Legacy HTTP status code.
## See Also
* [OpenTelemetry Semantic Conventions - OpenTelemetry specs](https://opentelemetry.io/docs/specs/semconv/)
correlated-logs.md 2.5 KB
# Workflow: Find Correlated Logs
This workflow guides you through pulling application logs correlated with a
specific trace ID to troubleshoot runtime errors.
## Basic Workflow
1. **Identify Trace / Span**: Search for failed requests or traces that
returned error codes in a specific project and time range:
```bash
# Location: scripts/search_traces/
./run.sh \
--projects eval-project \
--filter="status:error" \
--start-time "2026-06-25T13:00:00Z" \
--end-time "2026-06-25T14:00:00Z" \
--limit=5
```
2. **Fetch Logs**: Query GCP Logging client for entries associated with the
trace ID, limiting the query to the same time range:
```bash
# Location: scripts/fetch_related_logs/
./run.sh \
--trace-projects eval-project \
--trace-id=<TRACE_ID> \
--start-time "2026-06-25T13:00:00Z" \
--end-time "2026-06-25T14:00:00Z" \
--limit=100
```
3. **Pinpoint Errors**: Look for stack traces or error levels in the output
logs.
## Advanced Details
### LogEntry Schema
Logs are queried and structured according to the Google Cloud Logging LogEntry
schema.
### Correlation Mechanisms
Logs are correlated with traces using two fields:
- **`trace`**: The resource path of the trace (e.g.
`projects/PROJECT_ID/traces/TRACE_ID`). In some telemetry configurations,
this may appear without the prefix as just the raw `TRACE_ID`.
- **`spanId`**: The hex string format of the span ID (e.g.
`spanId="1234567890abcdef"`).
### Multi-Project Log Scopes
In distributed architectures, the GCP project receiving the trace telemetry (the
trace project) might be different from the project where the application writes
its log entries (the logs project).
- If you do not see logs returned from the trace project, specify alternative
logging projects using the `--log-projects` flag.
- Observability Scopes can be inspected to identify which logging projects
monitor the target trace projects.
## See Also
* [Logs-to-Trace Correlation Concept - Trace Skill docs](./logs-trace-correlation.md)
* [Observability Scopes Concept - Trace Skill docs](./observability-scopes.md)
* [LogEntry REST API Reference - Google Cloud docs](https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry)
* [Logging Query Language Reference - Google Cloud docs](https://cloud.google.com/logging/docs/view/logging-query-language)
* [Finding Traces in Console - Google Cloud docs](https://cloud.google.com/trace/docs/finding-traces)
decision-tree.md 2.1 KB
# Workflow: Trace Querying Decision Tree
This guide helps agents select the optimal method for querying distributed
traces in a GCP environment.
## Overview of Querying Methods
There are three primary ways to search and fetch trace telemetry:
1. **Local Script Utilities**
2. **Model Context Protocol (MCP) Tools**
3. **Observability Analytics (BigQuery SQL)**
## Decision Tree & Recommendations
```mermaid
graph TD
Start[Need to query trace data] --> Size{Data Size & Complexity}
Size -->|Massive volume / Complex SQL| BQ[Use BigQuery Observability Analytics]
Size -->|Standard search / Single Trace| Environment{Execution Environment}
Environment -->|Agent Shell / Scripting| Scripts[Use Local Script Utilities]
Environment -->|External / MCP Client| MCP[Use MCP Tools]
```
### 1. Local Script Utilities (Recommended First)
* **When**: Searching traces, fetching spans, or extracting correlated logs in
the local shell.
* **Why**: Scripts (e.g. `search_traces`, `fetch_related_logs`) are optimized
for token usage and output formatting. They group results cleanly to prevent
context bloat.
* **Key Commands**:
- Search: `./scripts/search_traces/run.sh --filter "latency:2s"`
- Logs: `./scripts/fetch_related_logs/run.sh --trace-id TRACE_ID`
### 2. Model Context Protocol (MCP) Tools
* **When**: Operating via an external client that connects to the Cloud Trace
MCP server.
* **Why**: The MCP server exposes direct schema-backed tools (`list_traces`
and `get_trace`). Note that MCP endpoints might have permissions/access in
sandboxed environments that local scripts do not have access to.
### 3. Observability Analytics (BigQuery)
* **When**: Conducting aggregate analysis, calculating complex stats (e.g.
percentiles over time), or joining traces with system logs.
* **Why**: Provides full SQL querying capabilities over massive datasets.
* **Link**:
[Observability Analytics (BigQuery SQL)](./querying-observability-analytics.md)
## See Also
* [Cloud Trace MCP Tools](./querying-mcp.md)
* [Cloud Trace API (v1) Query Syntax](./filter-syntax.md)
filter-syntax.md 4.0 KB
# Cloud Trace Query Syntax (v1)
This reference outlines the filter query syntax and predicates supported by the
Google Cloud Trace API (v1) filter engine.
## Query Predicates
Trace search filters consist of one or more space-separated predicates that
restrict results.
### 1. Root Span Matchers
- `root:[PREFIX]`: Matches traces where the root span name starts with the
given prefix.
- Example: `root:/v1/`
- `+root:[NAME]`: Matches traces where the root span name matches the given
name exactly.
- Example: `+root:/v1/checkout`
### 2. Any Span Matchers
- `span:[PREFIX]`: Matches traces where any span name (root or child) starts
with the given prefix.
- Example: `span:db_`
- `+span:[NAME]`: Matches traces where any span name matches the given name
exactly.
- Example: `+span:db_query`
### 3. Latency Matcher
- `latency:[DURATION]`: Matches traces with overall latency greater than or
equal to the specified duration.
- Example: `latency:1.5s`
- Valid duration suffixes: `ms` (milliseconds), `s` (seconds), `m`
(minutes). No spaces are allowed (e.g., `800ms`, `2.5s`).
### 4. Label Matchers
- `label:[KEY]`: Matches traces where any span has the specified label key present, regardless of its value.
- Example: `label:error.type`
- `[KEY]:[VAL_PREFIX]`: Matches traces where any span has a label matching the
key, and the label value starts with the prefix.
- Example: `http.status_code:5`
- `+[KEY]:[VAL]`: Matches traces where any span has a label matching the key,
and the label value matches the value exactly.
- Example: `+http.status_code:500`
### 5. Root Label Matchers
- `^label:[KEY]`: Matches traces where the root span has the specified label key present, regardless of its value.
- Example: `^label:error.type`
- `^[KEY]:[VAL_PREFIX]`: Matches traces where the root span has a label
matching the key, and the label value starts with the prefix.
- Example: `^http.method:GET`
- `+^[KEY]:[VAL]`: Matches traces where the root span has a label matching the
key, and the label value matches the value exactly.
- Example: `+^http.method:GET`
### 6. Status Matcher
- `error:true`: Matches traces containing at least one span with a failed
status (errors).
- `error:false`: Matches traces containing no spans with failed status.
## Query Evaluation Behavior & Limitations
### Independent Span Matching (Trace-level AND)
Predicates in a query are evaluated at the **trace level**, not the span level. When you combine multiple predicates, the filter engine returns traces where **each predicate matches at least one span**, but they do not need to match the **same** span.
* **Gotcha**: The query `+rpc.method:MyService/MyMethod label:error.type` matches a trace if Span A is `MyService/MyMethod` (success) and Span B has `error.type` (failed database call). It does *not* guarantee that `MyMethod` itself failed.
* **Mitigation**: The agent/client must post-filter the returned traces to verify that the specific target span has the error.
### Key Presence and Post-Filtering
While `label:KEY` filters for traces containing the specified label key, some instrumentations might explicitly populate labels with default/success values (e.g. `rpc.response.status_code:ok` or `error.type:None`).
* **Mitigation**: Always post-filter the results programmatically to verify the actual values and ensure they meet the error criteria (e.g. status is not `OK`).
## See Also
* [Trace Filter Syntax - Google Cloud docs](https://cloud.google.com/trace/docs/finding-traces#filter_syntax)
* [Finding Traces in Console - Google Cloud docs](https://cloud.google.com/trace/docs/finding-traces)
* [Trace REST API v1 Reference - Google Cloud docs](https://cloud.google.com/trace/docs/reference/v1/rest)
* [Trace REST API v2 Reference - Google Cloud docs](https://cloud.google.com/trace/docs/reference/v2/rest)
* [Traces and Spans Concept - Google Cloud docs](https://docs.cloud.google.com/trace/docs/traces-and-spans)
index.md 2.7 KB
# GCP Trace Querying References
This master index catalogs all reference documentation, conventions, concepts, and workflows for Google Cloud Trace querying.
## Workflows
- [Troubleshoot Slow Requests](./troubleshoot-latency.md): Step-by-step procedure for root-causing high latency in distributed traces.
- [Find Correlated Logs](./correlated-logs.md): Workflow for finding and inspecting Cloud Logging entries correlated by Trace ID.
- [Trace Querying Decision Tree](./decision-tree.md): Guide for selecting the optimal query tool (Trace API v1 vs. MCP vs. SQL Analytics).
- [Console Deep Links](./console-deep-links.md): Instructions for constructing shareable Google Cloud Console URLs for traces.
- [Workflows Overview](./workflows-overview.md): High-level overview of operational workflows.
## Query Syntax & Tools
- [Trace Query Filter Syntax](./filter-syntax.md): Complete reference for Cloud Trace API v1 filter operators (`root:`, `latency:`, `+span:`, `error:true`).
- [API Limits and Constraints](./api-limits.md): Quotas, timestamp restrictions, filter limits, and batch sizes.
- [Observability Analytics (BigQuery SQL)](./querying-observability-analytics.md): Querying distributed trace logs and metrics using BigQuery SQL.
- [Cloud Trace MCP Tools](./querying-mcp.md): Querying traces via Model Context Protocol (MCP) server tools.
## Concepts & Architecture
- [Observability Scopes](./observability-scopes.md): Managing cross-project telemetry visibility and `_Default` observability scopes.
- [Distributed Traces](./concepts-trace.md): Conceptual overview of trace identifiers, timelines, and root spans.
- [Spans](./concepts-span.md): Anatomical breakdown of spans, parent-child hierarchies, and labels.
- [Logs-to-Trace Correlation](./logs-trace-correlation.md): How trace contexts are injected and correlated in Cloud Logging entries.
- [Knowledge Overview](./knowledge-overview.md): Comprehensive index of core knowledge topics.
## Semantic Conventions
- [Conventions Overview](./conventions.md): Master guide for span naming, HTTP status mapping, and label conventions.
- [OpenTelemetry Core](./conventions-otel.md): Standard W3C and OpenTelemetry attribute schemas.
- [OpenTelemetry HTTP](./conventions-otel-http.md): HTTP method, target, status code, and route conventions.
- [OpenTelemetry gRPC & RPC](./conventions-otel-grpc.md): RPC service, method, and status code conventions.
- [OpenTelemetry GenAI](./conventions-otel-genai.md): Semantic conventions for LLM requests, prompts, token counts, and completions.
- [GCP App Hub & Service Conventions](./conventions-gcp.md): Canonical Google Cloud service and application metadata labels.
- [GCP Legacy Labels](./conventions-gcp-legacy.md): Backward-compatible legacy Google Cloud Trace span attributes.
knowledge-overview.md 3.2 KB
# GCP Trace Querying Knowledge Base
This index documents the core concepts, query utilities, and telemetry
conventions for GCP distributed tracing.
## 1. When and Why to Look at Trace Data
Distributed traces provide a visualization of request execution flows across
microservices. Look at trace data to:
* Identify latency bottlenecks in slow request paths.
* Pinpoint the service or operation causing request failures.
* Analyze execution paths and span hierarchies in distributed systems.
## 2. Ways to Query Trace
Trace data can be searched and retrieved using multiple methods. By default,
agents should use the supplied `search_traces` script or the MCP endpoints.
For detailed criteria on which method to select, see the
[Trace Querying Decision Tree](./decision-tree.md).
* [Cloud Trace API (v1) Query Filter Syntax](./filter-syntax.md):
Filter queries for trace search.
* [MCP Trace Querying Tools](./querying-mcp.md): Automated tools exposed
to the agent environment.
* [Observability Analytics (BigQuery SQL)](./querying-observability-analytics.md):
Querying exported traces and logs using SQL in BigQuery.
## 3. How and Why to Look at Correlated Logs
Correlated logs connect individual log entries with the request context (traces
and spans).
* **Why**: Correlating logs helps you inspect detailed execution logs, error
payloads, and intermediate state for the exact duration of a specific span.
* **How**: Use the `fetch_related_logs` script to retrieve log entries stamped
with `trace` and `spanId` context fields.
* **Workflow Guide**: See
[Workflow: Find Correlated Logs](./correlated-logs.md) for
step-by-step instructions.
## 4. Concepts and Conventions
Deep dives into tracing structures and instrumentation standards:
* [Distributed Traces](./concepts-trace.md): Overview of trace structures and
identifiers.
* [Spans](./concepts-span.md): Spans, parent-child relationships, and
attributes.
* [Observability Scopes](./observability-scopes.md): Scope-based
multi-project telemetry query routing.
* [Trace Span Conventions](./conventions.md): OpenTelemetry (OTel), GCP,
and legacy span attributes.
* [API Limits and Constraints](./api-limits.md): Quotas, retention limits, and
endpoint constraints.
## See Also
* [Cloud Observability Docs - Google Cloud docs](https://cloud.google.com/stackdriver/docs)
* [Cloud Trace Overview - Google Cloud docs](https://docs.cloud.google.com/trace/docs)
* [Trace API Reference - Google Cloud docs](https://docs.cloud.google.com/trace/docs/reference)
* [Trace Client Libraries - Google Cloud docs](https://docs.cloud.google.com/trace/docs/client-libraries)
* [Finding Traces Using Filters - Google Cloud docs](https://docs.cloud.google.com/trace/docs/trace-filters)
* [Trace Span Labels - Google Cloud docs](https://docs.cloud.google.com/trace/docs/trace-labels)
* [Trace Schema Reference - Google Cloud docs](https://docs.cloud.google.com/trace/docs/reference/trace-schema)
* [Traces Concept - OpenTelemetry docs](https://opentelemetry.io/docs/concepts/signals/traces/)
* [Semantic Conventions - OpenTelemetry docs](https://opentelemetry.io/docs/concepts/semantic-conventions/)
logs-trace-correlation.md 1.7 KB
# Logs-to-Trace Correlation
This document details how logs and traces are correlated in Google Cloud.
---
## Correlation Fields
Google Cloud Logging automatically parses and maps log entries to traces when specific attributes are set:
1. **`logging.googleapis.com/trace`**:
- Stores the full resource path of the trace: `projects/[PROJECT_ID]/traces/[TRACE_ID]`
- Allows Cloud Logging to correlate log entries with a specific trace.
2. **`logging.googleapis.com/spanId`**:
- Stores the active span ID as a hexadecimal string.
- Allows correlation of log entries with a specific span within the trace.
---
## Fetching Correlated Logs
The `fetch_related_logs` script automates log retrieval by constructing a query filter:
- Standard Filter: `trace =~ "projects/.*/traces/{trace_id}"`
- Span Filter: `trace =~ "projects/.*/traces/{trace_id}" AND spanId="{span_id}"`
This script queries logs across all relevant projects (including log projects resolved via Observability Scopes) and consolidates results sorted by timestamp.
---
## See Also
* [Structured Logging Special Fields - Google Cloud docs](https://cloud.google.com/logging/docs/structured-logging#special-payload-fields)
* [Viewing Correlated Logs in Trace Details - Google Cloud docs](https://cloud.google.com/trace/docs/viewing-details#viewing_logs)
* [Correlation with Traces - OpenTelemetry docs](https://opentelemetry.io/docs/specs/otel/logs/#correlation-with-traces)
* [LogEntry REST API Reference - Google Cloud docs](https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry)
* [Logging Query Language Reference - Google Cloud docs](https://cloud.google.com/logging/docs/view/logging-query-language)
observability-scopes.md 3.0 KB
# Concept: Observability Scopes
Observability Scopes, Metrics Scopes, Log Scopes, and Trace Scopes are distinct
but related concepts in Google Cloud used to manage and query telemetry data
across project boundaries.
## Scope Types
1. **Observability Scopes**: A control-plane resource that groups projects
together for a unified operations view. It acts as the coordinator that
connects the different types of scopes (Log Scopes, Trace Scopes, Metrics
Scopes) together. The default observability scope is named `_Default`.
2. **Log Scopes**: Groups resource containers (projects, folders,
organizations) for Cloud Logging. It allows querying logs across all grouped
projects.
3. **Trace Scopes**: Groups resource containers for Cloud Trace, allowing
unified trace exploration.
4. **Metrics Scopes**: Groups resource containers for Cloud Monitoring metrics
(independent from Logging/Trace scopes).
## Scope Resolution Directions
### Trace -> Logs Resolution
When querying logs correlated with a trace in a given project, resolve the
scoped logging projects via the following sequence:
1. **Get Default Observability Scope**:
- Query: `GET
https://observability.googleapis.com/v1/projects/{project_id}/locations/global/scopes/_Default`
- Retrieve the `logScope` resource name from the response.
2. **Get Log Scope Details**:
- Query: `GET https://logging.googleapis.com/v2/{log_scope_name}`
- Retrieve the list of scoped resource paths from the `resourceNames` list
field (e.g. `projects/{monitored_project_id}`).
### Logs -> Trace Resolution
When fetching a trace given a log with tracing information (e.g., when the
`projects/[PROJECT_ID]/traces/` prefix is missing from the log entry), look up
the Trace Scopes of candidate projects to resolve the candidate values of
`[PROJECT_ID]`:
1. **Query default observability scope**:
- Query: `GET
https://observability.googleapis.com/v1/projects/{project_id}/locations/global/scopes/_Default`
- Retrieve the `traceScope` resource name from the response.
2. **Get Trace Scope details**:
- Query: `GET https://observability.googleapis.com/v1/{trace_scope_name}`
- Parse candidate project IDs from the `resourceNames` list field (e.g.
`projects/{monitored_project_id}`).
## See Also
* [Observability Scopes Overview - Google Cloud docs](https://docs.cloud.google.com/stackdriver/docs/observability/scopes)
* [Observability Scopes REST API Reference - Google Cloud docs](https://docs.cloud.google.com/stackdriver/docs/reference/observability/api/rest/v1/projects.locations.scopes)
* [Create and Manage Log Scopes - Google Cloud docs](https://docs.cloud.google.com/logging/docs/log-scope/create-and-manage)
* [Create and Manage Trace Scopes - Google Cloud docs](https://docs.cloud.google.com/trace/docs/trace-scope/create-and-manage)
* [Create and Manage Metrics Scopes - Google Cloud docs](https://docs.cloud.google.com/monitoring/settings/multiple-projects.md.txt)
querying-mcp.md 2.3 KB
# Querying Traces via MCP Tools
This page documents how to query and analyze traces using Model Context Protocol
(MCP) tools.
## Registered MCP Tools
When the Cloud Trace MCP server is configured and connected, the following tools
become available to the agent environment:
### 1. `list_traces`
* **Description**: Lists traces in the target GCP project that match a v1
filter query expression.
* **Arguments**:
* `projectId` (string, required): ID of the Cloud project where the trace
data is stored.
* `startTime` (string, required): Query start time (RFC 3339 timestamp).
* `endTime` (string, required): Query end time (RFC 3339 timestamp).
* `filter` (string, optional): The filter expression (e.g. `latency:2s`).
* `pageSize` (integer, optional): Maximum number of traces to return
(default is 100).
### 2. `get_trace`
* **Description**: Retrieves all spans associated with a specific trace ID.
* **Arguments**:
* `projectId` (string, required): ID of the Cloud project where the trace
data is stored.
* `traceId` (string, required): The 32-character hex trace ID.
## Guidance: Scripts vs. MCP Tools
* **Use Local Script Utilities** (`search_traces`, `fetch_entire_trace`,
`fetch_related_logs`) as the default entry point. Scripts are optimized to
format results cleanly and filter out redundant fields, preventing context
window bloat in the agent environment.
* **Use MCP Tools** (`list_traces`, `get_trace`) if running in an external
client environment without access to a local shell or script repository, or
when using automated MCP tool registries that inject standard query actions.
Note that MCP endpoints might have permissions/access in sandboxed
environments that local scripts do not have access to.
## See Also
* [Model Context Protocol for Cloud Trace - Google Cloud docs](https://docs.cloud.google.com/trace/docs/reference/mcp/mcp)
* [Cloud Trace MCP `list_traces` Tool - Google Cloud docs](https://docs.cloud.google.com/trace/docs/reference/mcp/mcp/tools_list/list_traces.md.txt)
* [Cloud Trace MCP `get_trace` Tool - Google Cloud docs](https://docs.cloud.google.com/trace/docs/reference/mcp/mcp/tools_list/get_trace.md.txt)
* [Cloud Trace Query Syntax (v1)](./filter-syntax.md)
querying-observability-analytics.md 4.9 KB
# Querying Traces via Observability Analytics
Observability Analytics allows you to perform SQL queries directly on your Cloud
Trace data.
## When to Use Observability Analytics
* **Aggregate Metrics**: Calculating aggregate percentiles (p95, p99),
averages, or error rates across thousands of request traces.
* **Complex Filtering**: Filtering traces by multiple complex conditions,
pattern matching on JSON attributes, or joining trace data with logging
buckets.
* **Cross-Service Reports**: Building dashboards in Looker Studio or querying
from external big data tools.
By default, for individual trace investigations or simple searches, prefer using
the **Local Script Utilities** or **MCP Tools** because they are faster and
consume fewer tokens.
## Linked Datasets in BigQuery
To query trace data outside the Google Cloud Console (e.g. from BigQuery Studio,
Looker, or standard client libraries), you must create a **linked dataset** in
BigQuery.
### 1. Checking for Existing Linked Datasets
Before creating a new linked dataset, check if one has already been set up in your BigQuery project:
1. List datasets in your BigQuery project to check for a dataset associated with logs/traces (often named `_Trace` or `observability_analytics` or the custom name chosen during creation):
```bash
gcloud alpha bq datasets list --project="your-project-id"
```
2. Verify that the `_AllSpans` view exists and is queryable in that dataset (replace `LINK_ID` with the dataset name found):
```bash
gcloud alpha bq tables describe "_AllSpans" \
--dataset="LINK_ID" \
--project="your-project-id"
```
### 2. How to Create a Linked Dataset
If no dataset exists, you can link the system trace dataset to BigQuery using `gcloud` (replace `LINK_ID` with your desired BigQuery dataset name, and adjust `--location` if your bucket is regionalized):
```bash
gcloud logging links create "LINK_ID" \
--bucket="_Trace" \
--location="global" \
--project="your-project-id"
```
This creates a read-only dataset in BigQuery that links directly to the underlying trace data store.
## Schema Reference
The system-defined view `_Trace.Spans._AllSpans` has the following schema
structure:
| Field Path | SQL Type | Description |
| :--------------- | :---------- | :--------------------------------- |
| `trace_id` | `STRING` | The 128-bit unique identifier for |
: : : the trace (hex format). :
| `span_id` | `STRING` | The 64-bit unique identifier for |
: : : the span (hex format). :
| `parent_span_id` | `STRING` | The identifier of the parent span. |
| `name` | `STRING` | The display name of the span |
: : : (operation name). :
| `kind` | `INT64` | Span kind (e.g., `2` for |
: : : `SPAN_KIND_SERVER`, `3` for :
: : : `SPAN_KIND_CLIENT`). :
| `start_time` | `TIMESTAMP` | Start timestamp of the span. |
| `end_time` | `TIMESTAMP` | End timestamp of the span. |
| `status` | `RECORD` | Status record containing `code` |
: : : (INT64) and `message` (STRING). :
| `attributes` | `JSON` | Key-value attributes associated |
: : : with the span (e.g. :
: : : `attributes.http.request.method`). :
| `resource` | `RECORD` | Resource record containing |
: : : `attributes` (JSON) of the :
: : : executing resource. :
## Example SQL Queries
### 1. List Spans for a Specific Trace ID
```sql
SELECT
span_id,
parent_span_id,
name,
start_time,
end_time,
TIMESTAMP_DIFF(end_time, start_time, MILLISECOND) AS duration_ms
FROM
`your-project-id._Trace.Spans._AllSpans`
WHERE
trace_id = '3c114a8bb37e74bb032c7ae9566b85d0'
ORDER BY
start_time ASC;
```
### 2. Find Spans with Errors
```sql
SELECT
trace_id,
span_id,
name,
status.message
FROM
`your-project-id._Trace.Spans._AllSpans`
WHERE
status.code != 0
LIMIT 100;
```
### 3. Extract JSON Attribute Values
To extract nested JSON values from the `attributes` field:
```sql
SELECT
trace_id,
span_id,
name,
LAX_STRING(attributes.http.request.method) AS http_method,
LAX_INT64(attributes.http.response.status_code) AS status_code
FROM
`your-project-id._Trace.Spans._AllSpans`
WHERE
LAX_STRING(attributes.http.request.method) IS NOT NULL
LIMIT 100;
```
## See Also
* [Trace SQL Analytics - Google Cloud docs](https://cloud.google.com/trace/docs/analytics)
* [BigQuery Linked Datasets Introduction - Google Cloud docs](https://cloud.google.com/bigquery/docs/analytics-hub-introduction#linked_datasets)
troubleshoot-latency.md 2.1 KB
# Workflow: Troubleshoot Slow Requests
This workflow guides you through identifying latency bottlenecks using Cloud Trace.
## Steps
1. **Search Traces**: Use the search script to filter traces with high latency in a specific project and time window:
```bash
# Location: scripts/search_traces/
./run.sh \
--projects eval-project \
--filter="latency:1s" \
--start-time "2026-06-25T13:00:00Z" \
--end-time "2026-06-25T14:00:00Z" \
--limit=5
```
2. **Fetch Trace Spans**: Once you identify a slow trace ID, fetch its spans:
```bash
# Location: scripts/fetch_entire_trace/
./run.sh \
--project eval-project \
--trace-id=<TRACE_ID>
```
3. **Analyze Bottlenecks**: Sort spans by duration and inspect child relationships to isolate the component contributing the most to overall execution time.
## Latency Analysis Guidelines
When inspecting spans, consider the following patterns:
### Sequential vs. Parallel Bottlenecks
- **Single Bottleneck**: A single long-running child span that accounts for most of the parent span's latency. Focus optimization efforts on that component.
- **Serial Execution Overhead**: Latency caused by executing multiple fast requests sequentially rather than in parallel. Look for a pattern of consecutive, non-overlapping child spans.
- **Parallel Fan-out**: If child spans execute concurrently (overlapping timelines), the parent's latency is bounded by the slowest child.
### Retries and Failures
- **Error Retries**: Latency spikes can be caused by internal service retries after a transient failure. Check if a slow span contains child spans with error status indicating failed attempts preceding a successful call.
---
## See Also
* [Distributed Traces Concept - Trace Skill docs](./concepts-trace.md)
* [Spans Concept - Trace Skill docs](./concepts-span.md)
* [Finding Traces in Console - Google Cloud docs](https://cloud.google.com/trace/docs/finding-traces)
* [Viewing Trace Details - Google Cloud docs](https://cloud.google.com/trace/docs/viewing-details)
* [View App Latency - Google Cloud docs](https://docs.cloud.google.com/trace/docs/trace-app-latency.md.txt)
workflows-overview.md 0.9 KB
# GCP Trace Querying Workflows
Follow these step-by-step guides to diagnose latency, investigate errors, select
query methods, or configure tracing MCP tools.
## Workflows
* [Trace Querying Decision Tree](./decision-tree.md):
Decision-making tree to select local scripts, MCP tools, or Observability
Analytics.
* [Troubleshoot Slow Requests](./troubleshoot-latency.md): Guides you
through identifying latency bottlenecks, sequential execution overhead, and
parallel fan-out delays using Trace timelines.
* [Find Correlated Logs](./correlated-logs.md): Walkthrough of pulling
application logs matching a specific trace ID to diagnose errors and runtime
exceptions.
* [Generate Console Deep Links](./console-deep-links.md): Explains how to generate
deep links to the Cloud Trace Explorer and Cloud Logging for a specific
trace and span ID.
run.sh 0.2 KB
#!/bin/bash
set -euf -o pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
export PYTHONPATH="${SCRIPT_DIR}/src:${PYTHONPATH:-}"
exec "${SCRIPT_DIR}/../run_python_with_deps/run.sh" "${SCRIPT_DIR}/src/main.py" "$@"
test.sh 0.3 KB
#!/bin/bash
set -euf -o pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
export PYTHONPATH="${SCRIPT_DIR}/src:${SCRIPT_DIR}/tests:${PYTHONPATH:-}"
exec "${SCRIPT_DIR}/../run_python_with_deps/run.sh" -m unittest discover -s "${SCRIPT_DIR}/tests" -p "*_test.py"
main.py 1.8 KB
#!/usr/bin/env python3
"""Fetches all spans within a trace by ID."""
import argparse
import json
import logging
import secrets
import sys
from google.cloud import trace_v1
from google.protobuf.json_format import MessageToDict
_logger = logging.getLogger(__name__)
def fetch_entire_trace(project_id: str, trace_id: str) -> list[dict]:
client = trace_v1.TraceServiceClient()
trace_response = client.get_trace(project_id=project_id, trace_id=trace_id)
spans_data = []
for span in trace_response.spans:
spans_data.append(MessageToDict(span._pb))
return spans_data
def main():
parser = argparse.ArgumentParser(
description="Fetch details of all trace spans."
)
parser.head = getattr(parser, "head", None) # avoid linter warning
parser.add_argument("--trace-id", required=True, help="Trace ID")
parser.add_argument("--project", required=True, help="GCP Project ID.")
parser.add_argument(
"--output", type=str, help="Optional output file path to write results."
)
parser.add_argument(
"--no-wrapper-tag",
action="store_true",
default=False,
help="Do not wrap output in untrusted telemetry tags.",
)
args = parser.parse_args()
spans = fetch_entire_trace(args.project, args.trace_id)
raw_json = json.dumps(spans, indent=2)
if args.no_wrapper_tag:
output_str = raw_json
else:
token = secrets.token_hex(8)
output_str = f"<untrusted_telemetry_{token}>\n{raw_json}\n</untrusted_telemetry_{token}>"
if args.output:
with open(args.output, "w") as f:
f.write(output_str)
_logger.info("Results written to: %s", args.output)
else:
print(output_str)
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO)
try:
main()
except Exception as err:
_logger.exception(err)
sys.exit(1)
main_test.py 3.9 KB
import json
import sys
import unittest
from unittest import mock
# Mock trace_v1
mock_trace = mock.MagicMock()
mock_trace_v1 = mock.MagicMock()
mock_trace.trace_v1 = mock_trace_v1
with mock.patch.dict(
"sys.modules",
{"google.cloud": mock_trace, "google.cloud.trace_v1": mock_trace_v1},
):
import main as main_module
class TestFetchEntireTrace(unittest.TestCase):
def _patch_message_to_dict(self, return_val):
"""Robustly patches MessageToDict for both module and function level imports."""
mock_to_dict = mock.MagicMock(return_value=return_val)
patcher_global = mock.patch(
"google.protobuf.json_format.MessageToDict", mock_to_dict
)
if hasattr(main_module, "MessageToDict"):
patcher_module = mock.patch.object(
main_module, "MessageToDict", mock_to_dict
)
return patcher_global, patcher_module, mock_to_dict
else:
return patcher_global, None, mock_to_dict
def test_fetch_entire_trace_success(self):
with mock.patch.object(
main_module.trace_v1, "TraceServiceClient"
) as mock_client_class:
mock_client = mock_client_class.return_value
mock_span = mock.MagicMock()
mock_span._pb = mock.MagicMock()
mock_response = mock.MagicMock()
mock_response.spans = [mock_span]
mock_client.get_trace.return_value = mock_response
p_global, p_module, mock_to_dict = self._patch_message_to_dict(
{"name": "span-1", "spanId": "s1"}
)
with p_global:
if p_module:
with p_module:
result = main_module.fetch_entire_trace("test-proj", "trace-123")
else:
result = main_module.fetch_entire_trace("test-proj", "trace-123")
self.assertEqual(result, [{"name": "span-1", "spanId": "s1"}])
mock_client.get_trace.assert_called_once_with(
project_id="test-proj", trace_id="trace-123"
)
@mock.patch.object(
main_module,
"fetch_entire_trace",
return_value=[{"name": "span-1", "spanId": "s1"}],
)
@mock.patch("builtins.print")
@mock.patch("sys.argv", ["main.py", "--trace-id", "t1", "--project", "p1"])
def test_main_cli_stdout(self, mock_print, mock_fetch):
main_module.main()
mock_fetch.assert_called_once_with("p1", "t1")
mock_print.assert_called_once()
printed_str = mock_print.call_args[0][0]
payload = printed_str.split(">", 1)[1].rsplit("<", 1)[0].strip()
printed_json = json.loads(payload)
self.assertEqual(printed_json, [{"name": "span-1", "spanId": "s1"}])
@mock.patch.object(
main_module,
"fetch_entire_trace",
return_value=[{"name": "span-1", "spanId": "s1"}],
)
@mock.patch(
"sys.argv",
[
"main.py",
"--trace-id",
"t1",
"--project",
"p1",
"--output",
"out.json",
],
)
@mock.patch("builtins.open", new_callable=mock.mock_open)
def test_main_cli_file_write(self, mock_file_open, mock_fetch):
main_module.main()
mock_fetch.assert_called_once_with("p1", "t1")
mock_file_open.assert_called_once_with("out.json", "w")
mock_file_open().write.assert_called_once()
written_data = mock_file_open().write.call_args[0][0]
payload = written_data.split(">", 1)[1].rsplit("<", 1)[0].strip()
self.assertEqual(json.loads(payload), [{"name": "span-1", "spanId": "s1"}])
@mock.patch.object(
main_module,
"fetch_entire_trace",
return_value=[{"name": "span-1", "spanId": "s1"}],
)
@mock.patch("builtins.print")
@mock.patch(
"sys.argv",
["main.py", "--trace-id", "t1", "--project", "p1", "--no-wrapper-tag"],
)
def test_main_cli_no_wrapper_tag(self, mock_print, mock_fetch):
main_module.main()
mock_fetch.assert_called_once_with("p1", "t1")
mock_print.assert_called_once_with(
json.dumps([{"name": "span-1", "spanId": "s1"}], indent=2)
)
if __name__ == "__main__":
unittest.main()
run.sh 0.2 KB
#!/bin/bash
set -euf -o pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
export PYTHONPATH="${SCRIPT_DIR}/src:${PYTHONPATH:-}"
exec "${SCRIPT_DIR}/../run_python_with_deps/run.sh" "${SCRIPT_DIR}/src/main.py" "$@"
test.sh 0.4 KB
#!/bin/bash
set -euf -o pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
TESTING_DIR="$(cd "${SCRIPT_DIR}/../../../../testing/gcp-trace-querying" && pwd)"
export PYTHONPATH="${SCRIPT_DIR}/src:${SCRIPT_DIR}/tests:${TESTING_DIR}:${TESTING_DIR}/mock_gcp:${TESTING_DIR}/shared:${PYTHONPATH:-}"
exec "${SCRIPT_DIR}/../run_python_with_deps/run.sh" -m unittest discover -s "${SCRIPT_DIR}/tests" -p "*_test.py"
log_fetcher.py 7.4 KB
"""Retrieves correlated logs using Cloud Logging and Cloud Trace APIs."""
import datetime
import logging
from google.cloud import logging as cloud_logging
from google.cloud import trace_v1
from observability_scopes import resolve_query_projects
from timestamp_utils import validate_iso8601
_logger = logging.getLogger(__name__)
def _to_datetime(ts) -> datetime.datetime | None:
"""Converts a protobuf Timestamp or datetime object to standard datetime."""
if ts is None:
return None
if hasattr(ts, "to_datetime"):
return ts.to_datetime()
if isinstance(ts, datetime.datetime):
return ts
return None
def _build_log_filter(
trace_id: str,
trace_projects: list[str],
span_id: str | None,
start_ts: str | None,
end_ts: str | None,
) -> str:
"""Builds a structured log query filter."""
trace_filters = [
f'trace = "projects/{p}/traces/{trace_id}"' for p in trace_projects
]
trace_clause = (
trace_filters[0]
if len(trace_filters) == 1
else f"({' OR '.join(trace_filters)})"
)
parts = [trace_clause]
if span_id:
parts.append(f'spanId="{span_id}"')
if start_ts:
parts.append(f'timestamp >= "{start_ts}"')
if end_ts:
parts.append(f'timestamp <= "{end_ts}"')
return " AND ".join(parts)
def _format_entry(entry, log_project: str) -> dict:
"""Formats a log entry into a standardized dictionary."""
if isinstance(entry.payload, (str, dict)):
payload = entry.payload
else:
payload = str(entry.payload)
trace_proj = None
if entry.trace:
parts = entry.trace.split("/")
if len(parts) >= 2 and parts[0] == "projects":
trace_proj = parts[1]
return {
"timestamp": entry.timestamp.isoformat() if entry.timestamp else None,
"severity": entry.severity,
"log_name": entry.log_name,
"payload": payload,
"span_id": entry.span_id,
"log_project": log_project,
"trace_project": trace_proj,
}
def _extract_project_from_log_name(log_name: str) -> str:
"""Extracts the project ID from a log resource name."""
parts = log_name.split("/")
if len(parts) >= 2 and parts[0] == "projects":
return parts[1]
return ""
def _infer_time_range_from_project(
trace_client: trace_v1.TraceServiceClient, trace_proj: str, trace_id: str
) -> tuple[datetime.datetime | None, datetime.datetime | None]:
"""Fetches min start and max end times from spans in a specific project."""
try:
trace = trace_client.get_trace(project_id=trace_proj, trace_id=trace_id)
starts = [_to_datetime(s.start_time) for s in trace.spans if s.start_time]
ends = [_to_datetime(s.end_time) for s in trace.spans if s.end_time]
starts = [dt for dt in starts if dt is not None]
ends = [dt for dt in ends if dt is not None]
return (
min(starts) if starts else None,
max(ends) if ends else None,
)
except Exception as e:
_logger.warning(
"Failed to fetch trace %s from project %s: %s",
trace_id,
trace_proj,
e,
)
return None, None
def _infer_time_range_from_trace(
trace_client: trace_v1.TraceServiceClient,
trace_projects: list[str],
trace_id: str,
) -> tuple[str | None, str | None]:
"""Queries Trace API to determine active trace time bounds."""
min_start, max_end = None, None
for trace_proj in trace_projects:
start_dt, end_dt = _infer_time_range_from_project(
trace_client, trace_proj, trace_id
)
if start_dt and (min_start is None or start_dt < min_start):
min_start = start_dt
if end_dt and (max_end is None or end_dt > max_end):
max_end = end_dt
start_ts = (
(min_start - datetime.timedelta(seconds=5))
.isoformat()
.replace("+00:00", "Z")
if min_start
else None
)
end_ts = (
(max_end + datetime.timedelta(seconds=5))
.isoformat()
.replace("+00:00", "Z")
if max_end
else None
)
return start_ts, end_ts
def _fetch_entries_batch(
client: cloud_logging.Client,
log_projects: list[str],
trace_id: str,
trace_projects: list[str],
span_id: str | None,
start_ts: str | None,
end_ts: str | None,
limit: int,
) -> list[dict]:
"""Fetches log entries from multiple projects in a single API call."""
resource_names = [f"projects/{p}" for p in log_projects]
filter_str = _build_log_filter(
trace_id, trace_projects, span_id, start_ts, end_ts
)
pager = client.list_entries(
resource_names=resource_names,
filter_=filter_str,
page_size=limit,
order_by="timestamp desc",
)
return [
_format_entry(entry, _extract_project_from_log_name(entry.log_name))
for entry in pager
]
def _fetch_entries_individually(
client: cloud_logging.Client,
log_projects: list[str],
trace_id: str,
trace_projects: list[str],
span_id: str | None,
start_ts: str | None,
end_ts: str | None,
limit: int,
) -> list[dict]:
"""Fallback method to fetch log entries by querying projects one-by-one."""
all_logs = []
fetch_errors = []
filter_str = _build_log_filter(
trace_id, trace_projects, span_id, start_ts, end_ts
)
for log_proj in log_projects:
try:
pager = client.list_entries(
resource_names=[f"projects/{log_proj}"],
filter_=filter_str,
page_size=limit,
order_by="timestamp desc",
)
all_logs.extend([_format_entry(entry, log_proj) for entry in pager])
except Exception as e:
_logger.warning("Failed to fetch logs from project %s: %s", log_proj, e)
fetch_errors.append((log_proj, str(e)))
if not all_logs and fetch_errors:
raise RuntimeError(
f"Logging API query failed for project '{fetch_errors[0][0]}': {fetch_errors[0][1]}"
)
return all_logs
def fetch_logs(
trace_id: str,
trace_projects: list[str],
span_id: str | None = None,
limit: int = 100,
log_projects: list[str] | None = None,
start_time: str | None = None,
end_time: str | None = None,
) -> list[dict]:
"""Retrieves, sorts, and limits trace-correlated log entries."""
log_projects_to_query = resolve_query_projects(trace_projects, log_projects)
try:
trace_client = trace_v1.TraceServiceClient()
except Exception as e:
_logger.warning("Failed to initialize TraceServiceClient: %s", e)
trace_client = None
if (not start_time or not end_time) and trace_client:
inferred_start, inferred_end = _infer_time_range_from_trace(
trace_client, trace_projects, trace_id
)
start_time = start_time or inferred_start
end_time = end_time or inferred_end
start_ts = validate_iso8601(start_time)
end_ts = validate_iso8601(end_time)
try:
logging_client = cloud_logging.Client()
except Exception as e:
_logger.error("Failed to initialize cloud logging client: %s", e)
return []
try:
all_logs = _fetch_entries_batch(
logging_client,
list(log_projects_to_query),
trace_id,
trace_projects,
span_id,
start_ts,
end_ts,
limit,
)
except Exception as e:
_logger.warning(
"Batch query failed (likely permissions issue). Falling back to"
" individual queries: %s",
e,
)
all_logs = _fetch_entries_individually(
logging_client,
list(log_projects_to_query),
trace_id,
trace_projects,
span_id,
start_ts,
end_ts,
limit,
)
all_logs.sort(
key=lambda x: x["timestamp"] if x["timestamp"] else "", reverse=True
)
return all_logs[:limit]
main.py 2.4 KB
#!/usr/bin/env python3
"""Fetches Google Cloud Logging entries correlated with a trace and/or span."""
import argparse
import json
import logging
import secrets
import sys
from log_fetcher import fetch_logs
_logger = logging.getLogger(__name__)
def _parse_args() -> argparse.Namespace:
"""Defines and parses command-line arguments."""
parser = argparse.ArgumentParser(
description="Fetch logs correlated with a GCP Trace."
)
parser.head = getattr(parser, "head", None) # avoid linter warning
parser.add_argument("--trace-id", required=True, help="GCP Trace ID")
parser.add_argument(
"--span-id", help="Optional GCP Span ID to narrow search"
)
parser.add_argument(
"--trace-projects",
nargs="+",
required=True,
help="List of trace projects to scan.",
)
parser.add_argument(
"--log-projects", nargs="+", help="Logging projects to scan."
)
parser.add_argument("--start-time", help="Optional start time ISO 8601")
parser.add_argument("--end-time", help="Optional end time ISO 8601")
parser.add_argument(
"--limit", type=int, default=100, help="Max log entries to return"
)
parser.add_argument(
"--output",
type=str,
help="Optional output file path to write results.",
)
parser.add_argument(
"--no-wrapper-tag",
action="store_true",
default=False,
help="Do not wrap output in untrusted telemetry tags.",
)
return parser.parse_args()
def _execute_fetch(args: argparse.Namespace):
"""Orchestrates fetching and writing/printing output."""
logs = fetch_logs(
trace_id=args.trace_id,
span_id=args.span_id,
limit=args.limit,
trace_projects=args.trace_projects,
log_projects=args.log_projects,
start_time=args.start_time,
end_time=args.end_time,
)
raw_json = json.dumps(logs, indent=2)
if args.no_wrapper_tag:
output_str = raw_json
else:
token = secrets.token_hex(8)
output_str = f"<untrusted_telemetry_{token}>\n{raw_json}\n</untrusted_telemetry_{token}>"
if args.output:
with open(args.output, "w") as f:
f.write(output_str)
_logger.info("Results written to: %s", args.output)
else:
print(output_str)
def main():
args = _parse_args()
_execute_fetch(args)
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO)
try:
main()
except Exception as err:
_logger.exception(err)
sys.exit(1)
observability_scopes.py 3.0 KB
"""Resolves logging query projects using GCP Observability Scopes."""
import json
import logging
from typing import Optional, Set
import google.auth as google_auth
from google.auth.transport.urllib3 import AuthorizedHttp
_logger = logging.getLogger(__name__)
def _get_authorized_http() -> AuthorizedHttp | None:
"""Initializes an authorized HTTP client using default credentials."""
try:
credentials, _ = google_auth.default(
scopes=["https://www.googleapis.com/auth/cloud-platform"]
)
return AuthorizedHttp(credentials)
except Exception as e:
_logger.warning("Failed to initialize authorized HTTP client: %s", e)
return None
def _fetch_default_observability_scope(
http: AuthorizedHttp, trace_proj: str
) -> str | None:
"""Retrieves the logScope resource name for the project's Default scope."""
url = (
"https://observability.googleapis.com/v1/projects/"
f"{trace_proj}/locations/global/scopes/_Default"
)
try:
resp = http.request("GET", url, timeout=10.0)
if resp.status == 200:
return json.loads(resp.data.decode("utf-8")).get("logScope")
_logger.warning(
"Observability scope request failed with status %d: %s",
resp.status,
resp.data.decode("utf-8"),
)
except Exception as e:
_logger.warning("Failed to fetch observability scope: %s", e)
return None
def _fetch_logging_scope_projects(
http: AuthorizedHttp, log_scope_name: str
) -> list[str]:
"""Retrieves resource names from the specified log scope."""
url = f"https://logging.googleapis.com/v2/{log_scope_name}"
try:
resp = http.request("GET", url, timeout=10.0)
if resp.status == 200:
return json.loads(resp.data.decode("utf-8")).get("resourceNames", [])
_logger.warning(
"Logging scope request failed with status %d: %s",
resp.status,
resp.data.decode("utf-8"),
)
except Exception as e:
_logger.warning("Failed to fetch logging scope projects: %s", e)
return []
def _parse_project_ids(resource_names: list[str]) -> set[str]:
"""Extracts project IDs from resource names."""
project_ids = set()
for rn in resource_names:
parts = rn.split("/")
if len(parts) >= 2 and parts[-2] == "projects":
project_ids.add(parts[-1])
return project_ids
def resolve_query_projects(
trace_projects: list[str], log_projects: list[str] | None
) -> set[str]:
"""Resolves the set of logging project IDs to query."""
resolved = set()
if log_projects:
resolved.update(log_projects)
http = _get_authorized_http()
if not http:
return resolved | set(trace_projects)
for trace_proj in trace_projects:
log_scope_name = _fetch_default_observability_scope(http, trace_proj)
if not log_scope_name:
resolved.add(trace_proj)
continue
resources = _fetch_logging_scope_projects(http, log_scope_name)
parsed = _parse_project_ids(resources)
if parsed:
resolved.update(parsed)
else:
resolved.add(trace_proj)
return resolved
timestamp_utils.py 0.6 KB
"""Shared timestamp utility functions for trace querying scripts."""
from datetime import datetime
from typing import Optional
def parse_iso8601(ts_str: str) -> datetime:
"""Parses an ISO 8601 timestamp string (supporting Z suffix) into a datetime."""
normalized = ts_str.replace("Z", "+00:00")
return datetime.fromisoformat(normalized)
def validate_iso8601(ts_str: Optional[str]) -> Optional[str]:
if not ts_str:
return None
try:
parse_iso8601(ts_str)
return ts_str
except ValueError:
raise ValueError(f"Invalid ISO 8601 timestamp: {ts_str}")
main_test.py 10.6 KB
"""Unit tests for fetch_related_logs script bundle modules."""
import datetime
import json
import unittest
from unittest import mock
# Mock google.cloud SDKs in sys.modules prior to importing log_fetcher/observability_scopes
mock_logging = mock.MagicMock()
mock_trace = mock.MagicMock()
mock_auth = mock.MagicMock()
mock_auth_transport_urllib3 = mock.MagicMock()
mock_urllib3 = mock.MagicMock()
with mock.patch.dict(
"sys.modules",
{
"google.cloud": mock_logging,
"google.cloud.logging": mock_logging,
"google.cloud.trace_v1": mock_trace,
"google.auth": mock_auth,
"google.auth.transport": mock.MagicMock(),
"google.auth.transport.urllib3": mock_auth_transport_urllib3,
"urllib3": mock_urllib3,
},
):
import log_fetcher
import main
import observability_scopes
class TestFetchRelatedLogs(unittest.TestCase):
def setUp(self):
super().setUp()
mock_logging.reset_mock()
mock_trace.reset_mock()
mock_auth.reset_mock()
mock_auth_transport_urllib3.reset_mock()
mock_urllib3.reset_mock()
mock_auth.default.return_value = (mock.MagicMock(), "proj-a")
self.mock_pool = mock.MagicMock()
mock_auth_transport_urllib3.AuthorizedHttp.return_value = self.mock_pool
def test_to_datetime_conversion(self):
"""Verifies _to_datetime handles None, protobuf Timestamp, and datetime."""
self.assertIsNone(log_fetcher._to_datetime(None))
now = datetime.datetime(2026, 6, 25, 13, 0, 0, tzinfo=datetime.timezone.utc)
self.assertEqual(log_fetcher._to_datetime(now), now)
mock_ts = mock.MagicMock(spec=["to_datetime"])
mock_ts.to_datetime.return_value = now
self.assertEqual(log_fetcher._to_datetime(mock_ts), now)
def test_resolve_query_projects_only_trace(self):
res = observability_scopes.resolve_query_projects(["proj-a"], None)
self.assertEqual(res, {"proj-a"})
def test_resolve_query_projects_both(self):
res = observability_scopes.resolve_query_projects(
["proj-a"], ["proj-b", "proj-a"]
)
self.assertEqual(res, {"proj-a", "proj-b"})
def test_resolve_query_projects_with_observability_scopes(self):
mock_creds = mock.MagicMock()
mock_creds.token = "mock-token"
mock_auth.default.return_value = (mock_creds, "proj-a")
r1 = mock.MagicMock()
r1.status = 200
r1.data = json.dumps({
"name": "projects/proj-a/locations/global/scopes/_Default",
"logScope": "projects/proj-a/locations/global/logScopes/my-scope",
}).encode("utf-8")
r2 = mock.MagicMock()
r2.status = 200
r2.data = json.dumps({
"name": "projects/proj-a/locations/global/logScopes/my-scope",
"resourceNames": [
"projects/proj-monitored-1",
"projects/proj-monitored-2",
],
}).encode("utf-8")
self.mock_pool.request.side_effect = [r1, r2]
res = observability_scopes.resolve_query_projects(["proj-a"], ["proj-b"])
self.assertEqual(res, {"proj-monitored-1", "proj-monitored-2", "proj-b"})
self.mock_pool.request.assert_has_calls([
mock.call(
"GET",
"https://observability.googleapis.com/v1/projects/"
"proj-a/locations/global/scopes/_Default",
timeout=10.0,
),
mock.call(
"GET",
"https://logging.googleapis.com/v2/projects/proj-a/"
"locations/global/logScopes/my-scope",
timeout=10.0,
),
])
def test_resolve_query_projects_observability_scopes_error_fallback(self):
mock_creds = mock.MagicMock()
mock_creds.token = "mock-token"
mock_auth.default.return_value = (mock_creds, "proj-a")
self.mock_pool.request.side_effect = Exception("API error")
res = observability_scopes.resolve_query_projects(["proj-a"], None)
self.assertEqual(res, {"proj-a"})
@mock.patch.object(log_fetcher.cloud_logging, "Client")
def test_fetch_logs_success(self, mock_logging_client_class):
mock_logging_client = mock_logging_client_class.return_value
mock_entry = mock.MagicMock()
mock_entry.payload = "Test log line"
mock_entry.timestamp = datetime.datetime(
2026, 6, 24, 12, 0, 0, tzinfo=datetime.timezone.utc
)
mock_entry.severity = "INFO"
mock_entry.log_name = "projects/trace-proj-a/logs/test-log"
mock_entry.span_id = "span-1"
mock_entry.trace = "projects/trace-proj-a/traces/trace-123"
mock_logging_client.list_entries.return_value = [mock_entry]
result = log_fetcher.fetch_logs(
trace_id="trace-123",
trace_projects=["trace-proj-a"],
span_id="span-1",
limit=5,
start_time="2026-06-25T13:00:00Z",
end_time="2026-06-25T14:00:00Z",
)
self.assertEqual(len(result), 1)
self.assertEqual(result[0]["payload"], "Test log line")
self.assertEqual(result[0]["timestamp"], "2026-06-24T12:00:00+00:00")
self.assertEqual(result[0]["trace_project"], "trace-proj-a")
mock_logging_client.list_entries.assert_called_once_with(
resource_names=["projects/trace-proj-a"],
filter_=(
'trace = "projects/trace-proj-a/traces/trace-123" AND'
' spanId="span-1" AND timestamp >= "2026-06-25T13:00:00Z" AND'
' timestamp <= "2026-06-25T14:00:00Z"'
),
page_size=5,
order_by="timestamp desc",
)
@mock.patch.object(log_fetcher.trace_v1, "TraceServiceClient")
@mock.patch.object(log_fetcher.cloud_logging, "Client")
def test_fetch_logs_time_range_inference(
self, mock_logging_client_class, mock_trace_client_class
):
mock_trace_client_instance = mock_trace_client_class.return_value
mock_logging_client_instance = mock_logging_client_class.return_value
mock_trace_response = mock.MagicMock()
# Test with native datetime.datetime instances (which caused the original AttributeError)
mock_span_1 = mock.MagicMock(spec=["start_time", "end_time"])
mock_span_1.start_time = datetime.datetime(
2026, 6, 25, 13, 0, 5, tzinfo=datetime.timezone.utc
)
mock_span_1.end_time = datetime.datetime(
2026, 6, 25, 13, 0, 10, tzinfo=datetime.timezone.utc
)
mock_span_2 = mock.MagicMock(spec=["start_time", "end_time"])
mock_span_2.start_time = datetime.datetime(
2026, 6, 25, 13, 0, 0, tzinfo=datetime.timezone.utc
)
mock_span_2.end_time = datetime.datetime(
2026, 6, 25, 13, 0, 15, tzinfo=datetime.timezone.utc
)
mock_trace_response.spans = [mock_span_1, mock_span_2]
mock_trace_client_instance.get_trace.return_value = mock_trace_response
mock_entry = mock.MagicMock()
mock_entry.payload = "Log entry within time window"
mock_entry.timestamp = datetime.datetime(
2026, 6, 25, 13, 0, 8, tzinfo=datetime.timezone.utc
)
mock_entry.severity = "INFO"
mock_entry.log_name = "projects/trace-proj-a/logs/test-log"
mock_entry.span_id = "span-1"
mock_entry.trace = "projects/trace-proj-a/traces/trace-123"
mock_logging_client_instance.list_entries.return_value = [mock_entry]
result = log_fetcher.fetch_logs(
trace_id="trace-123",
trace_projects=["trace-proj-a"],
span_id="span-1",
limit=5,
start_time=None,
end_time=None,
)
self.assertEqual(len(result), 1)
mock_trace_client_instance.get_trace.assert_called_once_with(
project_id="trace-proj-a", trace_id="trace-123"
)
mock_logging_client_instance.list_entries.assert_called_once_with(
resource_names=["projects/trace-proj-a"],
filter_=(
'trace = "projects/trace-proj-a/traces/trace-123" AND'
' spanId="span-1" AND timestamp >= "2026-06-25T12:59:55Z" AND'
' timestamp <= "2026-06-25T13:00:20Z"'
),
page_size=5,
order_by="timestamp desc",
)
@mock.patch.object(log_fetcher.trace_v1, "TraceServiceClient")
@mock.patch.object(log_fetcher.cloud_logging, "Client")
def test_fetch_logs_time_range_inference_fallback(
self, mock_logging_client_class, mock_trace_client_class
):
mock_trace_client_instance = mock_trace_client_class.return_value
mock_logging_client_instance = mock_logging_client_class.return_value
mock_trace_client_instance.get_trace.side_effect = Exception(
"Trace API error"
)
mock_logging_client_instance.list_entries.return_value = []
result = log_fetcher.fetch_logs(
trace_id="trace-123",
trace_projects=["trace-proj-a"],
span_id="span-1",
limit=5,
start_time=None,
end_time=None,
)
self.assertEqual(len(result), 0)
mock_trace_client_instance.get_trace.assert_called_once_with(
project_id="trace-proj-a", trace_id="trace-123"
)
mock_logging_client_instance.list_entries.assert_called_once_with(
resource_names=["projects/trace-proj-a"],
filter_=(
'trace = "projects/trace-proj-a/traces/trace-123" AND'
' spanId="span-1"'
),
page_size=5,
order_by="timestamp desc",
)
@mock.patch.object(main, "fetch_logs", return_value=[{"payload": "test log"}])
@mock.patch("builtins.print")
@mock.patch(
"sys.argv", ["main.py", "--trace-id", "t1", "--trace-projects", "p1"]
)
def test_main_cli_stdout(self, mock_print, mock_fetch):
main.main()
mock_fetch.assert_called_once_with(
trace_id="t1",
span_id=None,
limit=100,
trace_projects=["p1"],
log_projects=None,
start_time=None,
end_time=None,
)
mock_print.assert_called_once()
printed_str = mock_print.call_args[0][0]
payload = printed_str.split(">", 1)[1].rsplit("<", 1)[0].strip()
self.assertEqual(json.loads(payload), [{"payload": "test log"}])
@mock.patch.object(main, "fetch_logs", return_value=[{"payload": "test log"}])
@mock.patch(
"sys.argv",
[
"main.py",
"--trace-id",
"t1",
"--trace-projects",
"p1",
"--output",
"out.json",
],
)
@mock.patch("builtins.open", new_callable=mock.mock_open)
def test_main_cli_file_write(self, mock_file_open, mock_fetch):
main.main()
mock_fetch.assert_called_once_with(
trace_id="t1",
span_id=None,
limit=100,
trace_projects=["p1"],
log_projects=None,
start_time=None,
end_time=None,
)
mock_file_open.assert_called_once_with("out.json", "w")
mock_file_open().write.assert_called_once()
written_data = mock_file_open().write.call_args[0][0]
payload = written_data.split(">", 1)[1].rsplit("<", 1)[0].strip()
self.assertEqual(json.loads(payload), [{"payload": "test log"}])
if __name__ == "__main__":
unittest.main()
timestamp_utils_test.py 1.1 KB
import datetime
import unittest
import timestamp_utils
class TestTimestampUtils(unittest.TestCase):
def test_parse_iso8601_with_z(self):
res = timestamp_utils.parse_iso8601("2026-06-25T13:00:00Z")
expected = datetime.datetime(
2026, 6, 25, 13, 0, 0, tzinfo=datetime.timezone.utc
)
self.assertEqual(res, expected)
def test_parse_iso8601_with_offset(self):
res = timestamp_utils.parse_iso8601("2026-06-25T13:00:00+02:00")
tz = datetime.timezone(datetime.timedelta(hours=2))
expected = datetime.datetime(2026, 6, 25, 13, 0, 0, tzinfo=tz)
self.assertEqual(res, expected)
def test_validate_iso8601_valid(self):
res = timestamp_utils.validate_iso8601("2026-06-25T13:00:00Z")
self.assertEqual(res, "2026-06-25T13:00:00Z")
def test_validate_iso8601_invalid(self):
with self.assertRaises(ValueError):
timestamp_utils.validate_iso8601("invalid-time")
def test_validate_iso8601_empty(self):
self.assertIsNone(timestamp_utils.validate_iso8601(None))
self.assertIsNone(timestamp_utils.validate_iso8601(""))
if __name__ == "__main__":
unittest.main()
run.sh 0.2 KB
#!/bin/bash
set -euf -o pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
export PYTHONPATH="${SCRIPT_DIR}/src:${PYTHONPATH:-}"
exec "${SCRIPT_DIR}/../run_python_with_deps/run.sh" "${SCRIPT_DIR}/src/main.py" "$@"
test.sh 0.3 KB
#!/bin/bash
set -euf -o pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
export PYTHONPATH="${SCRIPT_DIR}/src:${SCRIPT_DIR}/tests:${PYTHONPATH:-}"
exec "${SCRIPT_DIR}/../run_python_with_deps/run.sh" -m unittest discover -s "${SCRIPT_DIR}/tests" -p "*_test.py"
main.py 2.6 KB
#!/usr/bin/env python3
"""Fetches details of a specific span within a trace by querying the trace v1 API."""
import argparse
import json
import logging
import secrets
import sys
from typing import Optional
from google.cloud import trace_v1
from google.protobuf.json_format import MessageToDict
def _span_id_to_int(span_id_str: str) -> Optional[int]:
try:
if span_id_str.startswith("0x"):
return int(span_id_str, 16)
return int(span_id_str, 10)
except ValueError:
try:
return int(span_id_str, 16)
except ValueError:
return None
def fetch_span(project_id: str, trace_id: str, span_id: str) -> dict:
client = trace_v1.TraceServiceClient()
trace_response = client.get_trace(project_id=project_id, trace_id=trace_id)
# First Pass (Exact String Match)
for span in trace_response.spans:
if span_id == str(span.span_id):
return MessageToDict(span._pb)
# Second Pass (Integer Fallback)
target_span_val = _span_id_to_int(span_id)
if target_span_val is not None:
for span in trace_response.spans:
db_span_val = _span_id_to_int(str(span.span_id))
if db_span_val is not None and target_span_val == db_span_val:
return MessageToDict(span._pb)
raise ValueError(f"Span {span_id} not found in trace {trace_id}")
def main():
parser = argparse.ArgumentParser(description="Fetch details of a trace span.")
parser.head = getattr(parser, "head", None) # avoid linter warning
parser.add_argument("--trace-id", required=True, help="Trace ID")
parser.add_argument("--span-id", required=True, help="Span ID")
parser.add_argument("--project", required=True, help="GCP Project ID.")
parser.add_argument(
"--output", type=str, help="Optional output file path to write results."
)
parser.add_argument(
"--no-wrapper-tag",
action="store_true",
default=False,
help="Do not wrap output in untrusted telemetry tags.",
)
args = parser.parse_args()
project_id = args.project
try:
span_data = fetch_span(project_id, args.trace_id, args.span_id)
raw_json = json.dumps(span_data, indent=2)
if args.no_wrapper_tag:
output_str = raw_json
else:
token = secrets.token_hex(8)
output_str = f"<untrusted_telemetry_{token}>\n{raw_json}\n</untrusted_telemetry_{token}>"
if args.output:
with open(args.output, "w") as f:
f.write(output_str)
print(f"Results written to: {args.output}")
else:
print(output_str)
sys.exit(0)
except Exception as e:
logging.exception(e)
sys.exit(1)
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")
main()
main_test.py 5.1 KB
import json
import sys
import unittest
from unittest import mock
# Mock trace_v1 client
mock_trace = mock.MagicMock()
mock_trace_v1 = mock.MagicMock()
mock_trace.trace_v1 = mock_trace_v1
with mock.patch.dict(
"sys.modules",
{"google.cloud": mock_trace, "google.cloud.trace_v1": mock_trace_v1},
):
import main as main_module
class TestFetchTraceSpan(unittest.TestCase):
def test_fetch_span_exact_match(self):
with mock.patch.object(
main_module.trace_v1, "TraceServiceClient"
) as mock_client_class:
mock_client = mock_client_class.return_value
mock_span = mock.MagicMock()
mock_span.span_id = "123"
mock_span._pb = mock.MagicMock()
mock_response = mock.MagicMock()
mock_response.spans = [mock_span]
mock_client.get_trace.return_value = mock_response
with mock.patch.object(main_module, "MessageToDict") as mock_to_dict:
mock_to_dict.return_value = {"name": "my-span", "spanId": "123"}
result = main_module.fetch_span("test-proj", "trace-abc", "123")
self.assertEqual(result, {"name": "my-span", "spanId": "123"})
mock_client.get_trace.assert_called_once_with(
project_id="test-proj", trace_id="trace-abc"
)
mock_to_dict.assert_called_once_with(mock_span._pb)
def test_fetch_span_integer_fallback_hex(self):
with mock.patch.object(
main_module.trace_v1, "TraceServiceClient"
) as mock_client_class:
mock_client = mock_client_class.return_value
mock_span = mock.MagicMock()
mock_span.span_id = "123" # DB is decimal 123
mock_span._pb = mock.MagicMock()
mock_response = mock.MagicMock()
mock_response.spans = [mock_span]
mock_client.get_trace.return_value = mock_response
with mock.patch.object(main_module, "MessageToDict") as mock_to_dict:
mock_to_dict.return_value = {"name": "my-span", "spanId": "123"}
# User queries using hex format 7b (which is decimal 123)
result = main_module.fetch_span("test-proj", "trace-abc", "7b")
self.assertEqual(result, {"name": "my-span", "spanId": "123"})
mock_to_dict.assert_called_once_with(mock_span._pb)
def test_fetch_span_integer_fallback_0x_hex(self):
with mock.patch.object(
main_module.trace_v1, "TraceServiceClient"
) as mock_client_class:
mock_client = mock_client_class.return_value
mock_span = mock.MagicMock()
mock_span.span_id = "123"
mock_span._pb = mock.MagicMock()
mock_response = mock.MagicMock()
mock_response.spans = [mock_span]
mock_client.get_trace.return_value = mock_response
with mock.patch.object(main_module, "MessageToDict") as mock_to_dict:
mock_to_dict.return_value = {"name": "my-span", "spanId": "123"}
# User queries using hex format with prefix 0x7b
result = main_module.fetch_span("test-proj", "trace-abc", "0x7b")
self.assertEqual(result, {"name": "my-span", "spanId": "123"})
mock_to_dict.assert_called_once_with(mock_span._pb)
def test_fetch_span_not_found(self):
with mock.patch.object(
main_module.trace_v1, "TraceServiceClient"
) as mock_client_class:
mock_client = mock_client_class.return_value
mock_span = mock.MagicMock()
mock_span.span_id = "123"
mock_span._pb = mock.MagicMock()
mock_response = mock.MagicMock()
mock_response.spans = [mock_span]
mock_client.get_trace.return_value = mock_response
with self.assertRaises(ValueError) as ctx:
main_module.fetch_span("test-proj", "trace-abc", "999")
self.assertIn("Span 999 not found in trace trace-abc", str(ctx.exception))
@mock.patch.object(
main_module,
"fetch_span",
return_value={"name": "my-span", "spanId": "123"},
)
@mock.patch("builtins.print")
@mock.patch(
"sys.argv",
["main.py", "--trace-id", "t1", "--span-id", "s1", "--project", "p1"],
)
def test_main_cli_stdout(self, mock_print, mock_fetch):
with self.assertRaises(SystemExit) as cm:
main_module.main()
self.assertEqual(cm.exception.code, 0)
mock_fetch.assert_called_once_with("p1", "t1", "s1")
mock_print.assert_called_once()
printed_str = mock_print.call_args[0][0]
payload = printed_str.split(">", 1)[1].rsplit("<", 1)[0].strip()
self.assertEqual(json.loads(payload), {"name": "my-span", "spanId": "123"})
@mock.patch.object(
main_module,
"fetch_span",
return_value={"name": "my-span", "spanId": "123"},
)
@mock.patch("builtins.print")
@mock.patch(
"sys.argv",
[
"main.py",
"--trace-id",
"t1",
"--span-id",
"s1",
"--project",
"p1",
"--no-wrapper-tag",
],
)
def test_main_cli_no_wrapper_tag(self, mock_print, mock_fetch):
with self.assertRaises(SystemExit) as cm:
main_module.main()
self.assertEqual(cm.exception.code, 0)
mock_fetch.assert_called_once_with("p1", "t1", "s1")
mock_print.assert_called_once_with(
json.dumps({"name": "my-span", "spanId": "123"}, indent=2)
)
if __name__ == "__main__":
unittest.main()
run.sh 0.1 KB
#!/bin/bash
set -euf -o pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
exec python3 "${SCRIPT_DIR}/src/main.py" "$@"
test.sh 0.3 KB
#!/bin/bash
set -euf -o pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
export PYTHONPATH="${SCRIPT_DIR}/src:${SCRIPT_DIR}/tests:${PYTHONPATH:-}"
exec "${SCRIPT_DIR}/../run_python_with_deps/run.sh" -m unittest discover -s "${SCRIPT_DIR}/tests" -p "*_test.py"
main.py 1.7 KB
#!/usr/bin/env python3
"""Generates Google Cloud Console deep links for traces and logs."""
import argparse
import sys
from urllib.parse import quote
def generate_links(
project: str, trace_id: str, span_id: str = None
) -> tuple[str, str]:
"""Generates deep links for Cloud Trace and Cloud Logging."""
# 1. Cloud Trace Link
if span_id:
trace_link = f"https://console.cloud.google.com/traces/explorer;traceId={trace_id};spanId={span_id}?project={project}"
else:
trace_link = f"https://console.cloud.google.com/traces/explorer;traceId={trace_id}?project={project}"
# 2. Cloud Logging Link
log_query = f'trace="projects/{project}/traces/{trace_id}"'
if span_id:
log_query += f' AND spanId="{span_id}"'
# URL encode the query parameter for the logs viewer
encoded_query = quote(log_query, safe="")
logging_link = f"https://console.cloud.google.com/logs/query;query={encoded_query}?project={project}"
return trace_link, logging_link
def main():
parser = argparse.ArgumentParser(
description=(
"Generate Cloud Console deep links for traces and correlated logs."
)
)
parser.head = getattr(parser, "head", None) # avoid linter warning
parser.add_argument(
"--project", required=True, help="Google Cloud Project ID"
)
parser.add_argument("--trace-id", required=True, help="32-character Trace ID")
parser.add_argument("--span-id", help="Optional Span ID")
args = parser.parse_args()
trace_link, logging_link = generate_links(
args.project, args.trace_id, args.span_id
)
print(f"Cloud Trace Deep Link:\n{trace_link}\n")
print(f"Cloud Logging Deep Link:\n{logging_link}")
if __name__ == "__main__":
main()
main_test.py 2.7 KB
import unittest
from unittest import mock
from urllib.parse import quote
from main import generate_links
class TestGenerateLinks(unittest.TestCase):
def test_generate_links_without_span_id(self):
project = "test-project"
trace_id = "testtraceid1234567890abcdef123"
trace_link, logging_link = generate_links(project, trace_id)
expected_trace = "https://console.cloud.google.com/traces/explorer;traceId=testtraceid1234567890abcdef123?project=test-project"
self.assertEqual(trace_link, expected_trace)
expected_log_query = (
'trace="projects/test-project/traces/testtraceid1234567890abcdef123"'
)
expected_logging = (
f"https://console.cloud.google.com/logs/query;query={quote(expected_log_query, safe='')}?project=test-project"
)
self.assertEqual(logging_link, expected_logging)
def test_generate_links_with_span_id(self):
project = "test-project"
trace_id = "testtraceid1234567890abcdef123"
span_id = "123456"
trace_link, logging_link = generate_links(project, trace_id, span_id)
expected_trace = "https://console.cloud.google.com/traces/explorer;traceId=testtraceid1234567890abcdef123;spanId=123456?project=test-project"
self.assertEqual(trace_link, expected_trace)
expected_log_query = (
'trace="projects/test-project/traces/testtraceid1234567890abcdef123"'
' AND spanId="123456"'
)
expected_logging = (
f"https://console.cloud.google.com/logs/query;query={quote(expected_log_query, safe='')}?project=test-project"
)
self.assertEqual(logging_link, expected_logging)
@mock.patch(
"sys.argv",
["main.py", "--project", "test-proj", "--trace-id", "trace123"],
)
@mock.patch("builtins.print")
@mock.patch("main.generate_links", return_value=("link1", "link2"))
def test_main_cli_without_span(self, mock_gen, mock_print):
import main as main_module
main_module.main()
mock_gen.assert_called_once_with("test-proj", "trace123", None)
mock_print.assert_any_call("Cloud Trace Deep Link:\nlink1\n")
mock_print.assert_any_call("Cloud Logging Deep Link:\nlink2")
@mock.patch(
"sys.argv",
[
"main.py",
"--project",
"test-proj",
"--trace-id",
"trace123",
"--span-id",
"span456",
],
)
@mock.patch("builtins.print")
@mock.patch("main.generate_links", return_value=("link1", "link2"))
def test_main_cli_with_span(self, mock_gen, mock_print):
import main as main_module
main_module.main()
mock_gen.assert_called_once_with("test-proj", "trace123", "span456")
mock_print.assert_any_call("Cloud Trace Deep Link:\nlink1\n")
mock_print.assert_any_call("Cloud Logging Deep Link:\nlink2")
if __name__ == "__main__":
unittest.main()
run.sh 0.2 KB
#!/bin/bash
set -euf -o pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
export PYTHONPATH="${SCRIPT_DIR}/src:${PYTHONPATH:-}"
exec "${SCRIPT_DIR}/../run_python_with_deps/run.sh" "${SCRIPT_DIR}/src/main.py" "$@"
test.sh 0.3 KB
#!/bin/bash
set -euf -o pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
export PYTHONPATH="${SCRIPT_DIR}/src:${SCRIPT_DIR}/tests:${PYTHONPATH:-}"
exec "${SCRIPT_DIR}/../run_python_with_deps/run.sh" -m unittest discover -s "${SCRIPT_DIR}/tests" -p "*_test.py"
main.py 0.4 KB
#!/usr/bin/env python3
"""Resolves and outputs the active GCP Project ID, scanning standard variables and auth configs."""
import argparse
import sys
import project_resolver
def main():
try:
project_id = project_resolver.resolve_project_id()
print(project_id)
except RuntimeError as err:
print(f"Error: {err}", file=sys.stderr)
sys.exit(1)
if __name__ == "__main__":
main()
project_resolver.py 2.0 KB
"""Utility to resolve the active GCP Project ID from environment and config."""
import json
import os
import subprocess
from typing import Optional
try:
from google import auth as google_auth
except ImportError:
google_auth = None
def _resolve_project_from_env_vars(env_vars: list[str]) -> Optional[str]:
for var in env_vars:
project_id = os.environ.get(var)
if project_id:
return project_id.strip()
return None
def _resolve_project_from_telemetry_env_vars() -> Optional[str]:
env_vars = [
"GOOGLE_CLOUD_TRACE_PROJECT",
"GOOGLE_CLOUD_TELEMETRY_PROJECT",
]
return _resolve_project_from_env_vars(env_vars)
def _resolve_project_from_current_project_env_vars() -> Optional[str]:
env_vars = [
"GOOGLE_CLOUD_PROJECT",
"GCLOUD_PROJECT",
"DEVSHELL_PROJECT_ID",
]
return _resolve_project_from_env_vars(env_vars)
def _resolve_project_from_gcloud_config() -> Optional[str]:
try:
result = subprocess.run(
[
"gcloud",
"config",
"list",
"--format='text(core.project)'",
"--quiet",
],
capture_output=True,
text=True,
check=True,
)
project_id = result.stdout.strip()
if project_id and project_id != "(unset)":
return project_id
except (subprocess.SubprocessError, FileNotFoundError):
pass
return None
def _resolve_project_from_application_credentials() -> Optional[str]:
if google_auth is None:
return None
try:
unused_creds, project_id = google_auth.default()
return project_id
except Exception:
return None
def resolve_project_id() -> str:
"""Scans environment variables, gcloud config, and credentials to find project ID."""
for resolver in [
_resolve_project_from_telemetry_env_vars,
_resolve_project_from_gcloud_config,
_resolve_project_from_current_project_env_vars,
_resolve_project_from_application_credentials,
]:
project_id = resolver()
if project_id:
return project_id
raise RuntimeError("Could not resolve GCP Project ID")
integration_test.py 2.7 KB
import os
import shutil
import subprocess
import tempfile
import unittest
class TestGetTraceProjectIntegration(unittest.TestCase):
def setUp(self):
self.temp_dir = tempfile.mkdtemp()
self.script_path = os.path.abspath(
os.path.join(os.path.dirname(__file__), "../run.sh")
)
# Copy current environment but clear project-related vars
self.env = os.environ.copy()
self.env.pop("GOOGLE_CLOUD_TRACE_PROJECT", None)
self.env.pop("GOOGLE_CLOUD_TELEMETRY_PROJECT", None)
self.env.pop("GOOGLE_CLOUD_PROJECT", None)
self.env.pop("GCLOUD_PROJECT", None)
self.env.pop("DEVSHELL_PROJECT_ID", None)
self.env.pop("GOOGLE_APPLICATION_CREDENTIALS", None)
self.env["TMPDIR"] = self.temp_dir
self.env["TEMP"] = self.temp_dir
def tearDown(self):
shutil.rmtree(self.temp_dir)
def test_resolve_from_env_var(self):
self.env["GOOGLE_CLOUD_TRACE_PROJECT"] = "integration-env-proj"
result = subprocess.run(
[self.script_path],
env=self.env,
capture_output=True,
text=True,
)
self.assertEqual(result.returncode, 0)
self.assertEqual(result.stdout.strip(), "integration-env-proj")
def test_resolve_from_gcloud_mock(self):
# Create a mock gcloud executable in the temp dir
gcloud_mock_path = os.path.join(self.temp_dir, "gcloud")
with open(gcloud_mock_path, "w") as f:
f.write("#!/bin/sh\n")
# Check if it was called with 'config list'
f.write('if [ "$1" = "config" ] && [ "$2" = "list" ]; then\n')
f.write(' echo "gcloud-mock-proj"\n')
f.write("else\n")
f.write(" exit 1\n")
f.write("fi\n")
os.chmod(gcloud_mock_path, 0o755)
# Prepend temp dir to PATH so our mock gcloud is found first
self.env["PATH"] = f"{self.temp_dir}:{self.env.get('PATH', '')}"
result = subprocess.run(
[self.script_path],
env=self.env,
capture_output=True,
text=True,
)
self.assertEqual(result.returncode, 0)
self.assertEqual(result.stdout.strip(), "gcloud-mock-proj")
def test_failure_when_no_project(self):
# Mock gcloud to return (unset)
gcloud_mock_path = os.path.join(self.temp_dir, "gcloud")
with open(gcloud_mock_path, "w") as f:
f.write("#!/bin/sh\n")
f.write('echo "(unset)"\n')
os.chmod(gcloud_mock_path, 0o755)
self.env["PATH"] = f"{self.temp_dir}:{self.env.get('PATH', '')}"
self.env["GOOGLE_APPLICATION_CREDENTIALS"] = "/nonexistent/creds.json"
result = subprocess.run(
[self.script_path],
env=self.env,
capture_output=True,
text=True,
)
self.assertNotEqual(result.returncode, 0)
self.assertIn("Error: Could not resolve GCP Project ID", result.stderr)
if __name__ == "__main__":
unittest.main()
project_resolver_test.py 2.8 KB
import os
import subprocess
import unittest
from unittest import mock
from project_resolver import resolve_project_id
@mock.patch("project_resolver.google_auth.default")
@mock.patch("subprocess.run")
class TestGetTraceProject(unittest.TestCase):
@mock.patch.dict(os.environ, {}, clear=True)
def test_resolve_empty(self, mock_run, mock_auth):
mock_run.side_effect = FileNotFoundError()
mock_auth.return_value = (None, None)
with self.assertRaises(RuntimeError):
resolve_project_id()
@mock.patch.dict(os.environ, {"GOOGLE_CLOUD_TRACE_PROJECT": "trace-proj"})
def test_resolve_from_trace_project(self, mock_run, mock_auth):
self.assertEqual(resolve_project_id(), "trace-proj")
@mock.patch.dict(os.environ, {"GOOGLE_CLOUD_TELEMETRY_PROJECT": "telem-proj"})
def test_resolve_from_telemetry_project(self, mock_run, mock_auth):
self.assertEqual(resolve_project_id(), "telem-proj")
@mock.patch.dict(os.environ, {"DEVSHELL_PROJECT_ID": "shell-proj"})
def test_resolve_from_devshell(self, mock_run, mock_auth):
mock_run.side_effect = FileNotFoundError()
self.assertEqual(resolve_project_id(), "shell-proj")
@mock.patch.dict(os.environ, {}, clear=True)
def test_resolve_from_gcloud(self, mock_run, mock_auth):
mock_proc = mock.MagicMock()
mock_proc.stdout = "gcloud-proj-999\n"
mock_run.return_value = mock_proc
self.assertEqual(resolve_project_id(), "gcloud-proj-999")
@mock.patch.dict(os.environ, {}, clear=True)
def test_resolve_from_gcloud_unset(self, mock_run, mock_auth):
mock_proc = mock.MagicMock()
mock_proc.stdout = "(unset)\n"
mock_run.return_value = mock_proc
mock_auth.return_value = (None, "creds-proj-123")
self.assertEqual(resolve_project_id(), "creds-proj-123")
@mock.patch.dict(os.environ, {}, clear=True)
def test_resolve_from_gcloud_failed(self, mock_run, mock_auth):
mock_run.side_effect = subprocess.CalledProcessError(1, "gcloud")
mock_auth.return_value = (None, "creds-proj-123")
self.assertEqual(resolve_project_id(), "creds-proj-123")
@mock.patch.dict(os.environ, {}, clear=True)
def test_resolve_from_credentials(self, mock_run, mock_auth):
mock_run.side_effect = FileNotFoundError()
mock_auth.return_value = (None, "creds-proj-123")
self.assertEqual(resolve_project_id(), "creds-proj-123")
@mock.patch.dict(os.environ, {}, clear=True)
def test_resolve_from_credentials_error(self, mock_run, mock_auth):
mock_run.side_effect = FileNotFoundError()
try:
from google.auth.exceptions import GoogleAuthError
except ImportError:
class GoogleAuthError(Exception):
pass
mock_auth.side_effect = GoogleAuthError("Auth failed")
with self.assertRaises(RuntimeError):
resolve_project_id()
if __name__ == "__main__":
unittest.main()
requirements.txt 0.1 KB
google-cloud-trace==1.20.0
google-cloud-logging==3.16.0
google-auth==2.55.1
urllib3==2.2.1
run.sh 2.0 KB
#!/bin/bash
# run.sh
# Launcher for running Python scripts with managed dependencies.
# Allows scripts to use PyPI dependencies without global installation.
set -euf -o pipefail
# Prevent Python from prepending the current working directory to sys.path.
# This protects against local directories overshadowing core/standard library modules.
export PYTHONSAFEPATH=1
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null && pwd)"
# Detect if we are running under the offline agent evaluation framework.
TEMP_DIR="${RUNTIME_ENV_DIR:-${TMP_DIR:-${TMPDIR:-/tmp}}}"
TESTING_DIR="${GCP_TRACE_MOCK_DIR:-}"
if [[ -z "${TESTING_DIR}" || ! -d "${TESTING_DIR}/mock_gcp" ]]; then
CURR_DIR="${SCRIPT_DIR}"
while [[ "${CURR_DIR}" != "/" && "${CURR_DIR}" != "." ]]; do
if [[ -d "${CURR_DIR}/_internal/mock_gcp" ]]; then
TESTING_DIR="${CURR_DIR}/_internal"
break
elif [[ -d "${CURR_DIR}/testing/gcp-trace-querying/mock_gcp" ]]; then
TESTING_DIR="${CURR_DIR}/testing/gcp-trace-querying"
break
elif [[ -d "${CURR_DIR}/mock_gcp" ]]; then
TESTING_DIR="${CURR_DIR}"
break
fi
CURR_DIR="$(dirname "${CURR_DIR}")"
done
fi
IS_MOCK_REQUESTED=false
if [[ "${USE_MOCK_GCP:-false}" == "true" ]]; then
IS_MOCK_REQUESTED=true
elif [[ "${USE_MOCK_GCP:-false}" != "false" ]]; then
IS_MOCK_REQUESTED=false
elif compgen -G "${TEMP_DIR}/*mock_trace_state*.json" > /dev/null 2>&1 || compgen -G "${TEMP_DIR}/.*mock_trace_state*.json" > /dev/null 2>&1; then
IS_MOCK_REQUESTED=true
fi
if [[ "${IS_MOCK_REQUESTED}" == "true" && -n "${TESTING_DIR}" && -d "${TESTING_DIR}/mock_gcp" ]]; then
MOCK_GCP_DIR="${TESTING_DIR}/mock_gcp"
if [[ "${1:-}" == -* ]]; then
TARGET_SRC_DIR=""
else
TARGET_SRC_DIR="$(cd "$(dirname "${1:-}")" >/dev/null 2>&1 && pwd || true)"
fi
export PYTHONPATH="${TARGET_SRC_DIR}:${MOCK_GCP_DIR}:${TESTING_DIR}:${TESTING_DIR}/shared:${PYTHONPATH:-}"
exec python3 "$@"
fi
exec python3 "${SCRIPT_DIR}/src/manage_venv.py" "$@"
test.sh 0.4 KB
#!/bin/bash
set -euf -o pipefail
# Prevent Python from prepending the current working directory to sys.path.
# This protects against local directories overshadowing core/standard library modules.
export PYTHONSAFEPATH=1
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null && pwd)"
exec python3 -m unittest discover -s "${SCRIPT_DIR}/tests" -p "*_test.py"
cleanup_env.py 2.1 KB
"""Cleans up old, unused virtual environments in a background process.
We create a new virtual environment directory daily (using the current date path
in the hash) to ensure that updates to standard dependencies or requirements
are picked up eventually, even if the requirements hash didn't change.
To prevent these daily virtual environments from filling up the disk
indefinitely,
this background cleanup task deletes any virtualenv whose use.lock file is not
exclusively locked (indicating it is not currently in use by any active process)
and does not belong to the current day.
"""
import datetime
import fcntl
import os
import pathlib
import shutil
import sys
def _remove_empty_parents(d: pathlib.Path):
"""Prunes empty parent date directories up to 3 levels (YYYY/MM/DD).
Args:
d: The parent directory path to start pruning from.
"""
for _ in range(3):
if d.exists() and not os.listdir(d):
d.rmdir()
d = d.parent
else:
break
def _clean_if_unused(venv_dir: pathlib.Path, lock_file: pathlib.Path):
"""Attempts to delete the virtualenv if it is not currently in use.
It attempts to acquire an exclusive non-blocking lock on the virtualenv's
use.lock. If successful, it means no other active script process is currently
running using this environment, and it is safe to delete it.
Args:
venv_dir: The absolute path to the virtualenv directory to delete.
lock_file: The path to the use.lock file inside the virtualenv.
"""
try:
fd = os.open(lock_file, os.O_WRONLY)
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
os.close(fd)
shutil.rmtree(venv_dir)
_remove_empty_parents(venv_dir.parent)
except (BlockingIOError, OSError):
pass
def main():
"""Sweeps the virtualenv base directory and triggers cleanup on older envs."""
if len(sys.argv) < 2:
sys.exit(1)
venv_base = pathlib.Path(sys.argv[1])
today_str = datetime.date.today().strftime("%Y/%m/%d")
for lock_file in venv_base.glob("**/use.lock"):
if today_str not in str(lock_file):
_clean_if_unused(lock_file.parent, lock_file)
if __name__ == "__main__":
main()
lock_manager.py 2.5 KB
"""Lock management utility for virtual environment setup and usage.
To prevent race conditions when multiple skill tool scripts are invoked
simultaneously, we implement two locking mechanisms:
1. Setup Lock (.setup.lock): An exclusive flock acquired during setup.
This prevents concurrent execution instances from running 'pip install' or
'venv.create' on the same virtualenv directory simultaneously, which would
corrupt the virtual environment.
2. Use Lock (use.lock): A shared flock acquired during python script execution.
It remains active as long as the Python process runs (making the file
descriptor
inheritable across execv). The background cleanup sweep checks if it can
acquire
an exclusive lock on use.lock; if it fails (because a shared use lock is
held),
it knows the environment is still in use and skips deletion.
"""
import fcntl
import os
import pathlib
def acquire_setup_lock(venv_base: pathlib.Path, req_hash: str) -> int:
"""Acquires an exclusive blocking lock for the setup phase of the virtualenv.
This blocks any concurrent process trying to initialize or write to the
same virtualenv directory until the current process completes installation
and releases it.
Args:
venv_base: The path to the parent directory of all virtualenvs.
req_hash: The sha256 hash string of requirements.txt.
Returns:
The open file descriptor pointing to the setup lock file.
"""
lock_dir = venv_base / "locks"
lock_dir.mkdir(parents=True, exist_ok=True)
setup_lock_file = lock_dir / f"{req_hash}.setup.lock"
fd = os.open(setup_lock_file, os.O_CREAT | os.O_WRONLY, 0o666)
fcntl.flock(fd, fcntl.LOCK_EX)
return fd
def release_setup_lock(fd: int):
"""Releases the exclusive setup lock and closes its file descriptor.
Args:
fd: The open file descriptor representing the setup lock.
"""
fcntl.flock(fd, fcntl.LOCK_UN)
os.close(fd)
def acquire_use_lock(venv_dir: pathlib.Path) -> int:
"""Acquires a shared lock representing active execution usage.
This file descriptor is explicitly set to be inheritable so that the flock
remains held by the Python process when it transitions via execv into
the target python execution context.
Args:
venv_dir: The directory of the active virtualenv.
Returns:
The open file descriptor pointing to the use lock file.
"""
use_lock_file = venv_dir / "use.lock"
use_lock_file.touch(exist_ok=True)
fd = os.open(use_lock_file, os.O_RDONLY)
fcntl.flock(fd, fcntl.LOCK_SH)
os.set_inheritable(fd, True)
return fd
manage_venv.py 1.7 KB
"""Manages virtualenv creation, locking, requirements sync, and cleanup."""
import pathlib
import sys
# Ensure sibling modules under src/ can be imported when PYTHONSAFEPATH=1.
_script_dir = str(pathlib.Path(__file__).parent.resolve())
if _script_dir not in sys.path:
sys.path.insert(0, _script_dir)
# pylint: disable=g-import-not-at-top
from lock_manager import acquire_setup_lock
from lock_manager import acquire_use_lock
from lock_manager import release_setup_lock
from path_resolver import get_requirements_hash
from path_resolver import resolve_paths
from venv_cleaner import trigger_background_cleanup
from venv_executor import execute_python
from venv_setup import setup_venv_if_missing
# pylint: enable=g-import-not-at-top
def setup_and_lock_venv(
venv_base: pathlib.Path, venv_dir: pathlib.Path, req_file: pathlib.Path
):
"""Secures setup and execution locks, and initializes the virtualenv.
Args:
venv_base: The path to the parent virtualenv directory.
venv_dir: The target path where the virtualenv should exist.
req_file: The path to requirements.txt.
"""
req_hash = get_requirements_hash(req_file)
setup_fd = acquire_setup_lock(venv_base, req_hash)
setup_venv_if_missing(venv_dir, req_file)
acquire_use_lock(venv_dir)
release_setup_lock(setup_fd)
def main():
"""Main entrypoint orchestrating path setup, locking, and execution."""
if len(sys.argv) < 2:
print("Usage: manage_venv.py <script.py> [args...]", file=sys.stderr)
sys.exit(1)
req_file, venv_base, venv_dir = resolve_paths()
setup_and_lock_venv(venv_base, venv_dir, req_file)
trigger_background_cleanup(venv_base.parent)
execute_python(venv_dir)
if __name__ == "__main__":
main()
path_resolver.py 3.4 KB
"""Path resolution utility for virtualenv management.
Computes unique hashes of requirements.txt configurations and maps absolute
locations for active virtual environments.
"""
import datetime
import hashlib
import os
import pathlib
import tempfile
_WORKSPACE_MARKERS = (
".git",
".jj",
".hg",
"WORKSPACE",
"WORKSPACE.bazel",
"MODULE.bazel",
)
def get_requirements_hash(req_file: pathlib.Path) -> str:
"""Computes a SHA256 hash of the requirements file contents.
This hash is used as a directory component to uniquely identify a distinct set
of dependency requirements, ensuring that environment setup only triggers
when requirements are changed.
Args:
req_file: The path to the requirements.txt file.
Returns:
A string containing the SHA256 hex representation of the file contents.
"""
h = hashlib.sha256()
with open(req_file, "rb") as f:
h.update(f.read())
return h.hexdigest()
def find_workspace_root(path: pathlib.Path) -> pathlib.Path:
"""Walks up from path until finding a directory containing a workspace marker.
Args:
path: File or directory path to start searching from.
Returns:
The workspace root directory Path if a marker is found, or the resolved
starting path.
"""
resolved_path = path.resolve()
for current in [resolved_path] + list(resolved_path.parents):
for marker in _WORKSPACE_MARKERS:
if (current / marker).exists():
return current
return resolved_path
def get_workspace_identifier(path: pathlib.Path) -> str:
"""Extracts a unique, fingerprinted workspace subpath identifier.
Fingerprints the workspace root directory path (including all ancestor paths)
to construct a collision-free per-workspace subpath.
Args:
path: Path to resolve workspace identifier for.
Returns:
A unique per-workspace subpath string formatted as 'dirname_hash'.
"""
ws_root = find_workspace_root(path)
full_path_str = str(ws_root)
ws_name = ws_root.name or "workspace"
path_hash = hashlib.sha256(full_path_str.encode("utf-8")).hexdigest()[:12]
return f"{ws_name}_{path_hash}"
def get_temp_dir() -> pathlib.Path:
"""Returns temporary directory path respecting TMP_DIR or TMPDIR overrides."""
tmp_env = os.environ.get("TMP_DIR") or os.environ.get("TMPDIR")
if tmp_env:
return pathlib.Path(tmp_env)
return pathlib.Path(tempfile.gettempdir())
def resolve_paths() -> tuple[pathlib.Path, pathlib.Path, pathlib.Path]:
"""Resolves paths for requirements, virtualenv base, and active virtualenv.
The active virtualenv path is partitioned by fingerprinted workspace ID, date
(YYYY/MM/DD) and config hash to enforce daily virtualenv refresh cycles and
isolate concurrent evaluation runs.
Returns:
A tuple containing:
- req_file: Path to requirements.txt.
- venv_base: Path to parent virtualenv base directory under temp space
(workspace-specific).
- venv_dir: Path to the specific virtualenv directory.
"""
this_dir = pathlib.Path(__file__).parent.resolve()
req_file = this_dir.parent.parent / "requirements.txt"
if not req_file.exists():
req_file = this_dir.parent.parent.parent / "requirements.txt"
root_base = get_temp_dir() / "gcp_trace_querying_venvs"
ws_id = get_workspace_identifier(this_dir)
venv_base = root_base / ws_id
date_path = datetime.date.today().strftime("%Y/%m/%d")
venv_dir = venv_base / date_path / get_requirements_hash(req_file)
return req_file, venv_base, venv_dir
venv_cleaner.py 0.8 KB
"""Triggers background cleanup task for old virtual environments.
Spawns an asynchronous process that runs independently of the main thread
to sweep and delete expired virtual environments.
"""
import pathlib
import subprocess
import sys
def trigger_background_cleanup(venv_base: pathlib.Path):
"""Spawns cleanup_env.py in the background to clean up stale virtualenvs.
This triggers a sweep of old directories without blocking the main execution
thread of the active script.
Args:
venv_base: The path to the parent directory containing all virtualenvs.
"""
script_dir = pathlib.Path(__file__).parent.resolve()
subprocess.Popen(
[sys.executable, str(script_dir / "cleanup_env.py"), str(venv_base)],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
venv_executor.py 1.2 KB
"""Executes target script within the context of the virtual environment.
Sets up required PYTHONPATH environment variables so that local shared modules
are visible, and execs the python binary within the virtual environment.
"""
import os
import pathlib
import sys
def execute_python(venv_dir: pathlib.Path) -> None:
"""Executes the target script using the virtualenv's Python binary.
Prepends the shared scripts directory to PYTHONPATH, then calls os.execv to
replace the current process with the virtualenv Python interpreter running
the user's script.
Args:
venv_dir: The path to the virtualenv directory to run under.
Raises:
OSError: If the execv call fails (this is caught internally, printed to
stderr, and triggers sys.exit(1)).
"""
python_path = venv_dir / "bin" / "python3"
script_dir = pathlib.Path(__file__).parent.resolve()
scripts_dir = script_dir.parent.parent
os.environ["PYTHONPATH"] = f"{scripts_dir}:{os.environ.get('PYTHONPATH', '')}"
try:
os.execv(str(python_path), [str(python_path)] + sys.argv[1:])
except OSError as e:
print(f"Error: Failed to execute {python_path}: {e}", file=sys.stderr)
sys.exit(1)
venv_setup.py 2.1 KB
"""Virtual environment initialization and package installation manager.
Handles directory setup, python virtual environment initialization, and
package installations from requirements configuration.
"""
import pathlib
import subprocess
import sys
import venv
def create_and_upgrade_pip(venv_dir: pathlib.Path, pip_path: pathlib.Path):
"""Creates the virtualenv directory and upgrades pip inside it.
Args:
venv_dir: The target path where the virtualenv should be created.
pip_path: The expected absolute path to the pip executable.
"""
venv_dir.mkdir(parents=True, exist_ok=True)
venv.create(venv_dir, system_site_packages=True, with_pip=True)
upgrade_args = [
str(pip_path),
"install",
"--timeout",
"3",
"--retries",
"0",
"--quiet",
"--upgrade",
"pip",
]
subprocess.run(upgrade_args, capture_output=True, check=False)
def install_requirements(pip_path: pathlib.Path, req_file: pathlib.Path):
"""Installs dependencies from the requirements file via pip.
Args:
pip_path: The absolute path to the pip executable.
req_file: The path to the requirements.txt file to install.
"""
install_args = [
str(pip_path),
"install",
"--timeout",
"3",
"--retries",
"0",
"--quiet",
"-r",
str(req_file),
]
res = subprocess.run(install_args, check=False)
if res.returncode != 0:
print(
"Warning: Failed to install dependencies. Proceeding anyway...",
file=sys.stderr,
)
def setup_venv_if_missing(venv_dir: pathlib.Path, req_file: pathlib.Path):
"""Initializes virtual environment and dependencies if not already present.
Args:
venv_dir: The target path where the virtualenv should exist.
req_file: The path to requirements.txt.
"""
if venv_dir.exists():
return
print(f"Creating virtual environment in {venv_dir}...", file=sys.stderr)
pip_path = venv_dir / "bin" / "pip"
create_and_upgrade_pip(venv_dir, pip_path)
print("Installing dependencies from requirements.txt...", file=sys.stderr)
install_requirements(pip_path, req_file)
cleanup_env_test.py 2.5 KB
"""Unit tests for cleanup_env utility."""
import fcntl
import os
import pathlib
import sys
import unittest
from unittest import mock
_script_dir = str(pathlib.Path(__file__).parent.parent / "src")
if _script_dir not in sys.path:
sys.path.insert(0, _script_dir)
# pylint: disable=g-import-not-at-top
from cleanup_env import _clean_if_unused
from cleanup_env import _remove_empty_parents
# pylint: enable=g-import-not-at-top
class TestCleanupEnv(unittest.TestCase):
@mock.patch("cleanup_env.os.listdir")
@mock.patch("cleanup_env.pathlib.Path.rmdir")
def test_remove_empty_parents(self, mock_rmdir, mock_listdir):
"""Verifies that remove_empty_parents recursively deletes empty paths."""
mock_listdir.side_effect = [
[],
["some_file"],
] # first is empty, second is not
with mock.patch("cleanup_env.pathlib.Path.exists") as mock_exists:
mock_exists.return_value = True
# Starting path /tmp/a/b/c
_remove_empty_parents(pathlib.Path("/tmp/a/b/c"))
# It should call rmdir once on the empty leaf directory, then stop on parent.
mock_rmdir.assert_called_once()
@mock.patch("cleanup_env.os.open")
@mock.patch("cleanup_env.os.close")
@mock.patch("cleanup_env.fcntl.flock")
@mock.patch("cleanup_env.shutil.rmtree")
def test_clean_if_unused_success(
self, mock_rmtree, mock_flock, mock_close, mock_open
):
"""Verifies environment is deleted if exclusive lock can be acquired."""
mock_open.return_value = 55
venv_dir = pathlib.Path("/tmp/old_venv")
lock_file = pathlib.Path("/tmp/old_venv/use.lock")
with mock.patch("cleanup_env._remove_empty_parents") as mock_remove_parents:
_clean_if_unused(venv_dir, lock_file)
mock_rmtree.assert_called_once_with(venv_dir)
mock_remove_parents.assert_called_once()
mock_flock.assert_called_once_with(55, fcntl.LOCK_EX | fcntl.LOCK_NB)
mock_close.assert_called_once_with(55)
@mock.patch("cleanup_env.os.open")
@mock.patch("cleanup_env.fcntl.flock")
@mock.patch("cleanup_env.shutil.rmtree")
def test_clean_if_unused_blocked_skips(
self, mock_rmtree, mock_flock, mock_open
):
"""Verifies deletion is skipped if a shared use lock blocks exclusive lock."""
mock_open.return_value = 55
mock_flock.side_effect = BlockingIOError
venv_dir = pathlib.Path("/tmp/active_venv")
lock_file = pathlib.Path("/tmp/active_venv/use.lock")
_clean_if_unused(venv_dir, lock_file)
mock_rmtree.assert_not_called()
if __name__ == "__main__":
unittest.main()
lock_manager_test.py 2.0 KB
"""Unit tests for lock_manager utility."""
import fcntl
import os
import pathlib
import sys
import unittest
from unittest import mock
_script_dir = str(pathlib.Path(__file__).parent.parent / "src")
if _script_dir not in sys.path:
sys.path.insert(0, _script_dir)
# pylint: disable=g-import-not-at-top
from lock_manager import acquire_setup_lock
from lock_manager import acquire_use_lock
from lock_manager import release_setup_lock
# pylint: enable=g-import-not-at-top
class TestLockManager(unittest.TestCase):
@mock.patch("lock_manager.os.open")
@mock.patch("lock_manager.fcntl.flock")
def test_acquire_setup_lock(self, mock_flock, mock_open):
"""Verifies that acquire_setup_lock opens lock file and requests exclusive lock."""
mock_open.return_value = 42
venv_base = pathlib.Path("/tmp/test_venvs")
fd = acquire_setup_lock(venv_base, "dummy_hash")
self.assertEqual(fd, 42)
mock_open.assert_called_once()
mock_flock.assert_called_once_with(42, fcntl.LOCK_EX)
@mock.patch("lock_manager.os.close")
@mock.patch("lock_manager.fcntl.flock")
def test_release_setup_lock(self, mock_flock, mock_close):
"""Verifies that release_setup_lock releases lock and closes fd."""
release_setup_lock(100)
mock_flock.assert_called_once_with(100, fcntl.LOCK_UN)
mock_close.assert_called_once_with(100)
@mock.patch("lock_manager.os.open")
@mock.patch("lock_manager.fcntl.flock")
@mock.patch("lock_manager.os.set_inheritable")
def test_acquire_use_lock(self, mock_inheritable, mock_flock, mock_open):
"""Verifies that acquire_use_lock requests shared lock and flags inheritable."""
mock_open.return_value = 84
venv_dir = pathlib.Path("/tmp/test_venvs/dummy_venv")
with mock.patch("lock_manager.pathlib.Path.touch") as mock_touch:
fd = acquire_use_lock(venv_dir)
self.assertEqual(fd, 84)
mock_touch.assert_called_once()
mock_flock.assert_called_once_with(84, fcntl.LOCK_SH)
mock_inheritable.assert_called_once_with(84, True)
if __name__ == "__main__":
unittest.main()
path_resolver_test.py 5.4 KB
"""Unit tests for path_resolver utility."""
import hashlib
import os
import pathlib
import sys
import tempfile
import unittest
from unittest import mock
_script_dir = str(pathlib.Path(__file__).parent.parent / "src")
if _script_dir not in sys.path:
sys.path.insert(0, _script_dir)
# pylint: disable=g-import-not-at-top
from path_resolver import _WORKSPACE_MARKERS
from path_resolver import find_workspace_root
from path_resolver import get_requirements_hash
from path_resolver import get_temp_dir
from path_resolver import get_workspace_identifier
from path_resolver import resolve_paths
# pylint: enable=g-import-not-at-top
class TestPathResolver(unittest.TestCase):
def test_get_requirements_hash(self):
"""Verifies SHA256 hashing matches computed sum of temp requirements."""
content = b"google-cloud-trace==1.20.0\n"
expected = hashlib.sha256(content).hexdigest()
with tempfile.NamedTemporaryFile("wb", delete=False) as temp_file:
temp_file.write(content)
temp_path = pathlib.Path(temp_file.name)
try:
self.assertEqual(get_requirements_hash(temp_path), expected)
finally:
temp_path.unlink(missing_ok=True)
def test_find_workspace_root_with_all_marker_types(self):
"""Verifies find_workspace_root recognizes each distinct workspace marker type."""
for marker in _WORKSPACE_MARKERS:
with tempfile.TemporaryDirectory() as tmp_dir:
root = pathlib.Path(tmp_dir)
marker_path = root / marker
if marker.startswith("."):
marker_path.mkdir(parents=True, exist_ok=True)
else:
marker_path.touch()
target_dir = root / "sub1" / "sub2"
target_dir.mkdir(parents=True, exist_ok=True)
found_root = find_workspace_root(target_dir)
self.assertEqual(
found_root,
root.resolve(),
f"Failed to find workspace root for marker '{marker}'",
)
def test_find_workspace_root_at_various_depths(self):
"""Verifies find_workspace_root works at 0, 1, 3, and 10 levels deep."""
depths = [0, 1, 3, 10]
for depth in depths:
with tempfile.TemporaryDirectory() as tmp_dir:
root = pathlib.Path(tmp_dir)
(root / "WORKSPACE").touch()
curr = root
for i in range(depth):
curr = curr / f"dir_{i}"
curr.mkdir(parents=True, exist_ok=True)
found_root = find_workspace_root(curr)
self.assertEqual(
found_root,
root.resolve(),
f"Failed to find workspace root at depth {depth}",
)
def test_find_workspace_root_when_no_markers_exist(self):
"""Verifies fallback when no workspace markers exist in parent tree."""
with tempfile.TemporaryDirectory() as tmp_dir:
deep_dir = pathlib.Path(tmp_dir) / "level1" / "level2" / "level3"
deep_dir.mkdir(parents=True, exist_ok=True)
original_exists = pathlib.Path.exists
def fake_exists(self):
if any(self.name == marker for marker in _WORKSPACE_MARKERS):
return False
return original_exists(self)
with mock.patch.object(pathlib.Path, "exists", fake_exists):
found_root = find_workspace_root(deep_dir)
self.assertEqual(found_root, deep_dir.resolve())
def test_find_workspace_root_at_filesystem_root(self):
"""Verifies find_workspace_root handles root directory '/' safely."""
root_path = pathlib.Path("/")
original_exists = pathlib.Path.exists
def fake_exists(self):
if any(self.name == marker for marker in _WORKSPACE_MARKERS):
return False
return original_exists(self)
with mock.patch.object(pathlib.Path, "exists", fake_exists):
found_root = find_workspace_root(root_path)
self.assertEqual(found_root, root_path.resolve())
def test_get_workspace_identifier_uniqueness_and_consistency(self):
"""Verifies workspace identifier produces consistent hashes and unique subpaths."""
with (
tempfile.TemporaryDirectory() as tmp_dir1,
tempfile.TemporaryDirectory() as tmp_dir2,
):
root1 = pathlib.Path(tmp_dir1)
(root1 / ".git").mkdir()
sub1 = root1 / "a" / "b"
sub1.mkdir(parents=True)
root2 = pathlib.Path(tmp_dir2)
(root2 / ".git").mkdir()
sub2 = root2 / "x" / "y"
sub2.mkdir(parents=True)
id1_a = get_workspace_identifier(sub1)
id1_b = get_workspace_identifier(root1)
id2 = get_workspace_identifier(sub2)
self.assertEqual(id1_a, id1_b)
self.assertNotEqual(id1_a, id2)
self.assertIn("_", id1_a)
def test_get_temp_dir_environment_overrides(self):
"""Verifies get_temp_dir respects TMP_DIR and TMPDIR environment variables."""
with mock.patch.dict(
os.environ, {"TMP_DIR": "/custom/tmp_dir"}, clear=True
):
self.assertEqual(get_temp_dir(), pathlib.Path("/custom/tmp_dir"))
with mock.patch.dict(os.environ, {"TMPDIR": "/custom/tmpdir"}, clear=True):
self.assertEqual(get_temp_dir(), pathlib.Path("/custom/tmpdir"))
def test_resolve_paths_returns_valid_structure(self):
"""Verifies resolved paths structure aligns with project layout."""
req_file, venv_base, venv_dir = resolve_paths()
self.assertTrue(req_file.is_absolute())
self.assertEqual(req_file.name, "requirements.txt")
self.assertIn("gcp_trace_querying_venvs", venv_base.as_posix())
self.assertIn(venv_base.as_posix(), venv_dir.as_posix())
if __name__ == "__main__":
unittest.main()
venv_setup_test.py 1.8 KB
"""Unit tests for venv_setup manager."""
import pathlib
import subprocess
import sys
import unittest
from unittest import mock
_script_dir = str(pathlib.Path(__file__).parent.parent / "src")
if _script_dir not in sys.path:
sys.path.insert(0, _script_dir)
# pylint: disable=g-import-not-at-top
from venv_setup import setup_venv_if_missing
# pylint: enable=g-import-not-at-top
class TestVenvSetup(unittest.TestCase):
@mock.patch("venv_setup.pathlib.Path.exists")
def test_setup_venv_if_exists_does_nothing(self, mock_exists):
"""Verifies setup skips installation if the target directory already exists."""
mock_exists.return_value = True
venv_dir = pathlib.Path("/tmp/existing_venv")
req_file = pathlib.Path("/tmp/req.txt")
with mock.patch("venv_setup.venv.create") as mock_create:
setup_venv_if_missing(venv_dir, req_file)
mock_create.assert_not_called()
@mock.patch("venv_setup.pathlib.Path.exists")
@mock.patch("venv_setup.venv.create")
@mock.patch("venv_setup.subprocess.run")
def test_setup_venv_initializes_missing(
self, mock_run, mock_create, mock_exists
):
"""Verifies setup runs venv.create and pip install when target is missing."""
mock_exists.return_value = False
venv_dir = pathlib.Path("/tmp/missing_venv")
req_file = pathlib.Path("/tmp/req.txt")
mock_run.return_value = mock.MagicMock(returncode=0)
with mock.patch("venv_setup.pathlib.Path.mkdir") as mock_mkdir:
setup_venv_if_missing(venv_dir, req_file)
mock_mkdir.assert_called_once_with(parents=True, exist_ok=True)
mock_create.assert_called_once_with(
venv_dir, system_site_packages=True, with_pip=True
)
self.assertEqual(
mock_run.call_count, 2
) # 1 for pip upgrade, 1 for requirements install
if __name__ == "__main__":
unittest.main()
run.sh 0.2 KB
#!/bin/bash
set -euf -o pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
export PYTHONPATH="${SCRIPT_DIR}/src:${PYTHONPATH:-}"
exec "${SCRIPT_DIR}/../run_python_with_deps/run.sh" "${SCRIPT_DIR}/src/main.py" "$@"
test.sh 0.3 KB
#!/bin/bash
set -euf -o pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
export PYTHONPATH="${SCRIPT_DIR}/src:${SCRIPT_DIR}/tests:${PYTHONPATH:-}"
exec "${SCRIPT_DIR}/../run_python_with_deps/run.sh" -m unittest discover -s "${SCRIPT_DIR}/tests" -p "*_test.py"
main.py 2.1 KB
#!/usr/bin/env python3
"""CLI wrapper to search and list traces in a GCP project."""
import argparse
import json
import logging
import secrets
import sys
from trace_searcher import search_traces
_logger = logging.getLogger(__name__)
def main():
parser = argparse.ArgumentParser(description="Search GCP Cloud Traces.")
parser.head = getattr(parser, "head", None) # avoid linter warning
parser.add_argument(
"--filter", required=True, help="Trace query filter expression"
)
parser.add_argument(
"--start-time", type=str, help="Optional start time ISO 8601"
)
parser.add_argument("--end-time", type=str, help="Optional end time ISO 8601")
parser.add_argument(
"--projects",
nargs="+",
required=True,
help="List of GCP Project IDs to search.",
)
parser.add_argument(
"--limit", type=int, default=10, help="Max traces to return"
)
parser.add_argument(
"--examples-per-cluster",
type=int,
default=3,
help="Max trace summary examples per cluster",
)
parser.add_argument(
"--output", type=str, help="Optional output file path to write results."
)
parser.add_argument(
"--no-wrapper-tag",
action="store_true",
default=False,
help="Do not wrap output in untrusted telemetry tags.",
)
args = parser.parse_args()
traces = search_traces(
projects=args.projects,
filter_query=args.filter,
limit=args.limit,
start_time_str=args.start_time,
end_time_str=args.end_time,
examples_per_cluster=args.examples_per_cluster,
)
raw_json = json.dumps(traces, indent=2)
if args.no_wrapper_tag:
output_str = raw_json
else:
token = secrets.token_hex(8)
output_str = f"<untrusted_telemetry_{token}>\n{raw_json}\n</untrusted_telemetry_{token}>"
if args.output:
with open(args.output, "w") as f:
f.write(output_str)
_logger.info("Results written to: %s", args.output)
else:
print(output_str)
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO)
try:
main()
except Exception as err:
_logger.exception(err)
sys.exit(1)
timestamp_utils.py 1.5 KB
"""Shared timestamp utility functions for trace querying scripts."""
from datetime import datetime, timezone
from typing import Any, Optional
from google.protobuf.timestamp_pb2 import Timestamp
def parse_iso8601(ts_str: str) -> datetime:
"""Parses an ISO 8601 timestamp string (supporting Z suffix) into a datetime."""
normalized = ts_str.replace("Z", "+00:00")
return datetime.fromisoformat(normalized)
def parse_timestamp(ts_str: Optional[str]) -> Optional[Timestamp]:
"""Parses ISO8601 string and converts to protobuf Timestamp."""
if not ts_str:
return None
try:
dt = parse_iso8601(ts_str)
ts = Timestamp()
epoch_seconds = dt.timestamp()
ts.seconds = int(epoch_seconds)
ts.nanos = int((epoch_seconds - ts.seconds) * 1e9)
return ts
except Exception as e:
raise ValueError(
f"Invalid timestamp '{ts_str}'. Must be ISO 8601 (e.g."
f" 2026-06-25T13:00:00Z). Error: {e}"
)
def to_datetime(val: Any) -> datetime:
"""Converts string, datetime or Timestamp dict to timezone-aware datetime."""
if isinstance(val, datetime):
if val.tzinfo is None:
return val.replace(tzinfo=timezone.utc)
return val
if isinstance(val, str):
return parse_iso8601(val)
if isinstance(val, dict):
seconds = val.get("seconds")
nanos = val.get("nanos", 0)
if seconds is not None:
return datetime.fromtimestamp(
int(seconds) + int(nanos) * 1e-9, tz=timezone.utc
)
raise ValueError(f"Unsupported timestamp format: {val}")
trace_searcher.py 16.0 KB
"""Logic for searching and listing traces using GCP Trace client library."""
from datetime import datetime, timezone
import hashlib
import logging
from typing import Any, Dict, List, Optional
from google.cloud import trace_v1
from google.protobuf.json_format import MessageToDict
from timestamp_utils import parse_iso8601, parse_timestamp, to_datetime
_logger = logging.getLogger(__name__)
def _is_status_code_error(val: Any) -> bool:
"""Returns True if the status code value represents an error."""
if val is None:
return False
val_int = None
if isinstance(val, (int, float)):
val_int = int(val)
elif isinstance(val, str):
try:
val_int = int(val)
except ValueError:
pass
if val_int is not None:
# Standard HTTP status codes
if 100 <= val_int < 600:
return val_int < 200 or val_int >= 400
# RPC numeric status codes (0 is OK, non-zero is error)
return val_int != 0
if isinstance(val, str):
val_clean = val.strip().lower()
return val_clean not in ("ok", "success")
return True
class ErrorCheckResult:
"""Result of checking a span for errors."""
def __init__(self, is_error: bool, causes: Dict[str, Any]):
self.is_error = is_error
self.causes = causes
def _check_otel_http_error(
labels: Dict[str, Any], causes: Dict[str, Any]
) -> bool:
"""Checks for OTel/legacy HTTP errors."""
for key in (
"http.response.status_code",
"http.status_code",
"/http/status_code",
):
if key in labels:
val = labels[key]
if _is_status_code_error(val):
causes[key] = val
return True
return False
def _check_otel_grpc_error(
labels: Dict[str, Any], causes: Dict[str, Any]
) -> bool:
"""Checks for OTel gRPC/grpc.status errors."""
for key in ("rpc.grpc.status_code", "grpc.status"):
if key in labels:
val = labels[key]
if _is_status_code_error(val):
causes[key] = val
return True
return False
def _check_rpc_system_error(
labels: Dict[str, Any], causes: Dict[str, Any]
) -> bool:
"""Checks for RPC response status errors."""
if "rpc.response.status_code" in labels:
val = labels["rpc.response.status_code"]
if _is_status_code_error(val):
causes["rpc.response.status_code"] = val
system = labels.get("rpc.system.name")
if system:
causes["rpc.system.name"] = system
return True
return False
def _check_generic_error_attributes(
labels: Dict[str, Any], causes: Dict[str, Any]
) -> bool:
"""Checks for generic error attributes/labels."""
error_pairs = {
"error.type": "error.message",
"error.message": "error.type",
"/error/name": "/error/message",
"/error/message": "/error/name",
}
for key, other_key in error_pairs.items():
if key in labels:
val = labels[key]
if val is not None and isinstance(val, str) and val.strip():
causes[key] = val
if other_key in labels and labels[other_key] is not None:
causes[other_key] = labels[other_key]
return True
return False
def _check_gcp_top_level_status(status: Any, causes: Dict[str, Any]) -> bool:
"""Checks top level status object for errors."""
if isinstance(status, dict):
code = status.get("code")
if code is not None:
try:
if int(code) != 0:
causes["status"] = status
return True
except (ValueError, TypeError):
pass
elif isinstance(status, str):
status_clean = status.strip().lower()
if status_clean and status_clean not in ("ok", "0"):
causes["status"] = status
return True
return False
def check_error_span(span: Dict[str, Any]) -> ErrorCheckResult:
"""Checks if a span is an error and extracts the cause.
Follows OpenTelemetry Semantic Conventions and Google RPC status codes.
"""
labels = span.get("labels") or span.get("attributes") or {}
causes = {}
if _check_otel_http_error(labels, causes):
return ErrorCheckResult(True, causes)
if _check_otel_grpc_error(labels, causes):
return ErrorCheckResult(True, causes)
if _check_rpc_system_error(labels, causes):
return ErrorCheckResult(True, causes)
if _check_generic_error_attributes(labels, causes):
return ErrorCheckResult(True, causes)
status = span.get("status")
if status and _check_gcp_top_level_status(status, causes):
return ErrorCheckResult(True, causes)
return ErrorCheckResult(False, {})
def is_error_span(span: Dict[str, Any]) -> bool:
"""Checks if a span represents an error."""
return check_error_span(span).is_error
def _get_span_start(span: Dict[str, Any]) -> datetime:
"""Gets span start time."""
return to_datetime(span.get("startTime"))
def _get_span_end(span: Dict[str, Any]) -> datetime:
"""Gets span end time."""
return to_datetime(span.get("endTime"))
def _get_service_identifiers(span: Dict[str, Any]) -> Dict[str, str]:
"""Extracts all service-related identifiers from a span's labels/attributes."""
labels = span.get("labels") or span.get("attributes") or {}
ids = {}
# 1. OTel service attributes
otel_name = labels.get("service.name")
if otel_name:
ids["otel_service_name"] = str(otel_name)
otel_ns = labels.get("service.namespace")
if otel_ns:
ids["otel_service_namespace"] = str(otel_ns)
# 2. AppHub attributes
apphub_id = labels.get("gcp.apphub.service.id")
if apphub_id:
ids["apphub_service_id"] = str(apphub_id)
apphub_workload = labels.get("gcp.apphub.workload.id")
if apphub_workload:
ids["apphub_workload_id"] = str(apphub_workload)
# 3. GCP MCP attributes
mcp_id = labels.get("gcp.mcp.server.id")
if mcp_id:
ids["gcp_mcp_server_id"] = str(mcp_id)
return ids
def _get_canonical_service_name(ids: Dict[str, str]) -> Optional[str]:
"""Resolves a single canonical service name string from the identifiers."""
if "otel_service_name" in ids:
name = ids["otel_service_name"]
ns = ids.get("otel_service_namespace")
return f"{ns}/{name}" if ns else name
if "apphub_service_id" in ids:
return ids["apphub_service_id"]
if "gcp_mcp_server_id" in ids:
return ids["gcp_mcp_server_id"]
return None
def _extract_error_labels(span: Dict[str, Any]) -> Dict[str, Any]:
"""Extracts labels indicating the failure from a span."""
res = check_error_span(span)
if not res.is_error:
return {}
error_labels = dict(res.causes)
labels = span.get("labels") or span.get("attributes") or {}
# Also capture general keys containing 'message' or 'error' (case-insensitive)
for k, v in labels.items():
k_lower = k.lower()
if v is not None and ("message" in k_lower or "error" in k_lower):
# Don't overwrite if already set by cause detection
if k not in error_labels:
error_labels[k] = v
return error_labels
_trace_client: Optional[trace_v1.TraceServiceClient] = None
def _get_trace_client() -> trace_v1.TraceServiceClient:
"""Instantiates and caches the TraceServiceClient."""
global _trace_client
if _trace_client is None:
_trace_client = trace_v1.TraceServiceClient()
return _trace_client
class TraceExample:
"""Holds distilled trace metrics."""
def __init__(
self,
trace_id: str,
earliest_timestamp: Optional[str],
last_timestamp: Optional[str],
duration_seconds: float,
num_spans: int,
unique_services: List[str],
unique_attribute_keys: List[str],
longest_non_root_span_duration_seconds: float,
num_error_spans: int,
errors: List[Dict[str, Any]],
):
self.trace_id = trace_id
self.earliest_timestamp = earliest_timestamp
self.last_timestamp = last_timestamp
self.duration_seconds = duration_seconds
self.num_spans = num_spans
self.unique_services = unique_services
self.unique_attribute_keys = unique_attribute_keys
self.longest_non_root_span_duration_seconds = (
longest_non_root_span_duration_seconds
)
self.num_error_spans = num_error_spans
self.errors = errors
def to_dict(self) -> Dict[str, Any]:
res = {}
omit_fields = {
"unique_services",
"num_spans",
"num_error_spans",
"unique_attribute_keys",
}
for k, v in self.__dict__.items():
if k in omit_fields:
continue
# Omit fields whose values are None or empty lists/sets
if v is not None and v != [] and v != set():
res[k] = v
return res
class TraceCluster:
"""Represents a cluster of traces grouped by service set, spans, and errors."""
def __init__(
self,
services: List[str],
num_spans: int,
num_error_spans: int,
matching_trace_ids: List[str],
unique_attribute_keys: List[str],
examples: List[TraceExample],
):
self.services = services
self.num_spans = num_spans
self.num_error_spans = num_error_spans
self.matching_trace_ids = matching_trace_ids
self.unique_attribute_keys = unique_attribute_keys
self.examples = examples
@property
def total_matching_traces(self) -> int:
return len(self.matching_trace_ids)
@property
def cluster_id(self) -> str:
"""Computes MD5 hash (hex digest) of cluster signature."""
services_str = ",".join(self.services)
canonical = f"services={services_str};num_spans={self.num_spans};num_error_spans={self.num_error_spans}"
return hashlib.md5(canonical.encode("utf-8")).hexdigest()
def to_dict(self) -> Dict[str, Any]:
return {
"cluster_id": self.cluster_id,
"services": self.services,
"unique_attribute_keys": self.unique_attribute_keys,
"num_spans": self.num_spans,
"num_error_spans": self.num_error_spans,
"total_matching_traces": self.total_matching_traces,
"matching_trace_ids": self.matching_trace_ids,
"examples": [e.to_dict() for e in self.examples],
}
def distill_trace(trace: Dict[str, Any]) -> TraceExample:
"""Computes distilled characteristics of a trace."""
trace_id = trace.get("traceId") or trace.get("trace_id") or ""
spans = trace.get("spans", [])
if not spans:
return TraceExample(
trace_id=trace_id,
earliest_timestamp=None,
last_timestamp=None,
duration_seconds=0.0,
num_spans=0,
unique_services=[],
unique_attribute_keys=[],
longest_non_root_span_duration_seconds=0.0,
num_error_spans=0,
errors=[],
)
min_start = None
max_end = None
unique_services = set()
unique_attribute_keys = set()
longest_non_root_span_duration_seconds = 0.0
num_error_spans = 0
errors = []
for span in spans:
start_dt = None
end_dt = None
if "startTime" in span:
try:
start_dt = _get_span_start(span)
if min_start is None or start_dt < min_start:
min_start = start_dt
except Exception:
pass
if "endTime" in span:
try:
end_dt = _get_span_end(span)
if max_end is None or end_dt > max_end:
max_end = end_dt
except Exception:
pass
service_ids = _get_service_identifiers(span)
service_name = _get_canonical_service_name(service_ids)
if service_name:
unique_services.add(service_name)
labels = span.get("labels") or span.get("attributes") or {}
for key in labels.keys():
unique_attribute_keys.add(key)
parent_id = span.get("parentSpanId") or span.get("parent_span_id")
if parent_id is not None and parent_id != 0 and parent_id != "0":
if start_dt and end_dt:
span_dur = (end_dt - start_dt).total_seconds()
if span_dur > longest_non_root_span_duration_seconds:
longest_non_root_span_duration_seconds = span_dur
if is_error_span(span):
num_error_spans += 1
error_labels = _extract_error_labels(span)
service_identifier = service_name or span.get("name") or ""
errors.append({
"span_id": span.get("spanId") or span.get("span_id") or "",
"service": service_identifier,
"service_identifiers": service_ids,
"error_signifying_labels": error_labels,
})
duration_seconds = 0.0
if min_start and max_end:
duration_seconds = (max_end - min_start).total_seconds()
earliest_timestamp_str = None
if min_start:
earliest_timestamp_str = min_start.isoformat().replace("+00:00", "Z")
last_timestamp_str = None
if max_end:
last_timestamp_str = max_end.isoformat().replace("+00:00", "Z")
return TraceExample(
trace_id=trace_id,
earliest_timestamp=earliest_timestamp_str,
last_timestamp=last_timestamp_str,
duration_seconds=duration_seconds,
num_spans=len(spans),
unique_services=sorted(list(unique_services)),
unique_attribute_keys=sorted(list(unique_attribute_keys)),
longest_non_root_span_duration_seconds=longest_non_root_span_duration_seconds,
num_error_spans=num_error_spans,
errors=errors,
)
def search_traces(
projects: List[str],
filter_query: str,
limit: int,
start_time_str: Optional[str] = None,
end_time_str: Optional[str] = None,
examples_per_cluster: int = 3,
) -> Dict[str, Any]:
"""Searches traces, distills them, and groups by unique services."""
# Time range validation: verify the difference does not exceed 7 days
if start_time_str and end_time_str:
start_dt = parse_iso8601(start_time_str)
end_dt = parse_iso8601(end_time_str)
if abs((end_dt - start_dt).total_seconds()) > 604800:
raise ValueError(
"The difference between start_time and end_time cannot exceed 7 days"
" (604800 seconds)."
)
client = _get_trace_client()
start_time = parse_timestamp(start_time_str)
end_time = parse_timestamp(end_time_str)
all_traces = []
search_errors = []
for proj in projects:
try:
req = {
"project_id": proj,
"filter": filter_query,
"page_size": limit,
"order_by": "trace_id",
}
if start_time:
req["start_time"] = start_time
if end_time:
req["end_time"] = end_time
traces_pager = client.list_traces(request=req)
for trace in traces_pager:
all_traces.append(MessageToDict(trace._pb))
except Exception as e:
_logger.warning("Failed to search traces in project %s: %s", proj, e)
search_errors.append((proj, str(e)))
if not all_traces and search_errors:
raise RuntimeError(
f"Trace API query failed for project '{search_errors[0][0]}': {search_errors[0][1]}"
)
retrieved_traces = all_traces[:limit]
clusters_map = {}
for trace in retrieved_traces:
example = distill_trace(trace)
cluster_key = (
frozenset(example.unique_services),
example.num_spans,
example.num_error_spans,
)
if cluster_key not in clusters_map:
clusters_map[cluster_key] = []
clusters_map[cluster_key].append(example)
clusters = []
for cluster_key, examples in clusters_map.items():
services_frozenset, num_spans, num_error_spans = cluster_key
services_list = sorted(list(services_frozenset))
matching_trace_ids = sorted([e.trace_id for e in examples])
unique_keys_set = set()
for e in examples:
unique_keys_set.update(e.unique_attribute_keys)
unique_attribute_keys = sorted(list(unique_keys_set))
clusters.append(
TraceCluster(
services=services_list,
num_spans=num_spans,
num_error_spans=num_error_spans,
matching_trace_ids=matching_trace_ids,
unique_attribute_keys=unique_attribute_keys,
examples=examples,
)
)
# Sort clusters:
# - Rank clusters containing traces with errors higher (sorted by the maximum error spans count of any trace in the cluster descending).
# - Then sort by the maximum latency/duration of any trace in the cluster descending.
# - Finally, sort by the total count of traces in the cluster descending.
clusters.sort(
key=lambda c: (
-c.num_error_spans,
-(max(e.duration_seconds for e in c.examples) if c.examples else 0.0),
-c.total_matching_traces,
)
)
# Cap examples per cluster
for c in clusters:
c.examples = c.examples[:examples_per_cluster]
return {"clusters": [c.to_dict() for c in clusters]}
main_test.py 2.7 KB
import json
import sys
import unittest
from unittest import mock
# Mock trace_v1 dependencies by directly injecting into sys.modules
mock_trace = mock.MagicMock()
mock_trace_v1 = mock.MagicMock()
mock_trace.trace_v1 = mock_trace_v1
sys.modules["google.cloud"] = mock_trace
sys.modules["google.cloud.trace_v1"] = mock_trace_v1
import main
class TestMainCli(unittest.TestCase):
@mock.patch(
"sys.argv",
["main.py", "--filter", "latency:1s", "--projects", "p1", "p2"],
)
@mock.patch("main.search_traces")
def test_main_success(self, mock_search_traces):
mock_search_traces.return_value = {"clusters": []}
with mock.patch("builtins.print") as mock_print:
main.main()
mock_search_traces.assert_called_once_with(
projects=["p1", "p2"],
filter_query="latency:1s",
limit=10,
start_time_str=None,
end_time_str=None,
examples_per_cluster=3,
)
mock_print.assert_called_once()
@mock.patch(
"sys.argv",
[
"main.py",
"--filter",
"latency:1s",
"--projects",
"p1",
"--examples-per-cluster",
"5",
],
)
@mock.patch("main.search_traces")
def test_main_custom_examples_per_cluster(self, mock_search_traces):
mock_search_traces.return_value = {"clusters": []}
with mock.patch("builtins.print") as mock_print:
main.main()
mock_search_traces.assert_called_once_with(
projects=["p1"],
filter_query="latency:1s",
limit=10,
start_time_str=None,
end_time_str=None,
examples_per_cluster=5,
)
mock_print.assert_called_once()
@mock.patch(
"sys.argv", ["main.py", "--filter", "latency:1s", "--projects", "p1"]
)
@mock.patch("main.search_traces")
def test_main_error_propagation(self, mock_search_traces):
mock_search_traces.side_effect = RuntimeError("API error")
with self.assertRaises(RuntimeError):
main.main()
@mock.patch(
"sys.argv",
[
"main.py",
"--filter",
"latency:1s",
"--projects",
"p1",
"--no-wrapper-tag",
],
)
@mock.patch("main.search_traces")
def test_main_no_wrapper_tag(self, mock_search_traces):
mock_search_traces.return_value = {"clusters": []}
with mock.patch("builtins.print") as mock_print:
main.main()
mock_search_traces.assert_called_once_with(
projects=["p1"],
filter_query="latency:1s",
limit=10,
start_time_str=None,
end_time_str=None,
examples_per_cluster=3,
)
mock_print.assert_called_once_with(json.dumps({"clusters": []}, indent=2))
if __name__ == "__main__":
unittest.main()
timestamp_utils_test.py 1.7 KB
import unittest
from google.protobuf.timestamp_pb2 import Timestamp
import timestamp_utils
class TestTimestampUtils(unittest.TestCase):
def test_parse_timestamp_valid(self):
ts = timestamp_utils.parse_timestamp("2026-06-25T13:00:00Z")
self.assertIsNotNone(ts)
self.assertIsInstance(ts, Timestamp)
self.assertEqual(ts.seconds, 1782392400)
def test_parse_timestamp_invalid(self):
with self.assertRaises(ValueError):
timestamp_utils.parse_timestamp("invalid-date")
def test_parse_iso8601(self):
dt = timestamp_utils.parse_iso8601("2026-06-25T13:00:00Z")
self.assertEqual(dt.year, 2026)
self.assertEqual(dt.month, 6)
self.assertEqual(dt.day, 25)
self.assertEqual(dt.hour, 13)
def test_to_datetime_datetime(self):
from datetime import datetime, timezone
dt = datetime(2026, 6, 25, 13, 0, 0)
res = timestamp_utils.to_datetime(dt)
self.assertEqual(res.tzinfo, timezone.utc)
dt_tz = datetime(2026, 6, 25, 13, 0, 0, tzinfo=timezone.utc)
res_tz = timestamp_utils.to_datetime(dt_tz)
self.assertEqual(res_tz, dt_tz)
def test_to_datetime_str(self):
from datetime import datetime, timezone
res = timestamp_utils.to_datetime("2026-06-25T13:00:00Z")
self.assertEqual(res.year, 2026)
self.assertEqual(res.tzinfo, timezone.utc)
def test_to_datetime_dict(self):
from datetime import datetime, timezone
res = timestamp_utils.to_datetime(
{"seconds": 1782392400, "nanos": 500000000}
)
self.assertEqual(res.year, 2026)
self.assertEqual(res.second, 0)
self.assertEqual(res.microsecond, 500000)
def test_to_datetime_invalid(self):
with self.assertRaises(ValueError):
timestamp_utils.to_datetime(123456)
if __name__ == "__main__":
unittest.main()
trace_searcher_test.py 17.4 KB
import hashlib
import sys
import unittest
from unittest import mock
# Mock trace_v1 dependencies by directly injecting into sys.modules
mock_trace = mock.MagicMock()
mock_trace_v1 = mock.MagicMock()
mock_trace.trace_v1 = mock_trace_v1
sys.modules["google.cloud"] = mock_trace
sys.modules["google.cloud.trace_v1"] = mock_trace_v1
import timestamp_utils
import trace_searcher
class TestTraceSearcher(unittest.TestCase):
def test_get_trace_client_caching(self):
# Verify client is cached
with mock.patch.object(
trace_searcher.trace_v1, "TraceServiceClient"
) as mock_client_class:
mock_client_class.return_value = mock.MagicMock()
# Reset local global cache first
trace_searcher._trace_client = None
client1 = trace_searcher._get_trace_client()
client2 = trace_searcher._get_trace_client()
self.assertIs(client1, client2)
mock_client_class.assert_called_once()
def test_time_range_validation(self):
# Verify difference <= 7 days is OK, > 7 days raises ValueError
with mock.patch.object(
trace_searcher, "_get_trace_client"
) as mock_get_client:
mock_client = mock.MagicMock()
mock_get_client.return_value = mock_client
mock_client.list_traces.return_value = []
# OK: exactly 7 days
trace_searcher.search_traces(
projects=["p"],
filter_query="*",
limit=1,
start_time_str="2026-06-25T13:00:00Z",
end_time_str="2026-07-02T13:00:00Z",
)
# Fails: 7 days and 1 second
with self.assertRaises(ValueError) as ctx:
trace_searcher.search_traces(
projects=["p"],
filter_query="*",
limit=1,
start_time_str="2026-06-25T13:00:00Z",
end_time_str="2026-07-02T13:00:01Z",
)
self.assertIn("cannot exceed 7 days", str(ctx.exception))
def test_get_service_identifiers(self):
# 1. OTel with namespace
span1 = {"labels": {"service.name": "my-svc", "service.namespace": "my-ns"}}
self.assertEqual(
trace_searcher._get_service_identifiers(span1),
{"otel_service_name": "my-svc", "otel_service_namespace": "my-ns"},
)
# 2. OTel without namespace
span2 = {"labels": {"service.name": "my-svc"}}
self.assertEqual(
trace_searcher._get_service_identifiers(span2),
{"otel_service_name": "my-svc"},
)
# 3. GcpAppHub
span3 = {
"labels": {
"gcp.apphub.service.id": "hub-svc",
"gcp.apphub.workload.id": "hub-workload",
}
}
self.assertEqual(
trace_searcher._get_service_identifiers(span3),
{"apphub_service_id": "hub-svc", "apphub_workload_id": "hub-workload"},
)
# 4. GcpMcpServer
span4 = {"labels": {"gcp.mcp.server.id": "mcp-svc"}}
self.assertEqual(
trace_searcher._get_service_identifiers(span4),
{"gcp_mcp_server_id": "mcp-svc"},
)
# 5. Fallback/Empty
span5 = {"labels": {"some-other-label": "val"}}
self.assertEqual(trace_searcher._get_service_identifiers(span5), {})
def test_get_canonical_service_name(self):
self.assertEqual(
trace_searcher._get_canonical_service_name({
"otel_service_name": "my-svc",
"otel_service_namespace": "my-ns",
}),
"my-ns/my-svc",
)
self.assertEqual(
trace_searcher._get_canonical_service_name(
{"otel_service_name": "my-svc"}
),
"my-svc",
)
self.assertEqual(
trace_searcher._get_canonical_service_name(
{"apphub_service_id": "hub-svc"}
),
"hub-svc",
)
self.assertEqual(
trace_searcher._get_canonical_service_name(
{"gcp_mcp_server_id": "mcp-svc"}
),
"mcp-svc",
)
self.assertIsNone(trace_searcher._get_canonical_service_name({}))
def test_distill_trace_all_features(self):
trace = {
"traceId": "trace-999",
"spans": [
{
"spanId": "1",
"startTime": "2026-06-25T13:00:00.100Z",
"endTime": "2026-06-25T13:00:01.200Z",
"labels": {
"/http/status_code": "200",
"env": "prod",
"service.name": "service-a",
},
},
{
"spanId": "2",
"parentSpanId": "1",
"startTime": "2026-06-25T13:00:00.200Z",
"endTime": "2026-06-25T13:00:00.800Z",
"labels": {
"db.type": "mysql",
"gcp.apphub.service.id": "service-b",
},
},
{
"spanId": "3",
"parentSpanId": "1",
"startTime": "2026-06-25T13:00:00.500Z",
"endTime": "2026-06-25T13:00:01.500Z",
"status": {"code": 13, "message": "Failed"},
"labels": {
"foo": "bar",
"gcp.mcp.server.id": "service-c",
},
},
{
"spanId": "4",
"startTime": "2026-06-25T13:00:00.300Z",
"endTime": "2026-06-25T13:00:00.400Z",
"labels": {
"/http/status_code": "500",
"service.name": "service-a",
},
},
],
}
distilled_example = trace_searcher.distill_trace(trace)
self.assertEqual(distilled_example.trace_id, "trace-999")
self.assertEqual(
distilled_example.earliest_timestamp, "2026-06-25T13:00:00.100000Z"
)
self.assertEqual(
distilled_example.last_timestamp, "2026-06-25T13:00:01.500000Z"
)
self.assertAlmostEqual(distilled_example.duration_seconds, 1.4)
self.assertEqual(distilled_example.num_spans, 4)
self.assertEqual(
distilled_example.unique_services,
["service-a", "service-b", "service-c"],
)
self.assertEqual(
distilled_example.unique_attribute_keys,
[
"/http/status_code",
"db.type",
"env",
"foo",
"gcp.apphub.service.id",
"gcp.mcp.server.id",
"service.name",
],
)
self.assertAlmostEqual(
distilled_example.longest_non_root_span_duration_seconds, 1.0
)
self.assertEqual(distilled_example.num_error_spans, 2)
# Verify error details inlined structure
self.assertEqual(len(distilled_example.errors), 2)
err1 = distilled_example.errors[0]
self.assertEqual(err1["span_id"], "3")
self.assertEqual(err1["service"], "service-c")
self.assertEqual(
err1["error_signifying_labels"],
{"status": {"code": 13, "message": "Failed"}},
)
# test leaner to_dict serialization (omit unique_services, num_spans, num_error_spans, unique_attribute_keys)
dist_dict = distilled_example.to_dict()
self.assertEqual(dist_dict["trace_id"], "trace-999")
self.assertNotIn("unique_services", dist_dict)
self.assertNotIn("num_spans", dist_dict)
self.assertNotIn("num_error_spans", dist_dict)
self.assertNotIn("unique_attribute_keys", dist_dict)
self.assertIn("errors", dist_dict)
def test_clustering_and_sorting_rules_updated(self):
# We want to test sorting rules and cluster_id:
# 1. Grouped by service, num_spans, num_error_spans
# 2. Clusters containing traces with errors are ranked higher (sorted by num_error_spans descending)
# 3. Then sort by maximum latency/duration descending
# 4. Finally sort by total count of traces descending
with mock.patch.object(
trace_searcher, "_get_trace_client"
) as mock_get_client:
mock_client = mock.MagicMock()
mock_get_client.return_value = mock_client
t1 = {
"traceId": "t1",
"spans": [{
"startTime": "2026-06-25T13:00:00Z",
"endTime": "2026-06-25T13:00:10Z", # 10s
"labels": {"service.name": "A"},
}],
}
t2 = {
"traceId": "t2",
"spans": [{
"startTime": "2026-06-25T13:00:00Z",
"endTime": "2026-06-25T13:00:05Z", # 5s
"labels": {"service.name": "B"},
"status": {"code": 1}, # error
}],
}
t3a = {
"traceId": "t3a",
"spans": [
{
"startTime": "2026-06-25T13:00:00Z",
"endTime": "2026-06-25T13:00:02Z", # 2s
"labels": {"service.name": "C"},
"status": {"code": 1}, # error
},
{
"startTime": "2026-06-25T13:00:00Z",
"endTime": "2026-06-25T13:00:01Z",
"labels": {"service.name": "C"},
"status": {"code": 2}, # error (total 2 errors, 2 spans)
},
],
}
t3b = {
"traceId": "t3b",
"spans": [{
"startTime": "2026-06-25T13:00:00Z",
"endTime": "2026-06-25T13:00:01Z", # 1s
"labels": {"service.name": "C"}, # 1 span, 0 errors
}],
}
t4 = {
"traceId": "t4",
"spans": [{
"startTime": "2026-06-25T13:00:00Z",
"endTime": "2026-06-25T13:00:20Z", # 20s
"labels": {"service.name": "D"},
}],
}
mock_traces = [mock.MagicMock() for _ in range(5)]
for i, pb in enumerate(mock_traces):
pb._pb = mock.MagicMock()
mock_client.list_traces.return_value = mock_traces
with mock.patch.object(trace_searcher, "MessageToDict") as mock_to_dict:
mock_to_dict.side_effect = [t1, t2, t3a, t3b, t4]
result = trace_searcher.search_traces(
projects=["test-proj"],
filter_query="*",
limit=5,
examples_per_cluster=1,
)
clusters = result["clusters"]
self.assertEqual(len(clusters), 5)
# Expected sorting order:
# 1. Cluster C (spans=2, errors=2) -> max error spans = 2
# 2. Cluster B (spans=1, errors=1) -> max error spans = 1
# 3. Cluster D (spans=1, errors=0, duration=20s) -> max error spans = 0
# 4. Cluster A (spans=1, errors=0, duration=10s) -> max error spans = 0
# 5. Cluster C (spans=1, errors=0, duration=1s) -> max error spans = 0
# Cluster C (spans=2, errors=2)
c0 = clusters[0]
self.assertEqual(c0["services"], ["C"])
self.assertEqual(c0["unique_attribute_keys"], ["service.name"])
self.assertEqual(c0["num_spans"], 2)
self.assertEqual(c0["num_error_spans"], 2)
self.assertEqual(c0["total_matching_traces"], 1)
self.assertEqual(c0["matching_trace_ids"], ["t3a"])
self.assertNotIn("unique_attribute_keys", c0["examples"][0])
expected_cid_c2 = hashlib.md5(
b"services=C;num_spans=2;num_error_spans=2"
).hexdigest()
self.assertEqual(c0["cluster_id"], expected_cid_c2)
# Cluster B
c1 = clusters[1]
self.assertEqual(c1["services"], ["B"])
self.assertEqual(c1["unique_attribute_keys"], ["service.name"])
self.assertEqual(c1["num_spans"], 1)
self.assertEqual(c1["num_error_spans"], 1)
self.assertEqual(c1["matching_trace_ids"], ["t2"])
self.assertNotIn("unique_attribute_keys", c1["examples"][0])
expected_cid_b = hashlib.md5(
b"services=B;num_spans=1;num_error_spans=1"
).hexdigest()
self.assertEqual(c1["cluster_id"], expected_cid_b)
# Cluster D
c2 = clusters[2]
self.assertEqual(c2["services"], ["D"])
self.assertEqual(c2["unique_attribute_keys"], ["service.name"])
self.assertEqual(c2["num_spans"], 1)
self.assertEqual(c2["num_error_spans"], 0)
self.assertEqual(c2["matching_trace_ids"], ["t4"])
self.assertNotIn("unique_attribute_keys", c2["examples"][0])
expected_cid_d = hashlib.md5(
b"services=D;num_spans=1;num_error_spans=0"
).hexdigest()
self.assertEqual(c2["cluster_id"], expected_cid_d)
# Cluster A
c3 = clusters[3]
self.assertEqual(c3["services"], ["A"])
self.assertEqual(c3["unique_attribute_keys"], ["service.name"])
self.assertEqual(c3["num_spans"], 1)
self.assertEqual(c3["num_error_spans"], 0)
self.assertEqual(c3["matching_trace_ids"], ["t1"])
self.assertNotIn("unique_attribute_keys", c3["examples"][0])
expected_cid_a = hashlib.md5(
b"services=A;num_spans=1;num_error_spans=0"
).hexdigest()
self.assertEqual(c3["cluster_id"], expected_cid_a)
# Cluster C (spans=1, errors=0)
c4 = clusters[4]
self.assertEqual(c4["services"], ["C"])
self.assertEqual(c4["unique_attribute_keys"], ["service.name"])
self.assertEqual(c4["num_spans"], 1)
self.assertEqual(c4["num_error_spans"], 0)
self.assertEqual(c4["matching_trace_ids"], ["t3b"])
self.assertNotIn("unique_attribute_keys", c4["examples"][0])
expected_cid_c1 = hashlib.md5(
b"services=C;num_spans=1;num_error_spans=0"
).hexdigest()
self.assertEqual(c4["cluster_id"], expected_cid_c1)
def test_is_error_span_otel_http(self):
# OTel HTTP conventions: status in range [200, 399] is OK
self.assertFalse(
trace_searcher.is_error_span(
{"attributes": {"http.response.status_code": 200}}
)
)
self.assertFalse(
trace_searcher.is_error_span(
{"attributes": {"http.status_code": "302"}}
)
)
self.assertTrue(
trace_searcher.is_error_span(
{"attributes": {"http.response.status_code": 404}}
)
)
self.assertTrue(
trace_searcher.is_error_span({"attributes": {"http.status_code": 500}})
)
self.assertTrue(
trace_searcher.is_error_span(
{"attributes": {"http.response.status_code": 199}}
)
)
# Legacy GCP /http/status_code
self.assertFalse(
trace_searcher.is_error_span({"labels": {"/http/status_code": "200"}})
)
self.assertTrue(
trace_searcher.is_error_span({"labels": {"/http/status_code": "400"}})
)
self.assertTrue(
trace_searcher.is_error_span({"labels": {"/http/status_code": "500"}})
)
def test_is_error_span_otel_grpc(self):
# OTel gRPC conventions
self.assertFalse(
trace_searcher.is_error_span(
{"attributes": {"rpc.grpc.status_code": 0}}
)
)
self.assertTrue(
trace_searcher.is_error_span(
{"attributes": {"rpc.grpc.status_code": 14}}
)
)
# grpc.status
self.assertFalse(
trace_searcher.is_error_span({"attributes": {"grpc.status": "OK"}})
)
self.assertFalse(
trace_searcher.is_error_span({"attributes": {"grpc.status": "0"}})
)
self.assertTrue(
trace_searcher.is_error_span(
{"attributes": {"grpc.status": "UNAVAILABLE"}}
)
)
self.assertTrue(
trace_searcher.is_error_span({"attributes": {"grpc.status": 12}})
)
def test_is_error_span_rpc_system(self):
# rpc.system.name = grpc
self.assertFalse(
trace_searcher.is_error_span({
"attributes": {
"rpc.response.status_code": 0,
"rpc.system.name": "grpc",
}
})
)
self.assertTrue(
trace_searcher.is_error_span({
"attributes": {
"rpc.response.status_code": 14,
"rpc.system.name": "grpc",
}
})
)
# rpc.system.name = http / web-related
self.assertFalse(
trace_searcher.is_error_span({
"attributes": {
"rpc.response.status_code": 200,
"rpc.system.name": "http",
}
})
)
self.assertTrue(
trace_searcher.is_error_span({
"attributes": {
"rpc.response.status_code": 404,
"rpc.system.name": "http",
}
})
)
def test_is_error_span_generic_error_attributes(self):
# error.type or error.message
self.assertFalse(trace_searcher.is_error_span({"attributes": {}}))
self.assertTrue(
trace_searcher.is_error_span(
{"attributes": {"error.type": "RuntimeError"}}
)
)
self.assertTrue(
trace_searcher.is_error_span(
{"attributes": {"error.message": "Something failed"}}
)
)
def test_is_error_span_top_level_status(self):
# status as dictionary representing google.rpc.Status
self.assertFalse(trace_searcher.is_error_span({"status": {"code": 0}}))
self.assertTrue(
trace_searcher.is_error_span(
{"status": {"code": 3, "message": "Invalid argument"}}
)
)
# status as string
self.assertFalse(trace_searcher.is_error_span({"status": "OK"}))
self.assertFalse(trace_searcher.is_error_span({"status": "0"}))
self.assertTrue(trace_searcher.is_error_span({"status": "CANCELLED"}))
def test_extract_error_labels_generalized(self):
span = {
"attributes": {
"http.response.status_code": 500,
"error.message": "Server Error",
"some.other.attribute": "val",
}
}
extracted = trace_searcher._extract_error_labels(span)
self.assertEqual(extracted.get("http.response.status_code"), 500)
self.assertEqual(extracted.get("error.message"), "Server Error")
self.assertNotIn("some.other.attribute", extracted)
if __name__ == "__main__":
unittest.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