intentdataflow 0.3.10__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.
- intentdataflow-0.3.10.dist-info/METADATA +191 -0
- intentdataflow-0.3.10.dist-info/RECORD +83 -0
- intentdataflow-0.3.10.dist-info/WHEEL +5 -0
- intentdataflow-0.3.10.dist-info/entry_points.txt +2 -0
- intentdataflow-0.3.10.dist-info/licenses/LICENSE +202 -0
- intentdataflow-0.3.10.dist-info/licenses/NOTICE +4 -0
- intentdataflow-0.3.10.dist-info/top_level.txt +1 -0
- intentflow/__init__.py +2 -0
- intentflow/auth.py +30 -0
- intentflow/business_rules.py +77 -0
- intentflow/catalogs.py +100 -0
- intentflow/change_review.py +331 -0
- intentflow/checks/__init__.py +92 -0
- intentflow/checks/airflow3.py +174 -0
- intentflow/checks/business.py +27 -0
- intentflow/checks/catalog.py +43 -0
- intentflow/checks/cluster.py +81 -0
- intentflow/checks/contracts.py +79 -0
- intentflow/checks/cost.py +35 -0
- intentflow/checks/dbt_quality.py +90 -0
- intentflow/checks/dbt_run.py +83 -0
- intentflow/checks/deep.py +180 -0
- intentflow/checks/dq.py +53 -0
- intentflow/checks/elementary.py +50 -0
- intentflow/checks/external.py +91 -0
- intentflow/checks/lakehouse.py +46 -0
- intentflow/checks/lint.py +81 -0
- intentflow/checks/orchestration.py +148 -0
- intentflow/checks/probes.py +66 -0
- intentflow/checks/runtime_history.py +94 -0
- intentflow/checks/schema_drift.py +92 -0
- intentflow/checks/sql_quality.py +274 -0
- intentflow/checks/streaming.py +62 -0
- intentflow/cli.py +914 -0
- intentflow/contracts.py +107 -0
- intentflow/datadiff.py +172 -0
- intentflow/dbt_loader.py +194 -0
- intentflow/dbt_results.py +55 -0
- intentflow/dq_results.py +108 -0
- intentflow/extensions.py +51 -0
- intentflow/external.py +381 -0
- intentflow/http_utils.py +89 -0
- intentflow/i18n.py +76 -0
- intentflow/incidents.py +83 -0
- intentflow/integrations.py +139 -0
- intentflow/lakehouse.py +62 -0
- intentflow/lineage.py +336 -0
- intentflow/lineage_api.py +244 -0
- intentflow/lineage_oracle.py +374 -0
- intentflow/locale/pt.json +1300 -0
- intentflow/model.py +43 -0
- intentflow/monitoring.py +197 -0
- intentflow/notify.py +154 -0
- intentflow/ol_emit.py +93 -0
- intentflow/openlineage.py +168 -0
- intentflow/orchestrators/__init__.py +53 -0
- intentflow/orchestrators/airflow.py +69 -0
- intentflow/orchestrators/aws.py +93 -0
- intentflow/orchestrators/dagster.py +48 -0
- intentflow/orchestrators/dbtcloud.py +68 -0
- intentflow/orchestrators/extra.py +135 -0
- intentflow/orchestrators/ingestion.py +112 -0
- intentflow/orchestrators/kestra.py +27 -0
- intentflow/orchestrators/more.py +135 -0
- intentflow/orchestrators/prefect.py +53 -0
- intentflow/orchestrators/spark.py +118 -0
- intentflow/otel.py +53 -0
- intentflow/overview.py +123 -0
- intentflow/preflight.py +363 -0
- intentflow/promexport.py +39 -0
- intentflow/pyflow.py +554 -0
- intentflow/risks.py +178 -0
- intentflow/runner.py +264 -0
- intentflow/secrets_box.py +84 -0
- intentflow/sqlmesh_loader.py +134 -0
- intentflow/store.py +1006 -0
- intentflow/streaming.py +115 -0
- intentflow/totp.py +38 -0
- intentflow/warehouses/__init__.py +190 -0
- intentflow/warehouses/cloud.py +160 -0
- intentflow/warehouses/more.py +342 -0
- intentflow/web.html +878 -0
- intentflow/web.py +726 -0
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"""Read-only collectors for orchestrators. They normalize runs into `Run`."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from ..i18n import tr
|
|
5
|
+
from ..http_utils import urlopen as _urlopen
|
|
6
|
+
|
|
7
|
+
import base64
|
|
8
|
+
import json
|
|
9
|
+
import os
|
|
10
|
+
import urllib.error
|
|
11
|
+
import urllib.request
|
|
12
|
+
from dataclasses import dataclass
|
|
13
|
+
from datetime import datetime, UTC
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass
|
|
17
|
+
class Run:
|
|
18
|
+
system: str # airflow | kestra
|
|
19
|
+
pipeline: str # dag_id | namespace.flow
|
|
20
|
+
run_id: str
|
|
21
|
+
state: str # success | failed | running | queued | other
|
|
22
|
+
start: float | None
|
|
23
|
+
end: float | None
|
|
24
|
+
duration: float | None
|
|
25
|
+
url: str = ""
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def ts(s: str | None) -> float | None:
|
|
29
|
+
if not s:
|
|
30
|
+
return None
|
|
31
|
+
try:
|
|
32
|
+
d = datetime.fromisoformat(s.replace("Z", "+00:00"))
|
|
33
|
+
except ValueError:
|
|
34
|
+
return None
|
|
35
|
+
if d.tzinfo is None: # no time zone (e.g. Mage) = UTC; `timestamp()` of a naive datetime would use the local zone
|
|
36
|
+
d = d.replace(tzinfo=UTC)
|
|
37
|
+
return d.timestamp()
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def http_json(url: str, headers: dict | None = None, timeout: float = 15.0):
|
|
41
|
+
req = urllib.request.Request(url, headers={"Accept": "application/json", **(headers or {})})
|
|
42
|
+
try:
|
|
43
|
+
with _urlopen(req, timeout=timeout) as r:
|
|
44
|
+
return json.loads(r.read().decode() or "null")
|
|
45
|
+
except urllib.error.HTTPError as e:
|
|
46
|
+
raise RuntimeError(tr("HTTP {code} at {url}", code=e.code, url=url.split("?")[0])) from None
|
|
47
|
+
except urllib.error.URLError as e:
|
|
48
|
+
raise RuntimeError(tr("no connection to {url}: {reason}", url=url.split("?")[0], reason=e.reason)) from None
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def basic(user_env: str, pass_env: str) -> dict:
|
|
52
|
+
u, p = os.environ.get(user_env), os.environ.get(pass_env)
|
|
53
|
+
return {"Authorization": "Basic " + base64.b64encode(f"{u}:{p}".encode()).decode()} if u and p else {}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
"""Airflow through REST. v1 (Airflow 2.x, `/api/v1`, basic auth) or v2 (Airflow 3.x, `/api/v2`, Bearer token).
|
|
2
|
+
|
|
3
|
+
Credentials through environment variables: AIRFLOW_USER/AIRFLOW_PASSWORD or AIRFLOW_TOKEN.
|
|
4
|
+
"""
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
from ..i18n import tr
|
|
8
|
+
from ..http_utils import urlopen as _urlopen
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
import os
|
|
12
|
+
import time
|
|
13
|
+
import urllib.request
|
|
14
|
+
|
|
15
|
+
from . import Run, basic, http_json, ts
|
|
16
|
+
|
|
17
|
+
STATE = {"success": "success", "failed": "failed", "running": "running", "queued": "queued", "up_for_retry": "running",
|
|
18
|
+
"upstream_failed": "failed"}
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class AirflowClient:
|
|
22
|
+
def __init__(self, base_url: str, api: str = "v1", fetch=http_json, login=None):
|
|
23
|
+
self.base, self.api, self.fetch = base_url.rstrip("/"), api, fetch
|
|
24
|
+
self._login, self._jwt = login or self._post_token, None
|
|
25
|
+
|
|
26
|
+
def _post_token(self, user: str, password: str) -> str:
|
|
27
|
+
"""Airflow 3 (simple auth manager / FAB): POST /auth/token exchanges user and password for a JWT."""
|
|
28
|
+
req = urllib.request.Request(f"{self.base}/auth/token", method="POST", data=json.dumps({"username": user, "password": password}).encode(),
|
|
29
|
+
headers={"Content-Type": "application/json", "Accept": "application/json"})
|
|
30
|
+
try:
|
|
31
|
+
with _urlopen(req, timeout=15) as r:
|
|
32
|
+
return json.loads(r.read().decode())["access_token"]
|
|
33
|
+
except Exception as e:
|
|
34
|
+
raise RuntimeError(tr("Airflow 3 login failed at {url}: {error}", url=f"{self.base}/auth/token", error=getattr(e, "code", type(e).__name__))) from None
|
|
35
|
+
|
|
36
|
+
def _h(self) -> dict:
|
|
37
|
+
tok = os.environ.get("AIRFLOW_TOKEN")
|
|
38
|
+
if tok:
|
|
39
|
+
return {"Authorization": f"Bearer {tok}"}
|
|
40
|
+
user, pw = os.environ.get("AIRFLOW_USER"), os.environ.get("AIRFLOW_PASSWORD")
|
|
41
|
+
if self.api == "v2" and user and pw:
|
|
42
|
+
if not self._jwt or time.time() - self._jwt[1] > 1800: # the default token lasts 24 h; renew every 30 min
|
|
43
|
+
self._jwt = (self._login(user, pw), time.time())
|
|
44
|
+
return {"Authorization": f"Bearer {self._jwt[0]}"}
|
|
45
|
+
return basic("AIRFLOW_USER", "AIRFLOW_PASSWORD")
|
|
46
|
+
|
|
47
|
+
def _get(self, path: str):
|
|
48
|
+
return self.fetch(f"{self.base}/api/{self.api}{path}", self._h())
|
|
49
|
+
|
|
50
|
+
def dags(self, limit: int = 100) -> list[dict]:
|
|
51
|
+
return self._get(f"/dags?limit={limit}").get("dags", [])
|
|
52
|
+
|
|
53
|
+
def runs(self, per_dag: int = 10, limit_dags: int = 100) -> list[Run]:
|
|
54
|
+
out: list[Run] = []
|
|
55
|
+
for d in self.dags(limit_dags):
|
|
56
|
+
if d.get("is_paused"):
|
|
57
|
+
continue
|
|
58
|
+
did = d["dag_id"]
|
|
59
|
+
for r in self._get(f"/dags/{did}/dagRuns?order_by=-start_date&limit={per_dag}").get("dag_runs", []):
|
|
60
|
+
s, e = ts(r.get("start_date")), ts(r.get("end_date"))
|
|
61
|
+
out.append(Run("airflow", did, r["dag_run_id"], STATE.get(r.get("state", ""), "other"), s, e,
|
|
62
|
+
(e - s) if s and e else None, f"{self.base}/dags/{did}/grid"))
|
|
63
|
+
return out
|
|
64
|
+
|
|
65
|
+
def pools(self) -> list[dict]:
|
|
66
|
+
return self._get("/pools").get("pools", [])
|
|
67
|
+
|
|
68
|
+
def health(self) -> dict:
|
|
69
|
+
return self.fetch(f"{self.base}/api/{self.api}/health" if self.api == "v1" else f"{self.base}/api/v2/monitor/health", self._h())
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
"""AWS: Glue (job runs), Step Functions (executions) and Athena (queries), read-only, through `boto3` (optional).
|
|
2
|
+
|
|
3
|
+
Credentials: the default boto3 chain (`AWS_*` variables, profile, instance role). Region: `aws.region` / `AWS_REGION`.
|
|
4
|
+
Minimum permissions: glue:ListJobs, glue:GetJobRuns · states:ListStateMachines, states:ListExecutions ·
|
|
5
|
+
athena:ListQueryExecutions, athena:BatchGetQueryExecution (and, for the Athena warehouse, StartQueryExecution/GetQueryResults/GetTableMetadata + output S3).
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from ..i18n import tr
|
|
10
|
+
|
|
11
|
+
import os
|
|
12
|
+
|
|
13
|
+
from . import Run
|
|
14
|
+
|
|
15
|
+
GLUE = {"SUCCEEDED": "success", "FAILED": "failed", "ERROR": "failed", "TIMEOUT": "failed", "STOPPED": "failed", "EXPIRED": "failed",
|
|
16
|
+
"RUNNING": "running", "STOPPING": "running", "STARTING": "queued", "WAITING": "queued"}
|
|
17
|
+
SFN = {"SUCCEEDED": "success", "FAILED": "failed", "TIMED_OUT": "failed", "ABORTED": "failed", "RUNNING": "running", "PENDING_REDRIVE": "queued"}
|
|
18
|
+
ATHENA = {"SUCCEEDED": "success", "FAILED": "failed", "CANCELLED": "failed", "RUNNING": "running", "QUEUED": "queued"}
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def client(service: str, region: str | None = None, endpoint_url: str | None = None):
|
|
22
|
+
try:
|
|
23
|
+
import boto3 # type: ignore
|
|
24
|
+
except ImportError as e:
|
|
25
|
+
raise RuntimeError(tr("install `boto3` (pip install intentdataflow[aws])")) from e
|
|
26
|
+
kw = {"region_name": region or os.environ.get("AWS_REGION") or os.environ.get("AWS_DEFAULT_REGION")}
|
|
27
|
+
if endpoint_url:
|
|
28
|
+
kw["endpoint_url"] = endpoint_url
|
|
29
|
+
return boto3.client(service, **kw)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _ts(d) -> float | None:
|
|
33
|
+
return d.timestamp() if d else None
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class GlueClient:
|
|
37
|
+
def __init__(self, region=None, endpoint_url=None, boto=None):
|
|
38
|
+
self.c = boto or client("glue", region, endpoint_url)
|
|
39
|
+
|
|
40
|
+
def runs(self, jobs: int = 50, per_job: int = 10) -> list[Run]:
|
|
41
|
+
out = []
|
|
42
|
+
names = []
|
|
43
|
+
for page in self.c.get_paginator("list_jobs").paginate():
|
|
44
|
+
names += page.get("JobNames", [])
|
|
45
|
+
if len(names) >= jobs:
|
|
46
|
+
break
|
|
47
|
+
for n in names[:jobs]:
|
|
48
|
+
for r in self.c.get_job_runs(JobName=n, MaxResults=per_job).get("JobRuns", []):
|
|
49
|
+
state = GLUE.get(r.get("JobRunState", ""), "other")
|
|
50
|
+
s, e = _ts(r.get("StartedOn")), _ts(r.get("CompletedOn"))
|
|
51
|
+
done = state in ("success", "failed")
|
|
52
|
+
out.append(Run("glue", n, r["Id"], state, s, e if done else None, (r.get("ExecutionTime") or (e - s if s and e else None)) if done else None,
|
|
53
|
+
f"https://console.aws.amazon.com/gluestudio/home#/job/{n}/run/{r['Id']}"))
|
|
54
|
+
return out
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class StepFunctionsClient:
|
|
58
|
+
def __init__(self, region=None, endpoint_url=None, boto=None):
|
|
59
|
+
self.c = boto or client("stepfunctions", region, endpoint_url)
|
|
60
|
+
|
|
61
|
+
def runs(self, machines: int = 50, per_machine: int = 20) -> list[Run]:
|
|
62
|
+
out = []
|
|
63
|
+
for m in self.c.list_state_machines(maxResults=min(machines, 1000)).get("stateMachines", []):
|
|
64
|
+
for x in self.c.list_executions(stateMachineArn=m["stateMachineArn"], maxResults=per_machine).get("executions", []):
|
|
65
|
+
state = SFN.get(x.get("status", ""), "other")
|
|
66
|
+
s, e = _ts(x.get("startDate")), _ts(x.get("stopDate"))
|
|
67
|
+
done = state in ("success", "failed")
|
|
68
|
+
out.append(Run("stepfunctions", m["name"], x["name"], state, s, e if done else None, (e - s) if done and s and e else None, x.get("executionArn", "")))
|
|
69
|
+
return out
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class AthenaClient:
|
|
73
|
+
"""Athena query executions as runs (per workgroup); `DataScannedInBytes` goes into `scanned_bytes` (cost)."""
|
|
74
|
+
|
|
75
|
+
def __init__(self, region=None, endpoint_url=None, boto=None):
|
|
76
|
+
self.c = boto or client("athena", region, endpoint_url)
|
|
77
|
+
|
|
78
|
+
def runs(self, limit: int = 50) -> list[Run]:
|
|
79
|
+
ids = self.c.list_query_executions(MaxResults=min(limit, 50)).get("QueryExecutionIds", [])
|
|
80
|
+
out = []
|
|
81
|
+
try:
|
|
82
|
+
qes = self.c.batch_get_query_execution(QueryExecutionIds=ids).get("QueryExecutions", []) if ids else []
|
|
83
|
+
except Exception: # without athena:BatchGetQueryExecution (or an emulator without support): query one by one
|
|
84
|
+
qes = [self.c.get_query_execution(QueryExecutionId=i)["QueryExecution"] for i in ids]
|
|
85
|
+
for qe in qes:
|
|
86
|
+
st = qe.get("Status", {})
|
|
87
|
+
state = ATHENA.get(st.get("State", ""), "other")
|
|
88
|
+
s, e = _ts(st.get("SubmissionDateTime")), _ts(st.get("CompletionDateTime"))
|
|
89
|
+
ms = (qe.get("Statistics") or {}).get("EngineExecutionTimeInMillis")
|
|
90
|
+
done = state in ("success", "failed")
|
|
91
|
+
out.append(Run("athena", qe.get("WorkGroup", "primary"), qe["QueryExecutionId"], state, s, e if done else None,
|
|
92
|
+
(ms / 1000 if ms is not None else (e - s if s and e else None)) if done else None, ""))
|
|
93
|
+
return out
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
"""Dagster through GraphQL (`/graphql`): recent runs with state and timings. No credentials by default (OSS)."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from ..i18n import tr
|
|
5
|
+
from ..http_utils import urlopen as _urlopen
|
|
6
|
+
|
|
7
|
+
import json
|
|
8
|
+
import urllib.error
|
|
9
|
+
import urllib.request
|
|
10
|
+
|
|
11
|
+
from . import Run
|
|
12
|
+
|
|
13
|
+
STATE = {"SUCCESS": "success", "FAILURE": "failed", "CANCELED": "failed", "CANCELING": "failed", "STARTED": "running",
|
|
14
|
+
"STARTING": "running", "QUEUED": "queued", "NOT_STARTED": "queued", "MANAGED": "queued"}
|
|
15
|
+
QUERY = """query Runs($limit: Int!) { runsOrError(limit: $limit) { __typename
|
|
16
|
+
... on Runs { results { runId jobName status startTime endTime } }
|
|
17
|
+
... on PythonError { message } } }"""
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _gql(url: str, query: str, variables: dict, timeout: float = 15.0):
|
|
21
|
+
req = urllib.request.Request(url, data=json.dumps({"query": query, "variables": variables}).encode(), method="POST",
|
|
22
|
+
headers={"Content-Type": "application/json"})
|
|
23
|
+
try:
|
|
24
|
+
with _urlopen(req, timeout=timeout) as r:
|
|
25
|
+
return json.loads(r.read().decode())
|
|
26
|
+
except urllib.error.HTTPError as e:
|
|
27
|
+
raise RuntimeError(tr("HTTP {code} at {url}", code=e.code, url=url)) from None
|
|
28
|
+
except urllib.error.URLError as e:
|
|
29
|
+
raise RuntimeError(tr("no connection to {url}: {reason}", url=url, reason=e.reason)) from None
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class DagsterClient:
|
|
33
|
+
def __init__(self, base_url: str, gql=_gql):
|
|
34
|
+
self.url = base_url.rstrip("/") + "/graphql"
|
|
35
|
+
self.base = base_url.rstrip("/")
|
|
36
|
+
self.gql = gql
|
|
37
|
+
|
|
38
|
+
def runs(self, limit: int = 100) -> list[Run]:
|
|
39
|
+
d = self.gql(self.url, QUERY, {"limit": limit})
|
|
40
|
+
r = (d.get("data") or {}).get("runsOrError") or {}
|
|
41
|
+
if r.get("__typename") != "Runs":
|
|
42
|
+
raise RuntimeError(f"Dagster: {r.get('message', d.get('errors', tr('unexpected response')))}")
|
|
43
|
+
out = []
|
|
44
|
+
for x in r["results"]:
|
|
45
|
+
s, e = x.get("startTime"), x.get("endTime")
|
|
46
|
+
out.append(Run("dagster", x["jobName"], x["runId"], STATE.get(x["status"], "other"), s, e,
|
|
47
|
+
(e - s) if s and e else None, f"{self.base}/runs/{x['runId']}"))
|
|
48
|
+
return out
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
"""dbt Cloud (API v2): job runs and the artifacts of the last successful run.
|
|
2
|
+
|
|
3
|
+
Variables: DBT_CLOUD_TOKEN (service token, read-only). Config: `dbt_cloud.host` (default cloud.getdbt.com; use your
|
|
4
|
+
tenant's host), `dbt_cloud.account_id`, `dbt_cloud.job_id` (jobs that produce manifest/catalog/run_results).
|
|
5
|
+
Verification: a local HTTP server with the documented format; never against the real dbt Cloud.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from ..i18n import tr
|
|
10
|
+
|
|
11
|
+
import json
|
|
12
|
+
import os
|
|
13
|
+
import re
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
|
|
16
|
+
from . import Run, http_json, ts
|
|
17
|
+
|
|
18
|
+
STATUS = {1: "queued", 2: "queued", 3: "running", 10: "success", 20: "failed", 30: "failed"}
|
|
19
|
+
ARTIFACTS = ("manifest.json", "catalog.json", "run_results.json")
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _hms(s) -> float | None:
|
|
23
|
+
m = re.fullmatch(r"(\d+):(\d{2}):(\d{2})(?:\.\d+)?", str(s or ""))
|
|
24
|
+
return int(m.group(1)) * 3600 + int(m.group(2)) * 60 + int(m.group(3)) if m else None
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class DbtCloudClient:
|
|
28
|
+
def __init__(self, host: str | None, account_id: str | int, fetch=http_json):
|
|
29
|
+
h = (host or "cloud.getdbt.com").rstrip("/")
|
|
30
|
+
self.base = h if "://" in h else f"https://{h}"
|
|
31
|
+
self.account, self.fetch = str(account_id), fetch
|
|
32
|
+
|
|
33
|
+
def _h(self) -> dict:
|
|
34
|
+
t = os.environ.get("DBT_CLOUD_TOKEN")
|
|
35
|
+
return {"Authorization": f"Token {t}"} if t else {}
|
|
36
|
+
|
|
37
|
+
def _get(self, path: str):
|
|
38
|
+
return self.fetch(f"{self.base}/api/v2/accounts/{self.account}{path}", self._h())
|
|
39
|
+
|
|
40
|
+
def runs(self, limit: int = 100) -> list[Run]:
|
|
41
|
+
data = self._get(f"/runs/?order_by=-id&limit={limit}&include_related=%5B%22job%22%5D") or {}
|
|
42
|
+
out = []
|
|
43
|
+
for r in data.get("data") or []:
|
|
44
|
+
state = STATUS.get(r.get("status"), "other")
|
|
45
|
+
s, e = ts(r.get("started_at")), ts(r.get("finished_at"))
|
|
46
|
+
dur = r.get("run_duration") if isinstance(r.get("run_duration"), (int, float)) else _hms(r.get("duration"))
|
|
47
|
+
name = (r.get("job") or {}).get("name") or f"job-{r.get('job_definition_id')}"
|
|
48
|
+
out.append(Run("dbt_cloud", name, str(r.get("id")), state, s, e if state in ("success", "failed") else None,
|
|
49
|
+
dur if state in ("success", "failed") else None, r.get("href", "")))
|
|
50
|
+
return out
|
|
51
|
+
|
|
52
|
+
def pull_artifacts(self, job_id: str | int, dest: str | Path, run_id: str | int | None = None) -> dict:
|
|
53
|
+
"""Download manifest/catalog/run_results of the job's last successful run (or of `run_id`). `catalog.json` is optional."""
|
|
54
|
+
d = Path(dest)
|
|
55
|
+
d.mkdir(parents=True, exist_ok=True)
|
|
56
|
+
got, missing = [], []
|
|
57
|
+
for name in ARTIFACTS:
|
|
58
|
+
path = f"/runs/{run_id}/artifacts/{name}" if run_id else f"/jobs/{job_id}/artifacts/{name}"
|
|
59
|
+
try:
|
|
60
|
+
doc = self._get(path)
|
|
61
|
+
except RuntimeError as e:
|
|
62
|
+
if name == "manifest.json":
|
|
63
|
+
raise RuntimeError(tr("manifest.json unavailable for job {job}: {error} (the job must produce artifacts)", job=job_id, error=e)) from None
|
|
64
|
+
missing.append(name)
|
|
65
|
+
continue
|
|
66
|
+
(d / name).write_text(json.dumps(doc))
|
|
67
|
+
got.append(name)
|
|
68
|
+
return {"dir": str(d), "files": got, "missing": missing}
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
"""More run sources through REST, normalized into `Run`: Kafka Connect/Debezium, Apache Flink, Luigi, Rundeck, MLflow.
|
|
2
|
+
Each client accepts `fetch(url, headers)` (and `post` where the API requires POST) for tests.
|
|
3
|
+
"""
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
from ..i18n import tr
|
|
7
|
+
from ..http_utils import urlopen as _urlopen
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
import os
|
|
11
|
+
import urllib.request
|
|
12
|
+
|
|
13
|
+
from . import Run, http_json
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _post_json(url: str, body: dict, headers: dict | None = None, timeout: float = 15.0):
|
|
17
|
+
req = urllib.request.Request(url, data=json.dumps(body).encode(), method="POST", headers={"Content-Type": "application/json", **(headers or {})})
|
|
18
|
+
try:
|
|
19
|
+
with _urlopen(req, timeout=timeout) as r:
|
|
20
|
+
return json.loads(r.read().decode() or "null")
|
|
21
|
+
except urllib.error.HTTPError as e:
|
|
22
|
+
raise RuntimeError(tr("HTTP {code} at {url}", code=e.code, url=url.split("?")[0])) from None
|
|
23
|
+
except urllib.error.URLError as e:
|
|
24
|
+
raise RuntimeError(tr("no connection to {url}: {reason}", url=url.split("?")[0], reason=e.reason)) from None
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class KafkaConnectClient:
|
|
28
|
+
"""`GET /connectors?expand=status`: a FAILED connector or one with a FAILED task counts as a failure (CDC stopped)."""
|
|
29
|
+
|
|
30
|
+
def __init__(self, base_url: str, fetch=http_json):
|
|
31
|
+
self.base, self.fetch = base_url.rstrip("/"), fetch
|
|
32
|
+
|
|
33
|
+
def runs(self) -> list[Run]:
|
|
34
|
+
import time
|
|
35
|
+
now = time.time()
|
|
36
|
+
out = []
|
|
37
|
+
for name, info in (self.fetch(f"{self.base}/connectors?expand=status", {}) or {}).items():
|
|
38
|
+
st = info.get("status") or {}
|
|
39
|
+
states = [(st.get("connector") or {}).get("state", "")] + [t.get("state", "") for t in st.get("tasks", [])]
|
|
40
|
+
if any(s == "FAILED" for s in states):
|
|
41
|
+
state = "failed"
|
|
42
|
+
elif all(s == "RUNNING" for s in states if s):
|
|
43
|
+
state = "running"
|
|
44
|
+
else:
|
|
45
|
+
state = "other" # PAUSED/UNASSIGNED/RESTARTING
|
|
46
|
+
out.append(Run("kafka_connect", name, f"{name}:{state}", state, now, now if state == "failed" else None, None,
|
|
47
|
+
f"{self.base}/connectors/{name}/status"))
|
|
48
|
+
return out
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class FlinkClient:
|
|
52
|
+
STATE = {"FINISHED": "success", "FAILED": "failed", "CANCELED": "failed", "CANCELLING": "failed", "SUSPENDED": "failed", "FAILING": "failed",
|
|
53
|
+
"RUNNING": "running", "RESTARTING": "queued", "CREATED": "queued", "RECONCILING": "queued", "INITIALIZING": "queued"}
|
|
54
|
+
|
|
55
|
+
def __init__(self, base_url: str, fetch=http_json):
|
|
56
|
+
self.base, self.fetch = base_url.rstrip("/"), fetch
|
|
57
|
+
|
|
58
|
+
def runs(self) -> list[Run]:
|
|
59
|
+
out = []
|
|
60
|
+
for j in (self.fetch(f"{self.base}/jobs/overview", {}) or {}).get("jobs", []):
|
|
61
|
+
state = self.STATE.get(str(j.get("state", "")).upper(), "other")
|
|
62
|
+
s = (j.get("start-time") or 0) / 1000 or None
|
|
63
|
+
e = (j.get("end-time") or 0) / 1000 if (j.get("end-time") or 0) > 0 else None
|
|
64
|
+
done = state in ("success", "failed")
|
|
65
|
+
out.append(Run("flink", j.get("name", "?"), j.get("jid", ""), state, s, e if done else None,
|
|
66
|
+
((j.get("duration") or 0) / 1000 or ((e - s) if e and s else None)) if done else None, f"{self.base}/#/job/{j.get('jid', '')}/overview"))
|
|
67
|
+
return out
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class LuigiClient:
|
|
71
|
+
STATE = {"DONE": "success", "FAILED": "failed", "RUNNING": "running", "PENDING": "queued", "DISABLED": "failed", "UPSTREAM_FAILED": "failed",
|
|
72
|
+
"UPSTREAM_DISABLED": "failed"}
|
|
73
|
+
|
|
74
|
+
def __init__(self, base_url: str, fetch=http_json):
|
|
75
|
+
self.base, self.fetch = base_url.rstrip("/"), fetch
|
|
76
|
+
|
|
77
|
+
def runs(self) -> list[Run]:
|
|
78
|
+
import urllib.parse
|
|
79
|
+
q = urllib.parse.quote(json.dumps({"status": "", "upstream_status": "", "search": "", "filter_deps": False, "limit": 500}))
|
|
80
|
+
tasks = (self.fetch(f"{self.base}/api/task_list?data={q}", {}) or {}).get("response", {})
|
|
81
|
+
out = []
|
|
82
|
+
for tid, t in tasks.items():
|
|
83
|
+
state = self.STATE.get(str(t.get("status", "")).upper(), "other")
|
|
84
|
+
e = float(t["last_updated"]) if t.get("last_updated") and state in ("success", "failed") else None
|
|
85
|
+
s = float(t["start_time"]) if t.get("start_time") else None
|
|
86
|
+
out.append(Run("luigi", t.get("name", tid), tid, state, s, e, max(0.0, e - s) if e and s else None, f"{self.base}/#/{tid}"))
|
|
87
|
+
return out
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
class RundeckClient:
|
|
91
|
+
STATE = {"succeeded": "success", "failed": "failed", "aborted": "failed", "timedout": "failed", "failed-with-retry": "failed", "running": "running", "scheduled": "queued"}
|
|
92
|
+
|
|
93
|
+
def __init__(self, base_url: str, project: str, fetch=http_json, api: str = "41"):
|
|
94
|
+
self.base, self.project, self.fetch, self.api = base_url.rstrip("/"), project, fetch, api
|
|
95
|
+
|
|
96
|
+
def runs(self, limit: int = 100) -> list[Run]:
|
|
97
|
+
tok = os.environ.get("RUNDECK_TOKEN")
|
|
98
|
+
h = {"X-Rundeck-Auth-Token": tok, "Accept": "application/json"} if tok else {"Accept": "application/json"}
|
|
99
|
+
out = []
|
|
100
|
+
for x in (self.fetch(f"{self.base}/api/{self.api}/project/{self.project}/executions?max={limit}", h) or {}).get("executions", []):
|
|
101
|
+
state = self.STATE.get(str(x.get("status", "")).lower(), "other")
|
|
102
|
+
s = ((x.get("date-started") or {}).get("unixtime") or 0) / 1000 or None
|
|
103
|
+
e = ((x.get("date-ended") or {}).get("unixtime") or 0) / 1000 or None
|
|
104
|
+
done = state in ("success", "failed")
|
|
105
|
+
out.append(Run("rundeck", (x.get("job") or {}).get("name") or x.get("description", "?"), str(x.get("id")), state, s, e if done else None,
|
|
106
|
+
(e - s) if done and s and e else None, x.get("permalink", "")))
|
|
107
|
+
return out
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
class MLflowClient:
|
|
111
|
+
STATE = {"FINISHED": "success", "FAILED": "failed", "KILLED": "failed", "RUNNING": "running", "SCHEDULED": "queued"}
|
|
112
|
+
|
|
113
|
+
def __init__(self, base_url: str, fetch=http_json, post=_post_json):
|
|
114
|
+
self.base, self.fetch, self.post = base_url.rstrip("/"), fetch, post
|
|
115
|
+
|
|
116
|
+
def _h(self) -> dict:
|
|
117
|
+
t = os.environ.get("MLFLOW_TRACKING_TOKEN")
|
|
118
|
+
return {"Authorization": f"Bearer {t}"} if t else {}
|
|
119
|
+
|
|
120
|
+
def runs(self, limit: int = 100) -> list[Run]:
|
|
121
|
+
exps = self.post(f"{self.base}/api/2.0/mlflow/experiments/search", {"max_results": 100}, self._h()) or {}
|
|
122
|
+
names = {e["experiment_id"]: e.get("name", e["experiment_id"]) for e in exps.get("experiments", [])}
|
|
123
|
+
if not names:
|
|
124
|
+
return []
|
|
125
|
+
rs = self.post(f"{self.base}/api/2.0/mlflow/runs/search", {"experiment_ids": list(names), "max_results": limit, "order_by": ["attributes.start_time DESC"]}, self._h()) or {}
|
|
126
|
+
out = []
|
|
127
|
+
for r in rs.get("runs", []):
|
|
128
|
+
i = r.get("info", {})
|
|
129
|
+
state = self.STATE.get(str(i.get("status", "")).upper(), "other")
|
|
130
|
+
s = (int(i.get("start_time") or 0)) / 1000 or None
|
|
131
|
+
e = (int(i.get("end_time") or 0)) / 1000 or None
|
|
132
|
+
done = state in ("success", "failed")
|
|
133
|
+
out.append(Run("mlflow", names.get(i.get("experiment_id"), i.get("experiment_id", "?")), i.get("run_id", ""), state, s, e if done else None,
|
|
134
|
+
(e - s) if done and s and e else None, f"{self.base}/#/experiments/{i.get('experiment_id')}/runs/{i.get('run_id')}"))
|
|
135
|
+
return out
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
"""Ingestion tools (Airbyte, Fivetran) through REST, normalized into `Run`.
|
|
2
|
+
|
|
3
|
+
Airbyte: public API v1 (`/api/public/v1/jobs`, `/connections`). Auth: AIRBYTE_TOKEN, or AIRBYTE_CLIENT_ID/AIRBYTE_CLIENT_SECRET, or AIRBYTE_USER/AIRBYTE_PASSWORD.
|
|
4
|
+
Fivetran: `GET /v1/connectors` (Basic FIVETRAN_API_KEY:FIVETRAN_API_SECRET). Only the last sync per connector is available.
|
|
5
|
+
Verification: a real Airbyte OSS 1.15 (abctl); Fivetran only with a local HTTP server.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from ..i18n import tr
|
|
10
|
+
from ..http_utils import urlopen as _urlopen
|
|
11
|
+
|
|
12
|
+
import base64
|
|
13
|
+
import os
|
|
14
|
+
import re
|
|
15
|
+
import time
|
|
16
|
+
|
|
17
|
+
from . import Run, basic, http_json, ts
|
|
18
|
+
|
|
19
|
+
AIRBYTE_STATE = {"succeeded": "success", "failed": "failed", "incomplete": "failed", "cancelled": "failed", "running": "running", "pending": "queued"}
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _iso_seconds(d: str | None) -> float | None:
|
|
23
|
+
m = re.fullmatch(r"P(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+(?:\.\d+)?)S)?)?", d or "")
|
|
24
|
+
if not m or not any(m.groups()):
|
|
25
|
+
return None
|
|
26
|
+
dd, h, mi, s = (float(x or 0) for x in m.groups())
|
|
27
|
+
return dd * 86400 + h * 3600 + mi * 60 + s
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class AirbyteClient:
|
|
31
|
+
"""Auth (from the environment): AIRBYTE_TOKEN (ready Bearer) | AIRBYTE_CLIENT_ID + AIRBYTE_CLIENT_SECRET (exchanged for a token at
|
|
32
|
+
`/api/v1/applications/token`; it is what `abctl local credentials` shows) | AIRBYTE_USER/AIRBYTE_PASSWORD (Basic, older installs)."""
|
|
33
|
+
|
|
34
|
+
def __init__(self, base_url: str, fetch=http_json, login=None):
|
|
35
|
+
self.base, self.fetch, self._login, self._tok = base_url.rstrip("/"), fetch, login, None
|
|
36
|
+
|
|
37
|
+
def _post_token(self, cid: str, secret: str) -> str:
|
|
38
|
+
import json
|
|
39
|
+
import urllib.request
|
|
40
|
+
req = urllib.request.Request(f"{self.base}/api/v1/applications/token", method="POST",
|
|
41
|
+
data=json.dumps({"client_id": cid, "client_secret": secret, "grant-type": "client_credentials"}).encode(),
|
|
42
|
+
headers={"Content-Type": "application/json", "Accept": "application/json"})
|
|
43
|
+
try:
|
|
44
|
+
with _urlopen(req, timeout=15) as r:
|
|
45
|
+
return json.loads(r.read().decode())["access_token"]
|
|
46
|
+
except Exception as e:
|
|
47
|
+
raise RuntimeError(tr("Airbyte login failed at {url}: {error}", url=f"{self.base}/api/v1/applications/token", error=getattr(e, "code", type(e).__name__))) from None
|
|
48
|
+
|
|
49
|
+
def _h(self) -> dict:
|
|
50
|
+
tok = os.environ.get("AIRBYTE_TOKEN")
|
|
51
|
+
if tok:
|
|
52
|
+
return {"Authorization": f"Bearer {tok}"}
|
|
53
|
+
cid, sec = os.environ.get("AIRBYTE_CLIENT_ID"), os.environ.get("AIRBYTE_CLIENT_SECRET")
|
|
54
|
+
if cid and sec:
|
|
55
|
+
if self._tok is None or time.time() - self._tok[1] > 120: # tokens do Airbyte duram poucos minutos
|
|
56
|
+
self._tok = ((self._login or self._post_token)(cid, sec), time.time())
|
|
57
|
+
return {"Authorization": f"Bearer {self._tok[0]}"}
|
|
58
|
+
return basic("AIRBYTE_USER", "AIRBYTE_PASSWORD")
|
|
59
|
+
|
|
60
|
+
def _get(self, path: str):
|
|
61
|
+
return self.fetch(f"{self.base}/api/public/v1{path}", self._h())
|
|
62
|
+
|
|
63
|
+
def connections(self, limit: int = 100) -> dict[str, dict]:
|
|
64
|
+
return {c["connectionId"]: c for c in self._get(f"/connections?limit={limit}").get("data", [])}
|
|
65
|
+
|
|
66
|
+
def runs(self, limit: int = 100) -> list[Run]:
|
|
67
|
+
names = self.connections()
|
|
68
|
+
out = []
|
|
69
|
+
for j in self._get(f"/jobs?limit={limit}&orderBy=createdAt%7CDESC").get("data", []):
|
|
70
|
+
cid = j.get("connectionId", "")
|
|
71
|
+
c = names.get(cid, {})
|
|
72
|
+
s = ts(j.get("startTime"))
|
|
73
|
+
state = AIRBYTE_STATE.get(str(j.get("status", "")).lower(), "other")
|
|
74
|
+
e = ts(j.get("lastUpdatedAt")) if state in ("success", "failed") else None
|
|
75
|
+
dur = _iso_seconds(j.get("duration")) or ((e - s) if s and e else None)
|
|
76
|
+
label = c.get("name") or cid
|
|
77
|
+
out.append(Run("airbyte", f"{label}:{j.get('jobType', 'sync')}", str(j.get("jobId")), state, s, e, dur,
|
|
78
|
+
f"{self.base}/connections/{cid}/job-history" if cid else self.base))
|
|
79
|
+
return out
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
class FivetranClient:
|
|
83
|
+
def __init__(self, base_url: str = "https://api.fivetran.com", fetch=http_json):
|
|
84
|
+
self.base, self.fetch = base_url.rstrip("/"), fetch
|
|
85
|
+
|
|
86
|
+
def _h(self) -> dict:
|
|
87
|
+
k, s = os.environ.get("FIVETRAN_API_KEY"), os.environ.get("FIVETRAN_API_SECRET")
|
|
88
|
+
return {"Authorization": "Basic " + base64.b64encode(f"{k}:{s}".encode()).decode()} if k and s else {}
|
|
89
|
+
|
|
90
|
+
def runs(self, limit: int = 1000) -> list[Run]:
|
|
91
|
+
out, cursor = [], None
|
|
92
|
+
while len(out) < limit:
|
|
93
|
+
r = self.fetch(f"{self.base}/v1/connectors?limit=1000" + (f"&cursor={cursor}" if cursor else ""), self._h()).get("data", {})
|
|
94
|
+
for c in r.get("items", []):
|
|
95
|
+
st = c.get("status") or {}
|
|
96
|
+
ok, bad = ts(c.get("succeeded_at")), ts(c.get("failed_at"))
|
|
97
|
+
if st.get("sync_state") == "syncing":
|
|
98
|
+
state, when = "running", ts(c.get("sync_started_at")) or ok
|
|
99
|
+
elif bad and (not ok or bad > ok):
|
|
100
|
+
state, when = "failed", bad
|
|
101
|
+
elif ok:
|
|
102
|
+
state, when = "success", ok
|
|
103
|
+
else:
|
|
104
|
+
state, when = "other", None
|
|
105
|
+
if c.get("paused"):
|
|
106
|
+
continue
|
|
107
|
+
out.append(Run("fivetran", f"{c.get('schema') or c.get('id')}", f"{c.get('id')}@{int(when or 0)}", state, when, when if state != "running" else None,
|
|
108
|
+
None, f"https://fivetran.com/dashboard/connectors/{c.get('id')}"))
|
|
109
|
+
cursor = r.get("next_cursor")
|
|
110
|
+
if not cursor:
|
|
111
|
+
break
|
|
112
|
+
return out
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"""Kestra through REST (`/api/v1`). Basic auth: KESTRA_USER / KESTRA_PASSWORD."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from . import Run, basic, http_json, ts
|
|
5
|
+
|
|
6
|
+
STATE = {"SUCCESS": "success", "WARNING": "success", "FAILED": "failed", "KILLED": "failed", "RUNNING": "running",
|
|
7
|
+
"CREATED": "queued", "QUEUED": "queued", "RETRYING": "running", "RESTARTED": "running", "PAUSED": "running"}
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class KestraClient:
|
|
11
|
+
def __init__(self, base_url: str, fetch=http_json):
|
|
12
|
+
self.base, self.fetch = base_url.rstrip("/"), fetch
|
|
13
|
+
|
|
14
|
+
def _get(self, path: str):
|
|
15
|
+
return self.fetch(f"{self.base}/api/v1{path}", basic("KESTRA_USER", "KESTRA_PASSWORD"))
|
|
16
|
+
|
|
17
|
+
def flows(self, size: int = 200) -> list[dict]:
|
|
18
|
+
return self._get(f"/flows/search?size={size}").get("results", [])
|
|
19
|
+
|
|
20
|
+
def runs(self, size: int = 100) -> list[Run]:
|
|
21
|
+
out = []
|
|
22
|
+
for e in self._get(f"/executions/search?size={size}&sort=state.startDate:desc").get("results", []):
|
|
23
|
+
st = e.get("state", {})
|
|
24
|
+
s, en = ts(st.get("startDate")), ts(st.get("endDate"))
|
|
25
|
+
out.append(Run("kestra", f"{e.get('namespace')}.{e.get('flowId')}", e["id"], STATE.get(st.get("current", ""), "other"),
|
|
26
|
+
s, en, (en - s) if s and en else None, f"{self.base}/ui/executions/{e.get('namespace')}/{e.get('flowId')}/{e['id']}"))
|
|
27
|
+
return out
|