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.
 
 

841 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 = [ (k, v) for k, v in mod.__dict__.iteritems() if isinstance(v, vlanmang.SwitchConfig) ]
  149. res = []
  150. for name, i in mods:
  151. print 'probing %s' % `name`
  152. vlans = i.vlanconf.keys()
  153. switch = SNMPSwitch(i.host, i.community)
  154. #print `switch`
  155. switchpvid = switch.getpvid()
  156. #print `switchpvid`
  157. #import pdb; pdb.set_trace()
  158. portmapping = switch.getportmapping()
  159. invportmap = { y: x for x, y in portmapping.iteritems() }
  160. lufun = invportmap.__getitem__
  161. # get complete set of ports
  162. portlist = i.getportlist(lufun)
  163. ports = set(portmapping.iterkeys())
  164. # make sure switch agrees w/ them all
  165. if ports != portlist:
  166. raise ValueError('missing or extra ports found: %s' %
  167. `ports.symmetric_difference(portlist)`)
  168. # compare pvid
  169. pvidmap = getpvidmapping(i.vlanconf, lufun)
  170. switchpvid = switch.getpvid()
  171. res.extend((switch, name, 'setpvid', idx, vlan, switchpvid[idx]) for idx, vlan in
  172. pvidmap.iteritems() if switchpvid[idx] != vlan)
  173. # compare egress & untagged
  174. switchegress = switch.getegress(*vlans)
  175. egress = getegress(i.vlanconf, lufun)
  176. switchuntagged = switch.getuntagged(*vlans)
  177. untagged = getuntagged(i.vlanconf, lufun)
  178. for i in vlans:
  179. if not _cmpbits(switchegress[i], egress[i]):
  180. res.append((switch, name, 'setegress', i, egress[i], switchegress[i]))
  181. if not _cmpbits(switchuntagged[i], untagged[i]):
  182. res.append((switch, name, 'setuntagged', i, untagged[i], switchuntagged[i]))
  183. return res
  184. def getidxs(lst, lookupfun):
  185. '''Take a list of ports, and if any are a string, replace them w/
  186. the value returned by lookupfun(s).
  187. Note that duplicates are not detected or removed, both in the
  188. original list, and the values returned by the lookup function
  189. may duplicate other values in the list.'''
  190. return [ lookupfun(i) if isinstance(i, str) else i for i in lst ]
  191. def getpvidmapping(data, lookupfun):
  192. '''Return a mapping from vlan based table to a port: vlan
  193. dictionary. This only looks at that untagged part of the vlan
  194. configuration, and is used for finding what a port's Pvid should
  195. be.'''
  196. res = []
  197. for id in data:
  198. for i in data[id].get('u', []):
  199. if isinstance(i, str):
  200. i = lookupfun(i)
  201. res.append((i, id))
  202. return dict(res)
  203. def getegress(data, lookupfun):
  204. '''Return a dictionary, keyed by VLAN id with a bit string of ports
  205. that need to be enabled for egress. This include both tagged and
  206. untagged traffic.'''
  207. r = {}
  208. for id in data:
  209. r[id] = _intstobits(*(getidxs(data[id].get('u', []),
  210. lookupfun) + getidxs(data[id].get('t', []), lookupfun)))
  211. return r
  212. def getuntagged(data, lookupfun):
  213. '''Return a dictionary, keyed by VLAN id with a bit string of ports
  214. that need to be enabled for untagged egress.'''
  215. r = {}
  216. for id in data:
  217. r[id] = _intstobits(*getidxs(data[id].get('u', []), lookupfun))
  218. return r
  219. class SNMPSwitch(object):
  220. '''A class for manipulating switches via standard SNMP MIBs.'''
  221. def __init__(self, host, auth):
  222. self._eng = SnmpEngine()
  223. if isinstance(auth, str):
  224. self._cd = CommunityData(auth, mpModel=0)
  225. else:
  226. self._cd = auth
  227. self._targ = UdpTransportTarget((host, 161))
  228. def __repr__(self):
  229. return '<SNMPSwitch: auth=%s, targ=%s>' % (`self._cd`, `self._targ`)
  230. def _getmany(self, *oids):
  231. woids = [ ObjectIdentity(*oid) for oid in oids ]
  232. [ oid.resolveWithMib(_mvc) for oid in woids ]
  233. errorInd, errorStatus, errorIndex, varBinds = \
  234. next(getCmd(self._eng, self._cd, self._targ,
  235. ContextData(), *(ObjectType(oid) for oid in woids)))
  236. if errorInd: # pragma: no cover
  237. raise ValueError(errorInd)
  238. elif errorStatus:
  239. if str(errorStatus) == 'tooBig' and len(oids) > 1:
  240. # split the request in two
  241. pivot = len(oids) / 2
  242. a = self._getmany(*oids[:pivot])
  243. b = self._getmany(*oids[pivot:])
  244. return a + b
  245. raise ValueError('%s at %s' %
  246. (errorStatus.prettyPrint(), errorIndex and
  247. varBinds[int(errorIndex)-1][0] or '?'))
  248. else:
  249. if len(varBinds) != len(oids): # pragma: no cover
  250. raise ValueError('too many return values')
  251. return varBinds
  252. def _get(self, oid):
  253. varBinds = self._getmany(oid)
  254. varBind = varBinds[0]
  255. return varBind[1]
  256. def _set(self, oid, value):
  257. oid = ObjectIdentity(*oid)
  258. oid.resolveWithMib(_mvc)
  259. if isinstance(value, (int, long)):
  260. value = Integer(value)
  261. elif isinstance(value, str):
  262. value = OctetString(value)
  263. errorInd, errorStatus, errorIndex, varBinds = \
  264. next(setCmd(self._eng, self._cd, self._targ,
  265. ContextData(), ObjectType(oid, value)))
  266. if errorInd: # pragma: no cover
  267. raise ValueError(errorInd)
  268. elif errorStatus: # pragma: no cover
  269. raise ValueError('%s at %s' %
  270. (errorStatus.prettyPrint(), errorIndex and
  271. varBinds[int(errorIndex)-1][0] or '?'))
  272. else:
  273. for varBind in varBinds:
  274. if varBind[1] != value: # pragma: no cover
  275. raise RuntimeError('failed to set: %s' % ' = '.join([x.prettyPrint() for x in varBind]))
  276. def _walk(self, *oid):
  277. oid = ObjectIdentity(*oid)
  278. # XXX - keep these, this might stop working, no clue what managed to magically make things work
  279. # ref: http://snmplabs.com/pysnmp/examples/smi/manager/browsing-mib-tree.html#mib-objects-to-pdu-var-binds
  280. # 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
  281. #oid.addAsn1MibSource('/usr/share/snmp/mibs', '/Users/jmg/Nextcloud/Documents/user manuals/netgear/gs7xxt-v6.3.1.19-mibs')
  282. oid.resolveWithMib(_mvc)
  283. for (errorInd, errorStatus, errorIndex, varBinds) in nextCmd(
  284. self._eng, self._cd, self._targ, ContextData(),
  285. ObjectType(oid),
  286. lexicographicMode=False):
  287. if errorInd: # pragma: no cover
  288. raise ValueError(errorInd)
  289. elif errorStatus: # pragma: no cover
  290. raise ValueError('%s at %s' %
  291. (errorStatus.prettyPrint(), errorIndex and
  292. varBinds[int(errorIndex)-1][0] or '?'))
  293. else:
  294. for varBind in varBinds:
  295. yield varBind
  296. def getportmapping(self):
  297. '''Return a port name mapping. Keys are the port index
  298. and the value is the name from the IF-MIB::ifName entry.'''
  299. return { x[0][-1]: str(x[1]) for x in self._walk('IF-MIB',
  300. 'ifName') }
  301. def findport(self, name):
  302. '''Look up a port name and return it's port index. This
  303. looks up via the ifName table in IF-MIB.'''
  304. return [ x[0][-1] for x in self._walk('IF-MIB', 'ifName') if
  305. str(x[1]) == name ][0]
  306. def getvlanname(self, vlan):
  307. '''Return the name for the vlan. This returns the value in
  308. Q-BRIDGE-MIB:dot1qVlanStaticName.'''
  309. v = self._get(('Q-BRIDGE-MIB', 'dot1qVlanStaticName', vlan))
  310. return str(v).decode('utf-8')
  311. def createvlan(self, vlan, name):
  312. # createAndGo(4)
  313. self._set(('Q-BRIDGE-MIB', 'dot1qVlanStaticRowStatus',
  314. int(vlan)), 4)
  315. self._set(('Q-BRIDGE-MIB', 'dot1qVlanStaticName', int(vlan)),
  316. name)
  317. def deletevlan(self, vlan):
  318. self._set(('Q-BRIDGE-MIB', 'dot1qVlanStaticRowStatus',
  319. int(vlan)), 6) # destroy(6)
  320. def getvlans(self):
  321. '''Return an iterator with all the vlan ids.'''
  322. return (x[0][-1] for x in self._walk('Q-BRIDGE-MIB',
  323. 'dot1qVlanStatus'))
  324. def staticvlans(self):
  325. '''Return an iterator of the staticly defined/configured
  326. vlans. This sometimes excludes special built in vlans,
  327. like vlan 1.'''
  328. return (x[0][-1] for x in self._walk('Q-BRIDGE-MIB',
  329. 'dot1qVlanStaticName'))
  330. def getpvid(self):
  331. '''Returns a dictionary w/ the interface index as the key,
  332. and the pvid of the interface.'''
  333. return { x[0][-1]: int(x[1]) for x in self._walk('Q-BRIDGE-MIB',
  334. 'dot1qPvid') }
  335. def setpvid(self, port, vlan):
  336. '''Set the port's Pvid to vlan. This means that any packet
  337. received by the port that is untagged, will be routed the
  338. the vlan.'''
  339. self._set(('Q-BRIDGE-MIB', 'dot1qPvid', int(port)), Gauge32(vlan))
  340. def getegress(self, *vlans):
  341. '''Get a dictionary keyed by the specified VLANs, where each
  342. value is a bit string that preresents what ports that
  343. particular VLAN will be transmitted on.'''
  344. r = { x[-1]: _octstrtobits(y) for x, y in
  345. self._getmany(*(('Q-BRIDGE-MIB',
  346. 'dot1qVlanStaticEgressPorts', x) for x in vlans)) }
  347. return r
  348. def setegress(self, vlan, ports):
  349. '''Set the ports which the specified VLAN will have packets
  350. transmitted as either tagged, if unset in untagged, or
  351. untagged, if set in untagged, to bit bit string specified
  352. by ports.'''
  353. value = OctetString.fromBinaryString(ports)
  354. self._set(('Q-BRIDGE-MIB', 'dot1qVlanStaticEgressPorts',
  355. int(vlan)), value)
  356. def getuntagged(self, *vlans):
  357. '''Get a dictionary keyed by the specified VLANs, where each
  358. value is a bit string that preresents what ports that
  359. particular VLAN will be transmitted on as an untagged
  360. packet.'''
  361. r = { x[-1]: _octstrtobits(y) for x, y in
  362. self._getmany(*(('Q-BRIDGE-MIB',
  363. 'dot1qVlanStaticUntaggedPorts', x) for x in vlans)) }
  364. return r
  365. def setuntagged(self, vlan, ports):
  366. '''Set the ports which the specified VLAN will have packets
  367. transmitted as untagged to the bit string specified by ports.'''
  368. value = OctetString.fromBinaryString(ports)
  369. self._set(('Q-BRIDGE-MIB', 'dot1qVlanStaticUntaggedPorts',
  370. int(vlan)), value)
  371. def main():
  372. import pprint
  373. import sys
  374. changes = checkchanges('data')
  375. if not changes:
  376. print 'No changes to apply.'
  377. sys.exit(0)
  378. pprint.pprint([ x[1:] for x in changes ])
  379. res = raw_input('Apply the changes? (type yes to apply): ')
  380. if res != 'yes':
  381. print 'not applying changes.'
  382. sys.exit(1)
  383. print 'applying...'
  384. failed = []
  385. prevname = None
  386. for switch, name, verb, arg1, arg2, oldarg in changes:
  387. if prevname != name:
  388. print 'Configuring switch %s...' % `name`
  389. prevname = name
  390. print '%s: %s %s' % (verb, arg1, `arg2`)
  391. try:
  392. fun = getattr(switch, verb)
  393. fun(arg1, arg2)
  394. pass
  395. except Exception as e:
  396. print 'failed'
  397. failed.append((verb, arg1, arg2, e))
  398. if failed:
  399. print '%d failed to apply, they are:' % len(failed)
  400. for verb, arg1, arg2, e in failed:
  401. print '%s: %s %s: %s' % (verb, arg1, arg2, `e`)
  402. if __name__ == '__main__': # pragma: no cover
  403. main()
  404. class _TestMisc(unittest.TestCase):
  405. def setUp(self):
  406. import test_data
  407. self._test_data = test_data
  408. def test_intstobits(self):
  409. self.assertEqual(_intstobits(1, 5, 10), '1000100001')
  410. self.assertEqual(_intstobits(3, 4, 9), '001100001')
  411. def test_octstrtobits(self):
  412. self.assertEqual(_octstrtobits('\x00'), '0' * 8)
  413. self.assertEqual(_octstrtobits('\xff'), '1' * 8)
  414. self.assertEqual(_octstrtobits('\xf0'), '1' * 4 + '0' * 4)
  415. self.assertEqual(_octstrtobits('\x0f'), '0' * 4 + '1' * 4)
  416. def test_cmpbits(self):
  417. self.assertTrue(_cmpbits('111000', '111'))
  418. self.assertTrue(_cmpbits('000111000', '000111'))
  419. self.assertTrue(_cmpbits('11', '11'))
  420. self.assertTrue(_cmpbits('0', '000'))
  421. self.assertFalse(_cmpbits('0011', '11'))
  422. self.assertFalse(_cmpbits('11', '0011'))
  423. self.assertFalse(_cmpbits('10', '000'))
  424. self.assertFalse(_cmpbits('0', '1000'))
  425. self.assertFalse(_cmpbits('00010', '000'))
  426. self.assertFalse(_cmpbits('0', '001000'))
  427. def test_pvidegressuntagged(self):
  428. data = {
  429. 1: {
  430. 'u': [ 1, 5, 10 ] + range(13, 20),
  431. 't': [ 'lag2', 6, 7 ],
  432. },
  433. 10: {
  434. 'u': [ 2, 3, 6, 7, 8, 'lag2' ],
  435. },
  436. 13: {
  437. 'u': [ 4, 9 ],
  438. 't': [ 'lag2', 6, 7 ],
  439. },
  440. 14: {
  441. 't': [ 'lag2' ],
  442. },
  443. }
  444. swconf = SwitchConfig('', '', data, [ 'lag3' ])
  445. lookup = {
  446. 'lag2': 30,
  447. 'lag3': 31,
  448. }
  449. lufun = lookup.__getitem__
  450. check = dict(itertools.chain(enumerate([ 1, 10, 10, 13, 1, 10,
  451. 10, 10, 13, 1 ], 1), enumerate([ 1 ] * 7, 13),
  452. [ (30, 10) ]))
  453. # That a pvid mapping
  454. res = getpvidmapping(data, lufun)
  455. # is correct
  456. self.assertEqual(res, check)
  457. self.assertEqual(swconf.getportlist(lufun),
  458. set(xrange(1, 11)) | set(xrange(13, 20)) |
  459. set(lookup.values()))
  460. checkegress = {
  461. 1: '1000111001001111111' + '0' * (30 - 20) + '1',
  462. 10: '01100111' + '0' * (30 - 9) + '1',
  463. 13: '000101101' + '0' * (30 - 10) + '1',
  464. 14: '0' * (30 - 1) + '1',
  465. }
  466. self.assertEqual(getegress(data, lufun), checkegress)
  467. checkuntagged = {
  468. 1: '1000100001001111111',
  469. 10: '01100111' + '0' * (30 - 9) + '1',
  470. 13: '000100001',
  471. 14: '',
  472. }
  473. self.assertEqual(getuntagged(data, lufun), checkuntagged)
  474. #@unittest.skip('foo')
  475. @mock.patch('vlanmang.SNMPSwitch.getuntagged')
  476. @mock.patch('vlanmang.SNMPSwitch.getegress')
  477. @mock.patch('vlanmang.SNMPSwitch.getpvid')
  478. @mock.patch('vlanmang.SNMPSwitch.getportmapping')
  479. @mock.patch('importlib.import_module')
  480. def test_checkchanges(self, imprt, portmapping, gpvid, gegress, guntagged):
  481. # that import returns the test data
  482. imprt.side_effect = itertools.repeat(self._test_data)
  483. # that getportmapping returns the following dict
  484. ports = { x: 'g%d' % x for x in xrange(1, 24) }
  485. ports[30] = 'lag1'
  486. ports[31] = 'lag2'
  487. ports[32] = 'lag3'
  488. portmapping.side_effect = itertools.repeat(ports)
  489. # that the switch's pvid returns
  490. spvid = { x: 283 for x in xrange(1, 24) }
  491. spvid[30] = 5
  492. gpvid.side_effect = itertools.repeat(spvid)
  493. # the the extra port is caught
  494. self.assertRaises(ValueError, checkchanges, 'data')
  495. # that the functions were called
  496. imprt.assert_called_with('data')
  497. portmapping.assert_called()
  498. # XXX - check that an ignore statement is honored
  499. # delete the extra port
  500. del ports[32]
  501. # that the egress data provided
  502. gegress.side_effect = [ {
  503. 1: '1' * 10,
  504. 5: '1' * 10,
  505. 283: '00000000111111111110011000000100000',
  506. } ]
  507. # that the untagged data provided
  508. guntagged.side_effect = [ {
  509. 1: '1' * 10,
  510. 5: '1' * 8 + '0' * 10,
  511. 283: '00000000111111111110011',
  512. } ]
  513. res = checkchanges('data')
  514. # Make sure that the first one are all instances of SNMPSwitch
  515. # XXX make sure args for them are correct.
  516. self.assertTrue(all(isinstance(x[0], SNMPSwitch) for x in res))
  517. # Make sure that the name provided is correct
  518. self.assertTrue(all(x[1] == 'distswitch' for x in res))
  519. res = [ x[2:] for x in res ]
  520. validres = [ ('setpvid', x, 5, 283) for x in xrange(1, 9) ] + \
  521. [ ('setpvid', 20, 1, 283),
  522. ('setpvid', 21, 1, 283),
  523. ('setpvid', 30, 1, 5),
  524. ('setegress', 1, '0' * 19 + '11' + '0' * 8 + '1',
  525. '1' * 10),
  526. ('setuntagged', 1, '0' * 19 + '11' + '0' * 8 + '1',
  527. '1' * 10),
  528. ('setegress', 5, '1' * 8 + '0' * 11 + '11' + '0' * 8 +
  529. '1', '1' * 10),
  530. ]
  531. self.assertEqual(set(res), set(validres))
  532. class _TestSNMPSwitch(unittest.TestCase):
  533. def test_splitmany(self):
  534. # make sure that if we get a tooBig error that we split the
  535. # _getmany request
  536. switch = SNMPSwitch(None, None)
  537. @mock.patch('vlanmang.SNMPSwitch._getmany')
  538. def test_get(self, gm):
  539. # that a switch
  540. switch = SNMPSwitch(None, None)
  541. # when _getmany returns this structure
  542. retval = object()
  543. gm.side_effect = [[[ None, retval ]]]
  544. arg = object()
  545. # will return the correct value
  546. self.assertIs(switch._get(arg), retval)
  547. # and call _getmany w/ the correct arg
  548. gm.assert_called_with(arg)
  549. @mock.patch('pysnmp.hlapi.ContextData')
  550. @mock.patch('vlanmang.getCmd')
  551. def test_getmany(self, gc, cd):
  552. # that a switch
  553. switch = SNMPSwitch(None, None)
  554. lookup = { x: chr(x) for x in xrange(1, 10) }
  555. # when getCmd returns tooBig when too many oids are asked for
  556. def custgetcmd(eng, cd, targ, contextdata, *oids):
  557. # induce a too big error
  558. if len(oids) > 3:
  559. res = ( None, 'tooBig', None, None )
  560. else:
  561. #import pdb; pdb.set_trace()
  562. [ oid.resolveWithMib(_mvc) for oid in oids ]
  563. oids = [ ObjectType(x[0],
  564. OctetString(lookup[x[0][-1]])) for x in oids ]
  565. [ oid.resolveWithMib(_mvc) for oid in oids ]
  566. res = ( None, None, None, oids )
  567. return iter([res])
  568. gc.side_effect = custgetcmd
  569. #import pdb; pdb.set_trace()
  570. res = switch.getegress(*xrange(1, 10))
  571. # will still return the complete set of results
  572. self.assertEqual(res, { x: _octstrtobits(lookup[x]) for x in
  573. xrange(1, 10) })
  574. _skipSwitchTests = True
  575. class _TestSwitch(unittest.TestCase):
  576. def setUp(self):
  577. # If we don't have it, pretend it's true for now and
  578. # we'll recheck it later
  579. model = 'GS108T smartSwitch'
  580. if getattr(self, 'switchmodel', model) != model or \
  581. _skipSwitchTests: # pragma: no cover
  582. self.skipTest('Need a GS108T switch to run these tests')
  583. args = open('test.creds').read().split()
  584. self.switch = SNMPSwitch(*args)
  585. self.switchmodel = self.switch._get(('ENTITY-MIB',
  586. 'entPhysicalModelName', 1))
  587. if self.switchmodel != model: # pragma: no cover
  588. self.skipTest('Need a GS108T switch to run these tests')
  589. def test_misc(self):
  590. switch = self.switch
  591. self.assertEqual(switch.findport('g1'), 1)
  592. self.assertEqual(switch.findport('l1'), 14)
  593. def test_portnames(self):
  594. switch = self.switch
  595. resp = dict((x, 'g%d' % x) for x in xrange(1, 9))
  596. resp.update({ 13: 'cpu' })
  597. resp.update((x, 'l%d' % (x - 13)) for x in xrange(14, 18))
  598. self.assertEqual(switch.getportmapping(), resp)
  599. def test_egress(self):
  600. switch = self.switch
  601. egress = switch.getegress(1, 2, 3)
  602. checkegress = {
  603. 1: '1' * 8 + '0' * 5 + '1' * 4 + '0' * 23,
  604. 2: '0' * 8 * 5,
  605. 3: '0' * 8 * 5,
  606. }
  607. self.assertEqual(egress, checkegress)
  608. def test_untagged(self):
  609. switch = self.switch
  610. untagged = switch.getuntagged(1, 2, 3)
  611. checkuntagged = {
  612. 1: '1' * 8 * 5,
  613. 2: '1' * 8 * 5,
  614. 3: '1' * 8 * 5,
  615. }
  616. self.assertEqual(untagged, checkuntagged)
  617. def test_vlan(self):
  618. switch = self.switch
  619. existingvlans = set(switch.getvlans())
  620. while True:
  621. testvlan = random.randint(1,4095)
  622. if testvlan not in existingvlans:
  623. break
  624. # Test that getting a non-existant vlans raises an exception
  625. self.assertRaises(ValueError, switch.getvlanname, testvlan)
  626. self.assertTrue(set(switch.staticvlans()).issubset(existingvlans))
  627. pvidres = { x: 1 for x in xrange(1, 9) }
  628. pvidres.update({ x: 1 for x in xrange(14, 18) })
  629. self.assertEqual(switch.getpvid(), pvidres)
  630. testname = 'Sometestname'
  631. # Create test vlan
  632. switch.createvlan(testvlan, testname)
  633. testport = None
  634. try:
  635. # make sure the test vlan was created
  636. self.assertIn(testvlan, set(switch.staticvlans()))
  637. self.assertEqual(testname, switch.getvlanname(testvlan))
  638. switch.setegress(testvlan, '00100')
  639. pvidmap = switch.getpvid()
  640. testport = 3
  641. egressports = switch.getegress(testvlan)
  642. self.assertEqual(egressports[testvlan], '00100000' +
  643. '0' * 8 * 4)
  644. switch.setuntagged(testvlan, '00100')
  645. untaggedports = switch.getuntagged(testvlan)
  646. self.assertEqual(untaggedports[testvlan], '00100000' +
  647. '0' * 8 * 4)
  648. switch.setpvid(testport, testvlan)
  649. self.assertEqual(switch.getpvid()[testport], testvlan)
  650. finally:
  651. if testport:
  652. switch.setpvid(testport, pvidmap[3])
  653. switch.deletevlan(testvlan)