Something went wrong. Try again.
forked from libreqoe/libreqos
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187#!/usr/bin/env python3"""Standalone Netzur → LibreQoS integrationSupports zones and customers as separate arrays from API."""from pythonCheck import checkPythonVersioncheckPythonVersion()
from liblqos_python import ( exclude_sites, integration_common_use_mikrotik_ipv6, netzur_api_key, netzur_api_url, netzur_api_timeout,)
import jsonimport loggingfrom typing import Dict, List, Tuple
import requestsfrom requests.adapters import HTTPAdapterfrom urllib3.util.retry import Retry
from integrationCommon import NetworkGraph, NetworkNode, NodeType, apply_client_bandwidth_multiplier
logging.basicConfig(level=logging.INFO)LOG = logging.getLogger("netzur_integration")
def _build_session() -> requests.Session: retry = Retry( total=3, backoff_factor=1, status_forcelist=[429, 500, 502, 503, 504], allowed_methods=["GET"], ) adapter = HTTPAdapter(max_retries=retry)
session = requests.Session() session.headers.update({"Authorization": f"Bearer {netzur_api_key()}"}) session.mount("http://", adapter) session.mount("https://", adapter) return session
def fetch_netzur_data() -> Tuple[List[dict], List[dict]]: api_url = netzur_api_url() timeout = max(5, int(netzur_api_timeout())) session = _build_session()
response = session.get(api_url, timeout=timeout) response.raise_for_status() payload = response.json() zones = payload.get("zones", []) customers = payload.get("customers", []) LOG.info("[Netzur] Fetched %d zones and %d customers", len(zones), len(customers)) return zones, customers
def _build_exclusion_set() -> set: return {entry.lower().strip() for entry in exclude_sites() if entry}
def _split_ip_field(raw_value) -> List[str]: values: List[str] = [] if raw_value in (None, ""): return values
if isinstance(raw_value, (list, tuple, set)): parts = raw_value else: parts = str(raw_value).split(",")
seen = set() for part in parts: entry = str(part).strip() if not entry or entry in seen: continue seen.add(entry) values.append(entry)
return values
def createShaper() -> NetworkGraph: LOG.info("[Netzur] Starting sync") if integration_common_use_mikrotik_ipv6(): LOG.info("[Netzur] Mikrotik IPv6 enrichment enabled") zones, subscribers = fetch_netzur_data() exclusion = _build_exclusion_set() net = NetworkGraph() parents: Dict[str, int] = {} parent_counter = 30000
for zone in zones: name = str(zone.get("name", "")).strip() if not name or name.lower() in exclusion: continue if name not in parents: parents[name] = parent_counter zone_id = zone.get("id", zone.get("zone_id")) network_json_id = "" if zone_id not in (None, ""): network_json_id = f"netzur:zone:{zone_id}" net.addRawNode( NetworkNode( id=parent_counter, displayName=name, type=NodeType.site, download=apply_client_bandwidth_multiplier(zone.get("capacity_download_mbps")), upload=apply_client_bandwidth_multiplier(zone.get("capacity_upload_mbps")), networkJsonId=network_json_id, ) ) parent_counter += 1
for subscriber in subscribers: subscriber_id = str(subscriber.get("subscriber_id") or "").strip() if not subscriber_id: LOG.warning("[Netzur] Skipping customer without subscriber_id: %s", subscriber) continue
zone_name = str(subscriber.get("zone") or "").strip() if zone_name and zone_name.lower() in exclusion: continue
parent_id = parents.get(zone_name) customer_name = str(subscriber.get("customerName") or subscriber_id) address = str(subscriber.get("address") or "") circuit_id = f"netzur_{subscriber_id}"
net.addRawNode( NetworkNode( id=circuit_id, displayName=customer_name, type=NodeType.client, parentId=parent_id, address=address, customerName=customer_name, download=apply_client_bandwidth_multiplier(subscriber.get("download")), upload=apply_client_bandwidth_multiplier(subscriber.get("upload")), ) )
ipv4 = _split_ip_field(subscriber.get("ip")) ipv6 = _split_ip_field(subscriber.get("ipv6")) mac = str(subscriber.get("mac") or "").strip() if ipv4 or ipv6 or mac: net.addRawNode( NetworkNode( id=f"{circuit_id}_device", displayName=f"{customer_name}_device", type=NodeType.device, parentId=circuit_id, mac=mac, ipv4=ipv4, ipv6=ipv6, ) )
LOG.info("[Netzur] Built graph with %d nodes", len(net.nodes)) net.prepareTree() if integration_common_use_mikrotik_ipv6() and isinstance(net.ipv4ToIPv6, str): try: net.ipv4ToIPv6 = json.loads(net.ipv4ToIPv6) except json.JSONDecodeError as err: LOG.warning("[Netzur] Unable to parse Mikrotik IPv6 map: %s", err)
net.materializeCompiledTopology("python/netzur", "full") LOG.info("[Netzur] Topology import artifacts updated") for error in net.getErrors(): LOG.error("[Netzur] %s", error) return net
def importFromNetzur() -> None: try: createShaper() except Exception: LOG.exception("[Netzur] Import failed") raise
if __name__ == '__main__': importFromNetzur()