Skip to content

Commit

Permalink
[lint] Fix some syntax errors or warnings (sonic-net#127)
Browse files Browse the repository at this point in the history
* Fix some syntax errors or warnings
* Remove unused import, add staticmethod
  • Loading branch information
qiluo-msft authored Apr 27, 2020
1 parent 7632ee8 commit 2d266d4
Show file tree
Hide file tree
Showing 7 changed files with 41 additions and 26 deletions.
10 changes: 10 additions & 0 deletions src/ax_interface/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,19 +18,29 @@ def __str__(self):

class AgentError(AgentXInterfaceError):
""" Exception throwable by the Agent class. """
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)


class PDUError(AgentXInterfaceError):
""" Class of errors related to PDU encoding/decoding. """
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)


class PDUUnpackError(struct.error, PDUError):
""" Raised when the byte string unpacking fails. """
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)


class PDUPackError(struct.error, PDUError):
""" Raised when the PDU Encoding (byte packing) fails. """
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)


class UnsupportedPDUError(ValueError, PDUError):
""" Raised when the PDU type is not a known :class:`PduType`."""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
45 changes: 30 additions & 15 deletions src/ax_interface/mib.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,8 @@
import sys
import asyncio
import bisect
import random
import logging

from . import util
from . import logger

from . import logger, util
from .constants import ValueType
from .encodings import ValueRepresentation

Expand All @@ -20,6 +16,7 @@
"""
DEFAULT_REINIT_RATE = 60


class MIBUpdater:
"""
Interface for developing OID handlers that require persistent (or background) execution.
Expand All @@ -29,7 +26,7 @@ def __init__(self):
self.run_event = asyncio.Event()
self.frequency = DEFAULT_UPDATE_FREQUENCY
self.reinit_rate = DEFAULT_REINIT_RATE // DEFAULT_UPDATE_FREQUENCY
self.update_counter = self.reinit_rate + 1 # reinit_data when init
self.update_counter = self.reinit_rate + 1 # reinit_data when init

async def start(self):
# Run the update while we are allowed
Expand Down Expand Up @@ -161,17 +158,18 @@ def __call__(self, sub_id=None):
return self._callable_.__call__(*self._callable_args)

def get_sub_id(self, oid_key):
return oid_key[getattr(self, MIBEntry.PREFIXLEN):]
return oid_key[getattr(self, MIBEntry.PREFIXLEN) :]

def replace_sub_id(self, oid_key, sub_id):
return oid_key[:getattr(self, MIBEntry.PREFIXLEN)] + sub_id
return oid_key[: getattr(self, MIBEntry.PREFIXLEN)] + sub_id

def get_next(self, sub_id):
return None

def get_prefix(self):
return getattr(self, MIBEntry.PREFIX)


class SubtreeMIBEntry(MIBEntry):
def __init__(self, subtree, iterator, value_type, callable_, *args):
super().__init__(subtree, value_type, callable_, *args)
Expand Down Expand Up @@ -207,6 +205,7 @@ def get_next(self, sub_id):
logger.exception("SubtreeMIBEntry.get_next() caught an unexpected exception during iterator.get_next()")
return None


# Define MIB entry (subtree) with a callable, which accepts a starndard OID tuple as a paramter
class OidMIBEntry(MIBEntry):
def __init__(self, subtree, value_type, callable_):
Expand All @@ -218,12 +217,17 @@ def __iter__(self):
def __call__(self, sub_id):
return self._callable_.__call__(self.get_prefix() + sub_id)


class OverlayAdpaterMIBEntry(MIBEntry):
def __init__(self, underlay_mibentry, overlay_mibentry):
assert underlay_mibentry.value_type == overlay_mibentry.value_type
assert underlay_mibentry.subtree == overlay_mibentry.subtree

super().__init__(underlay_mibentry.subtree_str, underlay_mibentry.value_type, underlay_mibentry._callable_)
super().__init__(
underlay_mibentry.subtree_str,
underlay_mibentry.value_type,
underlay_mibentry._callable_,
)
self.underlay_mibentry = underlay_mibentry
self.overlay_mibentry = overlay_mibentry

Expand All @@ -247,6 +251,7 @@ def __call__(self, sub_id=None):
def get_next(self, sub_id):
return self.underlay_mibentry.get_next(sub_id)


class MIBTable(dict):
"""
Simplistic LUT for Get/GetNext OID. Interprets iterables as keys and implements the same interfaces as dict's.
Expand All @@ -260,10 +265,13 @@ def __init__(self, mib_cls, update_frequency=DEFAULT_UPDATE_FREQUENCY):
self.updater_instances = getattr(mib_cls, MIBMeta.UPDATERS)
self.prefixes = getattr(mib_cls, MIBMeta.PREFIXES)

@staticmethod
def _done_background_task_callback(fut):
ex = fut.exception()
if ex is not None:
exstr = "MIBTable background task caught an unexpected exception: {}".format(str(ex))
exstr = "MIBTable background task caught an unexpected exception: {}".format(
str(ex)
)
logger.error(exstr)

def start_background_tasks(self, event):
Expand All @@ -283,14 +291,11 @@ def _find_parent_prefix(self, item):
preceding_oids = oids[:left_insert_index]
if not preceding_oids:
return None
if preceding_oids[-1] == item[:len(preceding_oids[-1])]:
if preceding_oids[-1] == item[: len(preceding_oids[-1])]:
return preceding_oids[-1]
else:
return None

def _find_parent_oid_key(self, oid_key):
oids = sorted(self)

def _get_value(self, mib_entry, oid_key):
sub_id = mib_entry.get_sub_id(oid_key)
oid_value = mib_entry(sub_id)
Expand Down Expand Up @@ -368,7 +373,7 @@ def get_next(self, sr):
oid_key = remaining_oids[0]
mib_entry = self[oid_key]
try:
key1 = next(iter(mib_entry)) # get the first sub_id from the mib_etnry
key1 = next(iter(mib_entry)) # get the first sub_id from the mib_etnry
except StopIteration:
# handler returned None, which implies there's no data, keep walking.
remaining_oids = remaining_oids[1:]
Expand Down Expand Up @@ -402,3 +407,13 @@ def __setitem__(self, key, value):
if not hasattr(value, '__iter__'):
raise ValueError("Invalid key '{}'. All keys must be iterable types.".format(key))
super().__setitem__(key, value)

def __eq__(self, other):
if not isinstance(other, MIBTable):
return False
return (
dict.__eq__(self, other)
and self.prefixes == other.prefixes
and self.update_frequency == other.update_frequency
and self.updater_instances == other.updater_instances
)
4 changes: 0 additions & 4 deletions src/ax_interface/pdu.py
Original file line number Diff line number Diff line change
Expand Up @@ -255,7 +255,3 @@ def encode(self):
if self.context is not None:
ret += self.context.to_bytes(self.header.endianness)
return ret


# noinspection PyUnresolvedReferences
from . import pdu_implementations
1 change: 0 additions & 1 deletion src/ax_interface/protocol.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,6 @@ def parse_response(self, pdu):
else:
# TODO: some other administrative PDU
logger.debug("admin_recv[{}]".format(pdu))
pass

def data_received(self, data):
"""
Expand Down
1 change: 0 additions & 1 deletion src/sonic_ax_impl/mibs/ietf/rfc2737.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@

from sonic_ax_impl import mibs

import threading

@unique
class PhysicalClass(int, Enum):
Expand Down
5 changes: 1 addition & 4 deletions src/sonic_ax_impl/mibs/ietf/rfc4292.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,8 @@
import json
import ipaddress
from enum import unique, Enum

from sonic_ax_impl import mibs
from ax_interface import MIBMeta, ValueType, MIBUpdater, SubtreeMIBEntry
from ax_interface.encodings import OctetString
from ax_interface.util import mac_decimals, ip2tuple_v4
from ax_interface.util import ip2tuple_v4
from bisect import bisect_right

class RouteUpdater(MIBUpdater):
Expand Down
1 change: 0 additions & 1 deletion src/sonic_ax_impl/mibs/ietf/rfc4363.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import json
from enum import unique, Enum

from sonic_ax_impl import mibs
from swsssdk import port_util
Expand Down

0 comments on commit 2d266d4

Please sign in to comment.