first (big) draft
This commit is contained in:
@@ -0,0 +1,98 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
import_historical.py — Importe en une fois d'anciennes données de coûts,
|
||||
au format JSON produit par cost_report.py --json ou tenant_detail.py --json.
|
||||
|
||||
Les données importées sont stockées en granularity='monthly' (une ligne =
|
||||
une période, généralement un mois), pour ne pas se mélanger avec la
|
||||
collecte journalière du cron qui alimente granularity='daily'.
|
||||
|
||||
Formats acceptés (auto-détectés) :
|
||||
|
||||
1. Sortie multi-tenants de cost_report.py --json :
|
||||
{"start": "...", "end": "...", "results": [
|
||||
{"provider": "AWS", "name": "...", "status": "ok", "total": ..,
|
||||
"currency": "EUR", "by_service": {...}, ...},
|
||||
...
|
||||
]}
|
||||
|
||||
2. Sortie mono-tenant de tenant_detail.py --json :
|
||||
{"tenant": "...", "provider": "AWS", "start": "...", "end": "...",
|
||||
"total": .., "currency": "EUR", "by_service": {...}}
|
||||
|
||||
Utilisation :
|
||||
python import_historical.py --db ../cost_dashboard.db fichier1.json fichier2.json
|
||||
python import_historical.py --db ../cost_dashboard.db historique/*.json
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import sys
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).parent))
|
||||
|
||||
from db import get_connection, init_db, upsert_collection
|
||||
|
||||
|
||||
def import_file(conn, path: str) -> int:
|
||||
with open(path) as f:
|
||||
payload = json.load(f)
|
||||
|
||||
imported = 0
|
||||
collected_at = datetime.now(timezone.utc).isoformat()
|
||||
|
||||
if "results" in payload:
|
||||
# Format multi-tenants (cost_report.py --json)
|
||||
start, end = payload["start"], payload["end"]
|
||||
for r in payload["results"]:
|
||||
provider = r["provider"].lower()
|
||||
if r["status"] != "ok":
|
||||
continue
|
||||
upsert_collection(
|
||||
conn, provider, r["name"], "monthly", start, end,
|
||||
collected_at, "ok", data=r,
|
||||
)
|
||||
imported += 1
|
||||
|
||||
elif "tenant" in payload:
|
||||
# Format mono-tenant (tenant_detail.py --json)
|
||||
provider = payload["provider"].lower()
|
||||
upsert_collection(
|
||||
conn, provider, payload["tenant"], "monthly",
|
||||
payload["start"], payload["end"], collected_at, "ok", data=payload,
|
||||
)
|
||||
imported += 1
|
||||
|
||||
else:
|
||||
print(f" Format non reconnu, ignoré : {path}", file=sys.stderr)
|
||||
|
||||
return imported
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="Import ponctuel de données de coûts historiques")
|
||||
parser.add_argument("--db", default=None, help="Chemin vers la base SQLite")
|
||||
parser.add_argument("files", nargs="+", help="Fichier(s) JSON à importer")
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.db:
|
||||
init_db(args.db)
|
||||
conn = get_connection(args.db)
|
||||
else:
|
||||
init_db()
|
||||
conn = get_connection()
|
||||
|
||||
total_imported = 0
|
||||
for path in args.files:
|
||||
n = import_file(conn, path)
|
||||
print(f"{path} : {n} relevé(s) importé(s)")
|
||||
total_imported += n
|
||||
|
||||
conn.close()
|
||||
print(f"\nTotal : {total_imported} relevé(s) importé(s).")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user