Skip to content

Commit 413aa59

Browse files
committed
resouce: ethernetport: convert to asyncio
Follow the sync API deprecation and use an internal asyncio loop if no external loop can be retrieved. Signed-off-by: Rouven Czerwinski <[email protected]>
1 parent 9ebce94 commit 413aa59

File tree

1 file changed

+26
-19
lines changed

1 file changed

+26
-19
lines changed

labgrid/resource/ethernetport.py

Lines changed: 26 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -12,23 +12,27 @@ class SNMPSwitch:
1212
"""SNMPSwitch describes a switch accessible over SNMP. This class
1313
implements functions to query ports and the forwarding database."""
1414
hostname = attr.ib(validator=attr.validators.instance_of(str))
15+
loop = attr.ib()
1516

1617
def __attrs_post_init__(self):
18+
import pysnmp.hlapi.v3arch.asyncio as hlapi
19+
1720
self.logger = logging.getLogger(f"{self}")
1821
self.ports = {}
1922
self.fdb = {}
2023
self.macs_by_port = {}
24+
self.transport = self.loop.run_until_complete(hlapi.UdpTransportTarget.create((self.hostname, 161)))
2125
self._autodetect()
2226

2327
def _autodetect(self):
24-
from pysnmp import hlapi
28+
import pysnmp.hlapi.v3arch.asyncio as hlapi
2529

26-
for (errorIndication, errorStatus, _, varBindTable) in hlapi.getCmd(
30+
for (errorIndication, errorStatus, _, varBindTable) in self.loop.run_until_complete(hlapi.getCmd(
2731
hlapi.SnmpEngine(),
2832
hlapi.CommunityData('public'),
29-
hlapi.UdpTransportTarget((self.hostname, 161)),
33+
self.transport,
3034
hlapi.ContextData(),
31-
hlapi.ObjectType(hlapi.ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0))):
35+
hlapi.ObjectType(hlapi.ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0)))):
3236
if errorIndication:
3337
raise Exception(f"snmp error {errorIndication}")
3438
elif errorStatus:
@@ -51,7 +55,7 @@ def _get_ports(self):
5155
Returns:
5256
Dict[Dict[]]: ports and their values
5357
"""
54-
from pysnmp import hlapi
58+
import pysnmp.hlapi.v3arch.asyncio as hlapi
5559

5660
variables = [
5761
(hlapi.ObjectType(hlapi.ObjectIdentity('IF-MIB', 'ifIndex')), 'index'),
@@ -64,14 +68,14 @@ def _get_ports(self):
6468
]
6569
ports = {}
6670

67-
for (errorIndication, errorStatus, _, varBindTable) in hlapi.bulkCmd(
71+
for (errorIndication, errorStatus, _, varBindTable) in self.loop.run_until_complete(hlapi.bulkCmd(
6872
hlapi.SnmpEngine(),
6973
hlapi.CommunityData('public'),
70-
hlapi.UdpTransportTarget((self.hostname, 161)),
74+
self.transport,
7175
hlapi.ContextData(),
7276
0, 20,
7377
*[x[0] for x in variables],
74-
lexicographicMode=False):
78+
lexicographicMode=False)):
7579
if errorIndication:
7680
raise Exception(f"snmp error {errorIndication}")
7781
elif errorStatus:
@@ -93,18 +97,18 @@ def _get_fdb_dot1d(self):
9397
Returns:
9498
Dict[List[str]]: ports and their values
9599
"""
96-
from pysnmp import hlapi
100+
import pysnmp.hlapi.v3arch.asyncio as hlapi
97101

98102
ports = {}
99103

100-
for (errorIndication, errorStatus, _, varBindTable) in hlapi.bulkCmd(
104+
for (errorIndication, errorStatus, _, varBindTable) in self.loop.run_until_complete(hlapi.bulkCmd(
101105
hlapi.SnmpEngine(),
102106
hlapi.CommunityData('public'),
103-
hlapi.UdpTransportTarget((self.hostname, 161)),
107+
self.transport,
104108
hlapi.ContextData(),
105109
0, 50,
106110
hlapi.ObjectType(hlapi.ObjectIdentity('BRIDGE-MIB', 'dot1dTpFdbPort')),
107-
lexicographicMode=False):
111+
lexicographicMode=False)):
108112
if errorIndication:
109113
raise Exception(f"snmp error {errorIndication}")
110114
elif errorStatus:
@@ -126,18 +130,18 @@ def _get_fdb_dot1q(self):
126130
Returns:
127131
Dict[List[str]]: ports and their values
128132
"""
129-
from pysnmp import hlapi
133+
import pysnmp.hlapi.v3arch.asyncio as hlapi
130134

131135
ports = {}
132136

133-
for (errorIndication, errorStatus, _, varBindTable) in hlapi.bulkCmd(
137+
for (errorIndication, errorStatus, _, varBindTable) in self.loop.run_until_complete(hlapi.bulkCmd(
134138
hlapi.SnmpEngine(),
135139
hlapi.CommunityData('public'),
136-
hlapi.UdpTransportTarget((self.hostname, 161)),
140+
self.transport,
137141
hlapi.ContextData(),
138142
0, 50,
139143
hlapi.ObjectType(hlapi.ObjectIdentity('Q-BRIDGE-MIB', 'dot1qTpFdbPort')),
140-
lexicographicMode=False):
144+
lexicographicMode=False)):
141145
if errorIndication:
142146
raise Exception(f"snmp error {errorIndication}")
143147
elif errorStatus:
@@ -177,6 +181,9 @@ def update(self):
177181
self.logger.debug("updating macs by port")
178182
self._update_macs()
179183

184+
def deactivate(self):
185+
self.loop.close()
186+
180187

181188
@attr.s
182189
class EthernetPortManager(ResourceManager):
@@ -223,14 +230,16 @@ async def poll_neighbour(self):
223230

224231
await asyncio.sleep(1.0)
225232

233+
self.loop = asyncio.get_event_loop()
234+
226235
async def poll_switches(self):
227236
current = set(resource.switch for resource in self.resources)
228237
removed = set(self.switches) - current
229238
new = current - set(self.switches)
230239
for switch in removed:
231240
del self.switches[switch]
232241
for switch in new:
233-
self.switches[switch] = SNMPSwitch(switch)
242+
self.switches[switch] = SNMPSwitch(switch, self.loop)
234243
for switch in current:
235244
self.switches[switch].update()
236245
await asyncio.sleep(1.0)
@@ -248,7 +257,6 @@ async def poll(self, handler):
248257
import traceback
249258
traceback.print_exc(file=sys.stderr)
250259

251-
self.loop = asyncio.get_event_loop()
252260
self.poll_tasks.append(self.loop.create_task(poll(self, poll_neighbour)))
253261
self.poll_tasks.append(self.loop.create_task(poll(self, poll_switches)))
254262

@@ -309,7 +317,6 @@ def poll(self):
309317
resource.extra = extra
310318
self.logger.debug("new information for %s: %s", resource, extra)
311319

312-
313320
@target_factory.reg_resource
314321
@attr.s
315322
class SNMPEthernetPort(ManagedResource):

0 commit comments

Comments
 (0)