|
| 1 | +import os |
| 2 | +import gzip |
| 3 | +import shutil |
| 4 | +import hashlib |
| 5 | +import time |
| 6 | +import requests |
| 7 | +from datetime import datetime, timedelta |
| 8 | +from pathlib import Path |
| 9 | +from requests.exceptions import RequestException, ConnectionError, Timeout |
| 10 | + |
| 11 | +# Constants |
| 12 | +DATASET_FOLDER = Path("datasets") |
| 13 | +REMOTE_STORAGE_URL = "https://cloudexit-oss-data-eu.fsn1.your-objectstorage.com" |
| 14 | + |
| 15 | +def get_monday_date(): |
| 16 | + now = datetime.utcnow() |
| 17 | + monday = now - timedelta(days=now.weekday()) |
| 18 | + |
| 19 | + if now.weekday() == 0 and now.hour < 8: |
| 20 | + last_monday = monday - timedelta(days=7) |
| 21 | + return last_monday.strftime("cloudexit-%Y-%m-%d.db.gz") |
| 22 | + else: |
| 23 | + return monday.strftime("cloudexit-%Y-%m-%d.db.gz") |
| 24 | + |
| 25 | +def compute_file_hash(filepath): |
| 26 | + hash_sha256 = hashlib.sha256() |
| 27 | + with open(filepath, "rb") as f: |
| 28 | + for chunk in iter(lambda: f.read(4096), b""): |
| 29 | + hash_sha256.update(chunk) |
| 30 | + return hash_sha256.hexdigest() |
| 31 | + |
| 32 | +def download_file(url, destination, retries=3, delay=5): |
| 33 | + for attempt in range(retries): |
| 34 | + try: |
| 35 | + response = requests.get(url, stream=True, timeout=30) |
| 36 | + response.raise_for_status() |
| 37 | + |
| 38 | + with open(destination, "wb") as f: |
| 39 | + shutil.copyfileobj(response.raw, f) |
| 40 | + |
| 41 | + print(f"[INFO] Download successful: {destination}") |
| 42 | + return True |
| 43 | + |
| 44 | + except ConnectionError: |
| 45 | + print(f"[ERROR] Connection failed while downloading {url}. Retrying ({attempt + 1}/{retries})...") |
| 46 | + except Timeout: |
| 47 | + print(f"[ERROR] Request timed out while downloading {url}. Retrying ({attempt + 1}/{retries})...") |
| 48 | + except RequestException as e: |
| 49 | + print(f"[ERROR] Failed to download {url}: {e}") |
| 50 | + break |
| 51 | + |
| 52 | + time.sleep(delay) |
| 53 | + |
| 54 | + print(f"[ERROR] Unable to download file after {retries} attempts: {url}") |
| 55 | + return False |
| 56 | + |
| 57 | +def fetch_remote_checksum(checksum_url, retries=3, delay=5): |
| 58 | + for attempt in range(retries): |
| 59 | + try: |
| 60 | + response = requests.get(checksum_url, timeout=10) |
| 61 | + response.raise_for_status() |
| 62 | + return response.text.strip().split()[0] |
| 63 | + |
| 64 | + except ConnectionError: |
| 65 | + print(f"[ERROR] Connection failed when fetching {checksum_url}. Retrying ({attempt + 1}/{retries})...") |
| 66 | + except Timeout: |
| 67 | + print(f"[ERROR] Request timed out when fetching {checksum_url}. Retrying ({attempt + 1}/{retries})...") |
| 68 | + except RequestException as e: |
| 69 | + print(f"[ERROR] Failed to fetch {checksum_url}: {e}") |
| 70 | + break |
| 71 | + |
| 72 | + time.sleep(delay) |
| 73 | + |
| 74 | + print(f"[ERROR] Unable to fetch remote checksum after {retries} attempts.") |
| 75 | + return None |
| 76 | + |
| 77 | +def initialize_dataset(): |
| 78 | + DATASET_FOLDER.mkdir(exist_ok=True) |
| 79 | + |
| 80 | + latest_file = get_monday_date() |
| 81 | + latest_file_url = f"{REMOTE_STORAGE_URL}/{latest_file}" |
| 82 | + latest_checksum_url = f"{REMOTE_STORAGE_URL}/{latest_file}.sha256" |
| 83 | + latest_symlink_file = f"{REMOTE_STORAGE_URL}/cloudexit-latest.db.gz" |
| 84 | + latest_symlink_checksum_url = f"{REMOTE_STORAGE_URL}/cloudexit-latest.db.gz.sha256" |
| 85 | + |
| 86 | + local_db_path = DATASET_FOLDER / "data.db" |
| 87 | + local_compressed_path = DATASET_FOLDER / latest_file |
| 88 | + |
| 89 | + # Fetch checksum for the date-based file |
| 90 | + remote_checksum = fetch_remote_checksum(latest_checksum_url) |
| 91 | + if not remote_checksum: |
| 92 | + print(f"[INFO] Unable to fetch remote checksum from {latest_checksum_url}.") |
| 93 | + print(f"[INFO] Trying latest symlink from {latest_symlink_checksum_url}...") |
| 94 | + remote_checksum = fetch_remote_checksum(latest_symlink_checksum_url) |
| 95 | + latest_file_url = latest_symlink_file |
| 96 | + latest_file = "cloudexit-latest.db.gz" |
| 97 | + local_compressed_path = DATASET_FOLDER / latest_file |
| 98 | + |
| 99 | + if not remote_checksum: |
| 100 | + print("[ERROR] Unable to fetch any remote checksum. Skipping update.") |
| 101 | + |
| 102 | + else: |
| 103 | + # Check if local compressed file exists |
| 104 | + if local_compressed_path.exists(): |
| 105 | + local_checksum = compute_file_hash(local_compressed_path) |
| 106 | + if local_checksum == remote_checksum: |
| 107 | + print("[INFO] Local dataset is up-to-date. No download needed.") |
| 108 | + return |
| 109 | + else: |
| 110 | + print("[INFO] Local dataset is outdated. Removing old files and downloading new dataset...") |
| 111 | + |
| 112 | + # Remove all old compressed and extracted files |
| 113 | + for file in DATASET_FOLDER.glob("cloudexit-*.db.gz"): |
| 114 | + os.remove(file) |
| 115 | + if local_db_path.exists(): |
| 116 | + os.remove(local_db_path) |
| 117 | + |
| 118 | + # Download and extract dataset |
| 119 | + if download_file(latest_file_url, local_compressed_path): |
| 120 | + print(f"[INFO] Download successful. Extracting dataset from {latest_file}...") |
| 121 | + |
| 122 | + with gzip.open(local_compressed_path, "rb") as f_in, open(local_db_path, "wb") as f_out: |
| 123 | + shutil.copyfileobj(f_in, f_out) |
| 124 | + |
| 125 | + print("[INFO] Dataset updated successfully.") |
| 126 | + |
| 127 | + if not any(DATASET_FOLDER.iterdir()): |
| 128 | + print("[ERROR] Dataset folder is empty! Cannot proceed without data.") |
| 129 | + exit(1) |
0 commit comments