Skip to content

Commit

Permalink
[change] Optimize getCmd using snmpdump
Browse files Browse the repository at this point in the history
  • Loading branch information
purhan committed Jul 16, 2021
1 parent 034475c commit c5d932d
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 5 deletions.
9 changes: 7 additions & 2 deletions netengine/backends/snmp/airos.py
Original file line number Diff line number Diff line change
Expand Up @@ -460,12 +460,17 @@ def resources_to_dict(self):
)
return result

def to_dict(self):
return self._dict(
def to_dict(self, snmpdump=False):
if snmpdump:
self._snmp_dump = self.walk('1.3.6')
result = self._dict(
{
'type': 'DeviceMonitoring',
'general': {'uptime': self.uptime, 'local_time': self.local_time},
'resources': self.resources_to_dict,
'interfaces': self.interfaces_to_dict,
}
)
if snmpdump:
del self._snmp_dump
return result
26 changes: 25 additions & 1 deletion netengine/backends/snmp/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@

from netengine.backends import BaseBackend
from netengine.exceptions import NetEngineError
from pysnmp.hlapi import ContextData, ObjectIdentity, ObjectType, SnmpEngine, nextCmd

__all__ = ['SNMP']

Expand Down Expand Up @@ -94,6 +95,25 @@ def _oid(self, oid):
# ensure is string (could be unicode)
return str(oid)

def walk(self, oid):
result = dict()
for (errorIndication, errorStatus, errorIndex, varBinds) in nextCmd(
SnmpEngine(),
self.community,
self.transport,
ContextData(),
ObjectType(ObjectIdentity(oid)),
lexicographicMode=True,
):
if errorIndication:
raise NetEngineError(errorIndication)
elif errorStatus:
raise NetEngineError(errorStatus)
else:
for varBind in varBinds:
result[str(varBind[0])] = [None, None, None, [varBind]]
return result

def get(self, oid):
"""
alias to cmdgen.CommandGenerator().getCmd
Expand All @@ -107,7 +127,11 @@ def get(self, oid):
* (1, 3, 6, 1, 2, 1, 1, 5, 0)
"""
logger.info(f'DEBUG: SNMP GET {self._oid(oid)}')
return self._command.getCmd(self.community, self.transport, self._oid(oid))
try:
# if OID doesn't exist, then pysnmp returns an empty string
return self._snmp_dump.get(oid, [None, None, None, [[None, '']]])
except AttributeError:
return self._command.getCmd(self.community, self.transport, self._oid(oid))

def next(self, oid):
"""
Expand Down
9 changes: 7 additions & 2 deletions netengine/backends/snmp/openwrt.py
Original file line number Diff line number Diff line change
Expand Up @@ -545,8 +545,10 @@ def neighbors(self):
)
return result

def to_dict(self):
return self._dict(
def to_dict(self, snmpdump=False):
if snmpdump:
self._snmp_dump = self.walk('1.3.6')
result = self._dict(
{
'type': 'DeviceMonitoring',
'general': {'uptime': self.uptime, "local_time": self.local_time},
Expand All @@ -555,3 +557,6 @@ def to_dict(self):
'neighbors': self.neighbors,
}
)
if snmpdump:
del self._snmp_dump
return result

0 comments on commit c5d932d

Please sign in to comment.