-
Notifications
You must be signed in to change notification settings - Fork 59
/
IxNetL2L3NgpfLowLevel.py
executable file
·816 lines (661 loc) · 30.9 KB
/
IxNetL2L3NgpfLowLevel.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
import sys
import os
import re
import time
import IxNetwork
platform = 'windows'
ixNetTclServer = '192.168.70.3'
ixNetVersion = 9.0
licenseServerIp = '192.168.70.3'
licenseMode = 'subscription'
licenseTier = 'tier3'
ixChassisIp = '192.168.70.128'
portList = ['1/1', '2/1']
def ConnectToIxia( ixNetTclServer='', ixNetPort='8009', ixNetVersion='', username='admin', password='admin', platform='windows'):
if platform == 'windows':
ixNetConnect = ixNet.connect(ixNetTclServer, 'port', ixNetPort, '-version', ixNetVersion)
if platform == 'linux':
apiKey = ixNet.getApiKey(ixNetTclServer, '-username', username, '-password', password)
ixNetConnect = ixNet.connect(ixNetTclServer, 'port', ixNetPort, '-version', ixNetVersion, \
'-apiKey', apiKey, '-closeServerOnDisconnect', 1, '-setAttribute', 'strict')
print('Verifying ixNet.connect():', ixNetConnect) ;# ::ixNet::OK
if ixNetConnect != '::ixNet::OK':
print('Failed to connect to:', ixNetTclServer)
sys.exit()
else:
print('Successfully connected to:', ixNetTclServer)
def CreateNewBlankConfig():
print('\nCreating a blank configuration ...')
ixNet.execute('newConfig')
def AddIxiaChassis( ixChassisIp ):
print('\nAdding chassis: ', ixChassisIp)
ixChassisObj = ixNet.add(ixNet.getRoot()+'availableHardware', 'chassis', '-hostname', ixChassisIp)
ixNet.commit()
'''
ixChassisObj1: ::ixNet::OBJ-/availableHardware/chassis:L10988
ixChassisObj2: ::ixNet::OBJ-/availableHardware/chassis:"10.205.4.35"
'''
ixChassisObj = ixNet.remapIds(ixChassisObj)[0]
return ixChassisObj
def ClearPortOwnership( ixChassisObj, portList ):
for port in portList:
# port looks like '1 2'.
# port.split(' ') to convert string to list -> ['1', '2']
cardNumber = port.split('/')[0]
portNumber = port.split('/')[1]
# ::ixNet::OBJ-/availableHardware/chassis:"10.205.4.35"/card:1/port:2
#print ('Clearing port'), 'card:'+cardNumber+'/port:'+portNumber
print('Clearing port:', ixChassisObj+'/card:' + cardNumber + '/port:' + portNumber)
try:
ixNet.execute('clearOwnership', ixChassisObj+'/card:'+cardNumber+'/port:'+portNumber)
except Exception as e:
print('\nError: ClearPortOwnership: {}'.format(e))
def ConfigLicenseServer(licenseServerIp=None, licenseMode=None, licenseTier=None):
# licenseServerIp: The license server IP.
# licenseMode: subscription | perpetual| mixed
# licenseTier: tier1 | tier2 | tier3 ...
if licenseServerIp != "None":
print("\nConfiguring license server:", licenseServerIp)
ixNet.setAttribute(ixNet.getRoot()+'globals/licensing', '-licenseingServer', licenseServerIp)
if licenseMode != "None":
print("Configuring license mode:", licenseMode)
ixNet.setAttribute(ixNet.getRoot()+'globals/licensing', '-tier', licenseTier)
if licenseTier != "None":
print("Configuring license tier:", licenseTier)
ixNet.setAttribute(ixNet.getRoot()+'globals/licensing', '-mode', licenseMode)
ixNet.commit()
def CreateVPort( port ):
print('\nCreating VPort for %s' % port)
vPortObj = ixNet.add(ixNet.getRoot(), 'vport')
ixNet.commit()
vPortObj = ixNet.remapIds(vPortObj)[0]
return vPortObj
def ConnectToPorts(vPortList, portList, ixChassisObj):
print('\nConnectToPorts: vportList:', vPortList)
print('portList:', portList)
print('ixChassisObj:', ixChassisObj)
for vPort, port in zip(vPortList, portList):
cardNumber = port.split('/')[0]
portNumber = port.split('/')[1]
print('\nConnectToPort:', ixChassisObj + '/card:' + cardNumber + '/port:' + portNumber)
print('\tvPort =', vPort)
ixNet.setAttribute(vPort, \
'-connectedTo', ixChassisObj + '/card:' + cardNumber + '/port:' + portNumber
)
print('\nRebooting ports. Will take 40 seconds ...')
ixNet.commit()
def VerifyPortState( portList='', stopTime=120 ):
for vPort in ixNet.getList(ixNet.getRoot(), 'vport'):
assignedPort = ixNet.getAttribute(vPort, '-assignedTo')
print('\nVerifying port state on port::', assignedPort)
for timer in range(0, stopTime):
portState = ixNet.getAttribute(vPort, '-state')
print('\tCurrent port state:', portState)
if timer < stopTime and portState == 'up':
print('\tVerifyPortState: ', assignedPort + ' is up')
break
if timer < stopTime and portState != 'up':
print('\tVerifyPortState: %s is not up yet. Verifying %d/%d seconds' % (assignedPort, timer, stopTime))
time.sleep(1)
if timer == stopTime and portState != 'up':
print('\nPort can\'t come up. Exiting test')
return 1
def CreateTopologyPy(topologyName, vPorts):
print('\nCreateTopology: %s : %s' % (topologyName, vPorts))
topologyObj = ixNet.add(ixNet.getRoot(), 'topology')
ixNet.setMultiAttribute(topologyObj,
'-name', topologyName,
'-vports', vPorts
)
ixNet.commit()
return topologyObj
def CreateDeviceGroupPy(topologyObj, deviceGroupName, multiplier):
print('\nCreateDeviceGroup: %s : %s' % (topologyObj, deviceGroupName))
deviceGroupObj = ixNet.add(topologyObj, 'deviceGroup')
ixNet.setMultiAttribute(deviceGroupObj,
'-name', deviceGroupName,
'-multiplier', multiplier
)
ixNet.commit()
return deviceGroupObj
def CreateEthernetNgpfPy(deviceGroupObj, ethernetName):
print('\nCreateEthernetNgpfPy: %s : %s' % (deviceGroupObj, ethernetName))
ethernetObj = ixNet.add(deviceGroupObj, 'ethernet')
ixNet.setMultiAttribute(ethernetObj, '-name', 'ethernetName')
ixNet.commit()
return ethernetObj
def CreateIpv4NgpfPy(ethernetObj, ipv4Name):
print('\nCreateIpv4StackNgpf: %s : %s' % (ethernetObj, ipv4Name))
ipv4Obj = ixNet.add(ethernetObj, 'ipv4')
ixNet.setMultiAttribute(ipv4Obj, '-name', ipv4Name)
ixNet.commit()
return ipv4Obj
def ConfigIpv4AddressNgpfPy(ipv4Obj, startValue, step='0.0.0.1', direction='increment'):
print('\nConfigIpv4AddressNgpfPy: start=%s step=%s direction=%s' % (startValue, step, direction))
ipv4AddressObj = ixNet.getAttribute(ipv4Obj, '-address')
ixNet.setMultiAttribute(ipv4AddressObj,
'-clearOverlays', 'false',
'-pattern', 'counter'
)
ixNet.commit()
ipv4AddressObj2 = ixNet.add(ipv4AddressObj, 'counter')
ixNet.setMultiAttribute(ipv4AddressObj2,
'-start', startValue,
'-step', step,
'-direction', direction
)
ixNet.commit()
def ConfigIpv4GatewayNgpfPy(ipv4Obj, startValue, step='0.0.0.1', direction='increment'):
print('\nConfigIpv4GatewayNgpfPy:', ipv4Obj)
# ::ixNet::OBJ-/multivalue:112
ipv4GatewayObj = ixNet.getAttribute(ipv4Obj, '-gatewayIp')
ixNet.setMultiAttribute(ipv4GatewayObj,
'-clearOverlays', 'false',
'-pattern', 'counter'
)
ixNet.commit()
# ipv4GatewayObj2 = ::ixNet::OBJ-/multivalue:112/counter
ipv4GatewayObj2 = ixNet.add(ipv4GatewayObj, 'counter')
ixNet.setMultiAttribute(ipv4GatewayObj2,
'-start', startValue,
'-step', step,
'-direction', direction
)
ixNet.commit()
def StartAllProtocolsPy():
print('\nStartAllProtocolsPy')
ixNet.execute('startAllProtocols')
ixNet.commit()
time.sleep(2)
def DeviceGroupProtocolStackNgpfPy(deviceGroup, ipType):
# This Proc is an internal API for VerifyArpNgpf.
# It's created because each deviceGroup has IPv4/IPv6 and
# a deviceGroup could have inner deviceGroup that has IPv4/IPv6.
# Therefore, you can loop device groups.
import re
unresolvedArpList = []
for ethernet in ixNet.getList(deviceGroup, 'ethernet'):
for ipProtocol in ixNet.getList(ethernet, ipType):
resolvedGatewayMac = ixNet.getAttribute(ipProtocol, '-resolvedGatewayMac')
for index in range(0, len(resolvedGatewayMac)):
if (bool(re.match('.*Unresolved.*', resolvedGatewayMac[index]))):
multivalueNumber = ixNet.getAttribute(ipProtocol, '-address')
srcIpAddrNotResolved = ixNet.getAttribute(ixNet.getRoot()+multivalueNumber, '-values')[index]
print('\tFailed to resolveARP:', srcIpAddrNotResolved)
unresolvedArpList.append(srcIpAddrNotResolved)
if unresolvedArpList == []:
print('\tARP is resolved')
return 0
else:
return unresolvedArpList
def VerifyArpNgpfPy(ipType='ipv4'):
# This API requires:
# 1> DeviceGroupProtocolStacksNgpfPy
#
# ipType: ipv4 or ipv6
#
# This API will verify for ARP session resolvement on
# every TopologyGroup/DeviceGroup and/or
# TopologyGroup/DeviceGroup/DeviceGroup that has protocol "enabled".
#
# How it works?
# Each device group has a list of $sessionStatus: up, down or notStarted.
# If the deviceGroup has sessionStatus as "up", then ARP will be verified.
# It also has a list of $resolvedGatewayMac: MacAddress or removePacket[Unresolved]
# These two lists are aligned.
# If lindex 0 on $sessionSatus is up, then the API expects lindex 0 on $resolvedGatewayMac
# to have a mac address.
# If not, then arp is not resolved.
# This script will wait up to the $maxRetry before it declares failed.
#
# Return 0 if ARP passes.
# Return 1 if device group is not started
# Return a list of unresolved ARPs
print('\nVerifyArpNgpfPy')
startFlag = 0
unresolvedArpList = []
for topology in ixNet.getList(ixNet.getRoot(), 'topology'):
for deviceGroup in ixNet.getList(topology, 'deviceGroup'):
print('\n', deviceGroup)
deviceGroupStatus = ixNet.getAttribute(deviceGroup, '-status')
print('\tdeviceGroup status:', deviceGroupStatus)
if deviceGroupStatus == 'started':
startFlag = 1
arpResult = DeviceGroupProtocolStackNgpfPy(deviceGroup, ipType)
if arpResult != 0:
unresolvedArpList = unresolvedArpList + arpResult
if ixNet.getList(deviceGroup, 'deviceGroup') != '':
for innerDeviceGroup in ixNet.getList(deviceGroup, 'deviceGroup'):
print('\n', innerDeviceGroup)
arpResult = DeviceGroupProtocolStackNgpfPy(innerDeviceGroup, ipType)
if arpResult != 0:
unresolvedArpList = unresolvedArpList + arpResult
elif ixNet.getAttribute(deviceGroup, '-status') == 'mixed':
startFlag = 1
print('\tWarning: Ethernet stack is started, but layer3 is not started')
arpResult = DeviceGroupProtocolStackNgpf(deviceGroup, ipType)
if arpResult != 0:
unresolvedArpList = unresolvedArpList + arpResult
if ixNet.getList(deviceGroup, 'deviceGroup') != '':
for innerDeviceGroup in ixNet.getList(deviceGroup, 'deviceGroup'):
print('\n', innerDeviceGroup)
deviceGroupStatus2 = ixNet.getAttribute(innerDeviceGroup, '-status')
if deviceGroupStatus2 == 'started':
arpResult = DeviceGroupProtocolStackNgpfPy(deviceGroup, ipType)
if arpResult != 0:
unresolvedArpList = unresolvedArpList + arpResult
if unresolvedArpList == [] and startFlag == 1:
return 0
if unresolvedArpList == [] and startFlag == 0:
return 1
if unresolvedArpList != [] and startFlag == 1:
print('\n')
for unresolvedArp in unresolvedArpList:
print('UnresolvedArps:', unresolvedArp)
print('\n')
return unresolvedArpList
def CreateTrafficItem(name= 'My Traffic Item',
trafficType= 'ipv4',
transmitMode= 'interleaved',
biDirectional= '1',
routeMesh= 'oneToOne',
srcDestMesh= 'oneToOne'
):
print('\nCreating Traffic Item: %s ...' % name)
trafficItemObj = ixNet.add(ixNet.getRoot() + '/traffic', 'trafficItem')
ixNet.setMultiAttribute(trafficItemObj,
'-enabled', 'True',
'-name', name,
'-routeMesh', routeMesh,
'-srcDestMesh', srcDestMesh,
'-trafficType', trafficType,
'-transmitMode', transmitMode,
'-biDirectional', biDirectional,
)
ixNet.commit()
trafficItemObj = ixNet.remapIds(trafficItemObj)[0]
return trafficItemObj
def ConfigTracking( trafficItemObj, trackingList ):
print('\nConfiguring trackBy: %s ...' % trackingList)
ixNet.setAttribute(trafficItemObj + '/tracking',
'-trackBy', trackingList
)
ixNet.commit()
def CreateEndPointSet(trafficItemObj='',
name='Flow_Group',
srcEndpoints='',
destEndpoints=''
):
'''
Each endpoint is a highlevelstream in a Traffic Item
'''
print('\nCreating Endpoint: %s ...' % name)
endpointObj = ixNet.add(trafficItemObj, 'endpointSet',
'-name', name,
'-sources', srcEndpoints,
'-destinations', destEndpoints
)
ixNet.commit()
endpointObj = ixNet.remapIds(endpointObj)[0]
return endpointObj
def ConfigFlowGroup(flowGroupObj='', frameSize='128', frameRate='100'):
print('\nConfiguring Flow Group:', flowGroupObj)
print('\nConfiguring frame size:', frameSize)
ixNet.setAttribute(flowGroupObj + '/frameSize', '-fixedSize', frameSize)
print('\nConfiguring line rate: %s%s' % (frameRate, '%'))
ixNet.setAttribute(flowGroupObj + '/frameRate', '-rate', frameRate)
ixNet.commit()
def ConfigFlowGroupFrameCount(flowGroupObj, frameCount):
print('\nConfiguring frame count:', frameCount)
result = ixNet.setMultiAttribute(flowGroupObj + '/transmissionControl',
'-frameCount', frameCount,
'-type', 'fixedFrameCount'
)
ixNet.commit()
def ApplyTraffic():
print('\nApplying Traffic to hardware ...')
stopCounter = 10
for startCounter in range(1,10):
applyResult = ixNet.execute('apply', ixNet.getRoot() + 'traffic')
print('\nApplyTraffic: ', applyResult)
if applyResult != '::ixNet::OK' and startCounter < stopCounter:
print('\nApplyTraffic: Attempting to apply traffic:', startCounter+'/'+stopCounter+' tries')
time.sleep(1)
continue
if applyResult == '::ixNet::OK' and startCounter == stopCounter:
print('\nApplyTraffic Error:', applyResult)
ixNet.disconnect()
sys.exit()
if applyResult == '::ixNet::OK' and startCounter < stopCounter:
print('\nSuccessfully applied traffic to hardware')
break
def RegenerateAllTrafficItems():
for trafficItem in ixNet.getList(ixNet.getRoot()+'/traffic', 'trafficItem'):
regenerateResult = ixNet.execute('generate', trafficItem)
if regenerateResult != '::ixNet::OK':
print('\nRegenerateAllTrafficItem error:', trafficItem)
ixNet.disconnect()
sys.exit()
else:
print('\nRegenerateAllTrafficItem:', trafficItem)
def SendArp():
for vPort in ixNet.getList(ixNet.getRoot(), 'vport'):
for interface in ixNet.getList(vPort, 'interface'):
interfaceType = ixNet.getAttribute(interface, '-type')
# Don't send arps on Unconnected Routed or GRE interfaces
if re.search(r'default', interfaceType):
isIntEnabled = ixNet.getAttribute(interface, '-enabled')
if re.search(r'true', isIntEnabled, re.I):
print('Sent ARP on:', interface)
ixNet.execute('sendArp', interface)
ixNet.execute('sendNs', interface)
def VerifyArpDiscoveries():
'''
- Get a list of all the expected Gateway IP addresses for each vPort.
- Get only if the interface is enabled. We don't care about gateways if the
interface isn't enabled.
- Ignore Routed and GRE and Unconnected interfaces
- Then get a list of all the discovered arps.
- At the end, compare the two list. Any left overs are unresolved arps.
'''
resolvedArp = []
allIpGateways = []
for vPort in ixNet.getList(ixNet.getRoot(), 'vport'):
# Refresh the arp table on this vport first
ixNet.execute('refreshUnresolvedNeighbors', vPort)
currentVportInterfaceList = ixNet.getList(vPort, 'interface')
for interface in currentVportInterfaceList:
# Ignore the Unconnected Routed and GRE interfaces
interfaceType = ixNet.getAttribute(interface, '-type')
if re.search(r'default', interfaceType):
# Only append the gateway if the interface is enabled.
isIntEnabled = ixNet.getAttribute(interface, '-enabled')
if re.search(r'true', isIntEnabled, re.I):
ipv4Gateway = ixNet.getAttribute(interface+'/ipv4', '-gateway')
if re.search(r'null', ipv4Gateway, re.I) is None:
if ipv4Gateway not in allIpGateways:
allIpGateways.append(ipv4Gateway)
ipv6GatewayList = ixNet.getList(interface, 'ipv6')
if ipv6GatewayList:
for ipv6Gateway in ipv6GatewayList:
ipv6 = ixNet.getAttribute(ipv6Gateway, '-gateway')
if ipv6 != '0:0:0:0:0:0:0:0':
if ipv6 not in allIpGateways:
allIpGateways.append(ipv6)
print('\nExpected IP addresses to resolve ARPs:')
for arp in allIpGateways:
print('\t', arp)
for vPort in ixNet.getList(ixNet.getRoot(), 'vport'):
# Get all the discovered ARPs for the current vPort
vPortInterfaceList = ixNet.getList(vPort, 'discoveredNeighbor')
if vPortInterfaceList:
currentPort = ixTopo.getPort[vPort]
for vPortInt in vPortInterfaceList:
# vPortInt = ::ixNet::OBJ-/vport:1/discoveredNeighbor:1
currentVp = vPortInt.split('/')
currentVp = currentVp[:2]
currentVp = '/'.join(currentVp)
discoveredIp = ixNet.getAttribute(vPortInt, '-neighborIp')
discoveredMac = ixNet.getAttribute(vPortInt, '-neighborMac')
print('\nDiscovered arp on:', currentPort, ': ', discoveredIp, discoveredMac)
# discoveredMac is not empty or != 00:00:00:00:00:00
if discoveredMac is not '' and discoveredMac is not '00:00:00:00:00:00':
# if true, then append resolvedArp
if discoveredIp in allIpGateways:
resolvedArp.append(discoveredIp)
# Now compare the expected list of arps with what is resolved.
# Any left overs are unresovled arps.
for resolvedGateway in resolvedArp:
if resolvedGateway in allIpGateways:
ipGatewayIndex = allIpGateways.index(resolvedGateway)
allIpGateways.pop(ipGatewayIndex)
if allIpGateways:
print('\nError: Unresloved ARPs:')
for unresolvedArp in allIpGateways:
print('\t',(unresolvedArp))
ixNet.disconnect()
sys.exit()
else:
print('All ARPs are resolved')
def CheckTrafficState():
currentTrafficState = ixNet.getAttribute(ixNet.getRoot()+'traffic', '-state')
if currentTrafficState == '::ixNet::OK':
return 'notRunning'
elif currentTrafficState == 'stopped':
return 'stopped'
elif currentTrafficState == 'started':
return 'started'
elif currentTrafficState == 'locked':
return 'locked'
elif currentTrafficState == 'unapplied':
return 'unapplied'
elif currentTrafficState == 'startedWaitingForStreams':
return 'startedWaitingForStreams'
elif currentTrafficState == 'stoppedWaitingForStats':
return 'stoppedWaitingForStats'
else:
return currentTrafficState
def StartTraffic():
traffic = ixNet.getRoot()+'traffic'
print('\nStarting traffic ...')
for retry in range(1,10):
retry = retry + 1
try:
result = ixNet.execute('start', traffic)
if result != '::ixNet::OK':
print('\nFailed to start traffic:', result)
ixNet.disconnect()
sys.exit()
else:
print('\nExecuting startTraffic:', result)
break
except Exception as e:
print('\nException error: Failed to start traffic:', e)
print('\nRetrying:', retry, '/', 10)
time.sleep(1)
if retry == 10:
print('\nCan\'t start traffic. Exiting.')
ixNet.disconnect()
sys.exit()
time.sleep(2)
startCounter = 1
stopCounter = 11
for start in range(startCounter, stopCounter):
start = start + 1
trafficState = CheckTrafficState()
if trafficState == 'started':
print('Traffic started')
break
if trafficState == 'stopped':
print('Traffic stopped')
break
if trafficState == 'startedWaitingForStats' or trafficState == 'stoppedWaitingForStats':
print('Traffic started. Waiting for stats to complete')
break
if start < stopCounter:
if trafficState != 'started' or trafficState != 'startedWaitingForStats' or \
trafficState != 'stoppedWaitingForStats' or trafficStats != 'stopped':
print('\nStartTraffic: Current state = ', trafficState+'.'+' Waiting', start+'/'+stopCounter)
time.sleep(1)
if start == stopCounter:
if trafficState != 'started' or trafficState != 'startedWaitingForStats' or \
trafficState != 'stoppedWaitingForStats' or trafficStats != 'stopped':
print('\nFailed: Traffic failed to start')
ixNet.disconnect()
sys.exit()
def GetStatsPy( getStatsBy='Flow Statistics', csvFile=None, csvEnableFileTimestamp=False):
'''
Description:
This API will return you a Python Dict of all the stats
based on your specified stats. The exact stat name could
be found on your IxNetwork GUI statistic tablets.
Parameters:
getStatsBy = The exact name of the stat that could be found on the IxNetwork GUI.
csvFile = The name of the CSV file that you want to store stats in.
csvEnableFileTimestamp = Append a timestamp to the CSV file so they don't get overwritten.
This should only be used for getting the final stat result such as
when the traffic has completely stopped.
getStatsBy options (case sensitive):
"Port Statistics"
"Tx-Rx Frame Rate Statistics"
"Port CPU Statistics"
"Global Protocol Statistics"
"Protocols Summary"
"Port Summary"
"OSPFv2-RTR Drill Down"
"OSPFv2-RTR Per Port"
"IPv4 Drill Down"
"L2-L3 Test Summary Statistics"
"Flow Statistics"
"Traffic Item Statistics"
'''
viewList = ixNet.getList(ixNet.getRoot()+'/statistics', 'view')
statViewSelection = getStatsBy
try:
statsViewIndex = viewList.index('::ixNet::OBJ-/statistics/view:"' + getStatsBy +'"')
except Exception as errMsg:
sys.exit('\nNo such statistic name: %s' % getStatsBy)
# ::ixNet::OBJ-/statistics/view:"Flow Statistics"
view = viewList[statsViewIndex]
columnList = ixNet.getAttribute(view+'/page', '-columnCaptions')
#print '\n', columnList
if csvFile != None:
import csv
csvFileName = csvFile.replace(' ', '_')
if csvEnableFileTimestamp:
import datetime
timestamp = datetime.datetime.now().strftime('%H%M%S')
if '.' in csvFileName:
csvFileNameTemp = csvFileName.split('.')[0]
csvFileNameExtension = csvFileName.split('.')[1]
csvFileName = csvFileNameTemp+'_'+timestamp+'.'+csvFileNameExtension
else:
csvFileName = csvFileName+'_'+timestamp
csvFile = open(csvFileName, 'w')
csvWriteObj = csv.writer(csvFile)
csvWriteObj.writerow(columnList)
startTime = 1
stopTime = 30
for timer in range(startTime, stopTime + 1):
totalPages = ixNet.getAttribute(view+'/page', '-totalPages')
if totalPages == 'null':
print('GetStatView: Getting total pages for %s is not ready: %s/%s' % (getStatsBy, startTime, stopTime))
time.sleep(2)
else:
break
row = 0
statDict = {}
print('\nPlease wait for all the stats to be queried ...')
for currentPage in range(1, int(totalPages)+1):
ixNet.setAttribute(view+'/page', '-currentPage', currentPage)
ixNet.commit()
whileLoopStopCounter = 0
while (ixNet.getAttribute(view+'/page', '-isReady')) != 'true':
if whileLoopStopCounter == 5:
print ('\nGetStatView: Could not get stats')
return 1
if whileLoopStopCounter < 5:
print('\nGetStatView: Not ready yet. Waiting %s/5 seconds ...' % whileLoopStopCounter)
time.sleep(1)
whileLoopStopCounter += 1
pageList = ixNet.getAttribute(view+'/page', '-rowValues')
totalFlowStatistics = len(pageList)
for pageListIndex in range(0, totalFlowStatistics):
rowList = pageList[pageListIndex]
if csvFile != None:
csvWriteObj.writerow(rowList[0])
for rowIndex in range(0, len(rowList)):
row += 1
cellList = rowList[rowIndex]
statDict[row] = {}
# CellList: ['Ethernet - 002', 'Ethernet - 001', 'OSPF T1 to T2', '206.27.0.0-201.27.0.0', 'OSPF T1 to T2-FlowGroup-1 - Flow Group 0002', '1225', '1225', '0', '0', '0', '0', '0', '0', '156800', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '00:00:00.781', '00:00:00.849']
index = 0
for statValue in cellList:
statDict[row].update({columnList[index]: statValue})
index += 1
if csvFile != None:
csvFile.close()
return statDict
def DisconnectIxNet():
print('\nDisconnecting IxNetwork ...')
disconnect = ixNet.disconnect()
def PrintDict(obj, nested_level=0, output=sys.stdout):
"""
Print each dict key with indentions for readability.
"""
spacing = ' '
if type(obj) == dict:
print >> output, '%s' % ((nested_level) * spacing)
for k, v in obj.items():
if hasattr(v, '__iter__'):
print >> output, '%s%s:' % ((nested_level + 1) * spacing, k)
PrintDict(v, nested_level + 1, output)
else:
print >> output, '%s%s: %s' % ((nested_level + 1) * spacing, k, v)
print >> output, '%s' % (nested_level * spacing)
elif type(obj) == list:
print >> output, '%s[' % ((nested_level) * spacing)
for v in obj:
if hasattr(v, '__iter__'):
PrintDict(v, nested_level + 1, output)
else:
print >> output, '%s%s' % ((nested_level + 1) * spacing, v)
print >> output, '%s]' % ((nested_level) * spacing)
else:
print >> output, '%s%s' % (nested_level * spacing, obj)
ixNet = IxNetwork.IxNet()
class IxTopoNamespace: pass
ixTopo = IxTopoNamespace()
if platform == 'windows':
ConnectToIxia(ixNetTclServer=ixNetTclServer, ixNetPort='8009', ixNetVersion=ixNetVersion)
if platform == 'linux':
ConnectToIxia(ixNetTclServer=ixNetTclServer, ixNetPort=443, username='admin', password='admin', ixNetVersion=ixNetVersion, platform='linux')
CreateNewBlankConfig()
#ConfigLicenseServer(licenseServerIp=licenseServerIp, licenseMode=licenseMode, licenseTier=licenseTier)
ixChassisObj = AddIxiaChassis(ixChassisIp)
ClearPortOwnership(ixChassisObj, portList)
for port in portList:
CreateVPort(port)
#vport1Obj = CreateVPort('1/1')
#vport2Obj = CreateVPort('2/1')
#ixTopo.vPortList = [vport1Obj, vport2Obj]
ixTopo.vPortList = ixNet.getList(ixNet.getRoot(), 'vport')
ConnectToPorts(ixTopo.vPortList, portList, ixChassisObj)
if VerifyPortState():
sys.exit()
#topology1 = CreateTopologyPy('Topo1', vport1Obj)
#topology2 = CreateTopologyPy('Topo1', vport2Obj)
topology1 = CreateTopologyPy('Topo1', ixTopo.vPortList[0])
topology2 = CreateTopologyPy('Topo1', ixTopo.vPortList[1])
deviceGroup1 = CreateDeviceGroupPy(topology1, 'DG1', '1')
deviceGroup2 = CreateDeviceGroupPy(topology2, 'DG2', '1')
ethernet1 = CreateEthernetNgpfPy(deviceGroup1, 'Ethernet1')
ethernet2 = CreateEthernetNgpfPy(deviceGroup2, 'Ethernet2')
ipv41 = CreateIpv4NgpfPy(ethernet1, 'ipv41')
ConfigIpv4AddressNgpfPy(ipv41, '1.1.1.1')
ConfigIpv4GatewayNgpfPy(ipv41, '1.1.1.2')
ipv42 = CreateIpv4NgpfPy(ethernet2, 'ipv42')
ConfigIpv4AddressNgpfPy(ipv42, '1.1.1.2')
ConfigIpv4GatewayNgpfPy(ipv42, '1.1.1.1')
StartAllProtocolsPy()
VerifyArpNgpfPy()
#SendArp()
#VerifyArpDiscoveries()
trafficItem1Obj = CreateTrafficItem(name='ipv4')
# ::ixNet::OBJ-/traffic/trafficItem:1/endpointSet:1
endpoint1Obj = CreateEndPointSet(trafficItemObj=trafficItem1Obj,
name='FlowGroup1',
srcEndpoints=topology1,
destEndpoints=topology2
)
configElement1 = ixNet.getList(trafficItem1Obj, 'configElement')[0]
ConfigFlowGroup(flowGroupObj=configElement1, frameSize='256', frameRate='75')
ConfigTracking(trafficItem1Obj, ['flowGroup0', 'sourceDestEndpointPair0'])
RegenerateAllTrafficItems()
ApplyTraffic()
StartTraffic()
time.sleep(10)
stats = GetStatsPy()
#PrintDict(stats)
print('\n', stats)
DisconnectIxNet()