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/doctor.py
ADDED
|
@@ -0,0 +1,611 @@
|
|
|
1
|
+
"""``cloudleak doctor``: deterministic data-quality, finality and conformance-gap checks.
|
|
2
|
+
|
|
3
|
+
Every check has a stable ID, so CI pipelines can gate on specific checks and
|
|
4
|
+
the catalog can be documented. Status meanings:
|
|
5
|
+
|
|
6
|
+
PASS the property holds
|
|
7
|
+
INFO a fact worth knowing; not a defect
|
|
8
|
+
WARN results remain usable but a conclusion could be wrong without care
|
|
9
|
+
FAIL the data cannot support a trustworthy total until fixed
|
|
10
|
+
SKIP the check does not apply to these inputs
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
from collections import defaultdict
|
|
16
|
+
from dataclasses import dataclass, field
|
|
17
|
+
from decimal import Decimal
|
|
18
|
+
from typing import Any
|
|
19
|
+
|
|
20
|
+
from cloudleak.analysis import period_statuses
|
|
21
|
+
from cloudleak.engine import LoadedSource, Workspace
|
|
22
|
+
from cloudleak.money import display, fmt, pct
|
|
23
|
+
from cloudleak.providers import focus as focus_adapter
|
|
24
|
+
from cloudleak.providers.base import Columns, quote_ident
|
|
25
|
+
|
|
26
|
+
STATUSES = ("PASS", "INFO", "WARN", "FAIL", "SKIP")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass(frozen=True)
|
|
30
|
+
class CheckSpec:
|
|
31
|
+
check_id: str
|
|
32
|
+
title: str
|
|
33
|
+
category: str
|
|
34
|
+
description: str
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
CATALOG: list[CheckSpec] = [
|
|
38
|
+
CheckSpec("CL-ING-001", "Billing format recognized", "ingestion",
|
|
39
|
+
"Each file is identified as AWS CUR (legacy or 2.0), Azure cost export, GCP billing export or FOCUS."),
|
|
40
|
+
CheckSpec("CL-ING-002", "No file supplied twice", "ingestion",
|
|
41
|
+
"Byte-identical files (same SHA-256) would double count every row."),
|
|
42
|
+
CheckSpec("CL-ING-003", "Manifest completeness", "ingestion",
|
|
43
|
+
"Every data file a provider manifest lists is present, and no unlisted file sits beside it."),
|
|
44
|
+
CheckSpec("CL-ING-004", "Manifest row counts", "ingestion",
|
|
45
|
+
"Row counts declared by an Azure export manifest match the rows read."),
|
|
46
|
+
CheckSpec("CL-ING-005", "Cost values parse exactly", "ingestion",
|
|
47
|
+
"Every non-blank cost value is a plain decimal. Unparseable values are counted, never zeroed."),
|
|
48
|
+
CheckSpec("CL-ING-006", "Dates and billing periods parse", "ingestion",
|
|
49
|
+
"Every row has a usage date and a billing period CloudLeak can place in UTC."),
|
|
50
|
+
CheckSpec("CL-ING-007", "Decimal precision preserved", "ingestion",
|
|
51
|
+
"Cost values with more than 12 decimal places are rounded at the 12th place."),
|
|
52
|
+
CheckSpec("CL-ING-008", "Unambiguous column names", "ingestion",
|
|
53
|
+
"No two columns normalize to the same name."),
|
|
54
|
+
CheckSpec("CL-ACC-001", "Single currency per total", "accounting",
|
|
55
|
+
"Totals are never summed across currencies; rows without a currency are flagged."),
|
|
56
|
+
CheckSpec("CL-ACC-002", "Billing period finality", "accounting",
|
|
57
|
+
"Finality evidence for each billing period, including cases where invoice issuance is unknown."),
|
|
58
|
+
CheckSpec("CL-ACC-003", "Full-period coverage", "accounting",
|
|
59
|
+
"Whether each billing period contains usage for every day of the month."),
|
|
60
|
+
CheckSpec("CL-ACC-004", "Cost basis not mixed", "accounting",
|
|
61
|
+
"Azure actual and amortized exports for the same scope are reported separately, never summed."),
|
|
62
|
+
CheckSpec("CL-ACC-005", "Charge composition", "accounting",
|
|
63
|
+
"Tax, credits, refunds, discounts, fees and purchases are separated from usage."),
|
|
64
|
+
CheckSpec("CL-ACC-006", "No overlapping deliveries", "accounting",
|
|
65
|
+
"Identical line items in two different files indicate overlapping exports and double counting."),
|
|
66
|
+
CheckSpec("CL-ACC-007", "Billed versus effective cost", "accounting",
|
|
67
|
+
"Difference between billed and amortized (effective) cost, where both are present."),
|
|
68
|
+
CheckSpec("CL-ACC-008", "Every export covers every period", "accounting",
|
|
69
|
+
"A provider or billing account with no rows in a period that other exports cover. Comparisons "
|
|
70
|
+
"across that period would mistake a missing file for a change in spend."),
|
|
71
|
+
CheckSpec("CL-DQ-001", "Resource identifiers present", "data_quality",
|
|
72
|
+
"Share of usage cost carrying a resource ID; exports without resource IDs cannot support "
|
|
73
|
+
"resource-level findings."),
|
|
74
|
+
CheckSpec("CL-DQ-002", "Tag and label coverage", "data_quality",
|
|
75
|
+
"Share of usage cost carrying any tag or label."),
|
|
76
|
+
CheckSpec("CL-DQ-003", "Consistent tag keys", "data_quality",
|
|
77
|
+
"Tag keys that differ only by case or prefix (env, ENV, Environment) split ownership reports."),
|
|
78
|
+
CheckSpec("CL-DQ-004", "Identical rows within a file", "data_quality",
|
|
79
|
+
"Rows identical in every column. Kept, because Azure documents them as legitimate in "
|
|
80
|
+
"amortized exports; de-duplicating would understate spend."),
|
|
81
|
+
CheckSpec("CL-DQ-005", "Split cost allocation rows", "data_quality",
|
|
82
|
+
"AWS split cost allocation columns are present; split costs must not be added to parent costs."),
|
|
83
|
+
CheckSpec("CL-DQ-006", "Late-arriving usage", "data_quality",
|
|
84
|
+
"GCP usage billed to a later invoice month than the month it was used in."),
|
|
85
|
+
CheckSpec("CL-DQ-007", "Consistent GCP commitment schema", "data_quality",
|
|
86
|
+
"GCP exports with and without consumption_model columns for one billing account."),
|
|
87
|
+
CheckSpec("CL-DQ-008", "Negative usage rows", "data_quality",
|
|
88
|
+
"Negative-cost usage rows (corrections) reduce totals; they are kept and counted."),
|
|
89
|
+
CheckSpec("CL-DQ-009", "Recognized charge types", "data_quality",
|
|
90
|
+
"Charge or line-item types CloudLeak does not recognize are listed so they can be mapped."),
|
|
91
|
+
CheckSpec("CL-FOC-001", "FOCUS version", "focus",
|
|
92
|
+
"The FOCUS version inferred from the columns present (approximate, not certification)."),
|
|
93
|
+
CheckSpec("CL-FOC-002", "FOCUS columns CloudLeak relies on", "focus",
|
|
94
|
+
"Key FOCUS columns that are absent, and what analysis each enables."),
|
|
95
|
+
CheckSpec("CL-FOC-003", "FOCUS columns present but empty", "focus",
|
|
96
|
+
"Columns a provider includes but never populates. Cross-cloud SQL silently returns nothing for them."),
|
|
97
|
+
CheckSpec("CL-FOC-004", "FOCUS ChargeCategory values", "focus",
|
|
98
|
+
"ChargeCategory values outside Usage, Purchase, Tax, Credit and Adjustment."),
|
|
99
|
+
CheckSpec("CL-FOC-005", "FOCUS corrections", "focus",
|
|
100
|
+
"Rows with ChargeClass = Correction restate earlier periods."),
|
|
101
|
+
]
|
|
102
|
+
SPECS = {c.check_id: c for c in CATALOG}
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
@dataclass
|
|
106
|
+
class CheckResult:
|
|
107
|
+
check_id: str
|
|
108
|
+
status: str
|
|
109
|
+
message: str
|
|
110
|
+
scope: str = "all inputs"
|
|
111
|
+
remediation: str | None = None
|
|
112
|
+
metrics: dict[str, Any] = field(default_factory=dict)
|
|
113
|
+
|
|
114
|
+
@property
|
|
115
|
+
def title(self) -> str:
|
|
116
|
+
return SPECS[self.check_id].title
|
|
117
|
+
|
|
118
|
+
@property
|
|
119
|
+
def category(self) -> str:
|
|
120
|
+
return SPECS[self.check_id].category
|
|
121
|
+
|
|
122
|
+
def to_dict(self) -> dict:
|
|
123
|
+
from cloudleak.findings import _jsonable
|
|
124
|
+
return {
|
|
125
|
+
"check_id": self.check_id, "title": self.title, "category": self.category, "status": self.status,
|
|
126
|
+
"scope": self.scope, "message": self.message, "remediation": self.remediation,
|
|
127
|
+
"metrics": _jsonable(self.metrics),
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
@dataclass
|
|
132
|
+
class DoctorReport:
|
|
133
|
+
results: list[CheckResult]
|
|
134
|
+
|
|
135
|
+
def counts(self) -> dict[str, int]:
|
|
136
|
+
c = dict.fromkeys(STATUSES, 0)
|
|
137
|
+
for r in self.results:
|
|
138
|
+
c[r.status] += 1
|
|
139
|
+
return c
|
|
140
|
+
|
|
141
|
+
@property
|
|
142
|
+
def worst(self) -> str:
|
|
143
|
+
c = self.counts()
|
|
144
|
+
return "FAIL" if c["FAIL"] else "WARN" if c["WARN"] else "PASS"
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def _src_name(s: LoadedSource) -> str:
|
|
148
|
+
return s.file.display_name
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def run_doctor(ws: Workspace) -> DoctorReport:
|
|
152
|
+
out: list[CheckResult] = []
|
|
153
|
+
add = out.append
|
|
154
|
+
|
|
155
|
+
# ---- ingestion ---------------------------------------------------------
|
|
156
|
+
for s in ws.sources:
|
|
157
|
+
if s.mapping is None:
|
|
158
|
+
add(CheckResult("CL-ING-001", "FAIL", f"Unrecognized billing format ({len(s.columns)} columns).",
|
|
159
|
+
_src_name(s),
|
|
160
|
+
"Supply a native AWS CUR, Azure cost export, GCP billing export or FOCUS file. If this "
|
|
161
|
+
"is one, open an issue with a synthetic header example.",
|
|
162
|
+
{"columns_sample": s.columns[:12]}))
|
|
163
|
+
else:
|
|
164
|
+
m = s.mapping
|
|
165
|
+
label = m.dataset + (f" (FOCUS {m.focus_version})" if m.focus_version else "")
|
|
166
|
+
status = "WARN" if m.cost_basis == "unknown" or s.rows == 0 else "PASS"
|
|
167
|
+
if s.rows == 0:
|
|
168
|
+
m.notes.append("The file has a header but no data rows.")
|
|
169
|
+
add(CheckResult("CL-ING-001", status,
|
|
170
|
+
f"{label}; {s.rows:,} rows; cost basis: {m.cost_basis}"
|
|
171
|
+
+ (f" (from {s.basis_evidence})" if s.basis_evidence else "") + ".",
|
|
172
|
+
_src_name(s), " ".join(m.notes) or None,
|
|
173
|
+
{"dataset": m.dataset, "rows": s.rows, "cost_basis": m.cost_basis}))
|
|
174
|
+
if ws.sources and sum(s.rows for s in ws.sources) == 0:
|
|
175
|
+
add(CheckResult("CL-ING-001", "FAIL", "No data rows in any input file; there is nothing to audit.",
|
|
176
|
+
remediation="Check that the export finished and that you passed the data files."))
|
|
177
|
+
for name, reason in ws.discovery.skipped:
|
|
178
|
+
add(CheckResult("CL-ING-001", "INFO", f"Skipped: {reason}.", name))
|
|
179
|
+
|
|
180
|
+
by_sha: dict[str, list[str]] = defaultdict(list)
|
|
181
|
+
for s in ws.sources:
|
|
182
|
+
by_sha[s.file.sha256].append(_src_name(s))
|
|
183
|
+
dupes = {k: v for k, v in by_sha.items() if len(v) > 1}
|
|
184
|
+
if dupes:
|
|
185
|
+
for sha, names in dupes.items():
|
|
186
|
+
add(CheckResult("CL-ING-002", "FAIL", f"Identical content supplied {len(names)} times: {', '.join(names)}.",
|
|
187
|
+
remediation="Remove the duplicate copies; every row would otherwise be counted twice.",
|
|
188
|
+
metrics={"sha256": sha}))
|
|
189
|
+
else:
|
|
190
|
+
add(CheckResult("CL-ING-002", "PASS", f"{len(ws.sources)} distinct files."))
|
|
191
|
+
|
|
192
|
+
_manifest_checks(ws, add)
|
|
193
|
+
|
|
194
|
+
bad = ws.rows("""SELECT source_id, count(*) AS n, min(source_row) AS first_row, any_value(cost_raw) AS example
|
|
195
|
+
FROM items WHERE cost_parse_error GROUP BY 1 ORDER BY 1""")
|
|
196
|
+
names = {s.file.source_id: _src_name(s) for s in ws.sources}
|
|
197
|
+
if bad:
|
|
198
|
+
for b in bad:
|
|
199
|
+
add(CheckResult("CL-ING-005", "FAIL",
|
|
200
|
+
f"{b['n']:,} cost value(s) are not plain decimals (first at data row {b['first_row']}, "
|
|
201
|
+
f"e.g. {b['example'][:40]!r}). These rows are excluded from every total.",
|
|
202
|
+
names[b["source_id"]],
|
|
203
|
+
"Re-export without spreadsheet formatting (no thousands separators, currency symbols "
|
|
204
|
+
"or locale decimal commas).", {"rows": b["n"], "first_row": b["first_row"]}))
|
|
205
|
+
else:
|
|
206
|
+
add(CheckResult("CL-ING-005", "PASS", "Every cost value parsed as an exact decimal."))
|
|
207
|
+
|
|
208
|
+
undated = ws.rows("""SELECT source_id, count(*) FILTER (WHERE charge_start IS NULL) AS no_date,
|
|
209
|
+
count(*) FILTER (WHERE billing_period_start IS NULL) AS no_period,
|
|
210
|
+
min(source_row) FILTER (WHERE billing_period_start IS NULL) AS first_row
|
|
211
|
+
FROM items GROUP BY 1 HAVING no_date > 0 OR no_period > 0 ORDER BY 1""")
|
|
212
|
+
if undated:
|
|
213
|
+
for u in undated:
|
|
214
|
+
status = "FAIL" if u["no_period"] else "WARN"
|
|
215
|
+
add(CheckResult("CL-ING-006", status,
|
|
216
|
+
f"{u['no_period']:,} rows have no billing period and {u['no_date']:,} have no usage "
|
|
217
|
+
f"date" + (f" (first at data row {u['first_row']})" if u["first_row"] else "") + ".",
|
|
218
|
+
names[u["source_id"]],
|
|
219
|
+
"Check the date format; CloudLeak reads ISO 8601, 'YYYY-MM-DD HH:MM:SS UTC', "
|
|
220
|
+
"MM/DD/YYYY and YYYYMM invoice months.",
|
|
221
|
+
{"rows_without_period": u["no_period"], "rows_without_date": u["no_date"]}))
|
|
222
|
+
else:
|
|
223
|
+
add(CheckResult("CL-ING-006", "PASS", "Every row has a usage date and billing period."))
|
|
224
|
+
|
|
225
|
+
precise = ws.scalar(r"""SELECT count(*) FROM items
|
|
226
|
+
WHERE regexp_matches(cost_raw, '^[+-]?[0-9]*\.[0-9]{13,}$')""")
|
|
227
|
+
add(CheckResult("CL-ING-007", "INFO" if precise else "PASS",
|
|
228
|
+
f"{precise:,} cost values carry more than 12 decimal places and were rounded at the 12th."
|
|
229
|
+
if precise else "No cost value exceeds 12 decimal places."))
|
|
230
|
+
|
|
231
|
+
issues = [(s, i) for s in ws.sources for i in s.header_issues]
|
|
232
|
+
if issues:
|
|
233
|
+
for s, i in issues:
|
|
234
|
+
add(CheckResult("CL-ING-008", "WARN", i, _src_name(s), "Rename or drop one of the columns."))
|
|
235
|
+
else:
|
|
236
|
+
add(CheckResult("CL-ING-008", "PASS", "Column names are unambiguous."))
|
|
237
|
+
|
|
238
|
+
# ---- accounting --------------------------------------------------------
|
|
239
|
+
cur = ws.rows("""SELECT provider,
|
|
240
|
+
list(DISTINCT currency ORDER BY currency) FILTER (WHERE currency IS NOT NULL) AS cs,
|
|
241
|
+
count(*) FILTER (WHERE currency IS NULL) AS missing
|
|
242
|
+
FROM valid GROUP BY 1 ORDER BY 1""")
|
|
243
|
+
all_cur = sorted({c for r in cur for c in (r["cs"] or [])})
|
|
244
|
+
missing = sum(r["missing"] for r in cur)
|
|
245
|
+
if missing:
|
|
246
|
+
add(CheckResult("CL-ACC-001", "WARN", f"{missing:,} rows carry no currency; they are totalled as "
|
|
247
|
+
"currency 'None' and never merged with priced rows.",
|
|
248
|
+
remediation="Include the billing currency column in the export."))
|
|
249
|
+
if len(all_cur) > 1:
|
|
250
|
+
add(CheckResult("CL-ACC-001", "WARN", f"{len(all_cur)} billing currencies ({', '.join(all_cur)}). "
|
|
251
|
+
"Totals are kept separate per currency; no exchange rate is applied.",
|
|
252
|
+
metrics={"currencies": all_cur}))
|
|
253
|
+
elif not missing:
|
|
254
|
+
add(CheckResult("CL-ACC-001", "PASS", f"Single billing currency: {all_cur[0] if all_cur else 'none'}."))
|
|
255
|
+
|
|
256
|
+
statuses = period_statuses(ws)
|
|
257
|
+
for st in statuses:
|
|
258
|
+
scope = " ".join(x for x in (st.provider, st.billing_account_id, st.billing_period, st.currency,
|
|
259
|
+
f"({st.cost_basis})") if x)
|
|
260
|
+
if st.finality == "finalized":
|
|
261
|
+
add(CheckResult("CL-ACC-002", "PASS", f"Finalized: {st.reason}.", scope))
|
|
262
|
+
elif st.finality == "preliminary_estimate":
|
|
263
|
+
add(CheckResult("CL-ACC-002", "WARN", f"PRELIMINARY ESTIMATE: {st.reason}. Totals can still change; "
|
|
264
|
+
"invoice reconciliation is not conclusive.", scope,
|
|
265
|
+
"Re-run after the provider finalizes the period (AWS typically in the first days of the "
|
|
266
|
+
"following month, with late fees such as support posting after that)."))
|
|
267
|
+
else:
|
|
268
|
+
add(CheckResult("CL-ACC-002", "INFO", f"Finality unknown: {st.reason}.", scope))
|
|
269
|
+
if st.days_covered == 0:
|
|
270
|
+
add(CheckResult("CL-ACC-003", "INFO",
|
|
271
|
+
f"None of the {st.rows:,} rows has a charge date within {st.billing_period}. "
|
|
272
|
+
"Daily coverage cannot be established.", scope))
|
|
273
|
+
elif st.partial:
|
|
274
|
+
add(CheckResult("CL-ACC-003", "WARN",
|
|
275
|
+
f"Covers {st.days_covered} of {st.days_in_period} days ({st.first_day} to "
|
|
276
|
+
f"{st.last_day}). Compare the observed coverage before interpreting changes.", scope,
|
|
277
|
+
metrics={"days_covered": st.days_covered, "days_in_period": st.days_in_period}))
|
|
278
|
+
if statuses and not any(s.partial for s in statuses):
|
|
279
|
+
add(CheckResult("CL-ACC-003", "PASS", "Every billing period has usage on every day."))
|
|
280
|
+
|
|
281
|
+
mixed = ws.rows("""SELECT provider, sub_account_id, billing_period,
|
|
282
|
+
list(DISTINCT cost_basis ORDER BY cost_basis) AS bases
|
|
283
|
+
FROM valid GROUP BY ALL HAVING count(DISTINCT cost_basis) > 1 ORDER BY ALL""")
|
|
284
|
+
unknown_basis = ws.scalar("SELECT count(*) FROM valid WHERE cost_basis = 'unknown'")
|
|
285
|
+
for r in mixed:
|
|
286
|
+
add(CheckResult("CL-ACC-004", "WARN",
|
|
287
|
+
f"Both {' and '.join(r['bases'])} costs are present. They are reported side by side; "
|
|
288
|
+
"adding them would double count.",
|
|
289
|
+
f"{r['provider']} {r['sub_account_id'] or ''} {r['billing_period']}",
|
|
290
|
+
"Audit one basis at a time, or compare them deliberately."))
|
|
291
|
+
if unknown_basis:
|
|
292
|
+
add(CheckResult("CL-ACC-004", "WARN", f"{unknown_basis:,} rows have an unknown cost basis "
|
|
293
|
+
"(actual vs amortized).", remediation="Name the Azure export folder 'actual' or 'amortized'."))
|
|
294
|
+
if not mixed and not unknown_basis:
|
|
295
|
+
add(CheckResult("CL-ACC-004", "PASS", "One cost basis per scope and period."))
|
|
296
|
+
|
|
297
|
+
comp = ws.rows("""SELECT provider, billing_period, currency, cost_basis, charge_category,
|
|
298
|
+
sum(cost) AS amount, count(*) AS n
|
|
299
|
+
FROM valid WHERE charge_category NOT IN ('usage')
|
|
300
|
+
GROUP BY ALL ORDER BY ALL""")
|
|
301
|
+
if comp:
|
|
302
|
+
parts = defaultdict(list)
|
|
303
|
+
for r in comp:
|
|
304
|
+
parts[(r["provider"], r["billing_period"], r["currency"], r["cost_basis"])].append(
|
|
305
|
+
f"{r['charge_category']} {display(r['amount'])}")
|
|
306
|
+
for (p, period, c, b), items in parts.items():
|
|
307
|
+
add(CheckResult("CL-ACC-005", "INFO", "Non-usage charges: " + "; ".join(items) + ".",
|
|
308
|
+
f"{p} {period} {c} ({b})"))
|
|
309
|
+
else:
|
|
310
|
+
add(CheckResult("CL-ACC-005", "INFO", "Only usage charges present (no tax, credit, refund or fee rows)."))
|
|
311
|
+
|
|
312
|
+
# Identical line items in different files: overlapping deliveries. When at least half of a file
|
|
313
|
+
# reappears elsewhere, it is a duplicated delivery and totals are wrong -> FAIL.
|
|
314
|
+
overlap = ws.rows("""
|
|
315
|
+
WITH k AS (
|
|
316
|
+
SELECT source_id, provider,
|
|
317
|
+
hash(provider, billing_account_id, sub_account_id, resource_id, sku, sku_detail, charge_raw,
|
|
318
|
+
charge_start, charge_end, cost, usage_quantity, invoice_id, cost_basis, region) AS h
|
|
319
|
+
FROM valid),
|
|
320
|
+
c AS (SELECT h, count(DISTINCT source_id) AS ns FROM k GROUP BY h)
|
|
321
|
+
SELECT k.source_id, any_value(provider) AS provider, count(*) AS n,
|
|
322
|
+
count(*) FILTER (WHERE ns > 1) AS dup, count(DISTINCT h) FILTER (WHERE ns > 1) AS keys
|
|
323
|
+
FROM k JOIN c USING (h) GROUP BY 1 HAVING count(*) FILTER (WHERE ns > 1) > 0 ORDER BY 1""")
|
|
324
|
+
if overlap:
|
|
325
|
+
for r in overlap:
|
|
326
|
+
share = r["dup"] / r["n"]
|
|
327
|
+
status = "FAIL" if share >= 0.5 else "WARN"
|
|
328
|
+
add(CheckResult("CL-ACC-006", status,
|
|
329
|
+
f"{r['dup']:,} of {r['n']:,} rows ({share:.0%}) also appear identically in another file."
|
|
330
|
+
+ (" This file duplicates another delivery; totals count it twice."
|
|
331
|
+
if status == "FAIL" else " Overlapping deliveries double count."),
|
|
332
|
+
names[r["source_id"]], "Keep only the latest delivery for each billing period.",
|
|
333
|
+
{"duplicated_rows": r["dup"], "duplicated_line_items": r["keys"], "rows": r["n"]}))
|
|
334
|
+
else:
|
|
335
|
+
add(CheckResult("CL-ACC-006", "PASS", "No line item appears in more than one file."))
|
|
336
|
+
|
|
337
|
+
principal = ws.rows("""SELECT provider, billing_account_id, cost_basis,
|
|
338
|
+
list(DISTINCT billing_period ORDER BY billing_period) AS periods
|
|
339
|
+
FROM valid WHERE strftime(charge_date, '%Y-%m') = billing_period GROUP BY ALL""")
|
|
340
|
+
all_periods = sorted({p for r in principal for p in r["periods"]})
|
|
341
|
+
gaps = 0
|
|
342
|
+
for r in principal:
|
|
343
|
+
missing = [p for p in all_periods if p not in r["periods"]]
|
|
344
|
+
if missing:
|
|
345
|
+
gaps += 1
|
|
346
|
+
add(CheckResult("CL-ACC-008", "WARN",
|
|
347
|
+
f"No rows for {', '.join(missing)}, which other exports cover. Totals and "
|
|
348
|
+
"month-over-month comparisons for those periods omit this scope.",
|
|
349
|
+
f"{r['provider']} {r['billing_account_id'] or ''} ({r['cost_basis']})".replace(" ", " "),
|
|
350
|
+
"Supply the missing export, or compare only periods every scope covers."))
|
|
351
|
+
if principal and not gaps:
|
|
352
|
+
add(CheckResult("CL-ACC-008", "PASS", f"Every provider and billing account covers all "
|
|
353
|
+
f"{len(all_periods)} period(s)."))
|
|
354
|
+
|
|
355
|
+
eff = ws.rows("""SELECT provider, billing_period, currency, sum(cost) AS billed, sum(effective_cost) AS eff
|
|
356
|
+
FROM valid WHERE cost_basis = 'billed' GROUP BY ALL
|
|
357
|
+
HAVING count(effective_cost) = count(*) AND sum(cost) <> sum(effective_cost) ORDER BY ALL""")
|
|
358
|
+
for r in eff:
|
|
359
|
+
add(CheckResult("CL-ACC-007", "INFO",
|
|
360
|
+
f"Billed {display(r['billed'])} vs effective {display(r['eff'])} "
|
|
361
|
+
f"(difference {display(r['billed'] - r['eff'])}). Expected when commitments are paid "
|
|
362
|
+
"in one period and amortized across others.",
|
|
363
|
+
f"{r['provider']} {r['billing_period']} {r['currency']}"))
|
|
364
|
+
|
|
365
|
+
# ---- data quality ------------------------------------------------------
|
|
366
|
+
for s in ws.recognized:
|
|
367
|
+
caps, m = s.mapping.capabilities, s.mapping
|
|
368
|
+
if not caps.get("resource_id"):
|
|
369
|
+
hint = {
|
|
370
|
+
"aws": "Enable 'Include resource IDs' on the CUR / Data Export (INCLUDE_RESOURCES).",
|
|
371
|
+
"gcp": "Use the detailed usage cost export, which carries resource.name.",
|
|
372
|
+
}.get(m.provider, "Include the resource identifier column in the export.")
|
|
373
|
+
add(CheckResult("CL-DQ-001", "WARN", "No resource ID column: resource-level findings are impossible.",
|
|
374
|
+
_src_name(s), hint))
|
|
375
|
+
cov = ws.rows("""SELECT provider, currency, sum(cost) AS total,
|
|
376
|
+
sum(cost) FILTER (WHERE resource_id IS NOT NULL) AS with_id,
|
|
377
|
+
sum(cost) FILTER (WHERE tags IS NOT NULL) AS tagged
|
|
378
|
+
FROM valid WHERE charge_category = 'usage' AND cost > 0 GROUP BY ALL ORDER BY ALL""")
|
|
379
|
+
for r in cov:
|
|
380
|
+
total = r["total"] or Decimal(0)
|
|
381
|
+
with_id = r["with_id"] or Decimal(0)
|
|
382
|
+
add(CheckResult("CL-DQ-001", "INFO", f"{pct(with_id, total)} of positive usage cost carries a resource ID.",
|
|
383
|
+
f"{r['provider']} {r['currency']}",
|
|
384
|
+
metrics={"share": pct(with_id, total)}))
|
|
385
|
+
tagged = r["tagged"] or Decimal(0)
|
|
386
|
+
share = (tagged / total) if total else Decimal(0)
|
|
387
|
+
status = "WARN" if share < Decimal("0.5") else "PASS"
|
|
388
|
+
add(CheckResult("CL-DQ-002", status,
|
|
389
|
+
f"{pct(tagged, total)} of positive usage cost carries any tag or label "
|
|
390
|
+
f"({display(total - tagged, r['currency'])} untagged).",
|
|
391
|
+
f"{r['provider']} {r['currency']}",
|
|
392
|
+
{"aws": "Activate cost allocation tags in the Billing console; tags only appear in exports "
|
|
393
|
+
"after activation and are not backfilled.",
|
|
394
|
+
"gcp": "Apply labels to projects and resources; project labels can stand in for owners.",
|
|
395
|
+
"azure": "Apply tags at resource-group level and enable tag inheritance in Cost "
|
|
396
|
+
"Management."}.get(r["provider"]) if status == "WARN" else None,
|
|
397
|
+
{"tagged_share": pct(tagged, total), "untagged_cost": fmt(total - tagged)}))
|
|
398
|
+
|
|
399
|
+
keys = ws.rows("""SELECT provider, k, count(*) AS n FROM (
|
|
400
|
+
SELECT provider, unnest(json_keys(tags)) AS k FROM valid
|
|
401
|
+
WHERE tags IS NOT NULL AND json_valid(tags) AND json_type(tags) = 'OBJECT')
|
|
402
|
+
GROUP BY ALL""")
|
|
403
|
+
families: dict[tuple[str, str], set[str]] = defaultdict(set)
|
|
404
|
+
for r in keys:
|
|
405
|
+
base = r["k"].lower()
|
|
406
|
+
for prefix in ("user:", "user_", "tag:"):
|
|
407
|
+
if base.startswith(prefix):
|
|
408
|
+
base = base[len(prefix):]
|
|
409
|
+
base = {"environment": "env", "stage": "env"}.get(base, base).replace("-", "_")
|
|
410
|
+
families[(r["provider"], base)].add(r["k"])
|
|
411
|
+
conflicts = {k: v for k, v in families.items() if len(v) > 1}
|
|
412
|
+
for (p, base), variants in sorted(conflicts.items()):
|
|
413
|
+
add(CheckResult("CL-DQ-003", "WARN", f"Tag key '{base}' is spelled {len(variants)} ways: "
|
|
414
|
+
f"{', '.join(sorted(variants))}.", p,
|
|
415
|
+
"Standardize the key and use tag policies; reports group these separately until then."))
|
|
416
|
+
if not conflicts and keys:
|
|
417
|
+
add(CheckResult("CL-DQ-003", "PASS", "No tag key variants that differ only by case or prefix."))
|
|
418
|
+
|
|
419
|
+
for s in ws.recognized:
|
|
420
|
+
cols = [c for c in s.columns if c != "__cl_row"]
|
|
421
|
+
if not cols:
|
|
422
|
+
continue
|
|
423
|
+
sel = ", ".join(quote_ident(c) for c in cols)
|
|
424
|
+
r = ws.rows(f"""SELECT count(*) AS clusters, sum(c) AS rows FROM (
|
|
425
|
+
SELECT count(*) AS c FROM {quote_ident(s.table)} GROUP BY {sel} HAVING count(*) > 1)""")[0]
|
|
426
|
+
if r["clusters"]:
|
|
427
|
+
azure = s.mapping.provider == "azure"
|
|
428
|
+
add(CheckResult("CL-DQ-004", "INFO" if azure else "WARN",
|
|
429
|
+
f"{r['clusters']:,} groups of fully identical rows ({r['rows']:,} rows). Kept as "
|
|
430
|
+
"separate charges" + (": Azure documents identical rows in amortized exports, and "
|
|
431
|
+
"de-duplicating them understates spend." if azure else
|
|
432
|
+
"; confirm the file was not concatenated twice."),
|
|
433
|
+
_src_name(s), metrics={"clusters": r["clusters"], "rows": r["rows"]}))
|
|
434
|
+
if s.mapping.capabilities.get("split_cost_allocation"):
|
|
435
|
+
add(CheckResult("CL-DQ-005", "INFO",
|
|
436
|
+
"split_line_item_* columns present. CloudLeak totals use line_item_unblended_cost only "
|
|
437
|
+
"and never add split costs on top of parent instance costs.", _src_name(s)))
|
|
438
|
+
|
|
439
|
+
late = ws.rows("""SELECT currency, billing_period, count(*) AS n, sum(cost) AS amount FROM valid
|
|
440
|
+
WHERE provider = 'gcp' AND charge_date IS NOT NULL
|
|
441
|
+
AND strftime(charge_date, '%Y-%m') <> billing_period
|
|
442
|
+
GROUP BY ALL ORDER BY ALL""")
|
|
443
|
+
for r in late:
|
|
444
|
+
add(CheckResult("CL-DQ-006", "INFO",
|
|
445
|
+
f"{r['n']:,} rows ({display(r['amount'], r['currency'])}) were used in an earlier month but "
|
|
446
|
+
f"invoiced in {r['billing_period']}. CloudLeak assigns them to the invoice month.",
|
|
447
|
+
f"gcp {r['billing_period']}"))
|
|
448
|
+
gcp_sources = [s for s in ws.recognized if s.mapping.provider == "gcp"]
|
|
449
|
+
if gcp_sources:
|
|
450
|
+
shapes = {bool(s.mapping.capabilities.get("consumption_model")) for s in gcp_sources}
|
|
451
|
+
if len(shapes) > 1:
|
|
452
|
+
add(CheckResult("CL-DQ-007", "WARN",
|
|
453
|
+
"Some GCP files carry consumption_model columns and others do not. Commitment "
|
|
454
|
+
"discounts are represented differently between the two shapes; compare totals, "
|
|
455
|
+
"not credit lines, across them.", "gcp"))
|
|
456
|
+
|
|
457
|
+
neg = ws.rows("""SELECT provider, currency, count(*) AS n, sum(cost) AS amount FROM valid
|
|
458
|
+
WHERE charge_category = 'usage' AND cost < 0 GROUP BY ALL ORDER BY ALL""")
|
|
459
|
+
for r in neg:
|
|
460
|
+
add(CheckResult("CL-DQ-008", "INFO", f"{r['n']:,} negative usage rows totalling "
|
|
461
|
+
f"{display(r['amount'], r['currency'])} (corrections). Kept; they reduce totals.",
|
|
462
|
+
r["provider"]))
|
|
463
|
+
|
|
464
|
+
unk = ws.rows("""SELECT provider, charge_raw, count(*) AS n, sum(cost) AS amount FROM valid
|
|
465
|
+
WHERE charge_category = 'unknown' GROUP BY ALL ORDER BY amount DESC""")
|
|
466
|
+
if unk:
|
|
467
|
+
for r in unk[:20]:
|
|
468
|
+
add(CheckResult("CL-DQ-009", "WARN",
|
|
469
|
+
f"Unrecognized charge type {r['charge_raw']!r}: {r['n']:,} rows, "
|
|
470
|
+
f"{display(r['amount'])}. Counted in totals as 'unknown'.", r["provider"],
|
|
471
|
+
"Open an issue naming the charge type (no data rows) so it can be mapped."))
|
|
472
|
+
else:
|
|
473
|
+
add(CheckResult("CL-DQ-009", "PASS", "Every charge type is recognized."))
|
|
474
|
+
|
|
475
|
+
# ---- FOCUS -------------------------------------------------------------
|
|
476
|
+
focus_sources = [s for s in ws.recognized if s.detected == "focus"]
|
|
477
|
+
if not focus_sources:
|
|
478
|
+
add(CheckResult("CL-FOC-001", "SKIP", "No FOCUS files supplied."))
|
|
479
|
+
for s in focus_sources:
|
|
480
|
+
cols = Columns.from_names(s.columns)
|
|
481
|
+
add(CheckResult("CL-FOC-001", "INFO",
|
|
482
|
+
f"Columns suggest FOCUS {s.mapping.focus_version} or later. Inferred from column presence; "
|
|
483
|
+
"use the FinOps Foundation focus_validator for normative conformance.", _src_name(s)))
|
|
484
|
+
absent = [(k, why) for k, why in focus_adapter.KEY_COLUMNS.items() if k not in cols.by_norm]
|
|
485
|
+
if absent:
|
|
486
|
+
add(CheckResult("CL-FOC-002", "WARN",
|
|
487
|
+
"Missing: " + "; ".join(f"{k} ({why})" for k, why in absent) + ".", _src_name(s),
|
|
488
|
+
metrics={"missing": [k for k, _ in absent]}))
|
|
489
|
+
else:
|
|
490
|
+
add(CheckResult("CL-FOC-002", "PASS", "All key columns present.", _src_name(s)))
|
|
491
|
+
present = [k for k in focus_adapter.KEY_COLUMNS if k in cols.by_norm]
|
|
492
|
+
if present:
|
|
493
|
+
exprs = ", ".join(f"count(NULLIF(TRIM({cols.ref(k)}), '')) AS {quote_ident(k)}" for k in present)
|
|
494
|
+
filled = ws.rows(f"SELECT {exprs} FROM {quote_ident(s.table)}")[0]
|
|
495
|
+
empty = [k for k in present if filled[k] == 0]
|
|
496
|
+
if empty:
|
|
497
|
+
add(CheckResult("CL-FOC-003", "WARN",
|
|
498
|
+
"Present but never populated: " + "; ".join(
|
|
499
|
+
f"{k} ({focus_adapter.KEY_COLUMNS[k]})" for k in empty) + ".",
|
|
500
|
+
_src_name(s),
|
|
501
|
+
"Expect these analyses to be unavailable for this provider's FOCUS export; do not "
|
|
502
|
+
"join on these columns across clouds.", {"empty_columns": empty}))
|
|
503
|
+
else:
|
|
504
|
+
add(CheckResult("CL-FOC-003", "PASS", "Every key column present is populated.", _src_name(s)))
|
|
505
|
+
if cols.has("charge_category"):
|
|
506
|
+
allowed = ", ".join(f"'{v}'" for v in focus_adapter.VALID_CHARGE_CATEGORIES)
|
|
507
|
+
badcat = ws.rows(f"""SELECT {cols.ref('charge_category')} AS v, count(*) AS n
|
|
508
|
+
FROM {quote_ident(s.table)}
|
|
509
|
+
WHERE {cols.ref('charge_category')} NOT IN ({allowed})
|
|
510
|
+
OR {cols.ref('charge_category')} IS NULL GROUP BY 1 ORDER BY 2 DESC""")
|
|
511
|
+
if badcat:
|
|
512
|
+
add(CheckResult("CL-FOC-004", "WARN", "Non-standard ChargeCategory values: " + ", ".join(
|
|
513
|
+
f"{b['v']!r} ({b['n']:,})" for b in badcat[:8]) + ".", _src_name(s)))
|
|
514
|
+
else:
|
|
515
|
+
add(CheckResult("CL-FOC-004", "PASS", "ChargeCategory values are standard.", _src_name(s)))
|
|
516
|
+
if cols.has("charge_class"):
|
|
517
|
+
n = ws.scalar(f"""SELECT count(*) FROM {quote_ident(s.table)}
|
|
518
|
+
WHERE lower({cols.ref('charge_class')}) = 'correction'""")
|
|
519
|
+
if n:
|
|
520
|
+
add(CheckResult("CL-FOC-005", "INFO", f"{n:,} correction rows restate earlier periods.", _src_name(s)))
|
|
521
|
+
return DoctorReport(out)
|
|
522
|
+
|
|
523
|
+
|
|
524
|
+
def _tail2(text: str) -> str:
|
|
525
|
+
parts = [p for p in text.replace("\\", "/").split("/") if p]
|
|
526
|
+
return "/".join(parts[-2:])
|
|
527
|
+
|
|
528
|
+
|
|
529
|
+
def _manifest_checks(ws: Workspace, add) -> None:
|
|
530
|
+
"""Completeness and staleness of manifest-described deliveries.
|
|
531
|
+
|
|
532
|
+
A provider manifest names the files of exactly one delivery. Files are matched on
|
|
533
|
+
their last two path components (``<assembly or run id>/<file>``), so a file from an
|
|
534
|
+
older assembly or export run with the same file name is *not* mistaken for a listed one.
|
|
535
|
+
"""
|
|
536
|
+
manifests = ws.discovery.manifests
|
|
537
|
+
if not manifests:
|
|
538
|
+
add(CheckResult("CL-ING-003", "INFO",
|
|
539
|
+
"No provider manifest supplied, so delivery completeness cannot be verified.",
|
|
540
|
+
remediation="Include the export's manifest JSON alongside the data files."))
|
|
541
|
+
add(CheckResult("CL-ING-004", "SKIP", "No manifest row counts to compare."))
|
|
542
|
+
return
|
|
543
|
+
sources = list(ws.sources)
|
|
544
|
+
by_tail = {f"{s.file.path.parent.name}/{s.file.path.name}": s for s in sources}
|
|
545
|
+
|
|
546
|
+
def owned(m) -> list:
|
|
547
|
+
"""Sources this manifest lists."""
|
|
548
|
+
tails = {_tail2(k) for k in m.keys}
|
|
549
|
+
out = [s for t, s in by_tail.items() if t in tails]
|
|
550
|
+
flat = [s for s in by_base_items(m) if s not in out]
|
|
551
|
+
return out + flat
|
|
552
|
+
|
|
553
|
+
def by_base_items(m):
|
|
554
|
+
names = set(m.files)
|
|
555
|
+
return [s for s in sources if s.file.path.parent == m.path.parent and s.file.path.name in names]
|
|
556
|
+
|
|
557
|
+
claimed: dict[int, list] = defaultdict(list)
|
|
558
|
+
for m in manifests:
|
|
559
|
+
listed = owned(m)
|
|
560
|
+
for s in listed:
|
|
561
|
+
claimed[s.file.source_id].append(m)
|
|
562
|
+
scope = m.path.name
|
|
563
|
+
found_tails = {f"{s.file.path.parent.name}/{s.file.path.name}" for s in listed}
|
|
564
|
+
found_bases = {s.file.path.name for s in listed}
|
|
565
|
+
missing = [k for k in m.keys if _tail2(k) not in found_tails and k.rsplit("/", 1)[-1] not in found_bases]
|
|
566
|
+
if missing:
|
|
567
|
+
add(CheckResult("CL-ING-003", "FAIL", f"{len(missing)} file(s) listed in the manifest are missing: "
|
|
568
|
+
f"{', '.join(k.rsplit('/', 1)[-1] for k in missing[:5])}.", scope,
|
|
569
|
+
"Download the complete delivery; totals from a partial delivery understate spend.",
|
|
570
|
+
{"missing": [k.rsplit("/", 1)[-1] for k in missing]}))
|
|
571
|
+
elif m.keys:
|
|
572
|
+
add(CheckResult("CL-ING-003", "PASS", f"All {len(m.keys)} listed file(s) present.", scope))
|
|
573
|
+
if m.row_counts:
|
|
574
|
+
mism = [(s.file.path.name, m.row_counts[s.file.path.name], s.rows) for s in listed
|
|
575
|
+
if s.file.path.name in m.row_counts and m.row_counts[s.file.path.name] != s.rows]
|
|
576
|
+
if mism:
|
|
577
|
+
add(CheckResult("CL-ING-004", "FAIL", "; ".join(f"{n}: manifest {c:,} rows, read {r:,}"
|
|
578
|
+
for n, c, r in mism[:5]), scope,
|
|
579
|
+
"The file is truncated or from a different run than the manifest."))
|
|
580
|
+
else:
|
|
581
|
+
add(CheckResult("CL-ING-004", "PASS", "Row counts match the manifest.", scope))
|
|
582
|
+
|
|
583
|
+
# Files inside a manifest's delivery folder that no manifest lists: older assemblies / runs.
|
|
584
|
+
stale = []
|
|
585
|
+
for m in manifests:
|
|
586
|
+
if m.kind == "unknown":
|
|
587
|
+
continue
|
|
588
|
+
root = m.path.parent
|
|
589
|
+
for s in sources:
|
|
590
|
+
if s.file.source_id in claimed:
|
|
591
|
+
continue
|
|
592
|
+
if root in s.file.path.parents:
|
|
593
|
+
stale.append((m, s))
|
|
594
|
+
for m, s in stale:
|
|
595
|
+
add(CheckResult("CL-ING-003", "FAIL",
|
|
596
|
+
f"{s.file.path.parent.name}/{s.file.path.name} sits inside the delivery folder of "
|
|
597
|
+
f"{m.path.name} but is not listed in it: it belongs to an older delivery and double counts.",
|
|
598
|
+
s.file.display_name, "Delete files not listed in the current manifest, or pass only the "
|
|
599
|
+
"files the manifest lists."))
|
|
600
|
+
|
|
601
|
+
# Two complete deliveries of the same export and period.
|
|
602
|
+
groups: dict[tuple, list] = defaultdict(list)
|
|
603
|
+
for m in manifests:
|
|
604
|
+
if m.kind != "unknown" and m.billing_period and any(m in claimed[i] for i in claimed):
|
|
605
|
+
groups[(m.kind, m.identity, m.billing_period, str(m.path.parent.parent))].append(m)
|
|
606
|
+
for (kind, _ident, period, _root), ms in groups.items():
|
|
607
|
+
if len(ms) > 1:
|
|
608
|
+
add(CheckResult("CL-ING-003", "FAIL",
|
|
609
|
+
f"{len(ms)} deliveries of the same {kind} export for {period} are present "
|
|
610
|
+
f"({', '.join(str(x.path.parent.name) for x in ms[:4])}); every row would be counted "
|
|
611
|
+
f"{len(ms)} times.", period, "Keep only the latest delivery (newest manifest)."))
|