Skip to content
Snippets Groups Projects
router_interfaces.py 2.12 KiB
import logging

from resource_management import db, config, juniper
from resource_management.db import model

logger = logging.getLogger(__name__)


def load_router_interfaces(fqdn: str):
    """
    load all interface info from the router and
    update the db with the current information

    TODO: merge, not just create new
    """

    params = config.load()

    with juniper.router(
            hostname=fqdn,
            port=830,  # TODO: make this configurable?
            ssh_config=params['ssh']) as dev:

        aggregates = juniper.load_aggregates(dev)
        physical = juniper.load_installed_ethernet_ports(dev)
        logical = juniper.load_logical_interfaces(dev)

    def _find_lag_name(interface_name):
        for name, interfaces in aggregates.items():
            if interface_name in interfaces:
                return name
        return None

    with db.session_scope() as session:

        router_record = model.Router(fqdn=fqdn)
        session.add(router_record)

        # add all the lag records
        # keep a map for referencing below when adding physical interfaces
        agg_records = {}
        for a in aggregates.keys():
            record = model.LAG(
                name=a,
                router=router_record)
            session.add(record)
            agg_records[a] = record

        # add all the physical interface records
        # keep a map for referencing below when adding logical interfaces
        physical_records = {}
        for physical_name, _ in physical.items():
            record = model.PhysicalInterface(
                name=physical_name,
                router=router_record)
            lag_name = _find_lag_name(physical_name)
            if lag_name:
                record.lag = agg_records[lag_name]
            physical_records[physical_name] = record
            session.add(record)

        for physical_name, logical_names in logical.items():
            for ln in logical_names:
                record = model.LogicalInterface(
                    name=ln,
                    physical=physical_records[physical_name])
                session.add(record)

        session.commit()