|
| 1 | +#!/usr/bin/env python3 |
| 2 | +# -*- coding: utf-8 -*- |
| 3 | + |
| 4 | +import argparse |
| 5 | +import sys |
| 6 | +import gc |
| 7 | +from datetime import datetime |
| 8 | +import netaddr |
| 9 | +from sqlalchemy import select |
| 10 | +from sqlalchemy.orm import sessionmaker |
| 11 | +from db.model import Block |
| 12 | +from db.helper import create_postgres_pool |
| 13 | + |
| 14 | + |
| 15 | +def export_to_mmdb(connection_string, output_file, table="block"): |
| 16 | + """Export PostgreSQL table to MMDB format""" |
| 17 | + |
| 18 | + # Create database connection |
| 19 | + engine = create_postgres_pool(connection_string) |
| 20 | + Session = sessionmaker(bind=engine) |
| 21 | + session = Session() |
| 22 | + |
| 23 | + # Query all blocks with streaming to avoid memory issues |
| 24 | + print(f"Exporting table '{table}' to MMDB format...") |
| 25 | + query = select(Block) |
| 26 | + result = session.execute(query) |
| 27 | + |
| 28 | + # Use yield_per to stream blocks instead of loading all at once |
| 29 | + blocks = result.scalars().yield_per(1000) |
| 30 | + |
| 31 | + print(f"Starting export (streaming blocks)...") |
| 32 | + |
| 33 | + try: |
| 34 | + from mmdb_writer import MMDBWriter |
| 35 | + except ImportError: |
| 36 | + print("Error: mmdb_writer library not found. Please install it with: pip install mmdb-writer") |
| 37 | + sys.exit(1) |
| 38 | + |
| 39 | + writer = MMDBWriter( |
| 40 | + ip_version=6, |
| 41 | + ipv4_compatible=True, |
| 42 | + database_type="Network Info Block", |
| 43 | + languages=["en"], |
| 44 | + description={ |
| 45 | + "en": "Network block information from RIR databases" |
| 46 | + }, |
| 47 | + ) |
| 48 | + |
| 49 | + count = 0 |
| 50 | + |
| 51 | + for block in blocks: |
| 52 | + try: |
| 53 | + # Skip default route blocks that aren't real networks |
| 54 | + cidr = str(block.inetnum) |
| 55 | + if cidr in ['::/0', '0.0.0.0/0']: |
| 56 | + continue |
| 57 | + |
| 58 | + # Create the data structure for this network - minimize memory usage |
| 59 | + data = { |
| 60 | + "netname": block.netname or "", |
| 61 | + "country": block.country or "", |
| 62 | + "description": block.description or "", |
| 63 | + "maintained_by": block.maintained_by or "", |
| 64 | + "created": block.created.strftime('%Y-%m-%d') if block.created else "", |
| 65 | + "last_modified": block.last_modified.strftime('%Y-%m-%d') if block.last_modified else "", |
| 66 | + "source": block.source or "", |
| 67 | + "status": block.status or "" |
| 68 | + } |
| 69 | + |
| 70 | + # Insert network using IPSet with CIDR string list |
| 71 | + ipset = netaddr.IPSet([cidr]) |
| 72 | + writer.insert_network(ipset, data) |
| 73 | + count += 1 |
| 74 | + |
| 75 | + if count % 10000 == 0: |
| 76 | + print(f" Processed {count} blocks...") |
| 77 | + # Force garbage collection periodically |
| 78 | + gc.collect() |
| 79 | + |
| 80 | + except Exception as e: |
| 81 | + print(f"Warning: Failed to process block {block.inetnum}: {e}") |
| 82 | + continue |
| 83 | + |
| 84 | + # Write to file |
| 85 | + writer.to_db_file(output_file) |
| 86 | + print(f"Export completed successfully: {count} blocks -> {output_file}") |
| 87 | + |
| 88 | + session.close() |
| 89 | + |
| 90 | + |
| 91 | +def main(): |
| 92 | + parser = argparse.ArgumentParser(description="Export PostgreSQL table to MMDB format") |
| 93 | + parser.add_argument("-c", "--connection", |
| 94 | + default="postgresql://network_info:network_info@db:5432/network_info", |
| 95 | + help="Database connection string") |
| 96 | + parser.add_argument("-o", "--output", |
| 97 | + default="block_dump.mmdb", |
| 98 | + help="Output MMDB file path") |
| 99 | + parser.add_argument("-t", "--table", |
| 100 | + default="block", |
| 101 | + help="Table name to export") |
| 102 | + |
| 103 | + args = parser.parse_args() |
| 104 | + |
| 105 | + # Add date to output filename if not already present |
| 106 | + if "_$(date" not in args.output and not args.output.endswith(".mmdb"): |
| 107 | + args.output = f"{args.output}_{datetime.now().strftime('%Y-%m-%d')}.mmdb" |
| 108 | + elif not args.output.endswith(".mmdb"): |
| 109 | + args_output = args.output.rsplit(".", 1)[0] |
| 110 | + args.output = f"{args_output}_{datetime.now().strftime('%Y-%m-%d')}.mmdb" |
| 111 | + |
| 112 | + export_to_mmdb(args.connection, args.output, args.table) |
| 113 | + |
| 114 | + |
| 115 | +if __name__ == "__main__": |
| 116 | + main() |
0 commit comments