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
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
|
3
|
+
"$id": "https://github.com/pranavg21/cloudleak/schemas/finding.v1.schema.json",
|
|
4
|
+
"title": "cloudleak.finding.v1",
|
|
5
|
+
"description": "One evidence-graded CloudLeak finding. Billing data alone never exceeds evidence level L2, and verified_savings is always null at L1 and L2.",
|
|
6
|
+
"type": "object",
|
|
7
|
+
"additionalProperties": false,
|
|
8
|
+
"required": [
|
|
9
|
+
"schema_version", "finding_id", "report_run_id", "rule_id", "title", "summary", "classification",
|
|
10
|
+
"evidence_level", "severity", "provider", "billing_account_id", "sub_account_id", "resource_id",
|
|
11
|
+
"resource_id_source", "region", "service", "billing_period", "billing_period_start", "billing_period_end",
|
|
12
|
+
"period_finality", "currency", "financials", "exact_evidence", "unknown_information",
|
|
13
|
+
"potential_false_positives", "required_verification_steps", "owner_routing", "details", "review_status",
|
|
14
|
+
"action_risk", "approval_history", "verified_outcome", "reproducibility"
|
|
15
|
+
],
|
|
16
|
+
"properties": {
|
|
17
|
+
"schema_version": {"const": "cloudleak.finding.v1"},
|
|
18
|
+
"finding_id": {"type": "string", "pattern": "^clf_[0-9a-f]{20}$"},
|
|
19
|
+
"report_run_id": {"type": "string", "pattern": "^clr_[0-9a-f]{20}$"},
|
|
20
|
+
"rule_id": {"type": "string", "pattern": "^CL-[A-Z]{3}-[0-9]{3}$"},
|
|
21
|
+
"title": {"type": "string"},
|
|
22
|
+
"summary": {"type": "string"},
|
|
23
|
+
"classification": {"enum": ["qa_defect", "reconciliation_delta", "variance_driver", "billing_signature_candidate"]},
|
|
24
|
+
"evidence_level": {"enum": ["L1", "L2", "L3", "L4", "L5"]},
|
|
25
|
+
"severity": {"enum": ["info", "low", "medium", "high"]},
|
|
26
|
+
"provider": {"type": ["string", "null"]},
|
|
27
|
+
"billing_account_id": {"type": ["string", "null"]},
|
|
28
|
+
"sub_account_id": {"type": ["string", "null"]},
|
|
29
|
+
"resource_id": {"type": ["string", "null"]},
|
|
30
|
+
"resource_id_source": {"type": ["string", "null"]},
|
|
31
|
+
"region": {"type": ["string", "null"]},
|
|
32
|
+
"service": {"type": ["string", "null"]},
|
|
33
|
+
"billing_period": {"type": ["string", "null"], "pattern": "^[0-9]{4}-[0-9]{2}$"},
|
|
34
|
+
"billing_period_start": {"type": ["string", "null"], "format": "date-time"},
|
|
35
|
+
"billing_period_end": {"type": ["string", "null"], "format": "date-time"},
|
|
36
|
+
"period_finality": {"enum": ["finalized", "preliminary_estimate", "unknown"]},
|
|
37
|
+
"currency": {"type": ["string", "null"]},
|
|
38
|
+
"financials": {
|
|
39
|
+
"type": "object",
|
|
40
|
+
"additionalProperties": false,
|
|
41
|
+
"required": ["cost_basis", "observed_cost", "observed_effective_cost", "verified_savings"],
|
|
42
|
+
"properties": {
|
|
43
|
+
"cost_basis": {"type": ["string", "null"], "enum": ["billed", "amortized", "effective", "unknown", null]},
|
|
44
|
+
"observed_billed_cost": {"$ref": "#/$defs/money"},
|
|
45
|
+
"observed_cost": {"$ref": "#/$defs/money"},
|
|
46
|
+
"observed_effective_cost": {"$ref": "#/$defs/money"},
|
|
47
|
+
"verified_savings": {"$ref": "#/$defs/money"}
|
|
48
|
+
}
|
|
49
|
+
},
|
|
50
|
+
"exact_evidence": {
|
|
51
|
+
"type": "object",
|
|
52
|
+
"required": ["rule_id", "matched_rows", "matched_values", "source_sha256", "sample_rows"],
|
|
53
|
+
"properties": {
|
|
54
|
+
"rule_id": {"type": "string"},
|
|
55
|
+
"matched_rows": {"type": "integer", "minimum": 0},
|
|
56
|
+
"matched_values": {"type": "array", "items": {"type": "string"}},
|
|
57
|
+
"source_sha256": {"type": "array", "items": {"type": "string", "pattern": "^[0-9a-f]{64}$"}},
|
|
58
|
+
"sample_rows": {
|
|
59
|
+
"type": "array",
|
|
60
|
+
"items": {"type": "object", "required": ["source_id", "row"],
|
|
61
|
+
"properties": {"source_id": {"type": "integer"}, "row": {"type": "integer"}}}
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
},
|
|
65
|
+
"unknown_information": {"type": "array", "items": {"type": "string"}},
|
|
66
|
+
"potential_false_positives": {"type": "array", "items": {"type": "string"}},
|
|
67
|
+
"required_verification_steps": {
|
|
68
|
+
"type": "array",
|
|
69
|
+
"items": {
|
|
70
|
+
"type": "object",
|
|
71
|
+
"additionalProperties": false,
|
|
72
|
+
"required": ["description", "command", "tool", "action_risk"],
|
|
73
|
+
"properties": {
|
|
74
|
+
"description": {"type": "string"},
|
|
75
|
+
"command": {"type": ["string", "null"]},
|
|
76
|
+
"tool": {"type": ["string", "null"]},
|
|
77
|
+
"action_risk": {"const": "none_readonly"}
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
},
|
|
81
|
+
"owner_routing": {
|
|
82
|
+
"type": "object",
|
|
83
|
+
"required": ["status"],
|
|
84
|
+
"properties": {"status": {"enum": ["tag", "account", "unattributed"]}}
|
|
85
|
+
},
|
|
86
|
+
"details": {"type": "object"},
|
|
87
|
+
"review_status": {"enum": ["unreviewed", "investigating", "accepted", "dismissed", "resolved"]},
|
|
88
|
+
"action_risk": {"enum": ["none_readonly", "low", "medium", "high", "unknown"]},
|
|
89
|
+
"approval_history": {"type": "array"},
|
|
90
|
+
"verified_outcome": {"type": ["object", "null"]},
|
|
91
|
+
"reproducibility": {
|
|
92
|
+
"type": "object",
|
|
93
|
+
"required": ["cloudleak_version", "duckdb_version", "rule_pack_hash"],
|
|
94
|
+
"properties": {
|
|
95
|
+
"cloudleak_version": {"type": "string"},
|
|
96
|
+
"duckdb_version": {"type": "string"},
|
|
97
|
+
"rule_pack_hash": {"type": "string"}
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
},
|
|
101
|
+
"allOf": [
|
|
102
|
+
{
|
|
103
|
+
"if": {"properties": {"evidence_level": {"enum": ["L1", "L2"]}}},
|
|
104
|
+
"then": {"properties": {"financials": {"properties": {"verified_savings": {"type": "null"}}}}}
|
|
105
|
+
},
|
|
106
|
+
{
|
|
107
|
+
"if": {"properties": {"evidence_level": {"const": "L2"}}},
|
|
108
|
+
"then": {"properties": {
|
|
109
|
+
"unknown_information": {"minItems": 1},
|
|
110
|
+
"potential_false_positives": {"minItems": 1},
|
|
111
|
+
"required_verification_steps": {"minItems": 1}
|
|
112
|
+
}}
|
|
113
|
+
}
|
|
114
|
+
],
|
|
115
|
+
"$defs": {
|
|
116
|
+
"money": {
|
|
117
|
+
"description": "Exact decimal as a string (never a JSON number), or null.",
|
|
118
|
+
"type": ["string", "null"],
|
|
119
|
+
"pattern": "^-?[0-9]+\\.[0-9]{2,}$"
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
|
3
|
+
"$id": "https://github.com/pranavg21/cloudleak/schemas/report.v1.schema.json",
|
|
4
|
+
"title": "cloudleak.report.v1",
|
|
5
|
+
"description": "Envelope written by `cloudleak audit|doctor|variance|reconcile --output report.json`. Money values are exact decimal strings.",
|
|
6
|
+
"type": "object",
|
|
7
|
+
"required": ["schema_version", "tool", "run", "trust_boundary", "inputs", "periods", "totals", "findings", "limitations"],
|
|
8
|
+
"properties": {
|
|
9
|
+
"schema_version": {"const": "cloudleak.report.v1"},
|
|
10
|
+
"tool": {
|
|
11
|
+
"type": "object",
|
|
12
|
+
"required": ["name", "version", "duckdb_version", "rule_pack_version", "rule_pack_hash"]
|
|
13
|
+
},
|
|
14
|
+
"run": {
|
|
15
|
+
"type": "object",
|
|
16
|
+
"required": ["report_run_id", "command", "generated_at"],
|
|
17
|
+
"properties": {"report_run_id": {"type": "string", "pattern": "^clr_[0-9a-f]{20}$"}}
|
|
18
|
+
},
|
|
19
|
+
"trust_boundary": {
|
|
20
|
+
"type": "object",
|
|
21
|
+
"properties": {
|
|
22
|
+
"network_access": {"const": "none"},
|
|
23
|
+
"cloud_credentials": {"const": "none"},
|
|
24
|
+
"evidence_ceiling": {"const": "L2"}
|
|
25
|
+
}
|
|
26
|
+
},
|
|
27
|
+
"synthetic_data": {"type": "boolean"},
|
|
28
|
+
"inputs": {
|
|
29
|
+
"type": "array",
|
|
30
|
+
"items": {"type": "object", "required": ["source_id", "name", "format", "bytes", "sha256", "rows"]}
|
|
31
|
+
},
|
|
32
|
+
"periods": {
|
|
33
|
+
"type": "array",
|
|
34
|
+
"items": {
|
|
35
|
+
"type": "object",
|
|
36
|
+
"required": ["provider", "billing_period", "currency", "cost_basis", "finality", "days_covered", "total"],
|
|
37
|
+
"properties": {"finality": {"enum": ["finalized", "preliminary_estimate", "unknown"]}}
|
|
38
|
+
}
|
|
39
|
+
},
|
|
40
|
+
"totals": {"type": "array"},
|
|
41
|
+
"breakdowns": {"type": "object"},
|
|
42
|
+
"doctor": {"type": ["object", "null"]},
|
|
43
|
+
"variance": {"type": ["array", "null"]},
|
|
44
|
+
"findings": {"type": "array", "items": {"$ref": "finding.v1.schema.json"}},
|
|
45
|
+
"limitations": {"type": "array", "items": {"type": "string"}}
|
|
46
|
+
}
|
|
47
|
+
}
|
cloudleak/sources.py
ADDED
|
@@ -0,0 +1,298 @@
|
|
|
1
|
+
"""Zone 1 of the trust boundary: find input files and prove what they are.
|
|
2
|
+
|
|
3
|
+
Nothing here talks to a network. Every file is fingerprinted with SHA-256
|
|
4
|
+
before it is parsed, compressed files are checked for decompression bombs
|
|
5
|
+
and truncation, and manifests are parsed so the doctor can tell a complete
|
|
6
|
+
delivery from a partial one.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import gzip
|
|
12
|
+
import hashlib
|
|
13
|
+
import json
|
|
14
|
+
import os
|
|
15
|
+
import stat
|
|
16
|
+
import zlib
|
|
17
|
+
from dataclasses import dataclass, field
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
|
|
20
|
+
from cloudleak.errors import InputError
|
|
21
|
+
|
|
22
|
+
DATA_SUFFIXES = (".csv", ".csv.gz", ".parquet", ".snappy.parquet", ".gz.parquet", ".zstd.parquet")
|
|
23
|
+
MANIFEST_NAMES = ("manifest.json", "_manifest.json")
|
|
24
|
+
MAX_RATIO = 1000 # decompressed:compressed; billing CSVs compress ~10-40:1
|
|
25
|
+
CHUNK = 1 << 20
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass
|
|
29
|
+
class Manifest:
|
|
30
|
+
"""What a provider manifest claims was delivered."""
|
|
31
|
+
|
|
32
|
+
path: Path
|
|
33
|
+
kind: str # aws_cur_legacy | aws_data_exports | azure_cost_export | unknown
|
|
34
|
+
sha256: str
|
|
35
|
+
files: list[str] = field(default_factory=list) # basenames
|
|
36
|
+
row_counts: dict[str, int] = field(default_factory=dict) # basename -> rows
|
|
37
|
+
billing_period: str | None = None # YYYY-MM
|
|
38
|
+
declared_rows: int | None = None
|
|
39
|
+
columns: list[str] = field(default_factory=list)
|
|
40
|
+
keys: list[str] = field(default_factory=list) # full object keys as listed
|
|
41
|
+
identity: str = "" # which export this manifest belongs to (report / export name and scope)
|
|
42
|
+
|
|
43
|
+
def to_dict(self) -> dict:
|
|
44
|
+
return {
|
|
45
|
+
"path": str(self.path),
|
|
46
|
+
"kind": self.kind,
|
|
47
|
+
"sha256": self.sha256,
|
|
48
|
+
"files": sorted(self.files),
|
|
49
|
+
"billing_period": self.billing_period,
|
|
50
|
+
"declared_rows": self.declared_rows,
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@dataclass
|
|
55
|
+
class SourceFile:
|
|
56
|
+
path: Path
|
|
57
|
+
fmt: str # csv | csv.gz | parquet
|
|
58
|
+
size: int
|
|
59
|
+
sha256: str
|
|
60
|
+
source_id: int = 0
|
|
61
|
+
encoding: str = "utf-8"
|
|
62
|
+
decompressed_size: int | None = None
|
|
63
|
+
|
|
64
|
+
@property
|
|
65
|
+
def display_name(self) -> str:
|
|
66
|
+
return self.path.name
|
|
67
|
+
|
|
68
|
+
def to_dict(self, *, redact_paths: bool = False) -> dict:
|
|
69
|
+
return {
|
|
70
|
+
"source_id": self.source_id,
|
|
71
|
+
"name": f"source-{self.source_id:03d}" if redact_paths else self.path.name,
|
|
72
|
+
"format": self.fmt,
|
|
73
|
+
"bytes": self.size,
|
|
74
|
+
"sha256": self.sha256,
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _fmt_for(path: Path) -> str | None:
|
|
79
|
+
name = path.name.lower()
|
|
80
|
+
if name.endswith(".csv.gz") or name.endswith(".csv.gzip"):
|
|
81
|
+
return "csv.gz"
|
|
82
|
+
if name.endswith(".csv"):
|
|
83
|
+
return "csv"
|
|
84
|
+
if name.endswith(".parquet"):
|
|
85
|
+
return "parquet"
|
|
86
|
+
return None
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _sha256(path: Path) -> str:
|
|
90
|
+
digest = hashlib.sha256()
|
|
91
|
+
with path.open("rb") as fh:
|
|
92
|
+
for block in iter(lambda: fh.read(CHUNK), b""):
|
|
93
|
+
digest.update(block)
|
|
94
|
+
return digest.hexdigest()
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _check_gzip(path: Path, size: int, max_bytes: int) -> int:
|
|
98
|
+
"""Stream-decompress to detect bombs and truncation. Returns decompressed size."""
|
|
99
|
+
ratio_limit = max(size, 1) * MAX_RATIO
|
|
100
|
+
limit = min(max_bytes, ratio_limit)
|
|
101
|
+
total = 0
|
|
102
|
+
try:
|
|
103
|
+
with gzip.open(path, "rb") as fh:
|
|
104
|
+
while block := fh.read(min(CHUNK, limit - total + 1)):
|
|
105
|
+
total += len(block)
|
|
106
|
+
if total > limit:
|
|
107
|
+
if max_bytes <= ratio_limit:
|
|
108
|
+
raise InputError(f"{path.name}: exceeds the decompression budget of {max_bytes:,} bytes",
|
|
109
|
+
hint="Check the export or increase --max-decompressed-gb.")
|
|
110
|
+
raise InputError(
|
|
111
|
+
f"{path.name}: exceeds the decompression ratio limit of {MAX_RATIO}:1. "
|
|
112
|
+
"Refusing a possible decompression bomb.",
|
|
113
|
+
hint="Check the export and supply a regular uncompressed CSV if it is genuine.",
|
|
114
|
+
)
|
|
115
|
+
except (EOFError, zlib.error, gzip.BadGzipFile) as exc:
|
|
116
|
+
raise InputError(
|
|
117
|
+
f"{path.name}: compressed stream is truncated or corrupt ({exc}).",
|
|
118
|
+
hint="Download the file again; partial transfers are common for large exports.",
|
|
119
|
+
) from exc
|
|
120
|
+
return total
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _sniff_encoding(path: Path, fmt: str) -> str:
|
|
124
|
+
opener = gzip.open if fmt == "csv.gz" else open
|
|
125
|
+
with opener(path, "rb") as fh: # type: ignore[operator]
|
|
126
|
+
head = fh.read(4)
|
|
127
|
+
if head.startswith((b"\xff\xfe", b"\xfe\xff")):
|
|
128
|
+
return "utf-16"
|
|
129
|
+
return "utf-8"
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _parse_manifest(path: Path) -> Manifest:
|
|
133
|
+
try:
|
|
134
|
+
with path.open("rb") as stream:
|
|
135
|
+
raw = stream.read(64 * 1024 * 1024 + 1)
|
|
136
|
+
if len(raw) > 64 * 1024 * 1024:
|
|
137
|
+
raise InputError(f"{path.name}: manifest larger than 64 MiB")
|
|
138
|
+
doc = json.loads(raw.decode("utf-8-sig"))
|
|
139
|
+
except (UnicodeDecodeError, json.JSONDecodeError) as exc:
|
|
140
|
+
raise InputError(f"{path.name}: manifest is not valid JSON ({exc}).") from exc
|
|
141
|
+
if not isinstance(doc, dict):
|
|
142
|
+
raise InputError(f"{path.name}: expected a JSON object in the manifest")
|
|
143
|
+
sha = hashlib.sha256(raw).hexdigest()
|
|
144
|
+
|
|
145
|
+
def base(key: str) -> str:
|
|
146
|
+
return key.rstrip("/").rsplit("/", 1)[-1]
|
|
147
|
+
|
|
148
|
+
# AWS legacy CUR uses reportKeys and AWS Data Exports uses dataFiles.
|
|
149
|
+
if "reportKeys" in doc or "dataFiles" in doc:
|
|
150
|
+
key = "reportKeys" if "reportKeys" in doc else "dataFiles"
|
|
151
|
+
entries = doc[key]
|
|
152
|
+
if not isinstance(entries, list) or not all(isinstance(entry, str) and entry for entry in entries):
|
|
153
|
+
raise InputError(f"{path.name}: manifest {key} must be an array of filenames")
|
|
154
|
+
billing_period = doc.get("billingPeriod") or {}
|
|
155
|
+
columns = doc.get("columns") or []
|
|
156
|
+
if not isinstance(billing_period, dict) or not isinstance(columns, list):
|
|
157
|
+
raise InputError(f"{path.name}: invalid billingPeriod or columns in manifest")
|
|
158
|
+
period = _yyyymm(billing_period.get("start"))
|
|
159
|
+
if key == "reportKeys":
|
|
160
|
+
kind = "aws_cur_legacy"
|
|
161
|
+
cols = [f"{c.get('category')}/{c.get('name')}" for c in columns if isinstance(c, dict)]
|
|
162
|
+
ident = "|".join(str(doc.get(k, "")) for k in ("account", "reportName", "reportId"))
|
|
163
|
+
else:
|
|
164
|
+
kind = "aws_data_exports"
|
|
165
|
+
cols = [c["name"] for c in columns if isinstance(c, dict) and isinstance(c.get("name"), str)]
|
|
166
|
+
ident = "|".join(str(doc.get(k, "")) for k in ("account", "exportArn", "exportName", "reportName"))
|
|
167
|
+
return Manifest(path, kind, sha, [base(k) for k in entries], billing_period=period, columns=cols,
|
|
168
|
+
keys=list(entries), identity=ident)
|
|
169
|
+
# Azure Cost Management export manifest: blobs[] with dataRowCount
|
|
170
|
+
if "blobs" in doc:
|
|
171
|
+
if not isinstance(doc["blobs"], list):
|
|
172
|
+
raise InputError(f"{path.name}: manifest blobs must be an array")
|
|
173
|
+
files, counts, keys = [], {}, []
|
|
174
|
+
for blob in doc["blobs"]:
|
|
175
|
+
if not isinstance(blob, dict) or not isinstance(blob.get("blobName"), str) or not blob["blobName"]:
|
|
176
|
+
raise InputError(f"{path.name}: each manifest blob must include a filename")
|
|
177
|
+
keys.append(blob["blobName"])
|
|
178
|
+
name = base(blob["blobName"])
|
|
179
|
+
files.append(name)
|
|
180
|
+
if isinstance(blob.get("dataRowCount"), int):
|
|
181
|
+
counts[name] = blob["dataRowCount"]
|
|
182
|
+
cfg = doc.get("exportConfig") or {}
|
|
183
|
+
time_period = cfg.get("timePeriod") if isinstance(cfg, dict) else None
|
|
184
|
+
period = time_period.get("from") if isinstance(time_period, dict) else None
|
|
185
|
+
ident = "|".join(str(cfg.get(k, "")) for k in ("exportName", "resourceId")) if isinstance(cfg, dict) else ""
|
|
186
|
+
return Manifest(
|
|
187
|
+
path, "azure_cost_export", sha, files, counts, keys=keys, identity=ident,
|
|
188
|
+
billing_period=_yyyymm(period),
|
|
189
|
+
declared_rows=doc.get("dataRowCount") if isinstance(doc.get("dataRowCount"), int) else None,
|
|
190
|
+
)
|
|
191
|
+
return Manifest(path, "unknown", sha)
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def _yyyymm(text: object) -> str | None:
|
|
195
|
+
if not isinstance(text, str):
|
|
196
|
+
return None
|
|
197
|
+
digits = "".join(ch for ch in text if ch.isdigit())
|
|
198
|
+
if len(digits) >= 6:
|
|
199
|
+
return f"{digits[:4]}-{digits[4:6]}"
|
|
200
|
+
return None
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
@dataclass
|
|
204
|
+
class Discovery:
|
|
205
|
+
files: list[SourceFile]
|
|
206
|
+
manifests: list[Manifest]
|
|
207
|
+
skipped: list[tuple[str, str]] # (name, reason)
|
|
208
|
+
roots: list[Path]
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def discover(paths: list[str | os.PathLike], *, max_decompressed: int = 64 << 30) -> Discovery:
|
|
212
|
+
"""Resolve CLI paths into fingerprinted source files.
|
|
213
|
+
|
|
214
|
+
Directories are walked recursively in sorted order so source ids are
|
|
215
|
+
stable between runs. Symlinks are not followed out of the given roots.
|
|
216
|
+
"""
|
|
217
|
+
if not paths:
|
|
218
|
+
raise InputError("no input paths given")
|
|
219
|
+
if max_decompressed < 1:
|
|
220
|
+
raise InputError("the decompression budget must be at least one byte")
|
|
221
|
+
candidates: list[Path] = []
|
|
222
|
+
explicit_files: set[Path] = set()
|
|
223
|
+
roots: list[Path] = []
|
|
224
|
+
skipped: list[tuple[str, str]] = []
|
|
225
|
+
|
|
226
|
+
def walk_error(exc: OSError) -> None:
|
|
227
|
+
raise InputError(f"could not read input directory {exc.filename}: {exc.strerror}",
|
|
228
|
+
hint="Check directory permissions and confirm the export is accessible.") from exc
|
|
229
|
+
|
|
230
|
+
for raw in paths:
|
|
231
|
+
try:
|
|
232
|
+
p = Path(raw).expanduser().resolve(strict=True)
|
|
233
|
+
except FileNotFoundError as exc:
|
|
234
|
+
raise InputError(f"{raw}: no such file or directory") from exc
|
|
235
|
+
roots.append(p if p.is_dir() else p.parent)
|
|
236
|
+
if p.is_dir():
|
|
237
|
+
for dirpath, dirnames, filenames in os.walk(p, onerror=walk_error, followlinks=False):
|
|
238
|
+
dirnames[:] = sorted(d for d in dirnames if not d.startswith("."))
|
|
239
|
+
for fn in sorted(filenames):
|
|
240
|
+
if fn.startswith("."):
|
|
241
|
+
continue
|
|
242
|
+
child = Path(dirpath) / fn
|
|
243
|
+
if child.is_symlink():
|
|
244
|
+
target = child.resolve()
|
|
245
|
+
if p not in target.parents:
|
|
246
|
+
skipped.append((fn, "symlink pointing outside the input directory"))
|
|
247
|
+
continue
|
|
248
|
+
candidates.append(child)
|
|
249
|
+
else:
|
|
250
|
+
explicit_files.add(p)
|
|
251
|
+
candidates.append(p)
|
|
252
|
+
|
|
253
|
+
files: list[SourceFile] = []
|
|
254
|
+
manifests: list[Manifest] = []
|
|
255
|
+
seen: set[tuple[int, int]] = set()
|
|
256
|
+
for path in candidates:
|
|
257
|
+
lname = path.name.lower()
|
|
258
|
+
manifest = lname in MANIFEST_NAMES or lname.endswith("-manifest.json")
|
|
259
|
+
fmt = _fmt_for(path)
|
|
260
|
+
if not manifest and fmt is None:
|
|
261
|
+
reason = "unsupported file type"
|
|
262
|
+
if lname.endswith((".zip", ".tar", ".tgz", ".tar.gz", ".7z")):
|
|
263
|
+
reason = "archives are not opened; extract them first"
|
|
264
|
+
if path in explicit_files:
|
|
265
|
+
raise InputError(f"{path}: {reason}",
|
|
266
|
+
hint="Supply a billing CSV, CSV.GZ, Parquet or recognized manifest.")
|
|
267
|
+
if not lname.endswith((".json", ".md", ".txt", ".pdf")):
|
|
268
|
+
skipped.append((path.name, reason))
|
|
269
|
+
continue
|
|
270
|
+
info = path.stat()
|
|
271
|
+
if not stat.S_ISREG(info.st_mode):
|
|
272
|
+
raise InputError(f"{path}: expected a regular input file")
|
|
273
|
+
identity = (info.st_dev, info.st_ino)
|
|
274
|
+
if identity in seen:
|
|
275
|
+
continue
|
|
276
|
+
seen.add(identity)
|
|
277
|
+
if manifest:
|
|
278
|
+
manifests.append(_parse_manifest(path))
|
|
279
|
+
continue
|
|
280
|
+
size = info.st_size
|
|
281
|
+
if size == 0:
|
|
282
|
+
raise InputError(f"{path.name}: file is empty")
|
|
283
|
+
decompressed = None
|
|
284
|
+
if fmt == "csv.gz":
|
|
285
|
+
decompressed = _check_gzip(path, size, max_decompressed)
|
|
286
|
+
encoding = _sniff_encoding(path, fmt) if fmt != "parquet" else "binary"
|
|
287
|
+
files.append(SourceFile(path, fmt, size, _sha256(path), encoding=encoding,
|
|
288
|
+
decompressed_size=decompressed))
|
|
289
|
+
|
|
290
|
+
files.sort(key=lambda f: str(f.path))
|
|
291
|
+
for i, f in enumerate(files, 1):
|
|
292
|
+
f.source_id = i
|
|
293
|
+
if not files:
|
|
294
|
+
raise InputError(
|
|
295
|
+
"no billing files found (.csv, .csv.gz or .parquet)",
|
|
296
|
+
hint="Point cloudleak at the export directory or at individual files.",
|
|
297
|
+
)
|
|
298
|
+
return Discovery(files, manifests, skipped, sorted(set(roots)))
|