cloudleak-cli 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.
- cloudleak/__init__.py +49 -0
- cloudleak/__main__.py +3 -0
- cloudleak/_version.py +1 -0
- cloudleak/analysis.py +199 -0
- cloudleak/cli.py +503 -0
- cloudleak/diff.py +99 -0
- cloudleak/doctor.py +611 -0
- cloudleak/engine.py +487 -0
- cloudleak/errors.py +25 -0
- cloudleak/findings.py +223 -0
- cloudleak/fixtures.py +411 -0
- cloudleak/money.py +78 -0
- cloudleak/providers/__init__.py +19 -0
- cloudleak/providers/aws.py +133 -0
- cloudleak/providers/azure.py +163 -0
- cloudleak/providers/base.py +244 -0
- cloudleak/providers/focus.py +144 -0
- cloudleak/providers/gcp.py +147 -0
- cloudleak/publication.py +171 -0
- cloudleak/py.typed +0 -0
- cloudleak/reconcile.py +334 -0
- cloudleak/redact.py +655 -0
- cloudleak/render/__init__.py +1 -0
- cloudleak/render/formats.py +229 -0
- cloudleak/render/html.py +390 -0
- cloudleak/report.py +138 -0
- cloudleak/rules.py +403 -0
- cloudleak/schemas/__init__.py +1 -0
- cloudleak/schemas/finding.v1.schema.json +122 -0
- cloudleak/schemas/report.v1.schema.json +47 -0
- cloudleak/sources.py +298 -0
- cloudleak/variance.py +426 -0
- cloudleak_cli-0.1.0.dist-info/METADATA +284 -0
- cloudleak_cli-0.1.0.dist-info/RECORD +38 -0
- cloudleak_cli-0.1.0.dist-info/WHEEL +4 -0
- cloudleak_cli-0.1.0.dist-info/entry_points.txt +2 -0
- cloudleak_cli-0.1.0.dist-info/licenses/LICENSE +201 -0
- cloudleak_cli-0.1.0.dist-info/licenses/NOTICE +30 -0
cloudleak/__init__.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"""CloudLeak: offline audit for cloud billing exports.
|
|
2
|
+
|
|
3
|
+
Library use mirrors the CLI and returns the same ``cloudleak.report.v1`` dict
|
|
4
|
+
the JSON output contains::
|
|
5
|
+
|
|
6
|
+
from cloudleak import audit_path, doctor_path
|
|
7
|
+
report = audit_path(["exports/2026-10/"])
|
|
8
|
+
for finding in report["findings"]:
|
|
9
|
+
print(finding["rule_id"], finding["financials"]["observed_cost"])
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import os
|
|
15
|
+
from collections.abc import Sequence
|
|
16
|
+
from decimal import Decimal
|
|
17
|
+
|
|
18
|
+
from cloudleak._version import __version__
|
|
19
|
+
|
|
20
|
+
__all__ = ["__version__", "audit_path", "doctor_path"]
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def doctor_path(paths: Sequence[str | os.PathLike], *, memory_limit: str = "2GB") -> dict:
|
|
24
|
+
"""Run the data-quality checks and return a ``cloudleak.report.v1`` dict."""
|
|
25
|
+
from cloudleak import report
|
|
26
|
+
from cloudleak.doctor import run_doctor
|
|
27
|
+
from cloudleak.engine import Workspace
|
|
28
|
+
|
|
29
|
+
with Workspace(list(paths), memory_limit=memory_limit, allow_unknown=True) as ws:
|
|
30
|
+
return report.build(ws, command="doctor", args={}, doctor=run_doctor(ws))
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def audit_path(paths: Sequence[str | os.PathLike], *, memory_limit: str = "2GB",
|
|
34
|
+
min_cost: str = "1", variance: bool = True) -> dict:
|
|
35
|
+
"""Full audit (doctor, Level-2 findings, month-over-month bridge) as a ``cloudleak.report.v1`` dict."""
|
|
36
|
+
from cloudleak import report
|
|
37
|
+
from cloudleak import variance as var
|
|
38
|
+
from cloudleak.doctor import run_doctor
|
|
39
|
+
from cloudleak.engine import Workspace
|
|
40
|
+
from cloudleak.rules import run_rules
|
|
41
|
+
|
|
42
|
+
with Workspace(list(paths), memory_limit=memory_limit) as ws:
|
|
43
|
+
findings = run_rules(ws, min_cost=Decimal(min_cost))
|
|
44
|
+
bridges = None
|
|
45
|
+
if variance and len(var.principal_periods(ws)) >= 2:
|
|
46
|
+
bridges = var.compute(ws, *var.choose_periods(ws, None, None))
|
|
47
|
+
findings += var.variance_findings(bridges)
|
|
48
|
+
return report.build(ws, command="audit", args={"min_cost": min_cost}, doctor=run_doctor(ws),
|
|
49
|
+
findings=findings, bridges=bridges)
|
cloudleak/__main__.py
ADDED
cloudleak/_version.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.1.0"
|
cloudleak/analysis.py
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
"""Shared L1 analysis: period finality, coverage, spend breakdowns, ownership."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import calendar
|
|
6
|
+
import json
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from decimal import Decimal
|
|
9
|
+
|
|
10
|
+
from cloudleak.engine import Workspace
|
|
11
|
+
|
|
12
|
+
FINALITY_RANK = {"preliminary_estimate": 0, "unknown": 1, "finalized": 2}
|
|
13
|
+
OWNER_KEYS = ("owner", "team", "cost_center", "costcenter", "cost-center", "application", "app", "service",
|
|
14
|
+
"project", "squad", "department")
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass
|
|
18
|
+
class PeriodStatus:
|
|
19
|
+
provider: str
|
|
20
|
+
billing_account_id: str | None
|
|
21
|
+
billing_period: str
|
|
22
|
+
currency: str | None
|
|
23
|
+
cost_basis: str
|
|
24
|
+
finality: str # finalized | preliminary_estimate | unknown
|
|
25
|
+
reason: str
|
|
26
|
+
days_covered: int
|
|
27
|
+
days_in_period: int
|
|
28
|
+
first_day: str | None
|
|
29
|
+
last_day: str | None
|
|
30
|
+
rows: int
|
|
31
|
+
total: Decimal
|
|
32
|
+
|
|
33
|
+
@property
|
|
34
|
+
def partial(self) -> bool:
|
|
35
|
+
return self.days_covered < self.days_in_period
|
|
36
|
+
|
|
37
|
+
def to_dict(self) -> dict:
|
|
38
|
+
from cloudleak.money import fmt
|
|
39
|
+
return {
|
|
40
|
+
"provider": self.provider, "billing_account_id": self.billing_account_id,
|
|
41
|
+
"billing_period": self.billing_period, "currency": self.currency, "cost_basis": self.cost_basis,
|
|
42
|
+
"finality": self.finality, "reason": self.reason, "days_covered": self.days_covered,
|
|
43
|
+
"days_in_period": self.days_in_period, "first_day": self.first_day, "last_day": self.last_day,
|
|
44
|
+
"rows": self.rows, "total": fmt(self.total),
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def days_in(period: str) -> int:
|
|
49
|
+
return calendar.monthrange(int(period[:4]), int(period[5:7]))[1]
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def period_statuses(ws: Workspace, *, where: str = "TRUE") -> list[PeriodStatus]:
|
|
53
|
+
rows = ws.rows(f"""
|
|
54
|
+
SELECT provider, billing_account_id, billing_period, currency, cost_basis,
|
|
55
|
+
bool_and(starts_with(dataset, 'aws_cur')) AS aws_cur,
|
|
56
|
+
bool_and(starts_with(dataset, 'azure_')) AS azure,
|
|
57
|
+
bool_or(starts_with(dataset, 'focus')) AS focus,
|
|
58
|
+
count(*) AS n,
|
|
59
|
+
count(invoice_id) AS with_invoice,
|
|
60
|
+
count(DISTINCT charge_date) FILTER (
|
|
61
|
+
WHERE strftime(charge_date, '%Y-%m') = billing_period) AS days,
|
|
62
|
+
min(charge_date) AS first_day, max(charge_date) AS last_day,
|
|
63
|
+
sum(cost) AS total
|
|
64
|
+
FROM valid WHERE billing_period IS NOT NULL AND ({where})
|
|
65
|
+
GROUP BY ALL ORDER BY provider, billing_period, billing_account_id, currency, cost_basis
|
|
66
|
+
""")
|
|
67
|
+
out = []
|
|
68
|
+
for r in rows:
|
|
69
|
+
period = r["billing_period"]
|
|
70
|
+
dip = days_in(period)
|
|
71
|
+
days = int(r["days"] or 0)
|
|
72
|
+
n, inv = r["n"], r["with_invoice"]
|
|
73
|
+
if r["aws_cur"]:
|
|
74
|
+
if inv == n:
|
|
75
|
+
fin, why = "finalized", "every line item carries bill_invoice_id"
|
|
76
|
+
elif inv == 0:
|
|
77
|
+
fin, why = "preliminary_estimate", "bill_invoice_id is blank: AWS has not finalized this period"
|
|
78
|
+
else:
|
|
79
|
+
fin, why = "unknown", f"{n - inv} of {n} line items lack bill_invoice_id"
|
|
80
|
+
elif r["focus"]:
|
|
81
|
+
fin, why = "unknown", "FOCUS invoice identifiers can be assigned before an invoice is issued"
|
|
82
|
+
elif r["azure"]:
|
|
83
|
+
if n and inv == n:
|
|
84
|
+
fin, why = "finalized", "every row carries InvoiceId"
|
|
85
|
+
elif inv:
|
|
86
|
+
fin, why = "unknown", f"{n - inv} of {n} rows lack InvoiceId"
|
|
87
|
+
else:
|
|
88
|
+
fin, why = "unknown", "the export carries no populated invoice identifier"
|
|
89
|
+
else:
|
|
90
|
+
fin, why = "unknown", "this export type does not state invoice finality"
|
|
91
|
+
if days == 0:
|
|
92
|
+
fin, why = "unknown", "no charge dates fall within the assigned billing period"
|
|
93
|
+
elif days < dip and fin != "finalized" and not r["focus"]:
|
|
94
|
+
fin = "preliminary_estimate"
|
|
95
|
+
why = f"covers {days} of {dip} days" + (f"; {why}" if why else "")
|
|
96
|
+
out.append(PeriodStatus(
|
|
97
|
+
r["provider"], r["billing_account_id"], period, r["currency"], r["cost_basis"], fin, why, days, dip,
|
|
98
|
+
str(r["first_day"]) if r["first_day"] else None, str(r["last_day"]) if r["last_day"] else None,
|
|
99
|
+
n, r["total"] or Decimal(0),
|
|
100
|
+
))
|
|
101
|
+
return out
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def finality_lookup(statuses: list[PeriodStatus]) -> dict[tuple, str]:
|
|
105
|
+
"""(provider, billing_account_id, period) -> worst finality across currencies/bases."""
|
|
106
|
+
out: dict[tuple, str] = {}
|
|
107
|
+
for s in statuses:
|
|
108
|
+
key = (s.provider, s.billing_account_id, s.billing_period)
|
|
109
|
+
if key not in out or FINALITY_RANK[s.finality] < FINALITY_RANK[out[key]]:
|
|
110
|
+
out[key] = s.finality
|
|
111
|
+
return out
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def totals_finality(periods: list[dict]) -> dict[tuple, str]:
|
|
115
|
+
"""A provider total is finalized only when all contributing account scopes are finalized."""
|
|
116
|
+
out: dict[tuple, str] = {}
|
|
117
|
+
for period in periods:
|
|
118
|
+
key = tuple(period[k] for k in ("provider", "billing_period", "currency", "cost_basis"))
|
|
119
|
+
value = period["finality"]
|
|
120
|
+
if key not in out or FINALITY_RANK[value] < FINALITY_RANK[out[key]]:
|
|
121
|
+
out[key] = value
|
|
122
|
+
return out
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def totals(ws: Workspace, *, where: str = "TRUE") -> list[dict]:
|
|
126
|
+
"""Spend by provider, basis, period and currency, split by charge category."""
|
|
127
|
+
return ws.rows(f"""
|
|
128
|
+
SELECT provider, cost_basis, billing_period, currency,
|
|
129
|
+
sum(cost) AS total,
|
|
130
|
+
sum(cost) FILTER (WHERE charge_category = 'usage') AS usage,
|
|
131
|
+
sum(cost) FILTER (WHERE charge_category = 'purchase') AS purchase,
|
|
132
|
+
sum(cost) FILTER (WHERE charge_category = 'fee') AS fee,
|
|
133
|
+
sum(cost) FILTER (WHERE charge_category = 'tax') AS tax,
|
|
134
|
+
sum(cost) FILTER (WHERE charge_category IN ('credit')) AS credit,
|
|
135
|
+
sum(cost) FILTER (WHERE charge_category = 'refund') AS refund,
|
|
136
|
+
sum(cost) FILTER (WHERE charge_category = 'discount') AS discount,
|
|
137
|
+
sum(cost) FILTER (WHERE charge_category = 'adjustment') AS adjustment,
|
|
138
|
+
sum(cost) FILTER (WHERE charge_category = 'unknown') AS other,
|
|
139
|
+
sum(cost - gross_cost) AS embedded_credits,
|
|
140
|
+
count(*) AS rows
|
|
141
|
+
FROM valid WHERE {where} GROUP BY ALL ORDER BY provider, cost_basis, billing_period, currency
|
|
142
|
+
""")
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def breakdown(ws: Workspace, dim: str, *, limit: int = 15, where: str = "TRUE") -> list[dict]:
|
|
146
|
+
"""Top-N spend by a canonical dimension, per currency and basis, with an 'all others' row."""
|
|
147
|
+
allowed = {"service", "service_category", "sub_account_id", "region", "provider", "charge_category", "sku"}
|
|
148
|
+
if dim not in allowed:
|
|
149
|
+
raise ValueError(dim)
|
|
150
|
+
rows = ws.rows(f"""
|
|
151
|
+
WITH g AS (
|
|
152
|
+
SELECT currency, cost_basis, COALESCE(CAST({dim} AS VARCHAR), '(none)') AS key,
|
|
153
|
+
any_value(provider) AS provider, sum(cost) AS cost, count(*) AS rows
|
|
154
|
+
FROM valid WHERE {where} GROUP BY ALL
|
|
155
|
+
), r AS (
|
|
156
|
+
SELECT *, row_number() OVER (PARTITION BY currency, cost_basis ORDER BY cost DESC, key) AS rn FROM g
|
|
157
|
+
)
|
|
158
|
+
SELECT currency, cost_basis,
|
|
159
|
+
CASE WHEN rn <= {int(limit)} THEN key ELSE '(all others)' END AS key,
|
|
160
|
+
CASE WHEN rn <= {int(limit)} THEN provider END AS provider,
|
|
161
|
+
sum(cost) AS cost, sum(rows) AS rows, min(rn) AS rn
|
|
162
|
+
FROM r GROUP BY ALL ORDER BY currency, cost_basis, min(rn)
|
|
163
|
+
""")
|
|
164
|
+
return rows
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def owner_from_tags(tags_json: str | None) -> dict | None:
|
|
168
|
+
if not tags_json:
|
|
169
|
+
return None
|
|
170
|
+
try:
|
|
171
|
+
tags = json.loads(tags_json)
|
|
172
|
+
except (TypeError, ValueError):
|
|
173
|
+
return None
|
|
174
|
+
if not isinstance(tags, dict):
|
|
175
|
+
return None
|
|
176
|
+
norm = {}
|
|
177
|
+
for k, v in tags.items():
|
|
178
|
+
if v in (None, ""):
|
|
179
|
+
continue
|
|
180
|
+
key = str(k).lower()
|
|
181
|
+
for prefix in ("user:", "user_", "aws:", "tag:"):
|
|
182
|
+
if key.startswith(prefix):
|
|
183
|
+
key = key[len(prefix):]
|
|
184
|
+
norm.setdefault(key, (str(k), str(v)))
|
|
185
|
+
for want in OWNER_KEYS:
|
|
186
|
+
if want in norm:
|
|
187
|
+
k, v = norm[want]
|
|
188
|
+
return {"status": "tag", "key": k, "value": v}
|
|
189
|
+
return None
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def owner_routing(tags_json: str | None, sub_account_id: str | None, sub_account_name: str | None) -> dict:
|
|
193
|
+
found = owner_from_tags(tags_json)
|
|
194
|
+
if found:
|
|
195
|
+
return found
|
|
196
|
+
if sub_account_id or sub_account_name:
|
|
197
|
+
return {"status": "account", "value": sub_account_name or sub_account_id,
|
|
198
|
+
"note": "No owner tag; route to the account or project owner."}
|
|
199
|
+
return {"status": "unattributed", "note": "No owner tag and no account identifier."}
|