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.
@@ -0,0 +1,144 @@
1
+ """FOCUS adapter (FinOps Open Cost and Usage Specification 1.0 - 1.4).
2
+
3
+ CloudLeak reads FOCUS; it does not certify it. For normative conformance use
4
+ the FinOps Foundation's focus_validator. What CloudLeak adds is the semantic
5
+ layer: which columns a provider actually populated, whether invoice scope is
6
+ present, and what the data can support.
7
+
8
+ Version inference is approximate and stated as such: a file is labeled with
9
+ the newest version whose distinguishing columns it carries.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from cloudleak.errors import InputError
15
+ from cloudleak.providers.base import Columns, Mapping, month_start
16
+
17
+ # Columns whose presence distinguishes a FOCUS version (normalized names).
18
+ VERSION_MARKERS: list[tuple[str, tuple[str, ...]]] = [
19
+ ("1.4", ("invoice_detail_id", "commitment_program_eligibility_details")),
20
+ ("1.3", ("service_provider_name", "host_provider_name", "contract_applied", "allocated_method_details",
21
+ "allocated_method_id", "allocated_resource_id", "allocated_resource_name", "allocated_tags")),
22
+ ("1.2", ("invoice_id", "pricing_currency", "pricing_currency_effective_cost",
23
+ "pricing_currency_list_unit_price", "pricing_currency_contracted_unit_price")),
24
+ ("1.1", ("sku_meter", "sku_price_details", "service_subcategory", "capacity_reservation_id",
25
+ "capacity_reservation_status", "commitment_discount_quantity", "commitment_discount_unit")),
26
+ ("1.0", ("billed_cost", "effective_cost", "charge_period_start")),
27
+ ]
28
+
29
+ # Columns CloudLeak relies on, and what is lost when they are missing or empty.
30
+ KEY_COLUMNS: dict[str, str] = {
31
+ "billed_cost": "primary cost",
32
+ "effective_cost": "amortized view and commitment accounting",
33
+ "billing_currency": "currency isolation",
34
+ "billing_period_start": "billing period assignment",
35
+ "charge_period_start": "daily coverage and variance",
36
+ "charge_category": "separating tax, credits and purchases from usage",
37
+ "billing_account_id": "account scoping",
38
+ "sub_account_id": "account breakdowns",
39
+ "service_name": "service breakdowns",
40
+ "resource_id": "resource-level findings",
41
+ "region_id": "regional breakdowns",
42
+ "invoice_id": "invoice reconciliation",
43
+ "tags": "ownership attribution",
44
+ "commitment_discount_status": "unused commitment detection",
45
+ "sku_id": "SKU-level variance",
46
+ "consumed_quantity": "rate versus volume decomposition",
47
+ }
48
+
49
+ VALID_CHARGE_CATEGORIES = ("Usage", "Purchase", "Tax", "Credit", "Adjustment")
50
+
51
+
52
+ def score(cols: Columns) -> float:
53
+ core = ("billed_cost", "charge_period_start", "charge_category", "billing_currency", "service_name")
54
+ hits = sum(1 for c in core if c in cols.by_norm)
55
+ return 0.9 + hits / 100 if "billed_cost" in cols.by_norm and hits >= 3 else 0.0
56
+
57
+
58
+ def detect_version(cols: Columns) -> str:
59
+ for version, markers in VERSION_MARKERS:
60
+ if any(m in cols.by_norm for m in markers):
61
+ return version
62
+ return "1.0"
63
+
64
+
65
+ def provider_sql(cols: Columns) -> str:
66
+ name = cols.text("service_provider_name", "provider_name")
67
+ return (
68
+ f"CASE WHEN lower({name}) LIKE '%amazon%' OR lower({name}) LIKE 'aws%' THEN 'aws' "
69
+ f"WHEN lower({name}) LIKE '%microsoft%' OR lower({name}) LIKE '%azure%' THEN 'azure' "
70
+ f"WHEN lower({name}) LIKE '%google%' OR lower({name}) LIKE '%gcp%' THEN 'gcp' "
71
+ f"WHEN {name} IS NULL THEN 'focus' ELSE lower({name}) END"
72
+ )
73
+
74
+
75
+ def build(cols: Columns) -> Mapping:
76
+ c = cols
77
+ if c.has("invoice_issue_status", "invoice_detail_grain", "invoice_detail_created", "invoice_issue_date",
78
+ "invoice_detail_last_updated", "payment_currency_billed_cost", "invoice_detail_description",
79
+ "payment_currency_invoice_detail_id", "reference_invoice_id", "payment_terms", "payment_due_date"):
80
+ raise InputError("FOCUS invoice-detail data cannot be summed as cost and usage",
81
+ hint="Supply the cost-and-usage dataset separately.")
82
+ category = c.text("charge_category")
83
+ period = c.ts("billing_period_start")
84
+ charge_start = c.ts("charge_period_start")
85
+ status = c.text("commitment_discount_status")
86
+ pcat = c.text("pricing_category")
87
+ version = detect_version(c)
88
+ invoice = c.text("invoice_id")
89
+ if c.has("x_invoice_id"):
90
+ # Microsoft exports used an extension before InvoiceId was standardized.
91
+ azure_invoice = f"CASE WHEN {provider_sql(c)} = 'azure' THEN {c.text('x_invoice_id')} END"
92
+ invoice = f"coalesce({invoice}, {azure_invoice})"
93
+ m = Mapping(
94
+ provider="focus", # replaced per row by provider_sql in the engine
95
+ dataset=f"focus_{version.replace('.', '_')}",
96
+ cost_basis="billed",
97
+ cost_raw=c.text("billed_cost"),
98
+ cost=c.money("billed_cost"),
99
+ effective_cost=c.money("effective_cost"),
100
+ list_cost=c.money("list_cost"),
101
+ billing_account_id=c.text("billing_account_id"),
102
+ sub_account_id=c.text("sub_account_id"),
103
+ sub_account_name=c.text("sub_account_name"),
104
+ invoice_id=invoice,
105
+ invoice_issuer=c.text("invoice_issuer_name"),
106
+ billing_period_start=month_start(period),
107
+ charge_start=charge_start,
108
+ charge_end=c.ts("charge_period_end"),
109
+ currency=c.text("billing_currency"),
110
+ charge_raw=category,
111
+ charge_category=(
112
+ f"CASE lower({category}) WHEN 'usage' THEN 'usage' WHEN 'purchase' THEN 'purchase' "
113
+ f"WHEN 'tax' THEN 'tax' WHEN 'credit' THEN 'credit' WHEN 'adjustment' THEN 'adjustment' "
114
+ f"ELSE 'unknown' END"
115
+ ),
116
+ charge_class=c.text("charge_class"),
117
+ service=c.text("service_name"),
118
+ sku=c.text("sku_meter", "charge_description", "service_subcategory", "sku_id"),
119
+ sku_detail=c.text("charge_description", "sku_id"),
120
+ resource_id=c.text("resource_id"),
121
+ region=c.text("region_id", "region_name", "region"),
122
+ usage_quantity=c.money("consumed_quantity", "pricing_quantity"),
123
+ usage_unit=c.text("consumed_unit", "pricing_unit"),
124
+ tags=(
125
+ f"CASE WHEN json_valid({c.text('tags')}) THEN NULLIF(CAST({c.text('tags')} AS VARCHAR), '{{}}') END"
126
+ if c.has("tags") else "CAST(NULL AS VARCHAR)"
127
+ ),
128
+ pricing_model=(
129
+ f"CASE lower(COALESCE({pcat}, '')) WHEN 'standard' THEN 'on_demand' "
130
+ f"WHEN 'committed' THEN 'commitment' WHEN 'dynamic' THEN 'spot' ELSE 'unknown' END"
131
+ ),
132
+ commitment_status=f"lower({status})" if c.has("commitment_discount_status") else "CAST(NULL AS VARCHAR)",
133
+ focus_version=version,
134
+ provider_sql=provider_sql(c),
135
+ )
136
+ m.capabilities = {
137
+ "invoice_id": c.has("invoice_id", "x_invoice_id"),
138
+ "resource_id": c.has("resource_id"),
139
+ "tags": c.has("tags"),
140
+ "effective_cost": c.has("effective_cost"),
141
+ }
142
+ m.notes.append(f"Cost-and-usage columns suggest FOCUS {version} or later. Header inference alone "
143
+ "cannot establish version or provider conformance.")
144
+ return m
@@ -0,0 +1,147 @@
1
+ """Google Cloud Billing export adapter (standard and detailed usage cost).
2
+
3
+ Accounting notes encoded here:
4
+ * ``cost`` is gross. Net cost, the amount invoiced, is
5
+ ``cost + SUM(credits.amount)``. CloudLeak's primary cost is net.
6
+ * The invoice a row belongs to is ``invoice.month``, not the usage date.
7
+ Late-arriving usage posts to a later invoice month.
8
+ * Standard exports have no resource identifiers; detailed exports add
9
+ ``resource.name`` / ``resource.global_name``.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from cloudleak.providers.base import Columns, Mapping
15
+
16
+ SIGNATURE = ("service_description", "sku_description", "usage_start_time", "project_id",
17
+ "invoice_month", "billing_account_id", "cost_type", "credits")
18
+
19
+
20
+ def score(cols: Columns) -> float:
21
+ if "cost" not in cols.by_norm:
22
+ return 0.0
23
+ hits = sum(1 for c in SIGNATURE if c in cols.by_norm)
24
+ return hits / len(SIGNATURE) if cols.has("service_description", "sku_description") else 0.0
25
+
26
+
27
+ # Fields consumed from native BigQuery STRUCTs. Flatten only these children
28
+ # and retain their typed values until projecting to the canonical text schema.
29
+ STRUCT_FIELDS = {
30
+ "service": {"description"}, "sku": {"id", "description"}, "project": {"id", "name"},
31
+ "invoice": {"month"}, "resource": {"name", "global_name"},
32
+ "location": {"location", "region", "zone"},
33
+ "usage": {"amount", "unit", "amount_in_pricing_units", "pricing_unit"},
34
+ "consumption_model": {"id", "description"},
35
+ }
36
+
37
+
38
+ # DuckDB's generic JSON extraction parses bare decimal literals as DOUBLE.
39
+ # Tokenize valid JSON and quote its number tokens before extracting amounts.
40
+ # The first alternative consumes whole JSON strings, including escaped quotes.
41
+ CREDIT_JSON_MACRO = r"""CREATE MACRO cl_gcp_credit_json(input_json) AS
42
+ CASE WHEN regexp_matches(regexp_replace(input_json, '"(?:[^"\\]|\\.)*"', '""', 'g'),
43
+ ',\s*[}\]]|(?i)\b(nan|inf|infinity)\b')
44
+ THEN error('Invalid GCP credits JSON')
45
+ ELSE array_to_string(list_transform(regexp_extract_all(input_json,
46
+ '"(?:[^"\\]|\\.)*"|-?[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?|[^\s]'),
47
+ lambda tok: CASE WHEN regexp_matches(tok, '^-?[0-9]') THEN '"' || tok || '"' ELSE tok END), '') END"""
48
+
49
+
50
+ def build(cols: Columns) -> Mapping:
51
+ c = cols
52
+ cost_col = "unrounded_cost" if c.has("unrounded_cost") else "cost"
53
+ gross = c.money(cost_col)
54
+ credits = "0"
55
+ if c.has("credits_amount"):
56
+ amount = c.text("credits_amount")
57
+ credits = (f"CASE WHEN {amount} IS NULL THEN 0 ELSE "
58
+ f"COALESCE(cl_money({amount}), error('Invalid GCP credits.amount')) END")
59
+ if c.has("credits"):
60
+ cr = c.text("credits")
61
+ duplicate = (f"WHEN {c.text('credits_amount')} IS NOT NULL THEN error('Ambiguous GCP credit columns') "
62
+ if c.has("credits_amount") else "")
63
+ credits = (
64
+ f"CASE WHEN {cr} IS NULL THEN {credits} {duplicate}"
65
+ f"WHEN NOT json_valid({cr}) THEN error('Invalid GCP credits JSON') "
66
+ f"WHEN json_type({cr}) <> 'ARRAY' THEN error('GCP credits must be an array') "
67
+ f"ELSE (SELECT COALESCE(SUM(CASE WHEN list_count(list_filter(json_keys(e), lambda k: k = 'amount')) = 1 "
68
+ f"THEN COALESCE(cl_money(json_extract_string(e, '$.amount')), error('Invalid GCP credit amount')) "
69
+ f"ELSE error('Each GCP credit must have one amount') END), 0) "
70
+ f"FROM unnest(CAST(json_extract(cl_gcp_credit_json({cr}), '$[*]') AS JSON[])) AS credits(e)) END"
71
+ )
72
+ net = f"({gross} + {credits})"
73
+
74
+ inv = c.text("invoice_month")
75
+ usage_start = c.ts("usage_start_time", "usage_start_date")
76
+ period = (
77
+ f"CASE WHEN regexp_full_match({inv}, '[0-9]{{6}}') AND left({inv}, 4) <> '0000' "
78
+ f"AND try_strptime({inv}, '%Y%m') IS NOT NULL "
79
+ f"THEN CAST(try_strptime({inv}, '%Y%m') AS DATE) ELSE error('Missing or invalid GCP invoice.month') END"
80
+ if c.has("invoice_month") else "CAST(NULL AS DATE)"
81
+ )
82
+ labels = c.text("labels", "project_labels")
83
+ if c.has("labels"):
84
+ tags = (
85
+ f"CASE WHEN {labels} IS NULL OR NOT json_valid({labels}) THEN NULL "
86
+ f"WHEN json_type({labels}) = 'ARRAY' THEN NULLIF(CAST(to_json(map_from_entries("
87
+ f"list_transform(CAST(json_extract({labels}, '$[*]') AS JSON[]), "
88
+ f"lambda x: {{'key': json_extract_string(x, '$.key'), 'value': json_extract_string(x, '$.value')}})"
89
+ f")) AS VARCHAR), '{{}}') "
90
+ f"ELSE NULLIF(CAST({labels} AS VARCHAR), '{{}}') END"
91
+ )
92
+ else:
93
+ tags = "CAST(NULL AS VARCHAR)"
94
+
95
+ detailed = c.has("resource_name", "resource_global_name")
96
+ cost_type = c.text("cost_type")
97
+ m = Mapping(
98
+ provider="gcp",
99
+ dataset="gcp_detailed" if detailed else "gcp_standard",
100
+ cost_basis="billed",
101
+ cost_raw=c.text(cost_col),
102
+ cost=net,
103
+ gross_cost=gross,
104
+ effective_cost=net,
105
+ list_cost=c.money("cost_at_list"),
106
+ billing_account_id=c.text("billing_account_id"),
107
+ sub_account_id=c.text("project_id"),
108
+ sub_account_name=c.text("project_name"),
109
+ billing_period_start=period,
110
+ charge_start=usage_start,
111
+ charge_end=c.ts("usage_end_time", "usage_end_date"),
112
+ currency=c.text("currency"),
113
+ charge_raw=cost_type,
114
+ charge_category=(
115
+ f"CASE lower(COALESCE({cost_type}, 'regular')) WHEN 'regular' THEN 'usage' WHEN 'tax' THEN 'tax' "
116
+ f"WHEN 'adjustment' THEN 'adjustment' WHEN 'rounding_error' THEN 'adjustment' ELSE 'unknown' END"
117
+ ),
118
+ service=c.text("service_description"),
119
+ sku=c.text("sku_description"),
120
+ sku_detail=c.text("sku_id"),
121
+ resource_id=c.text("resource_global_name", "resource_name"),
122
+ region=c.text("location_region", "location_location", "location_zone"),
123
+ usage_quantity=c.money("usage_amount_in_pricing_units", "usage_amount"),
124
+ usage_unit=c.text("usage_pricing_unit", "usage_unit"),
125
+ tags=tags,
126
+ pricing_model=(
127
+ f"CASE WHEN {c.text('consumption_model_description', 'consumption_model_id')} IS NOT NULL "
128
+ f"AND lower({c.text('consumption_model_description', 'consumption_model_id')}) LIKE '%commit%' "
129
+ f"THEN 'commitment' ELSE 'unknown' END"
130
+ ) if c.has("consumption_model_description", "consumption_model_id") else "'unknown'",
131
+ )
132
+ m.capabilities = {
133
+ "invoice_id": False,
134
+ "invoice_month": c.has("invoice_month"),
135
+ "resource_id": detailed,
136
+ "tags": c.has("labels"),
137
+ "effective_cost": True,
138
+ "consumption_model": c.has("consumption_model_id", "consumption_model_description"),
139
+ "credits": c.has("credits", "credits_amount"),
140
+ }
141
+ if c.has("invoice_month"):
142
+ m.notes.append("GCP invoice.month identifies a billing month. Use --period and the billing account scope.")
143
+ else:
144
+ m.notes.append("GCP invoice.month is absent. The invoice period is unknown.")
145
+ if not c.has("credits", "credits_amount"):
146
+ m.notes.append("No credits column: net cost equals gross cost, which overstates spend if credits apply.")
147
+ return m
@@ -0,0 +1,171 @@
1
+ """Stage local reports and roll back ordinary failures while publishing a set."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import shutil
7
+ import stat
8
+ import tempfile
9
+ import time
10
+ from collections.abc import Callable, Iterator
11
+ from contextlib import ExitStack, contextmanager
12
+ from pathlib import Path
13
+
14
+ from cloudleak.errors import InputError
15
+
16
+
17
+ @contextmanager
18
+ def _lock_directory(parent: Path) -> Iterator[None]:
19
+ if os.name == "posix":
20
+ import fcntl
21
+
22
+ fd = os.open(parent, os.O_RDONLY)
23
+ try:
24
+ fcntl.flock(fd, fcntl.LOCK_EX)
25
+ yield
26
+ finally:
27
+ os.close(fd)
28
+ else:
29
+ # Directory creation is exclusive on Windows as well. A killed writer can
30
+ # leave this lock behind, so report the path and bound the wait.
31
+ lock = parent / ".cloudleak-publication-lock"
32
+ deadline = time.monotonic() + 10
33
+ while True:
34
+ try:
35
+ lock.mkdir(mode=0o700)
36
+ break
37
+ except FileExistsError:
38
+ if time.monotonic() >= deadline:
39
+ raise InputError(f"another writer holds {lock}",
40
+ hint="After confirming all writers have stopped, remove the lock.") from None
41
+ time.sleep(0.05)
42
+ try:
43
+ yield
44
+ finally:
45
+ lock.rmdir()
46
+
47
+
48
+ def _check_targets(destinations: list[Path], inputs: list[Path]) -> None:
49
+ protected = {(s.st_dev, s.st_ino) for s in (path.stat() for path in inputs)}
50
+ seen = set()
51
+ for dest in destinations:
52
+ try:
53
+ info = dest.stat()
54
+ except FileNotFoundError:
55
+ continue
56
+ if not stat.S_ISREG(info.st_mode):
57
+ raise InputError(f"{dest}: expected a regular report file")
58
+ identity = (info.st_dev, info.st_ino)
59
+ if identity in protected:
60
+ raise InputError(f"refusing to overwrite input file {dest}")
61
+ if identity in seen:
62
+ raise InputError(f"multiple report paths refer to the same file: {dest}")
63
+ seen.add(identity)
64
+
65
+
66
+ def publish_reports(paths: list[str], inputs: list[Path], render: Callable[[str], str]) -> None:
67
+ if not paths:
68
+ return
69
+ destinations = [Path(p).expanduser().resolve() for p in paths]
70
+ if len(set(destinations)) != len(destinations):
71
+ raise InputError("multiple report paths refer to the same destination")
72
+ if any(parent in destinations for dest in destinations for parent in dest.parents):
73
+ raise InputError("a report path is also a parent directory of another report")
74
+ parents = sorted({dest.parent for dest in destinations})
75
+ staged: dict[Path, Path] = {}
76
+ with ExitStack() as stack:
77
+ for parent in parents:
78
+ parent.mkdir(parents=True, exist_ok=True)
79
+ for raw, dest in zip(paths, destinations):
80
+ with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", newline="", prefix=".cloudleak-report-",
81
+ dir=dest.parent, delete=False) as stream:
82
+ staged[dest] = Path(stream.name)
83
+ stack.callback(staged[dest].unlink, missing_ok=True)
84
+ stream.write(render(raw))
85
+ _commit_files(staged, inputs)
86
+
87
+
88
+ def _commit_files(staged: dict[Path, Path], inputs: list[Path], *, locked: Path | None = None) -> None:
89
+ destinations = list(staged)
90
+ parents = sorted({dest.parent for dest in destinations})
91
+ backups: dict[Path, Path] = {}
92
+ with ExitStack() as stack:
93
+ # Stable acquisition order also covers writers sharing only part of a set.
94
+ for parent in parents:
95
+ if parent != locked:
96
+ stack.enter_context(_lock_directory(parent))
97
+ _check_targets(destinations, inputs)
98
+ committed = []
99
+ try:
100
+ if len(destinations) > 1:
101
+ for dest in destinations:
102
+ if dest.exists():
103
+ with tempfile.NamedTemporaryFile(prefix=".cloudleak-backup-", dir=dest.parent,
104
+ delete=False) as backup:
105
+ backups[dest] = Path(backup.name)
106
+ shutil.copy2(dest, backups[dest])
107
+ for dest, staged_path in staged.items():
108
+ os.replace(staged_path, dest)
109
+ committed.append(dest)
110
+ except BaseException:
111
+ recovery_errors = []
112
+ for dest in reversed(committed):
113
+ try:
114
+ if dest in backups:
115
+ os.replace(backups[dest], dest)
116
+ else:
117
+ dest.unlink()
118
+ except OSError as exc:
119
+ original = backups.pop(dest, None)
120
+ recovery_errors.append(f"{dest}: {exc}" + (f" (original at {original})" if original else ""))
121
+ if recovery_errors:
122
+ raise InputError("report rollback needs attention: " + "; ".join(recovery_errors)) from None
123
+ raise
124
+ finally:
125
+ for backup_path in backups.values():
126
+ backup_path.unlink(missing_ok=True)
127
+
128
+
129
+ def _check_demo_target(target: Path, force: bool) -> None:
130
+ if target.is_symlink() or (target.exists() and not target.is_dir()):
131
+ raise InputError(f"{target}: expected a demo directory")
132
+ if target.exists() and not force and any(target.iterdir()):
133
+ raise InputError(f"{target} is not empty", hint="Choose an empty directory or pass --force.")
134
+
135
+
136
+ @contextmanager
137
+ def staged_demo(target: Path, force: bool) -> Iterator[Path]:
138
+ """Publish only after generation and audit succeed. Preserve unrelated files on refresh."""
139
+ target = target.absolute()
140
+ _check_demo_target(target, force)
141
+ target.parent.mkdir(parents=True, exist_ok=True)
142
+ with tempfile.TemporaryDirectory(prefix=".cloudleak-demo-", dir=target.parent) as tmp:
143
+ tree = Path(tmp) / "demo"
144
+ tree.mkdir(mode=0o700)
145
+ yield tree
146
+ with _lock_directory(target.parent):
147
+ _check_demo_target(target, force)
148
+ if not target.exists():
149
+ os.rename(tree, target)
150
+ return
151
+ created = []
152
+ staged = {}
153
+ try:
154
+ for src in sorted(tree.rglob("*")):
155
+ dest = target / src.relative_to(tree)
156
+ if dest.is_symlink():
157
+ raise InputError(f"{dest}: refusing to follow a symlink in the demo destination")
158
+ if src.is_dir():
159
+ if not dest.exists():
160
+ dest.mkdir()
161
+ created.append(dest)
162
+ elif not dest.is_dir():
163
+ raise InputError(f"{dest}: expected a demo directory")
164
+ else:
165
+ staged[dest] = src
166
+ _commit_files(staged, [], locked=target.parent)
167
+ except BaseException:
168
+ for directory in reversed(created):
169
+ if not any(directory.iterdir()):
170
+ directory.rmdir()
171
+ raise
cloudleak/py.typed ADDED
File without changes