import logging import urllib.request import datetime import time from pathlib import Path from vendor import VendorResolver from oui_import import OUIImporter PROJECT_ROOT = ( Path(__file__).resolve().parent.parent ) DATABASE_DIR = ( PROJECT_ROOT / "database" ) OUI_DATABASE = ( DATABASE_DIR / "oui.sqlite" ) HTTP_HEADERS = { "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) " "AppleWebKit/537.36 " "(KHTML, like Gecko) " "Chrome/138.0 Safari/537.36" } DOWNLOAD_RETRIES = 3 DOWNLOAD_TIMEOUT = 60 CSV_FILES = { "oui.csv": "oui", "mam.csv": "mam", "oui36.csv": "oui36", } class VendorImporter: def __init__( self, config ): self.config = config self.log = logging.getLogger( "vendor_import" ) DATABASE_DIR.mkdir( parents=True, exist_ok=True ) # --------------------------------------------------------- # Загрузка IEEE CSV # --------------------------------------------------------- def download_csv_files(self): for filename, key in CSV_FILES.items(): url = self.config.vendor_sources[key] destination = ( DATABASE_DIR / filename ) success = False for attempt in range( 1, DOWNLOAD_RETRIES + 1 ): self.log.info( f"Downloading {filename} " f"(attempt {attempt}/{DOWNLOAD_RETRIES})" ) try: request = urllib.request.Request( url, headers=HTTP_HEADERS ) with urllib.request.urlopen( request, timeout=DOWNLOAD_TIMEOUT ) as response: if response.status != 200: raise RuntimeError( f"HTTP {response.status}" ) data = response.read() if len(data) < 1000: raise RuntimeError( "Downloaded file is too small" ) text = data.decode( "utf-8", errors="ignore" ) if "Assignment" not in text: raise RuntimeError( "Invalid IEEE CSV" ) destination.write_bytes( data ) size = ( destination.stat().st_size / 1024 / 1024 ) self.log.info( f"{filename} downloaded " f"({size:.2f} MB)" ) success = True break except KeyboardInterrupt: self.log.info( "CSV download cancelled" ) raise except Exception as error: self.log.warning( f"{filename}: {error}" ) if destination.exists(): destination.unlink() if attempt < DOWNLOAD_RETRIES: time.sleep(2) if not success: raise RuntimeError( f"Unable to download {filename}" ) # --------------------------------------------------------- # Полное создание IEEE базы # --------------------------------------------------------- def bootstrap(self): OUI_DATABASE.unlink( missing_ok=True ) self.download_csv_files() resolver = VendorResolver( OUI_DATABASE ) importer = OUIImporter( resolver, [ DATABASE_DIR / filename for filename in CSV_FILES ] ) result = importer.import_database() total = result["total"] stats = result["stats"] if ( stats["MA-L"] < 35000 or stats["MA-M"] < 5000 or stats["MA-S"] < 5000 ): resolver.close() OUI_DATABASE.unlink( missing_ok=True ) raise RuntimeError( "IEEE database verification failed.\n\n" f"MA-L: {stats['MA-L']}\n" f"MA-M: {stats['MA-M']}\n" f"MA-S: {stats['MA-S']}" ) resolver.set_metadata( "last_import", datetime.datetime.now( datetime.timezone.utc ).isoformat().replace( "+00:00", "Z" ) ) resolver.set_metadata( "records", total ) resolver.set_metadata( "schema_version", 1 ) resolver.set_metadata( "import_status", "ok" ) resolver.commit() resolver.close() self.log.info( "IEEE database created: " f"{total} records" )