Repository navigation
Expand file tree
/
Copy pathmain.py
More file actions
138 lines (111 loc) · 5.35 KB
/
Copy pathmain.py
File metadata and controls
138 lines (111 loc) · 5.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
"""db-replicator: scheduled logical export of one Cloud SQL database to Cloud Storage.
A Cloud Scheduler job publishes to a Pub/Sub topic.
An Eventarc trigger delivers each message here, and this function asks the
Cloud SQL Admin API to export one database to Cloud Storage:
gs://$EXPORT_BUCKET/$EXPORT_DATABASE/<event time>-<event id>.sql.gz
Design notes:
* The export target is fixed by environment variables. The message body is ignored,
so whoever can publish to the topic cannot point the export at another instance
or database.
* The object name comes from the event, not the clock. A redelivered message maps
to the same name, and Cloud SQL fails an export whose file already exists, so a
redelivery never writes a second copy.
* The function waits for the export operation, because Cloud SQL accepts an export
request even when the operation later fails.
* Every failure is written as a structured ERROR log, which an alert policy watches,
and the function then returns normally. Returning an error would make Pub/Sub
redeliver the message (the trigger's subscription retries with backoff for a day),
repeating the failure every few minutes.
"""
from __future__ import annotations
import json
import os
import re
import time
from collections.abc import Callable, Mapping
from datetime import UTC, datetime
from typing import Any
import functions_framework
from googleapiclient import discovery
COMPONENT = "db-replicator"
POLL_INTERVAL_SECONDS = 10
DEFAULT_POLL_TIMEOUT_SECONDS = 480 # headroom under the 540 s function timeout
REQUIRED_SETTINGS = ("EXPORT_PROJECT", "EXPORT_INSTANCE", "EXPORT_DATABASE", "EXPORT_BUCKET")
class ExportError(RuntimeError):
"""Cloud SQL reported that the export operation failed."""
def log(severity: str, message: str, **fields: Any) -> None:
"""Write one structured log line. Cloud Run reads ``severity`` from JSON on stdout."""
entry = {"severity": severity, "message": message, "component": COMPONENT, **fields}
print(json.dumps(entry, default=str), flush=True)
def load_config(environ: Mapping[str, str] = os.environ) -> dict[str, Any]:
missing = [name for name in REQUIRED_SETTINGS if not environ.get(name)]
if missing:
raise ValueError("missing environment variables: " + ", ".join(missing))
return {
"project": environ["EXPORT_PROJECT"],
"instance": environ["EXPORT_INSTANCE"],
"database": environ["EXPORT_DATABASE"],
"bucket": environ["EXPORT_BUCKET"],
"poll_timeout": int(environ.get("EXPORT_POLL_TIMEOUT_SECONDS", DEFAULT_POLL_TIMEOUT_SECONDS)),
}
def event_time(raw: str | None) -> datetime:
"""Parse the CloudEvent ``time`` attribute (RFC 3339). Falls back to now."""
if raw:
try:
parsed = datetime.fromisoformat(raw.replace("Z", "+00:00"))
except ValueError:
parsed = None
if parsed is not None:
return parsed.astimezone(UTC) if parsed.tzinfo else parsed.replace(tzinfo=UTC)
return datetime.now(UTC)
def export_uri(bucket: str, database: str, when: datetime, event_id: str | None) -> str:
safe_id = re.sub(r"[^A-Za-z0-9_-]", "", event_id or "") or "no-event-id"
return f"gs://{bucket}/{database}/{when:%Y-%m-%dT%H%M%SZ}-{safe_id}.sql.gz"
def build_client() -> Any:
"""Cloud SQL Admin API client, authenticated as the function's service account."""
return discovery.build("sqladmin", "v1", cache_discovery=False)
def run_export(
client: Any,
config: Mapping[str, Any],
uri: str,
*,
sleep: Callable[[float], None] = time.sleep,
monotonic: Callable[[], float] = time.monotonic,
) -> dict[str, Any]:
"""Start the export and wait for it. Returns the last operation seen."""
body = {"exportContext": {"fileType": "SQL", "uri": uri, "databases": [config["database"]]}}
operation = (
client.instances().export(project=config["project"], instance=config["instance"], body=body).execute()
)
log("INFO", "EXPORT_STARTED", uri=uri, operation=operation.get("name"))
deadline = monotonic() + config["poll_timeout"]
while operation.get("status") != "DONE":
if monotonic() >= deadline:
return operation
sleep(POLL_INTERVAL_SECONDS)
operation = client.operations().get(project=config["project"], operation=operation["name"]).execute()
errors = (operation.get("error") or {}).get("errors") or []
if errors:
raise ExportError("; ".join(f"{e.get('code')}: {e.get('message')}" for e in errors))
return operation
@functions_framework.cloud_event
def main(cloud_event: Any) -> None:
event_id = cloud_event.get("id")
try:
config = load_config()
uri = export_uri(config["bucket"], config["database"], event_time(cloud_event.get("time")), event_id)
operation = run_export(build_client(), config, uri)
except Exception as exc: # noqa: BLE001 - every failure must reach the alerted log line
log("ERROR", "EXPORT_FAILED", error=f"{type(exc).__name__}: {exc}", event_id=event_id)
return
if operation.get("status") == "DONE":
log("INFO", "EXPORT_SUCCEEDED", uri=uri, operation=operation.get("name"), event_id=event_id)
else:
log(
"WARNING",
"EXPORT_STILL_RUNNING",
uri=uri,
operation=operation.get("name"),
event_id=event_id,
waited_seconds=config["poll_timeout"],
)