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.
 
 

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