示例#1
0
    def data_validation(raw_data, entity=True, **kwargs):
        "Returns useful data and performs some initial validations"
        rdata = {}
        try:
            # Merge the results off al the commands into each interface found
            for value in raw_data.values():
                if not value:
                    continue
                for intf, intf_data in value.get("interfaces", {}).items():
                    if rdata.get(intf):
                        rdata[intf] = {**rdata[intf], **intf_data}
                    else:
                        rdata[intf] = intf_data
        except Exception as err:
            raise NetApiParseError(
                f"{str(err)}\nCould not retrieve data from: {raw_data}")

        # If no data is passed a known error
        if not rdata:
            raise NetApiParseError("No data to be parsed")

        if entity:
            if len(rdata) > 1:
                print("[WARNING]: Multiple interfaces present")

        return rdata
示例#2
0
文件: ping.py 项目: rlaneyjr/netapi
    def data_extractor(cls, raw_data, **kwargs):
        "Returns useful data and performs some initial validations"
        try:
            extracted_data = cls.extraction_operation(raw_data)
        except Exception as err:
            raise NetApiParseError(
                f"{str(err)}\nCould not retrieve data from: {raw_data}")

        # If no data is passed a known error
        if not extracted_data:
            raise NetApiParseError("No data to be parsed")

        return extracted_data
示例#3
0
    def data_constructor(hostname, version, interfaces, **kwargs):
        # If no data is passed a known error
        if not hostname and not version and not interfaces:
            raise NetApiParseError("No data to be parsed")

        raw_interfaces = list(interfaces.get("interfaces", {}).keys())

        parsed_data = dict(
            hostname=hostname.get("hostname"),
            os_version=version.get("version"),
            model=version.get("modelName"),
            serial_number=version.get("serialNumber"),
            uptime=pendulum.duration(seconds=version["uptime"]),
            up_since=pendulum.from_timestamp(version["bootupTimestamp"]),
            system_mac=version.get("systemMacAddress"),
            available_memory=kB(version.get("memFree")).Byte,
            total_memory=kB(version.get("memTotal")).Byte,
            os_arch=version.get("architecture"),
            hw_revision=version.get("hardwareRevision"),
            interfaces=sorted(
                [interface.interface_converter(x) for x in raw_interfaces],
                key=interface.sort_interface,
            ),
        )

        return parsed_data
示例#4
0
    def data_constructor(data, **kwargs):
        # If no data is passed a known error
        if not data:
            raise NetApiParseError("No data to be parsed")

        parsed_data = dict(
            group_id=data.get("groupId"),
            interface=data.get("interface"),
            instance=data.get("vrfName"),
            description=data.get("description"),
            virtual_mac=data.get("virtualMac"),
            virtual_ip_secondary=data.get("virtualIpSecondary"),
            master_ip=data.get("masterAddr"),
            virtual_ip=data.get("virtualIp"),
            priority=data.get("priority"),
            skew_time=data.get("skewTime"),
            version=data.get("version"),
            preempt=data.get("preempt"),
            preempt_delay=data.get("preemptDelay"),
            mac_advertisement_interval=data.get("macAddressInterval"),
            master_interval=data.get("masterInterval"),
            master_down_interval=float(data.get("masterDownInterval")) /
            1000.0,
            tracked_objects=data.get("trackedObjects"),
            status=data.get("state"),
            extra_attributes=dict(
                vrrp_advertisement_interval=data.get("vrrpAdvertInterval"),
                vrrp_id_disabled=data.get("vrIdDisabled"),
                vrrp_id_disabled_reason=data.get("vrIdDisabledReason"),
                bfd_peer_ip=data.get("bfdPeerAddr"),
                preempt_reload=data.get("preemptReload"),
            ),
        )

        return parsed_data
示例#5
0
    def data_validation(raw_data, entity=True, **kwargs):
        "Returns useful data and performs some initial validations"
        try:
            rdata = list(raw_data.values())[0].get("vrfs")
        except Exception as err:
            raise NetApiParseError(
                f"{str(err)}\nCould not retrieve data from: {raw_data}")

        # If no data is passed a known error
        if not rdata:
            raise NetApiParseError("No data to be parsed")

        if entity:
            if len(rdata) > 1:
                print("[WARNING]: Multiple entities present")

        return rdata
示例#6
0
    def data_constructor(vlan_id, data, **kwargs):
        # If no data is passed a known error
        if not data:
            raise NetApiParseError("No data to be parsed")

        interfaces = data.get("interfaces")

        parsed_data = dict(
            id=vlan_id,
            name=data.get("name"),
            dynamic=data.get("dynamic"),
            interfaces=list(interfaces.keys()) if interfaces else None,
            status=data.get("status"),
        )

        return parsed_data
示例#7
0
    def data_constructor(intf_name, data, **kwargs):
        # If no data is passed a known error
        if not data:
            raise NetApiParseError("No data to be parsed")

        statistics = data.get("interfaceStatistics", {})

        # Physical bit
        physical = dict(
            mac=data.get("physicalAddress"),
            mtu=data.get("mtu", 0),
            duplex=data.get("duplex"),
            bandwidth=data.get("bandwidth", 0),
        )

        # Addresses bit
        addr_info = data.get("interfaceAddress")
        if not addr_info:
            addresses = None
        else:
            addresses = dict(dhcp=addr_info.get("dhcp"), secondary_ipv4=[])
            for _ip in addr_info.get("secondaryIpsOrderedList", []):
                addresses["secondary_ipv4"].append(
                    f"{_ip['address']}/{_ip['maskLen']}")
            if addr_info.get("primaryIp"):
                _ip = addr_info["primaryIp"]
                addresses.update(ipv4=f"{_ip['address']}/{_ip['maskLen']}")
            if addr_info.get("linkLocalIp6"):
                _ip = addr_info["linkLocalIp6"]
                addresses.update(ipv6=f"{_ip['address']}/{_ip['maskLen']}")

        # Counters bit
        counter_info = data.get("interfaceCounters", {})
        if not counter_info:
            counters = None
        else:
            counters = dict(
                tx_broadcast_pkts=counter_info.get("outBroadcastPkts", 0.0),
                rx_broadcast_pkts=counter_info.get("inBroadcastPkts", 0.0),
                tx_unicast_pkts=counter_info.get("outUcastPkts", 0.0),
                rx_unicast_pkts=counter_info.get("inUcastPkts", 0.0),
                tx_multicast_pkts=counter_info.get("outMulticastPkts", 0.0),
                rx_multicast_pkts=counter_info.get("inMulticastPkts", 0.0),
                tx_bytes=counter_info.get("outOctets", 0.0),
                rx_bytes=counter_info.get("inOctets", 0.0),
                tx_errors_general=counter_info.get("totalOutErrors", 0.0),
                rx_errors_general=counter_info.get("totalInErrors", 0.0),
                tx_discards=counter_info.get("outDiscards", 0.0),
                rx_discards=counter_info.get("inDiscards", 0.0),
            )
            # Tx Errors
            tx_errors = counter_info.get("outputErrorsDetail")
            if tx_errors:
                counters.update(
                    tx_errors_collisions=tx_errors.get("collisions", 0.0),
                    tx_errors_deferred_transmissions=tx_errors.get(
                        "deferredTransmissions", 0.0),
                    tx_errors_tx_pause=tx_errors.get("txPause", 0.0),
                    tx_errors_late_collisions=tx_errors.get("lateCollisions"),
                )
            # Rx Errors
            rx_errors = counter_info.get("inputErrorsDetail")
            if rx_errors:
                counters.update(
                    rx_errors_runt=rx_errors.get("runtFrames", 0.0),
                    rx_errors_rx_pause=rx_errors.get("rxPause", 0.0),
                    rx_errors_fcs=rx_errors.get("fcsErrors", 0.0),
                    rx_errors_crc=rx_errors.get("alignmentErrors", 0.0),
                    rx_errors_giant=rx_errors.get("giantFrames", 0.0),
                    rx_errors_symbol=rx_errors.get("symbolErrors", 0.0),
                )

            # Statistics
            if statistics:
                counters.update(
                    rx_bits_rate=statistics.get("inBitsRate", 0.0),
                    rx_pkts_rate=statistics.get("inPktsRate", 0.0),
                    tx_bits_rate=statistics.get("outBitsRate", 0.0),
                    tx_pkts_rate=statistics.get("outPktsRate", 0.0),
                )

        # Optical bit
        optical = dict(
            tx=data.get("txPower"),
            rx=data.get("rxPower"),
            serial_number=data.get("vendorSn"),
            media_type=data.get("mediaType"),
        )

        if optical.get("tx") is not None and optical.get("rx") is not None:
            optical["status"] = interface.light_levels_alert(
                tx_power=optical["tx"], rx_power=optical["rx"], net_os="eos")

        if not any(optical.values()):
            optical = None

        parsed_data = dict(
            name=intf_name,
            forwarding_model=data.get("forwardingModel"),
            description=data.get("description"),
            instance=data.get("vrf"),
            status=data.get("interfaceStatus"),
            last_status_change=data.get("lastStatusChangeTimestamp"),
            last_clear=counter_info.get("lastClear"),
            number_status_changes=counter_info.get("linkStatusChanges"),
            update_interval=statistics.get("updateInterval"),
            members=list(data.get("memberInterfaces", {}).keys()),
            physical=physical,
            addresses=addresses,
            optical=optical,
            counters=counters,
        )

        return parsed_data