VLAN Manager tool
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

819 lines
23 KiB

  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. from pysnmp.hlapi import *
  4. from pysnmp.smi.builder import MibBuilder
  5. from pysnmp.smi.view import MibViewController
  6. import importlib
  7. import itertools
  8. import mock
  9. import random
  10. import unittest
  11. _mbuilder = MibBuilder()
  12. _mvc = MibViewController(_mbuilder)
  13. #import data
  14. # received packages
  15. # pvid: dot1qPvid
  16. #
  17. # tx packets:
  18. # dot1qVlanStaticEgressPorts
  19. # dot1qVlanStaticUntaggedPorts
  20. #
  21. # vlans:
  22. # dot1qVlanCurrentTable
  23. # lists ALL vlans, including baked in ones
  24. #
  25. # note that even though an snmpwalk of dot1qVlanStaticEgressPorts
  26. # skips over other vlans (only shows statics), the other vlans (1,2,3)
  27. # are still accessible via that oid
  28. #
  29. # LLDP:
  30. # 1.0.8802.1.1.2.1.4.1.1 aka LLDP-MIB, lldpRemTable
  31. class SwitchConfig(object):
  32. '''This is a simple object to store switch configuration for
  33. the checkchanges() function.
  34. host -- The host of the switch you are maintaining configuration of.
  35. community -- Either the SNMPv1 community name or a
  36. pysnmp.hlapi.UsmUserData object, either of which can write to the
  37. necessary MIBs to configure the VLANs of the switch.
  38. Example for SNMPv3 where the key for both authentication and
  39. encryption are the same:
  40. UsmUserData('username', key, key, authProtocol=usmHMACSHAAuthProtocol,
  41. privProtocol=usmDESPrivProtocol)
  42. vlanconf -- This is a dictionary w/ vlans as the key. Each value has
  43. a dictionary that contains keys, 'u' or 't', each of which
  44. contains the port that traffic should be sent untagged ('u') or
  45. tagged ('t'). Note that the Pvid (vlan of traffic that is
  46. received when untagged), is set to match the 'u' definition. The
  47. port is either an integer, which maps directly to the switch's
  48. index number, or it can be a string, which will be looked up via
  49. the IF-MIB::ifName table.
  50. Example specifies that VLANs 1 and 2 will be transmitted as tagged
  51. packets on the port named 'lag1'. That ports 1, 2, 3, 4 and 5 will
  52. be untagged on VLAN 1, and ports 6, 7, 8 and 9 will be untagged on
  53. VLAN 2:
  54. { 1: {
  55. 'u': [ 1, 2, 3, 4, 5 ],
  56. 't': [ 'lag1' ],
  57. },
  58. 2: {
  59. 'u': [ 6, 7, 8, 9 ],
  60. 't': [ 'lag1' ],
  61. },
  62. }
  63. ignports -- Ports that will be ignored and not required to be
  64. configured. List any ports that will not be active here, such as
  65. any unused lag ports.
  66. '''
  67. def __init__(self, host, community, vlanconf, ignports):
  68. self._host = host
  69. self._community = community
  70. self._vlanconf = vlanconf
  71. self._ignports = ignports
  72. @property
  73. def host(self):
  74. return self._host
  75. @property
  76. def community(self):
  77. return self._community
  78. @property
  79. def vlanconf(self):
  80. return self._vlanconf
  81. @property
  82. def ignports(self):
  83. return self._ignports
  84. def getportlist(self, lookupfun):
  85. '''Return a set of all the ports indexes in data. This
  86. includes, both vlanconf and ignports. Any ports using names
  87. will be resolved by being passed to the provided lookupfun.'''
  88. res = []
  89. for id in self._vlanconf:
  90. res.extend(self._vlanconf[id].get('u', []))
  91. res.extend(self._vlanconf[id].get('t', []))
  92. # add in the ignore ports
  93. res.extend(self.ignports)
  94. # eliminate dups so that lookupfun isn't called as often
  95. res = set(res)
  96. return set(getidxs(res, lookupfun))
  97. def _octstrtobits(os):
  98. '''Convert a string into a list of bits. Easier to figure out what
  99. ports are set.'''
  100. num = 1 # leading 1 to make sure leading zeros are not stripped
  101. for i in str(os):
  102. num = (num << 8) | ord(i)
  103. return bin(num)[3:]
  104. def _intstobits(*ints):
  105. '''Convert the int args to a string of bits in the expected format
  106. that SNMP expects for them. The results will be a string of '1's
  107. and '0's where the first one represents 1, and second one
  108. representing 2 and so on.'''
  109. v = 0
  110. for i in ints:
  111. v |= 1 << i
  112. r = list(bin(v)[2:-1])
  113. r.reverse()
  114. return ''.join(r)
  115. def _cmpbits(a, b):
  116. '''Compare two strings of bits to make sure they are equal.
  117. Trailing 0's are ignored.'''
  118. try:
  119. last1a = a.rindex('1')
  120. except ValueError:
  121. last1a = -1
  122. a = ''
  123. try:
  124. last1b = b.rindex('1')
  125. except ValueError:
  126. last1b = -1
  127. b = ''
  128. if last1a != -1:
  129. a = a[:last1a + 1]
  130. if last1b != -1:
  131. b = b[:last1b + 1]
  132. return a == b
  133. import vlanmang
  134. def checkchanges(module):
  135. '''Function to check for any differences between the switch, and the
  136. configured state.
  137. The parameter module is a string to the name of a python module. It
  138. will be imported, and any names that reference a vlanmang.SwitchConfig
  139. class will be validate that the configuration matches. If it does not,
  140. the returned list will contain a set of tuples, each one containing
  141. (verb, arg1, arg2, switcharg2). verb is what needs to be changed.
  142. arg1 is either the port (for setting Pvid), or the VLAN that needs to
  143. be configured. arg2 is what it needs to be set to. switcharg2 is
  144. what the switch is currently configured to, so that you can easily
  145. see what the effect of the configuration change is.
  146. '''
  147. mod = importlib.import_module(module)
  148. mods = [ i for i in mod.__dict__.itervalues() if isinstance(i, vlanmang.SwitchConfig) ]
  149. res = []
  150. for i in mods:
  151. vlans = i.vlanconf.keys()
  152. switch = SNMPSwitch(i.host, i.community)
  153. portmapping = switch.getportmapping()
  154. invportmap = { y: x for x, y in portmapping.iteritems() }
  155. lufun = invportmap.__getitem__
  156. # get complete set of ports
  157. portlist = i.getportlist(lufun)
  158. ports = set(portmapping.iterkeys())
  159. # make sure switch agrees w/ them all
  160. if ports != portlist:
  161. raise ValueError('missing or extra ports found: %s' %
  162. `ports.symmetric_difference(portlist)`)
  163. # compare pvid
  164. pvidmap = getpvidmapping(i.vlanconf, lufun)
  165. switchpvid = switch.getpvid()
  166. res.extend(('setpvid', idx, vlan, switchpvid[idx]) for idx, vlan in
  167. pvidmap.iteritems() if switchpvid[idx] != vlan)
  168. # compare egress & untagged
  169. switchegress = switch.getegress(*vlans)
  170. egress = getegress(i.vlanconf, lufun)
  171. switchuntagged = switch.getuntagged(*vlans)
  172. untagged = getuntagged(i.vlanconf, lufun)
  173. for i in vlans:
  174. if not _cmpbits(switchegress[i], egress[i]):
  175. res.append(('setegress', i, egress[i], switchegress[i]))
  176. if not _cmpbits(switchuntagged[i], untagged[i]):
  177. res.append(('setuntagged', i, untagged[i], switchuntagged[i]))
  178. return res, switch
  179. def getidxs(lst, lookupfun):
  180. '''Take a list of ports, and if any are a string, replace them w/
  181. the value returned by lookupfun(s).
  182. Note that duplicates are not detected or removed, both in the
  183. original list, and the values returned by the lookup function
  184. may duplicate other values in the list.'''
  185. return [ lookupfun(i) if isinstance(i, str) else i for i in lst ]
  186. def getpvidmapping(data, lookupfun):
  187. '''Return a mapping from vlan based table to a port: vlan
  188. dictionary. This only looks at that untagged part of the vlan
  189. configuration, and is used for finding what a port's Pvid should
  190. be.'''
  191. res = []
  192. for id in data:
  193. for i in data[id].get('u', []):
  194. if isinstance(i, str):
  195. i = lookupfun(i)
  196. res.append((i, id))
  197. return dict(res)
  198. def getegress(data, lookupfun):
  199. '''Return a dictionary, keyed by VLAN id with a bit string of ports
  200. that need to be enabled for egress. This include both tagged and
  201. untagged traffic.'''
  202. r = {}
  203. for id in data:
  204. r[id] = _intstobits(*(getidxs(data[id].get('u', []),
  205. lookupfun) + getidxs(data[id].get('t', []), lookupfun)))
  206. return r
  207. def getuntagged(data, lookupfun):
  208. '''Return a dictionary, keyed by VLAN id with a bit string of ports
  209. that need to be enabled for untagged egress.'''
  210. r = {}
  211. for id in data:
  212. r[id] = _intstobits(*getidxs(data[id].get('u', []), lookupfun))
  213. return r
  214. class SNMPSwitch(object):
  215. '''A class for manipulating switches via standard SNMP MIBs.'''
  216. def __init__(self, host, auth):
  217. self._eng = SnmpEngine()
  218. if isinstance(auth, str):
  219. self._cd = CommunityData(auth, mpModel=0)
  220. else:
  221. self._cd = auth
  222. self._targ = UdpTransportTarget((host, 161))
  223. def _getmany(self, *oids):
  224. woids = [ ObjectIdentity(*oid) for oid in oids ]
  225. [ oid.resolveWithMib(_mvc) for oid in woids ]
  226. errorInd, errorStatus, errorIndex, varBinds = \
  227. next(getCmd(self._eng, self._cd, self._targ,
  228. ContextData(), *(ObjectType(oid) for oid in woids)))
  229. if errorInd: # pragma: no cover
  230. raise ValueError(errorIndication)
  231. elif errorStatus:
  232. if str(errorStatus) == 'tooBig' and len(oids) > 1:
  233. # split the request in two
  234. pivot = len(oids) / 2
  235. a = self._getmany(*oids[:pivot])
  236. b = self._getmany(*oids[pivot:])
  237. return a + b
  238. raise ValueError('%s at %s' %
  239. (errorStatus.prettyPrint(), errorIndex and
  240. varBinds[int(errorIndex)-1][0] or '?'))
  241. else:
  242. if len(varBinds) != len(oids): # pragma: no cover
  243. raise ValueError('too many return values')
  244. return varBinds
  245. def _get(self, oid):
  246. varBinds = self._getmany(oid)
  247. varBind = varBinds[0]
  248. return varBind[1]
  249. def _set(self, oid, value):
  250. oid = ObjectIdentity(*oid)
  251. oid.resolveWithMib(_mvc)
  252. if isinstance(value, (int, long)):
  253. value = Integer(value)
  254. elif isinstance(value, str):
  255. value = OctetString(value)
  256. errorInd, errorStatus, errorIndex, varBinds = \
  257. next(setCmd(self._eng, self._cd, self._targ,
  258. ContextData(), ObjectType(oid, value)))
  259. if errorInd: # pragma: no cover
  260. raise ValueError(errorIndication)
  261. elif errorStatus: # pragma: no cover
  262. raise ValueError('%s at %s' %
  263. (errorStatus.prettyPrint(), errorIndex and
  264. varBinds[int(errorIndex)-1][0] or '?'))
  265. else:
  266. for varBind in varBinds:
  267. if varBind[1] != value: # pragma: no cover
  268. raise RuntimeError('failed to set: %s' % ' = '.join([x.prettyPrint() for x in varBind]))
  269. def _walk(self, *oid):
  270. oid = ObjectIdentity(*oid)
  271. # XXX - keep these, this might stop working, no clue what managed to magically make things work
  272. # ref: http://snmplabs.com/pysnmp/examples/smi/manager/browsing-mib-tree.html#mib-objects-to-pdu-var-binds
  273. # mibdump.py --mib-source '/Users/jmg/Nextcloud/Documents/user manuals/netgear/gs7xxt-v6.3.1.19-mibs' --mib-source /usr/share/snmp/mibs --rebuild rfc1212 pbridge vlan
  274. #oid.addAsn1MibSource('/usr/share/snmp/mibs', '/Users/jmg/Nextcloud/Documents/user manuals/netgear/gs7xxt-v6.3.1.19-mibs')
  275. oid.resolveWithMib(_mvc)
  276. for (errorInd, errorStatus, errorIndex, varBinds) in nextCmd(
  277. self._eng, self._cd, self._targ, ContextData(),
  278. ObjectType(oid),
  279. lexicographicMode=False):
  280. if errorInd: # pragma: no cover
  281. raise ValueError(errorInd)
  282. elif errorStatus: # pragma: no cover
  283. raise ValueError('%s at %s' %
  284. (errorStatus.prettyPrint(), errorIndex and
  285. varBinds[int(errorIndex)-1][0] or '?'))
  286. else:
  287. for varBind in varBinds:
  288. yield varBind
  289. def getportmapping(self):
  290. '''Return a port name mapping. Keys are the port index
  291. and the value is the name from the IF-MIB::ifName entry.'''
  292. return { x[0][-1]: str(x[1]) for x in self._walk('IF-MIB',
  293. 'ifName') }
  294. def findport(self, name):
  295. '''Look up a port name and return it's port index. This
  296. looks up via the ifName table in IF-MIB.'''
  297. return [ x[0][-1] for x in self._walk('IF-MIB', 'ifName') if
  298. str(x[1]) == name ][0]
  299. def getvlanname(self, vlan):
  300. '''Return the name for the vlan. This returns the value in
  301. Q-BRIDGE-MIB:dot1qVlanStaticName.'''
  302. v = self._get(('Q-BRIDGE-MIB', 'dot1qVlanStaticName', vlan))
  303. return str(v).decode('utf-8')
  304. def createvlan(self, vlan, name):
  305. # createAndGo(4)
  306. self._set(('Q-BRIDGE-MIB', 'dot1qVlanStaticRowStatus',
  307. int(vlan)), 4)
  308. self._set(('Q-BRIDGE-MIB', 'dot1qVlanStaticName', int(vlan)),
  309. name)
  310. def deletevlan(self, vlan):
  311. self._set(('Q-BRIDGE-MIB', 'dot1qVlanStaticRowStatus',
  312. int(vlan)), 6) # destroy(6)
  313. def getvlans(self):
  314. '''Return an iterator with all the vlan ids.'''
  315. return (x[0][-1] for x in self._walk('Q-BRIDGE-MIB',
  316. 'dot1qVlanStatus'))
  317. def staticvlans(self):
  318. '''Return an iterator of the staticly defined/configured
  319. vlans. This sometimes excludes special built in vlans,
  320. like vlan 1.'''
  321. return (x[0][-1] for x in self._walk('Q-BRIDGE-MIB',
  322. 'dot1qVlanStaticName'))
  323. def getpvid(self):
  324. '''Returns a dictionary w/ the interface index as the key,
  325. and the pvid of the interface.'''
  326. return { x[0][-1]: int(x[1]) for x in self._walk('Q-BRIDGE-MIB',
  327. 'dot1qPvid') }
  328. def setpvid(self, port, vlan):
  329. '''Set the port's Pvid to vlan. This means that any packet
  330. received by the port that is untagged, will be routed the
  331. the vlan.'''
  332. self._set(('Q-BRIDGE-MIB', 'dot1qPvid', int(port)), Gauge32(vlan))
  333. def getegress(self, *vlans):
  334. '''Get a dictionary keyed by the specified VLANs, where each
  335. value is a bit string that preresents what ports that
  336. particular VLAN will be transmitted on.'''
  337. r = { x[-1]: _octstrtobits(y) for x, y in
  338. self._getmany(*(('Q-BRIDGE-MIB',
  339. 'dot1qVlanStaticEgressPorts', x) for x in vlans)) }
  340. return r
  341. def setegress(self, vlan, ports):
  342. '''Set the ports which the specified VLAN will have packets
  343. transmitted as either tagged, if unset in untagged, or
  344. untagged, if set in untagged, to bit bit string specified
  345. by ports.'''
  346. value = OctetString.fromBinaryString(ports)
  347. self._set(('Q-BRIDGE-MIB', 'dot1qVlanStaticEgressPorts',
  348. int(vlan)), value)
  349. def getuntagged(self, *vlans):
  350. '''Get a dictionary keyed by the specified VLANs, where each
  351. value is a bit string that preresents what ports that
  352. particular VLAN will be transmitted on as an untagged
  353. packet.'''
  354. r = { x[-1]: _octstrtobits(y) for x, y in
  355. self._getmany(*(('Q-BRIDGE-MIB',
  356. 'dot1qVlanStaticUntaggedPorts', x) for x in vlans)) }
  357. return r
  358. def setuntagged(self, vlan, ports):
  359. '''Set the ports which the specified VLAN will have packets
  360. transmitted as untagged to the bit string specified by ports.'''
  361. value = OctetString.fromBinaryString(ports)
  362. self._set(('Q-BRIDGE-MIB', 'dot1qVlanStaticUntaggedPorts',
  363. int(vlan)), value)
  364. if __name__ == '__main__': # pragma: no cover
  365. import pprint
  366. import sys
  367. changes, switch = checkchanges('data')
  368. if not changes:
  369. print 'No changes to apply.'
  370. sys.exit(0)
  371. pprint.pprint(changes)
  372. res = raw_input('Apply the changes? (type yes to apply): ')
  373. if res != 'yes':
  374. print 'not applying changes.'
  375. sys.exit(1)
  376. print 'applying...'
  377. failed = []
  378. for verb, arg1, arg2, oldarg in changes:
  379. print '%s: %s %s' % (verb, arg1, `arg2`)
  380. try:
  381. fun = getattr(switch, verb)
  382. fun(arg1, arg2)
  383. pass
  384. except Exception as e:
  385. print 'failed'
  386. failed.append((verb, arg1, arg2, e))
  387. if failed:
  388. print '%d failed to apply, they are:' % len(failed)
  389. for verb, arg1, arg2, e in failed:
  390. print '%s: %s %s: %s' % (verb, arg1, arg2, `e`)
  391. class _TestMisc(unittest.TestCase):
  392. def setUp(self):
  393. import test_data
  394. self._test_data = test_data
  395. def test_intstobits(self):
  396. self.assertEqual(_intstobits(1, 5, 10), '1000100001')
  397. self.assertEqual(_intstobits(3, 4, 9), '001100001')
  398. def test_octstrtobits(self):
  399. self.assertEqual(_octstrtobits('\x00'), '0' * 8)
  400. self.assertEqual(_octstrtobits('\xff'), '1' * 8)
  401. self.assertEqual(_octstrtobits('\xf0'), '1' * 4 + '0' * 4)
  402. self.assertEqual(_octstrtobits('\x0f'), '0' * 4 + '1' * 4)
  403. def test_cmpbits(self):
  404. self.assertTrue(_cmpbits('111000', '111'))
  405. self.assertTrue(_cmpbits('000111000', '000111'))
  406. self.assertTrue(_cmpbits('11', '11'))
  407. self.assertTrue(_cmpbits('0', '000'))
  408. self.assertFalse(_cmpbits('0011', '11'))
  409. self.assertFalse(_cmpbits('11', '0011'))
  410. self.assertFalse(_cmpbits('10', '000'))
  411. self.assertFalse(_cmpbits('0', '1000'))
  412. self.assertFalse(_cmpbits('00010', '000'))
  413. self.assertFalse(_cmpbits('0', '001000'))
  414. def test_pvidegressuntagged(self):
  415. data = {
  416. 1: {
  417. 'u': [ 1, 5, 10 ] + range(13, 20),
  418. 't': [ 'lag2', 6, 7 ],
  419. },
  420. 10: {
  421. 'u': [ 2, 3, 6, 7, 8, 'lag2' ],
  422. },
  423. 13: {
  424. 'u': [ 4, 9 ],
  425. 't': [ 'lag2', 6, 7 ],
  426. },
  427. 14: {
  428. 't': [ 'lag2' ],
  429. },
  430. }
  431. swconf = SwitchConfig('', '', data, [ 'lag3' ])
  432. lookup = {
  433. 'lag2': 30,
  434. 'lag3': 31,
  435. }
  436. lufun = lookup.__getitem__
  437. check = dict(itertools.chain(enumerate([ 1, 10, 10, 13, 1, 10,
  438. 10, 10, 13, 1 ], 1), enumerate([ 1 ] * 7, 13),
  439. [ (30, 10) ]))
  440. # That a pvid mapping
  441. res = getpvidmapping(data, lufun)
  442. # is correct
  443. self.assertEqual(res, check)
  444. self.assertEqual(swconf.getportlist(lufun),
  445. set(xrange(1, 11)) | set(xrange(13, 20)) |
  446. set(lookup.values()))
  447. checkegress = {
  448. 1: '1000111001001111111' + '0' * (30 - 20) + '1',
  449. 10: '01100111' + '0' * (30 - 9) + '1',
  450. 13: '000101101' + '0' * (30 - 10) + '1',
  451. 14: '0' * (30 - 1) + '1',
  452. }
  453. self.assertEqual(getegress(data, lufun), checkegress)
  454. checkuntagged = {
  455. 1: '1000100001001111111',
  456. 10: '01100111' + '0' * (30 - 9) + '1',
  457. 13: '000100001',
  458. 14: '',
  459. }
  460. self.assertEqual(getuntagged(data, lufun), checkuntagged)
  461. #@unittest.skip('foo')
  462. @mock.patch('vlanmang.SNMPSwitch.getuntagged')
  463. @mock.patch('vlanmang.SNMPSwitch.getegress')
  464. @mock.patch('vlanmang.SNMPSwitch.getpvid')
  465. @mock.patch('vlanmang.SNMPSwitch.getportmapping')
  466. @mock.patch('importlib.import_module')
  467. def test_checkchanges(self, imprt, portmapping, gpvid, gegress, guntagged):
  468. # that import returns the test data
  469. imprt.side_effect = itertools.repeat(self._test_data)
  470. # that getportmapping returns the following dict
  471. ports = { x: 'g%d' % x for x in xrange(1, 24) }
  472. ports[30] = 'lag1'
  473. ports[31] = 'lag2'
  474. ports[32] = 'lag3'
  475. portmapping.side_effect = itertools.repeat(ports)
  476. # that the switch's pvid returns
  477. spvid = { x: 283 for x in xrange(1, 24) }
  478. spvid[30] = 5
  479. gpvid.side_effect = itertools.repeat(spvid)
  480. # the the extra port is caught
  481. self.assertRaises(ValueError, checkchanges, 'data')
  482. # that the functions were called
  483. imprt.assert_called_with('data')
  484. portmapping.assert_called()
  485. # XXX - check that an ignore statement is honored
  486. # delete the extra port
  487. del ports[32]
  488. # that the egress data provided
  489. gegress.side_effect = [ {
  490. 1: '1' * 10,
  491. 5: '1' * 10,
  492. 283: '00000000111111111110011000000100000',
  493. } ]
  494. # that the untagged data provided
  495. guntagged.side_effect = [ {
  496. 1: '1' * 10,
  497. 5: '1' * 8 + '0' * 10,
  498. 283: '00000000111111111110011',
  499. } ]
  500. res, switch = checkchanges('data')
  501. self.assertIsInstance(switch, SNMPSwitch)
  502. validres = [ ('setpvid', x, 5, 283) for x in xrange(1, 9) ] + \
  503. [ ('setpvid', 20, 1, 283),
  504. ('setpvid', 21, 1, 283),
  505. ('setpvid', 30, 1, 5),
  506. ('setegress', 1, '0' * 19 + '11' + '0' * 8 + '1',
  507. '1' * 10),
  508. ('setuntagged', 1, '0' * 19 + '11' + '0' * 8 + '1',
  509. '1' * 10),
  510. ('setegress', 5, '1' * 8 + '0' * 11 + '11' + '0' * 8 +
  511. '1', '1' * 10),
  512. ]
  513. self.assertEqual(set(res), set(validres))
  514. class _TestSNMPSwitch(unittest.TestCase):
  515. def test_splitmany(self):
  516. # make sure that if we get a tooBig error that we split the
  517. # _getmany request
  518. switch = SNMPSwitch(None, None)
  519. @mock.patch('vlanmang.SNMPSwitch._getmany')
  520. def test_get(self, gm):
  521. # that a switch
  522. switch = SNMPSwitch(None, None)
  523. # when _getmany returns this structure
  524. retval = object()
  525. gm.side_effect = [[[ None, retval ]]]
  526. arg = object()
  527. # will return the correct value
  528. self.assertIs(switch._get(arg), retval)
  529. # and call _getmany w/ the correct arg
  530. gm.assert_called_with(arg)
  531. @mock.patch('pysnmp.hlapi.ContextData')
  532. @mock.patch('vlanmang.getCmd')
  533. def test_getmany(self, gc, cd):
  534. # that a switch
  535. switch = SNMPSwitch(None, None)
  536. lookup = { x: chr(x) for x in xrange(1, 10) }
  537. # when getCmd returns tooBig when too many oids are asked for
  538. def custgetcmd(eng, cd, targ, contextdata, *oids):
  539. # induce a too big error
  540. if len(oids) > 3:
  541. res = ( None, 'tooBig', None, None )
  542. else:
  543. #import pdb; pdb.set_trace()
  544. [ oid.resolveWithMib(_mvc) for oid in oids ]
  545. oids = [ ObjectType(x[0],
  546. OctetString(lookup[x[0][-1]])) for x in oids ]
  547. [ oid.resolveWithMib(_mvc) for oid in oids ]
  548. res = ( None, None, None, oids )
  549. return iter([res])
  550. gc.side_effect = custgetcmd
  551. #import pdb; pdb.set_trace()
  552. res = switch.getegress(*xrange(1, 10))
  553. # will still return the complete set of results
  554. self.assertEqual(res, { x: _octstrtobits(lookup[x]) for x in
  555. xrange(1, 10) })
  556. _skipSwitchTests = True
  557. class _TestSwitch(unittest.TestCase):
  558. def setUp(self):
  559. # If we don't have it, pretend it's true for now and
  560. # we'll recheck it later
  561. model = 'GS108T smartSwitch'
  562. if getattr(self, 'switchmodel', model) != model or \
  563. _skipSwitchTests: # pragma: no cover
  564. self.skipTest('Need a GS108T switch to run these tests')
  565. args = open('test.creds').read().split()
  566. self.switch = SNMPSwitch(*args)
  567. self.switchmodel = self.switch._get(('ENTITY-MIB',
  568. 'entPhysicalModelName', 1))
  569. if self.switchmodel != model: # pragma: no cover
  570. self.skipTest('Need a GS108T switch to run these tests')
  571. def test_misc(self):
  572. switch = self.switch
  573. self.assertEqual(switch.findport('g1'), 1)
  574. self.assertEqual(switch.findport('l1'), 14)
  575. def test_portnames(self):
  576. switch = self.switch
  577. resp = dict((x, 'g%d' % x) for x in xrange(1, 9))
  578. resp.update({ 13: 'cpu' })
  579. resp.update((x, 'l%d' % (x - 13)) for x in xrange(14, 18))
  580. self.assertEqual(switch.getportmapping(), resp)
  581. def test_egress(self):
  582. switch = self.switch
  583. egress = switch.getegress(1, 2, 3)
  584. checkegress = {
  585. 1: '1' * 8 + '0' * 5 + '1' * 4 + '0' * 23,
  586. 2: '0' * 8 * 5,
  587. 3: '0' * 8 * 5,
  588. }
  589. self.assertEqual(egress, checkegress)
  590. def test_untagged(self):
  591. switch = self.switch
  592. untagged = switch.getuntagged(1, 2, 3)
  593. checkuntagged = {
  594. 1: '1' * 8 * 5,
  595. 2: '1' * 8 * 5,
  596. 3: '1' * 8 * 5,
  597. }
  598. self.assertEqual(untagged, checkuntagged)
  599. def test_vlan(self):
  600. switch = self.switch
  601. existingvlans = set(switch.getvlans())
  602. while True:
  603. testvlan = random.randint(1,4095)
  604. if testvlan not in existingvlans:
  605. break
  606. # Test that getting a non-existant vlans raises an exception
  607. self.assertRaises(ValueError, switch.getvlanname, testvlan)
  608. self.assertTrue(set(switch.staticvlans()).issubset(existingvlans))
  609. pvidres = { x: 1 for x in xrange(1, 9) }
  610. pvidres.update({ x: 1 for x in xrange(14, 18) })
  611. self.assertEqual(switch.getpvid(), pvidres)
  612. testname = 'Sometestname'
  613. # Create test vlan
  614. switch.createvlan(testvlan, testname)
  615. testport = None
  616. try:
  617. # make sure the test vlan was created
  618. self.assertIn(testvlan, set(switch.staticvlans()))
  619. self.assertEqual(testname, switch.getvlanname(testvlan))
  620. switch.setegress(testvlan, '00100')
  621. pvidmap = switch.getpvid()
  622. testport = 3
  623. egressports = switch.getegress(testvlan)
  624. self.assertEqual(egressports[testvlan], '00100000' +
  625. '0' * 8 * 4)
  626. switch.setuntagged(testvlan, '00100')
  627. untaggedports = switch.getuntagged(testvlan)
  628. self.assertEqual(untaggedports[testvlan], '00100000' +
  629. '0' * 8 * 4)
  630. switch.setpvid(testport, testvlan)
  631. self.assertEqual(switch.getpvid()[testport], testvlan)
  632. finally:
  633. if testport:
  634. switch.setpvid(testport, pvidmap[3])
  635. switch.deletevlan(testvlan)