orbee 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
orbee/__init__.py ADDED
@@ -0,0 +1 @@
1
+ """Orbee: understand your Google Cloud platform, across projects."""
orbee/__main__.py ADDED
@@ -0,0 +1,3 @@
1
+ from orbee.cli import app
2
+
3
+ app(prog_name="orbee")
File without changes
@@ -0,0 +1,54 @@
1
+ """Reads a Cloud Audit Logs payload, whichever form the Cloud Logging client hands it over in."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Mapping
6
+ from dataclasses import dataclass
7
+ from typing import Any
8
+
9
+ from google.cloud.audit.audit_log_pb2 import AuditLog
10
+ from google.protobuf.any_pb2 import Any as AnyProto
11
+
12
+
13
+ @dataclass(frozen=True, slots=True)
14
+ class AuditFields:
15
+ service: str | None = None
16
+ method: str | None = None
17
+ resource: str | None = None
18
+ actor: str | None = None
19
+ status_code: int = 0
20
+ status_message: str = ""
21
+
22
+
23
+ def audit_fields(payload: Any) -> AuditFields:
24
+ """The fields Orbee reads from an AuditLog.
25
+
26
+ The client hands over a dict, or the raw `Any` when the AuditLog nests a message of a type it
27
+ cannot decode (an IAM CreateRole request, the AuditData of a BigQuery job): that one is
28
+ unpacked as an AuditLog, its own fields are always known.
29
+ """
30
+ if isinstance(payload, AnyProto):
31
+ audit_log = AuditLog()
32
+ if not payload.Unpack(audit_log):
33
+ return AuditFields()
34
+ return AuditFields(
35
+ service=audit_log.service_name or None,
36
+ method=audit_log.method_name or None,
37
+ resource=audit_log.resource_name or None,
38
+ actor=audit_log.authentication_info.principal_email or None,
39
+ status_code=audit_log.status.code,
40
+ status_message=audit_log.status.message,
41
+ )
42
+ if not isinstance(payload, Mapping):
43
+ return AuditFields()
44
+ authentication = payload.get("authenticationInfo")
45
+ status = payload.get("status")
46
+ status = status if isinstance(status, Mapping) else {}
47
+ return AuditFields(
48
+ service=payload.get("serviceName"),
49
+ method=payload.get("methodName"),
50
+ resource=payload.get("resourceName"),
51
+ actor=authentication.get("principalEmail") if isinstance(authentication, Mapping) else None,
52
+ status_code=int(status.get("code") or 0),
53
+ status_message=str(status.get("message") or ""),
54
+ )
@@ -0,0 +1,14 @@
1
+ """Turns Google API errors into short reasons a person can act on."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+
7
+ from google.api_core.exceptions import GoogleAPICallError
8
+
9
+ _REST_PREFIX = re.compile(r"^(GET|POST|PUT|PATCH|DELETE) \S+: ")
10
+
11
+
12
+ def reason(exc: GoogleAPICallError) -> str:
13
+ """The API's message without the `POST https://...: ` prefix of REST clients."""
14
+ return _REST_PREFIX.sub("", exc.message or str(exc))
@@ -0,0 +1,131 @@
1
+ """Admin Activity audit logs exported by the org-setup aggregated log sink (terraform/modules/org-setup).
2
+
3
+ With partitioned tables, the sink writes every Admin Activity entry of the organization (or
4
+ folder) to a single table partitioned on `timestamp`: one query covers every project.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from datetime import datetime
10
+
11
+ from google.api_core.exceptions import Forbidden, GoogleAPICallError, NotFound
12
+ from google.cloud import bigquery
13
+
14
+ from orbee.adapters._errors import reason
15
+ from orbee.core.changes import ACTIVITY_TABLE, NO_FILTER, NOT_CHANGES, ChangeEvent, ChangeFilter
16
+ from orbee.core.errors import SourceUnavailableError
17
+ from orbee.core.scope import Scope
18
+
19
+ QueryParameter = bigquery.ScalarQueryParameter | bigquery.ArrayQueryParameter
20
+
21
+ _CHANGES_SQL = """
22
+ SELECT
23
+ timestamp,
24
+ REGEXP_EXTRACT(logName, r'^([a-zA-Z]+/[^/]+)/logs/') AS container,
25
+ protopayload_auditlog.serviceName AS service,
26
+ protopayload_auditlog.methodName AS method,
27
+ protopayload_auditlog.resourceName AS resource_name,
28
+ protopayload_auditlog.authenticationInfo.principalEmail AS actor,
29
+ insertId AS log_entry_id
30
+ FROM `{table}`
31
+ WHERE timestamp >= @since
32
+ AND timestamp < @until
33
+ AND protopayload_auditlog.methodName NOT IN UNNEST(@not_changes)
34
+ AND (@method IS NULL OR STRPOS(LOWER(protopayload_auditlog.methodName), LOWER(@method)) > 0)
35
+ AND (@resource IS NULL OR STRPOS(LOWER(protopayload_auditlog.resourceName), LOWER(@resource)) > 0)
36
+ AND (@actor IS NULL OR STRPOS(
37
+ LOWER(protopayload_auditlog.authenticationInfo.principalEmail), LOWER(@actor)
38
+ ) > 0)
39
+ AND (ARRAY_LENGTH(@projects) = 0 OR REGEXP_EXTRACT(logName, r'^projects/([^/]+)/') IN UNNEST(@projects))
40
+ ORDER BY timestamp DESC
41
+ LIMIT @limit
42
+ """
43
+
44
+
45
+ _LAST_CHANGE_SQL = """
46
+ SELECT
47
+ REGEXP_EXTRACT(logName, r'^projects/([^/]+)/') AS project_id,
48
+ MAX(timestamp) AS last_change
49
+ FROM `{table}`
50
+ WHERE timestamp >= @since
51
+ AND timestamp < @until
52
+ AND protopayload_auditlog.methodName NOT IN UNNEST(@not_changes)
53
+ GROUP BY project_id
54
+ HAVING project_id IS NOT NULL
55
+ """
56
+
57
+
58
+ def build_last_change_query(table: str, scope: Scope) -> tuple[str, list[QueryParameter]]:
59
+ parameters: list[QueryParameter] = [
60
+ bigquery.ScalarQueryParameter("since", "TIMESTAMP", scope.since),
61
+ bigquery.ScalarQueryParameter("until", "TIMESTAMP", scope.until),
62
+ bigquery.ArrayQueryParameter("not_changes", "STRING", list(NOT_CHANGES)),
63
+ ]
64
+ return _LAST_CHANGE_SQL.format(table=table), parameters
65
+
66
+
67
+ def build_changes_query(
68
+ table: str, scope: Scope, limit: int, match: ChangeFilter = NO_FILTER
69
+ ) -> tuple[str, list[QueryParameter]]:
70
+ parameters: list[QueryParameter] = [
71
+ bigquery.ScalarQueryParameter("since", "TIMESTAMP", scope.since),
72
+ bigquery.ScalarQueryParameter("until", "TIMESTAMP", scope.until),
73
+ bigquery.ArrayQueryParameter("projects", "STRING", sorted(scope.projects)),
74
+ bigquery.ScalarQueryParameter("limit", "INT64", limit),
75
+ bigquery.ArrayQueryParameter("not_changes", "STRING", list(NOT_CHANGES)),
76
+ bigquery.ScalarQueryParameter("method", "STRING", match.method),
77
+ bigquery.ScalarQueryParameter("resource", "STRING", match.resource),
78
+ bigquery.ScalarQueryParameter("actor", "STRING", match.actor),
79
+ ]
80
+ return _CHANGES_SQL.format(table=table), parameters
81
+
82
+
83
+ class BigQueryAuditEventSource:
84
+ def __init__(self, client: bigquery.Client, project: str, dataset: str, max_bytes_billed: int) -> None:
85
+ self._client = client
86
+ self._dataset = f"{project}.{dataset}"
87
+ self._table = f"{self._dataset}.{ACTIVITY_TABLE}"
88
+ self._max_bytes_billed = max_bytes_billed
89
+
90
+ @property
91
+ def description(self) -> str:
92
+ return f"BigQuery {self._dataset} (Admin Activity audit logs; without {', '.join(NOT_CHANGES)})"
93
+
94
+ def list_changes(
95
+ self, scope: Scope, limit: int, parent: str | None = None, match: ChangeFilter = NO_FILTER
96
+ ) -> list[ChangeEvent]:
97
+ # The sink exports the parent's own entries with its projects': `parent` adds nothing.
98
+ return [_to_event(row) for row in self._query(*build_changes_query(self._table, scope, limit, match))]
99
+
100
+ def last_change_per_project(self, scope: Scope) -> dict[str, datetime]:
101
+ rows = self._query(*build_last_change_query(self._table, scope))
102
+ return {row["project_id"]: row["last_change"] for row in rows}
103
+
104
+ def _query(self, sql: str, parameters: list[QueryParameter]) -> list[bigquery.Row]:
105
+ job_config = bigquery.QueryJobConfig(query_parameters=parameters, maximum_bytes_billed=self._max_bytes_billed)
106
+ try:
107
+ return list(self._client.query(sql, job_config=job_config).result())
108
+ except NotFound as exc:
109
+ # The sink creates the table with the first exported entry, minutes after it is applied.
110
+ raise SourceUnavailableError(
111
+ f"{self._table} not found: is the org-setup module applied, and has the sink exported any entry yet?"
112
+ ) from exc
113
+ except Forbidden as exc:
114
+ raise SourceUnavailableError(
115
+ f"no access to {self._dataset}: you need roles/bigquery.dataViewer on it "
116
+ "and roles/bigquery.jobUser on its project"
117
+ ) from exc
118
+ except GoogleAPICallError as exc:
119
+ raise SourceUnavailableError(f"BigQuery query on {self._table} failed: {reason(exc)}") from exc
120
+
121
+
122
+ def _to_event(row: bigquery.Row) -> ChangeEvent:
123
+ return ChangeEvent(
124
+ timestamp=row["timestamp"],
125
+ container=row["container"] or "unknown",
126
+ service=row["service"] or "unknown",
127
+ method=row["method"] or "unknown",
128
+ resource_name=row["resource_name"] or "",
129
+ actor=row["actor"],
130
+ log_entry_id=row["log_entry_id"],
131
+ )
@@ -0,0 +1,116 @@
1
+ """IAM bindings of a whole organization or folder from Cloud Asset Inventory: one search, no per-project call.
2
+
3
+ `searchAllIamPolicies` returns the policy of every resource below the scope that has one: the
4
+ organization, folders, projects and resources such as buckets, datasets or secrets. The query
5
+ narrows the policies at the source; the bindings are then filtered exactly with AccessFilter.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from collections.abc import Callable
11
+ from functools import cache
12
+ from typing import Any
13
+
14
+ from google.api_core.exceptions import Forbidden, GoogleAPICallError, InvalidArgument, NotFound
15
+
16
+ from orbee.adapters._errors import reason
17
+ from orbee.core.access import AccessFilter, Binding
18
+ from orbee.core.errors import SourceUnavailableError
19
+
20
+ _PAGE_SIZE = 500
21
+
22
+
23
+ def build_policy_query(match: AccessFilter) -> str:
24
+ """Cloud Asset query: `policy:` searches members and roles, `resource:` the resource name."""
25
+ terms = [f"policy:{_quote(value)}" for value in (match.member, match.role) if value is not None]
26
+ if match.resource is not None:
27
+ terms.append(f"resource:{_quote(match.resource)}")
28
+ return " AND ".join(terms)
29
+
30
+
31
+ class CloudAssetIamPolicySource:
32
+ """`search` is AssetServiceClient.search_all_iam_policies; `projects` lists (number, id) pairs."""
33
+
34
+ def __init__(
35
+ self,
36
+ search: Callable[..., Any],
37
+ projects: Callable[[], list[tuple[str, str]]],
38
+ organization_domain: Callable[[str], str | None],
39
+ ) -> None:
40
+ self._search = search
41
+ self._projects = cache(lambda: dict(projects()))
42
+ self._organization_domain = organization_domain
43
+
44
+ @property
45
+ def description(self) -> str:
46
+ return "Cloud Asset Inventory (IAM policies of the organization, folders, projects and resources)"
47
+
48
+ def search_bindings(self, parent: str, match: AccessFilter, limit: int) -> list[Binding]:
49
+ bindings: list[Binding] = []
50
+ # A resource indexed under two asset types (Cloud Functions gen1 and gen2) comes back twice.
51
+ seen: set[tuple[str, str, str, str | None]] = set()
52
+ try:
53
+ results = self._search(
54
+ request={"scope": parent, "query": build_policy_query(match), "page_size": _PAGE_SIZE}
55
+ )
56
+ for result in results:
57
+ for binding in self._bindings(result):
58
+ key = (binding.resource, binding.role, binding.member, binding.condition)
59
+ if key in seen:
60
+ continue
61
+ seen.add(key)
62
+ if match.matches(binding):
63
+ bindings.append(binding)
64
+ if len(bindings) >= limit:
65
+ return bindings
66
+ except Forbidden as exc:
67
+ raise SourceUnavailableError(
68
+ f"cannot search the IAM policies under {parent}: you need cloudasset.assets.searchAllIamPolicies "
69
+ f"(roles/cloudasset.viewer) on it, and the Cloud Asset API enabled on ORBEE_PROJECT ({reason(exc)})"
70
+ ) from exc
71
+ except (NotFound, InvalidArgument) as exc:
72
+ raise SourceUnavailableError(f"cannot search the IAM policies under {parent}: {reason(exc)}") from exc
73
+ except GoogleAPICallError as exc:
74
+ raise SourceUnavailableError(f"Cloud Asset Inventory search failed: {reason(exc)}") from exc
75
+ return bindings
76
+
77
+ def internal_domains(self, parent: str) -> frozenset[str]:
78
+ try:
79
+ domain = self._organization_domain(parent)
80
+ except GoogleAPICallError:
81
+ return frozenset()
82
+ return frozenset({domain.lower()}) if domain else frozenset()
83
+
84
+ def _bindings(self, result: Any) -> list[Binding]:
85
+ project_id = self._project_id(result.project)
86
+ return [
87
+ Binding(
88
+ resource=result.resource,
89
+ asset_type=result.asset_type,
90
+ project_id=project_id,
91
+ role=binding.role,
92
+ member=member,
93
+ condition=_condition(binding),
94
+ )
95
+ for binding in result.policy.bindings
96
+ for member in binding.members
97
+ ]
98
+
99
+ def _project_id(self, project: str) -> str | None:
100
+ """`projects/123456` → its project ID; the number itself when the project is not listed."""
101
+ if not project:
102
+ return None
103
+ number = project.removeprefix("projects/")
104
+ return self._projects().get(number, number)
105
+
106
+
107
+ def _condition(binding: Any) -> str | None:
108
+ condition = binding.condition
109
+ if condition is None or not (condition.title or condition.expression):
110
+ return None
111
+ return condition.title or condition.expression
112
+
113
+
114
+ def _quote(value: str) -> str:
115
+ escaped = value.replace("\\", "\\\\").replace('"', '\\"')
116
+ return f'"{escaped}"'
@@ -0,0 +1,313 @@
1
+ """Workload errors read from Cloud Logging at the source, nothing copied: Cloud Run, Cloud Composer, BigQuery.
2
+
3
+ One call covers every product and a batch of projects. Cloud Run writes 5xx request logs at ERROR,
4
+ and its container failures (crash, memory limit, startup probe) to `run.googleapis.com/varlog/system`;
5
+ Composer writes every Airflow component, task logs labelled with the DAG, task, run and try.
6
+ BigQuery writes a Data Access audit entry at ERROR for a job that fails (`jobservice.jobcompleted`)
7
+ or is refused when submitted (`JobService.InsertJob`); these logs are on by default.
8
+ Cloud Logging bills no read: the bound is the number of entries read (`limit`).
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from collections import Counter
14
+ from collections.abc import Callable, Mapping, Sequence
15
+ from concurrent.futures import ThreadPoolExecutor
16
+ from datetime import UTC, datetime
17
+ from typing import Any
18
+ from urllib.parse import unquote, urlsplit
19
+
20
+ from google.api_core.exceptions import Forbidden, GoogleAPICallError, NotFound
21
+ from google.cloud import logging
22
+
23
+ from orbee.adapters._audit_log import audit_fields
24
+ from orbee.adapters._errors import reason
25
+ from orbee.core.errors import SourceUnavailableError
26
+ from orbee.core.failures import (
27
+ BIGQUERY,
28
+ CLOUD_RUN,
29
+ COMPOSER,
30
+ Failure,
31
+ FailureKind,
32
+ FailureRead,
33
+ TaskRef,
34
+ UnreachableProject,
35
+ cloud_run_kind,
36
+ composer_kind,
37
+ )
38
+
39
+ COMPOSER_LOGS = ("airflow-worker", "airflow-scheduler", "airflow-triggerer", "airflow-dag-processor-manager")
40
+ _COMPOSER_RESOURCE = "cloud_composer_environment"
41
+ _CLOUD_RUN_RESOURCES = ("cloud_run_revision", "cloud_run_job")
42
+ _EXECUTION_LABEL = "run.googleapis.com/execution_name"
43
+ _DATA_ACCESS_LOG = "cloudaudit.googleapis.com/data_access"
44
+ _BIGQUERY_RESOURCES = ("bigquery_resource", "bigquery_project")
45
+ _BIGQUERY_JOB_METHODS = ("jobservice.jobcompleted", "google.cloud.bigquery.v2.JobService.InsertJob")
46
+ """The entries of a failed job. `jobservice.getqueryresults` repeats each failure of a query: left out."""
47
+ _MAX_PAGE_SIZE = 1000
48
+ _LIST_PERMISSION = "logging.logEntries.list"
49
+
50
+ IamTester = Callable[[str, list[str]], list[str]]
51
+ """(project, permissions) → the permissions the caller holds on the project."""
52
+
53
+
54
+ def build_failures_filter(since: datetime, until: datetime) -> str:
55
+ """Logging query: errors of Cloud Run services and jobs, and of the Airflow components of Composer."""
56
+ composer_logs = " OR ".join(f'log_id("{log}")' for log in COMPOSER_LOGS)
57
+ cloud_run = " OR ".join(f'resource.type="{resource}"' for resource in _CLOUD_RUN_RESOURCES)
58
+ bigquery = " OR ".join(f'resource.type="{resource}"' for resource in _BIGQUERY_RESOURCES)
59
+ jobs = " OR ".join(f'protoPayload.methodName="{method}"' for method in _BIGQUERY_JOB_METHODS)
60
+ return "\n".join(
61
+ [
62
+ "severity>=ERROR",
63
+ f'timestamp>="{_rfc3339(since)}"',
64
+ f'timestamp<"{_rfc3339(until)}"',
65
+ f'((resource.type="{_COMPOSER_RESOURCE}" AND ({composer_logs})) OR {cloud_run}'
66
+ f' OR (log_id("{_DATA_ACCESS_LOG}") AND ({bigquery}) AND ({jobs})))',
67
+ ]
68
+ )
69
+
70
+
71
+ class CloudLoggingFailureSource:
72
+ """Reads the projects in batches: one Cloud Logging call covers up to `batch_size` projects.
73
+
74
+ Access is checked first with testIamPermissions, which is fast and spends no Logging quota.
75
+ When a batch read hits the limit, the noisiest project keeps its entries and is reported as
76
+ truncated, and the batch is read again without it: one noisy service cannot hide the others.
77
+ """
78
+
79
+ def __init__(
80
+ self,
81
+ client: logging.Client,
82
+ iam: IamTester,
83
+ batch_size: int = 50,
84
+ max_rounds: int = 5,
85
+ workers: int = 8,
86
+ ) -> None:
87
+ self._client = client
88
+ self._iam = iam
89
+ self._batch_size = batch_size
90
+ self._max_rounds = max_rounds
91
+ self._workers = workers
92
+
93
+ @property
94
+ def description(self) -> str:
95
+ return (
96
+ "Cloud Logging (Cloud Run services and jobs; Cloud Composer Airflow components; "
97
+ "BigQuery jobs; severity >= ERROR)"
98
+ )
99
+
100
+ def unreadable(self, projects: Sequence[str]) -> dict[str, str]:
101
+ with ThreadPoolExecutor(max_workers=self._workers) as pool:
102
+ reasons = dict(zip(projects, pool.map(self._access_error, projects), strict=True))
103
+ return {project: reason for project, reason in reasons.items() if reason is not None}
104
+
105
+ def read_failures(self, projects: Sequence[str], since: datetime, until: datetime, limit: int) -> FailureRead:
106
+ unreachable = self.unreadable(projects)
107
+ readable = [project for project in projects if project not in unreachable]
108
+ query = build_failures_filter(since, until)
109
+ failures: list[Failure] = []
110
+ truncated: list[str] = []
111
+ for start in range(0, len(readable), self._batch_size):
112
+ batch = readable[start : start + self._batch_size]
113
+ try:
114
+ batch_failures, batch_truncated = self._read_batch(batch, query, limit)
115
+ except SourceUnavailableError as exc:
116
+ unreachable.update(dict.fromkeys(batch, str(exc)))
117
+ continue
118
+ failures += batch_failures
119
+ truncated += batch_truncated
120
+ return FailureRead(
121
+ failures=tuple(failures),
122
+ unreachable=tuple(UnreachableProject(project, reason) for project, reason in sorted(unreachable.items())),
123
+ truncated_projects=tuple(sorted(truncated)),
124
+ )
125
+
126
+ def _read_batch(self, projects: list[str], query: str, limit: int) -> tuple[list[Failure], list[str]]:
127
+ pending, kept, truncated = list(projects), [], []
128
+ for round_number in range(1, self._max_rounds + 1):
129
+ # One extra entry tells a complete read from a cut one.
130
+ failures = [to_failure(entry) for entry in _one_per_job(self._read(pending, query, limit + 1))]
131
+ if len(failures) <= limit:
132
+ return kept + failures, truncated
133
+ if round_number == self._max_rounds or len(pending) == 1:
134
+ return kept + failures[:limit], truncated + pending
135
+ noisiest = Counter(failure.project_id for failure in failures).most_common(1)[0][0]
136
+ kept += [failure for failure in failures[:limit] if failure.project_id == noisiest]
137
+ truncated.append(noisiest)
138
+ pending.remove(noisiest)
139
+ return kept, truncated + pending
140
+
141
+ def _access_error(self, project: str) -> str | None:
142
+ try:
143
+ granted = self._iam(project, [_LIST_PERMISSION])
144
+ except Forbidden:
145
+ granted = []
146
+ except NotFound:
147
+ return f"project {project} not found"
148
+ except GoogleAPICallError as exc:
149
+ return f"checking access to the logs of {project} failed: {reason(exc)}"
150
+ if _LIST_PERMISSION not in granted:
151
+ return f"no access to the logs of {project}: you need roles/logging.viewer on it"
152
+ return None
153
+
154
+ def _read(self, projects: Sequence[str], query: str, limit: int) -> list[Any]:
155
+ names = ", ".join(projects)
156
+ try:
157
+ # Entries are fetched page by page while iterating: errors surface inside list().
158
+ return list(
159
+ self._client.list_entries(
160
+ resource_names=[f"projects/{project}" for project in projects],
161
+ filter_=query,
162
+ order_by=logging.DESCENDING,
163
+ max_results=limit,
164
+ page_size=min(limit, _MAX_PAGE_SIZE),
165
+ )
166
+ )
167
+ except Forbidden as exc:
168
+ raise SourceUnavailableError(f"no access to the logs of {names}: you need roles/logging.viewer") from exc
169
+ except NotFound as exc:
170
+ raise SourceUnavailableError(f"not found: {names}") from exc
171
+ except GoogleAPICallError as exc:
172
+ raise SourceUnavailableError(f"Cloud Logging read failed: {reason(exc)}") from exc
173
+
174
+
175
+ def to_failure(entry: Any) -> Failure:
176
+ """A Cloud Run or Composer log entry (google.cloud.logging LogEntry) as a Failure."""
177
+ project = _resource_labels(entry).get("project_id") or _log_project(entry.log_name)
178
+ resource_type = entry.resource.type if entry.resource else ""
179
+ if resource_type == _COMPOSER_RESOURCE:
180
+ return _composer_failure(project, entry)
181
+ if resource_type in _BIGQUERY_RESOURCES:
182
+ return _bigquery_failure(project, entry)
183
+ return _cloud_run_failure(project, entry)
184
+
185
+
186
+ def _bigquery_failure(project: str, entry: Any) -> Failure:
187
+ fields = audit_fields(entry.payload)
188
+ return Failure(
189
+ timestamp=entry.timestamp,
190
+ project_id=project,
191
+ service=BIGQUERY,
192
+ workload=fields.actor or "unknown",
193
+ location="",
194
+ source_log=_log_id(entry.log_name),
195
+ kind=FailureKind.JOB,
196
+ message=fields.status_message or f"{fields.method or 'job'} failed (code {fields.status_code})",
197
+ log_entry_id=entry.insert_id,
198
+ )
199
+
200
+
201
+ def _one_per_job(entries: list[Any]) -> list[Any]:
202
+ """A job can fail in both BigQuery audit formats (InsertJob and jobcompleted): keep its first entry."""
203
+ seen: set[str] = set()
204
+ kept = []
205
+ for entry in entries:
206
+ job = _bigquery_job(entry)
207
+ if job is not None:
208
+ if job in seen:
209
+ continue
210
+ seen.add(job)
211
+ kept.append(entry)
212
+ return kept
213
+
214
+
215
+ def _bigquery_job(entry: Any) -> str | None:
216
+ """`projects/p/jobs/abc` of a BigQuery job entry, None for any other entry."""
217
+ if entry.resource is None or entry.resource.type not in _BIGQUERY_RESOURCES:
218
+ return None
219
+ resource = audit_fields(entry.payload).resource or ""
220
+ return resource if "/jobs/" in resource else None
221
+
222
+
223
+ def _composer_failure(project: str, entry: Any) -> Failure:
224
+ resource_labels = _resource_labels(entry)
225
+ source_log = _log_id(entry.log_name)
226
+ message = _message(entry.payload)
227
+ task = _task(entry.labels or {})
228
+ return Failure(
229
+ timestamp=entry.timestamp,
230
+ project_id=project,
231
+ service=COMPOSER,
232
+ workload=resource_labels.get("environment_name") or "unknown",
233
+ location=resource_labels.get("location") or "",
234
+ source_log=source_log,
235
+ kind=composer_kind(task, source_log, message),
236
+ message=message,
237
+ log_entry_id=entry.insert_id,
238
+ task=task,
239
+ )
240
+
241
+
242
+ def _cloud_run_failure(project: str, entry: Any) -> Failure:
243
+ resource_labels = _resource_labels(entry)
244
+ source_log = _log_id(entry.log_name)
245
+ execution = (entry.labels or {}).get(_EXECUTION_LABEL)
246
+ request = entry.http_request or {}
247
+ status = request.get("status")
248
+ request_line = _request_line(request) if status else ""
249
+ message = "\n".join(part for part in (request_line, _message(entry.payload)) if part)
250
+ return Failure(
251
+ timestamp=entry.timestamp,
252
+ project_id=project,
253
+ service=CLOUD_RUN,
254
+ workload=resource_labels.get("service_name") or resource_labels.get("job_name") or "unknown",
255
+ location=resource_labels.get("location") or "",
256
+ source_log=source_log,
257
+ kind=cloud_run_kind(source_log, execution),
258
+ message=message,
259
+ log_entry_id=entry.insert_id,
260
+ execution=execution,
261
+ http_status=int(status) if status else None,
262
+ )
263
+
264
+
265
+ def _task(labels: Mapping[str, str]) -> TaskRef | None:
266
+ dag_id, task_id = labels.get("workflow"), labels.get("task-id")
267
+ if not dag_id or not task_id:
268
+ return None
269
+ try_number = labels.get("try-number", "")
270
+ return TaskRef(
271
+ dag_id=dag_id,
272
+ task_id=task_id,
273
+ run=labels.get("run-id") or labels.get("execution-date"),
274
+ try_number=int(try_number) if try_number.isdigit() else None,
275
+ )
276
+
277
+
278
+ def _request_line(request: Mapping[str, Any]) -> str:
279
+ """`HTTP 503 GET /orders/12`: the path without host and query string, which may carry secrets."""
280
+ path = urlsplit(request.get("requestUrl") or "").path or "/"
281
+ return f"HTTP {request['status']} {request.get('requestMethod') or ''} {path}".replace(" ", " ")
282
+
283
+
284
+ def _resource_labels(entry: Any) -> Mapping[str, str]:
285
+ return (entry.resource.labels if entry.resource else None) or {}
286
+
287
+
288
+ def _log_project(log_name: str | None) -> str:
289
+ """`projects/p/logs/...` → `p`."""
290
+ parts = (log_name or "").split("/")
291
+ return parts[1] if len(parts) > 2 and parts[0] == "projects" else "unknown"
292
+
293
+
294
+ def _log_id(log_name: str | None) -> str:
295
+ """`projects/p/logs/run.googleapis.com%2Frequests` → `run.googleapis.com/requests`."""
296
+ if not log_name or "/logs/" not in log_name:
297
+ return "unknown"
298
+ return unquote(log_name.split("/logs/", 1)[1])
299
+
300
+
301
+ def _message(payload: Any) -> str:
302
+ if isinstance(payload, str):
303
+ return payload
304
+ if isinstance(payload, Mapping):
305
+ # Audit logs (a job execution that failed) carry their message in status.message.
306
+ status = payload.get("status")
307
+ status_message = status.get("message") if isinstance(status, Mapping) else None
308
+ return str(payload.get("message") or payload.get("msg") or status_message or dict(payload))
309
+ return "" if payload is None else str(payload)
310
+
311
+
312
+ def _rfc3339(moment: datetime) -> str:
313
+ return moment.astimezone(UTC).isoformat()