-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMiniNAM.py
2357 lines (2025 loc) · 132 KB
/
MiniNAM.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
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation;
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
#
# Created by Ahmed Khalid [email protected] and Jason Quinlan [email protected]
# 03 November 2017 - version number 1.0.1
import socket
from struct import *
from subprocess import *
import threading
from mininet.clean import cleanup
from mininet.cli import CLI
from mininet.log import lg, LEVELS, info, debug, warn, error
from mininet.net import MininetWithControlNet
from mininet.node import ( Host, Node, CPULimitedHost, Controller, OVSController,
Ryu, NOX, RemoteController, findController,
DefaultController, NullController,
UserSwitch, OVSSwitch, OVSBridge,
IVSSwitch )
from mininet.nodelib import LinuxBridge
from mininet.link import Link, TCLink, OVSLink, TCULink
from mininet.topo import ( SingleSwitchTopo, LinearTopo,
SingleSwitchReversedTopo, MinimalTopo )
from mininet.topolib import TreeTopo, TorusTopo
from mininet.util import customClass, specialClass, splitArgs
from mininet.util import buildTopo
from functools import partial
from mininet.examples.cluster import ( MininetCluster, RemoteHost,
RemoteOVSSwitch, RemoteLink,
SwitchBinPlacer, RandomPlacer,
ClusterCleanup )
from mininet.examples.clustercli import ClusterCLI
from optparse import OptionParser
import os
from tkMessageBox import showerror
import tkFont
import tkFileDialog
import tkSimpleDialog
import json
from distutils.version import StrictVersion
from mininet.term import makeTerm, cleanUpScreens
from mininet.net import Mininet, VERSION
from mininet.util import quietRun
import random
from threading import Thread
from Tkinter import *
import time
from cmath import pi
from math import atan2, sin, cos
from PIL import Image, ImageDraw
from PIL import ImageTk as itk
import Queue
from collections import OrderedDict
MININET_VERSION = re.sub(r'[^\d\.]', '', VERSION)
if StrictVersion(MININET_VERSION) > StrictVersion('2.0'):
from mininet.node import IVSSwitch
MININAM_VERSION = "1.0.1"
# Fix setuptools' evil madness, and open up (more?) security holes
if 'PYTHONPATH' in os.environ:
sys.path = os.environ[ 'PYTHONPATH' ].split( ':' ) + sys.path
Eth_Protocols = {'8':'IP', '1544':'ARP', '56710':'IPv6'}
IP_Protocols = {'1':'ICMP', '6':'TCP', '17':'UDP'}
TOPODEF = 'minimal'
TOPOS = {'minimal': MinimalTopo,
'linear': LinearTopo,
'reversed': SingleSwitchReversedTopo,
'single': SingleSwitchTopo,
'tree': TreeTopo,
'torus': TorusTopo}
SWITCHDEF = 'default'
SWITCHES = {'user': UserSwitch,
'ovs': OVSSwitch,
'ovsbr': OVSBridge,
# Keep ovsk for compatibility with 2.0
'ovsk': OVSSwitch,
'ivs': IVSSwitch,
'lxbr': LinuxBridge,
'default': OVSSwitch}
SWITCHES_TYPES = [switch.__name__ for switch in SWITCHES.values()]
HOSTDEF = 'proc'
HOSTS = {'proc': Host,
'rt': specialClass(CPULimitedHost, defaults=dict(sched='rt')),
'cfs': specialClass(CPULimitedHost, defaults=dict(sched='cfs'))}
HOSTS_TYPES = ['Host', 'CPULimitedHost']
CONTROLLERDEF = 'default'
CONTROLLERS = {'ref': Controller,
'ovsc': OVSController,
'nox': NOX,
'remote': RemoteController,
'ryu': Ryu,
'default': DefaultController, # Note: replaced below
'none': NullController}
CONTROLLERS_TYPES = [ctrlr.__name__ for ctrlr in CONTROLLERS.values()]
LINKDEF = 'default'
LINKS = {'default': Link,
'tc': TCLink,
'tcu': TCULink,
'ovs': OVSLink}
LINKS_TYPES = ['Link', 'TCLink', 'OVSLink', 'TCULink']
LEGACY_TYPES = ['LegacyRouter', 'LinuxRouter', 'LegacySwitch']
FLOWTIMEDEF = 'Fast'
FLOWTIME = OrderedDict([('Very Slow', 40000),('Slow',20000),('Fast', 5000), ('Very Fast', 1000), ('Real Time', 1)])
LinkTime = 0.1
def version( *_args ):
"print(Mininet and MiniNAM version and exit"
print("Mininet: %s" % MININET_VERSION)
print("MiniNAM: %s" % MININAM_VERSION)
sys.exit()
def packetParser(packet):
PacketInfo = {}
PacketInfo['eth_protocol'] = None
PacketInfo['srcMAC'] = None
PacketInfo['dstMAC'] = None
PacketInfo['s_addr'] = None
PacketInfo['d_addr'] = None
PacketInfo['ip_protocol'] = None
PacketInfo['ttl'] = None
PacketInfo['source_port'] = None
PacketInfo['dest_port'] = None
PacketInfo['sequence'] = None
PacketInfo['data'] = None
PacketInfo['icmp_type'] = None
PacketInfo['code'] = None
PacketInfo['checksum'] = None
PacketInfo['length'] = None
PacketInfo['protocol_type'] = None
try:
# parse ethernet header
eth_length = 14
eth_header = packet[:eth_length]
eth = unpack('!6s6sH', eth_header)
eth_protocol = socket.ntohs(eth[2])
dstMAC = ':'.join('%02x' % ord(b) for b in packet[0:6])
srcMAC = ':'.join('%02x' % ord(b) for b in packet[6:12])
PacketInfo['srcMAC'] = str(srcMAC)
PacketInfo['dstMAC'] = str(dstMAC)
PacketInfo['eth_protocol'] = str(eth_protocol)
# Parse IP packets, IP Protocol number = 8
if eth_protocol == 8:
# Parse IP header
# take first 20 characters for the ip header
ip_header = packet[eth_length:20 + eth_length]
# now unpack them
iph = unpack('!BBHHHBBH4s4s', ip_header)
version_ihl = iph[0]
ihl = version_ihl & 0xF
iph_length = ihl * 4
ttl = iph[5]
protocol = iph[6]
s_addr = socket.inet_ntoa(iph[8]);
d_addr = socket.inet_ntoa(iph[9]);
PacketInfo['s_addr'] = s_addr
PacketInfo['d_addr'] = d_addr
PacketInfo['ip_protocol'] = str(protocol)
PacketInfo['ttl'] = str(ttl)
# TCP protocol
if protocol == 6:
t = iph_length + eth_length
tcp_header = packet[t:t + 32]
# now unpack them
tcph = unpack('!HHLLBBHHHBBBBLL', tcp_header)
source_port = tcph[0]
dest_port = tcph[1]
sequence = tcph[2]
acknowledgement = tcph[3]
doff_reserved = tcph[4]
tcph_length = doff_reserved >> 4
TSVal = tcph[13]
h_size = eth_length + iph_length + tcph_length * 4
# get data from the packet
data = packet[h_size:]
PacketInfo['source_port'] = source_port
PacketInfo['dest_port'] = dest_port
PacketInfo['sequence'] = sequence
PacketInfo['acknowledgement'] = acknowledgement
PacketInfo['TSVal'] = TSVal
PacketInfo['data'] = data
# ICMP Packets
elif protocol == 1:
u = iph_length + eth_length
icmph_length = 4
icmp_header = packet[u:u + 4]
# now unpack them
icmph = unpack('!BBH', icmp_header)
icmp_type = icmph[0]
code = icmph[1]
checksum = icmph[2]
h_size = eth_length + iph_length + icmph_length
data_size = len(packet) - h_size
# get data from the packet
data = packet[h_size:]
PacketInfo['icmp_type'] = str(icmp_type)
PacketInfo['code'] = str(code)
PacketInfo['checksum'] = str(checksum)
PacketInfo['data'] = data
# UDP packets
elif protocol == 17:
u = iph_length + eth_length
udph_length = 8
udp_header = packet[u:u + 8]
# now unpack them
udph = unpack('!HHHH', udp_header)
source_port = udph[0]
dest_port = udph[1]
length = udph[2]
checksum = udph[3]
h_size = eth_length + iph_length + udph_length
data_size = len(packet) - h_size
# get data from the packet
data = packet[h_size:]
PacketInfo['source_port'] = source_port
PacketInfo['dest_port'] = dest_port
PacketInfo['length'] = length
PacketInfo['checksum'] = checksum
PacketInfo['data'] = data
# Other IP packet like IGMP can be parsed here.
else:
pass
#Parse ARP packets
elif eth_protocol == 1544:
arp_header = packet[14:42]
arph = unpack("!2sH1s1s2s6s4s6s4s", arp_header)
s_addr = socket.inet_ntoa(arph[6])
d_addr = socket.inet_ntoa(arph[8])
protocol_type = arph[1]
PacketInfo['s_addr'] = str(s_addr)
PacketInfo['d_addr'] = str(d_addr)
PacketInfo['protocol_type'] = protocol_type
#Other EthPackets like IPv6 can be parsed here.
else:
pass
return PacketInfo
except:
return PacketInfo
class PrefsDialog(tkSimpleDialog.Dialog):
"Preferences dialog"
def __init__(self, parent, title, prefDefaults):
self.prefValues = prefDefaults
tkSimpleDialog.Dialog.__init__(self, parent, title)
def body(self, master):
"Create dialog body"
self.rootFrame = master
# Field for displaying traffic flows
Label(self.rootFrame, text="Display traffic flows in the network").grid(row=0, sticky=W)
self.displayFlows = IntVar()
self.cdisplayFlows = Checkbutton(self.rootFrame, variable=self.displayFlows)
self.cdisplayFlows.grid(row=0, column=1, sticky=W)
if self.prefValues['displayFlows'] == 0:
self.cdisplayFlows.deselect()
else:
self.cdisplayFlows.select()
# Field for displaying hosts along with network topology
Label(self.rootFrame, text="Display hosts in the network:").grid(row=1, sticky=W)
self.displayHosts = IntVar()
self.cdisplayHosts = Checkbutton(self.rootFrame, variable=self.displayHosts)
self.cdisplayHosts.grid(row=1, column=1, sticky=W)
if self.prefValues['displayHosts'] == 0:
self.cdisplayHosts.deselect()
else:
self.cdisplayHosts.select()
# Field for Packet Flow Speed
Label(self.rootFrame, text="Speed of Packet Flow").grid(row=2, sticky=W)
self.flowTime = StringVar(self.rootFrame)
self.flowTime.set(FLOWTIME.keys()[FLOWTIME.values().index(self.prefValues['flowTime'])])
self.flowTimeMenu = OptionMenu(self.rootFrame, self.flowTime, *FLOWTIME.keys())
self.flowTimeMenu.grid(row=2, column=1, sticky=W)
# Field for Node Colors
Label(self.rootFrame, text="Color Code Packets By:").grid(row=3, sticky=W)
self.nodeColorsVar = StringVar(self.rootFrame)
self.nodeColorsOption = OptionMenu(self.rootFrame, self.nodeColorsVar, "Source", "Destination", "None")
self.nodeColorsOption.grid(row=3, column=1, sticky=W)
self.nodeColorsVar.set(self.prefValues['nodeColors'])
# Selection for color of packet type
self.typeColorsFrame= LabelFrame(self.rootFrame, text='Colors for Packet Types', padx=5, pady=5)
self.typeColorsFrame.grid(row=4, column=0, columnspan=2, sticky=EW)
for i in range(3):
self.typeColorsFrame.columnconfigure(i, weight=1)
self.typeColors = self.prefValues['typeColors']
# Selection of color for ARP
Label(self.typeColorsFrame, text="ARP").grid(row=0, column=0, sticky=W)
self.ARPColor = StringVar(self.typeColorsFrame)
self.ARPColor.set(self.typeColors["ARP"])
self.ARPColorMenu = OptionMenu(self.typeColorsFrame, self.ARPColor, "None", "Red", "Green", "Blue", "Purple")
self.ARPColorMenu.grid(row=1, column=0, sticky=W)
# Selection of color for TCP
Label(self.typeColorsFrame, text="TCP").grid(row=0, column=1, sticky=W)
self.TCPColor = StringVar(self.typeColorsFrame)
self.TCPColor.set(self.typeColors["TCP"])
self.TCPColorMenu = OptionMenu(self.typeColorsFrame, self.TCPColor, "None", "Red", "Green", "Blue", "Purple")
self.TCPColorMenu.grid(row=1, column=1, sticky=W)
# Selection of color for ICMP
Label(self.typeColorsFrame, text="ICMP").grid(row=0, column=2, sticky=W)
self.ICMPColor = StringVar(self.typeColorsFrame)
self.ICMPColor.set(self.typeColors["ICMP"])
self.ICMPColorMenu = OptionMenu(self.typeColorsFrame, self.ICMPColor, "None", "Red", "Green", "Blue", "Purple")
self.ICMPColorMenu.grid(row=1, column=2, sticky=W)
# Selection of color for UDP
Label(self.typeColorsFrame, text="UDP").grid(row=0, column=3, sticky=W)
self.UDPColor = StringVar(self.typeColorsFrame)
self.UDPColor.set(self.typeColors["UDP"])
self.UDPColorMenu = OptionMenu(self.typeColorsFrame, self.UDPColor, "None", "Red", "Green", "Blue", "Purple")
self.UDPColorMenu.grid(row=1, column=3, sticky=W)
# Selection of terminal type
Label(self.rootFrame, text="Default Terminal:").grid(row=5, sticky=W)
self.terminalVar = StringVar(self.rootFrame)
self.terminalOption = OptionMenu(self.rootFrame, self.terminalVar, "xterm", "gterm")
self.terminalOption.grid(row=5, column=1, sticky=W)
terminalType = self.prefValues['terminalType']
self.terminalVar.set(terminalType)
# Field for CLI
Label(self.rootFrame, text="Start CLI:").grid(row=6, sticky=W)
self.cliStart = IntVar()
self.cliButton = Checkbutton(self.rootFrame, variable=self.cliStart)
self.cliButton.grid(row=6, column=1, sticky=W)
if self.prefValues['startCLI'] == 0:
self.cliButton.deselect()
else:
self.cliButton.select()
# Field for showing IP Packets
Label(self.rootFrame, text="Show IP address on packets:").grid(row=7, sticky=W)
self.showAddrVar = StringVar(self.rootFrame)
self.showaddrOption = OptionMenu(self.rootFrame, self.showAddrVar, "Source", "Destination", "None")
self.showaddrOption.grid(row=7, column=1, sticky=W)
self.showAddrVar.set(self.prefValues['showAddr'])
# Field for showing nodeStats
Label(self.rootFrame, text="Show Node Statistics Box:").grid(row=8, sticky=W)
self.showNodeStats = IntVar()
self.cshowNodeStats = Checkbutton(self.rootFrame, variable=self.showNodeStats)
self.cshowNodeStats.grid(row=8, column=1, sticky=W)
if self.prefValues['showNodeStats'] == 0:
self.cshowNodeStats.deselect()
else:
self.cshowNodeStats.select()
# Field for identifying packets belonging to same flow
Label(self.rootFrame, text="Identify packets in the same flow and display in order:").grid(row=9, sticky=W)
self.identifyFlows = IntVar()
self.cidentifyFlows = Checkbutton(self.rootFrame, variable=self.identifyFlows)
self.cidentifyFlows.grid(row=9, column=1, sticky=W)
if self.prefValues['identifyFlows'] == 0:
self.cidentifyFlows.deselect()
else:
self.cidentifyFlows.select()
def apply(self):
flowTime = FLOWTIME[self.flowTime.get()]
self.typeColors['ARP'] = str(self.ARPColor.get())
self.typeColors['TCP'] = str(self.TCPColor.get())
self.typeColors['ICMP'] = str(self.ICMPColor.get())
self.typeColors['UDP'] = str(self.UDPColor.get())
typeColors = self.typeColors
self.result = {'displayFlows': self.displayFlows.get(),
'displayHosts': self.displayHosts.get(),
'flowTime': flowTime,
'nodeColors': self.nodeColorsVar.get(),
'typeColors': typeColors,
'terminalType': self.terminalVar.get(),
'startCLI': self.cliStart.get(),
'showAddr': self.showAddrVar.get(),
'showNodeStats': self.showNodeStats.get(),
'identifyFlows': self.identifyFlows.get()
}
class FiltersDialog(tkSimpleDialog.Dialog):
"Filters dialog"
def __init__(self, parent, title, filterDefaults):
self.filterValues = filterDefaults
tkSimpleDialog.Dialog.__init__(self, parent, title)
def body(self, master):
"Create dialog body"
self.rootFrame = master
# Field for Show Packet Types
Label(self.rootFrame, text="Show Packet Types:").grid(row=0, sticky=E)
self.showPackets = Text(self.rootFrame, height = 1)
self.showPackets.grid(row=0, column=1)
showPackets = self.filterValues['showPackets']
for item in showPackets:
self.showPackets.insert(END, item + ', ')
# Field for Hide Packet Types
Label(self.rootFrame, text="Hide Packet Types:").grid(row=2, sticky=E)
self.hidePackets = Text(self.rootFrame, height = 1)
self.hidePackets.grid(row=2, column=1)
hidePackets = self.filterValues['hidePackets']
for item in hidePackets:
self.hidePackets.insert(END, item + ', ')
# Field for Hide Packets From IP or MAC
Label(self.rootFrame, text="Hide Packets from IP or MAC:").grid(row=3, sticky=E)
self.hideFromIPMAC = Text(self.rootFrame, height = 1)
self.hideFromIPMAC.grid(row=3, column=1)
hideFromIPMAC = self.filterValues['hideFromIPMAC']
for item in hideFromIPMAC:
self.hideFromIPMAC.insert(END, item + ', ')
# Field for Hide Packet To IP or MAC
Label(self.rootFrame, text="Hide Packets To IP or MAC:").grid(row=4, sticky=E)
self.hideToIPMAC = Text(self.rootFrame, height = 1)
self.hideToIPMAC.grid(row=4, column=1)
hideToIPMAC = self.filterValues['hideToIPMAC']
for item in hideToIPMAC:
self.hideToIPMAC.insert(END, item + ', ')
# initial focus
return self.showPackets
def apply(self):
showPackets = str(self.showPackets.get("1.0",'end-1c')).replace(' ', '').replace('\n', '').replace('\r', '').split(',')
hidePackets = str(self.hidePackets.get("1.0",'end-1c')).replace(' ', '').replace('\n', '').replace('\r', '').split(',')
hideFromIPMAC = str(self.hideFromIPMAC.get("1.0",'end-1c')).replace(' ', '').replace('\n', '').replace('\r', '').split(',')
hideToIPMAC = str(self.hideToIPMAC.get("1.0",'end-1c')).replace(' ', '').replace('\n', '').replace('\r', '').split(',')
# Removing empty items from lists
showPackets = filter(None, showPackets)
hidePackets = filter(None, hidePackets)
hideFromIPMAC = filter(None, hideFromIPMAC)
hideToIPMAC = filter(None, hideToIPMAC)
self.result= {
'showPackets': showPackets,
'hidePackets': hidePackets,
'hideFromIPMAC': hideFromIPMAC,
'hideToIPMAC': hideToIPMAC
}
@staticmethod
def getOvsVersion():
"Return OVS version"
outp = quietRun("ovs-vsctl show")
r = r'ovs_version: "(.*)"'
m = re.search(r, outp)
if m is None:
print('Version check failed')
return None
else:
print('Open vSwitch version is '+m.group(1))
return m.group(1)
class NodeStats(object):
def __init__(self, widget):
self.widget = widget
self.tipwindow = None
self.id = None
self.x = self.y = 0
def showtip(self, text):
"Display text in nodeStats window"
self.text = text
if self.tipwindow or not self.text:
return
x, y, _cx, cy = self.widget.bbox("insert")
x = x + self.widget.winfo_rootx() + 27
y = y + cy + self.widget.winfo_rooty() +27
self.tipwindow = tw = Toplevel(self.widget)
tw.wm_overrideredirect(1)
tw.wm_geometry("+%d+%d" % (x, y))
try:
tw.tk.call("::tk::unsupported::MacWindowStyle",
"style", tw._w,
"help", "noActivates")
except TclError:
pass
label = Label(tw, text=self.text, justify=LEFT,
background="#ffffe0", relief=SOLID, borderwidth=1,
font=("tahoma", "8", "normal"))
label.pack(ipadx=1)
def hidetip(self):
tw = self.tipwindow
self.tipwindow = None
if tw:
tw.destroy()
class MiniNAM( Frame ):
"A realtime network animator for Mininet."
def __init__( self, parent=None, cheight=600, cwidth=1000 , net= None, locations={}):
Frame.__init__( self, parent )
self.action = None
#Defaults for preferences and filters
self.appPrefs={
'displayFlows': 1,
'displayHosts': 1,
'flowTime': FLOWTIME[FLOWTIMEDEF],
'nodeColors': 'Source',
'typeColors': {'ARP': 'Red', 'TCP': 'Green', 'ICMP': 'Blue', 'UDP': 'Green'},
'startCLI': 1,
'terminalType': 'xterm',
'showAddr': 'None',
'showNodeStats': 0,
'identifyFlows': 1
}
self.appFilters={
'showPackets': ['TCP', 'UDP', 'ICMP'], #ARP?
'hidePackets': ['IPv6'],
'hideFromIPMAC': ['0.0.0.0', '255.255.255.255'],
'hideToIPMAC': ['0.0.0.0', '255.255.255.255']
}
# Style
self.fixedFont = tkFont.Font ( family="DejaVu Sans Mono", size="14" )
self.font = ( 'Geneva', 9 )
self.smallFont = ( 'Geneva', 7 )
self.bg = 'white'
#If more hosts than this list then random colors are assigned to remaining hosts
self.HOST_COLORS = ['#E57300', '#FF66B2', '#fa0004', '#b1b106', '#957aff', '#FF00FF', '#2f90d0', '#818c8d',
'#A93226', '#1b2ef8', '#3ef979', '#7c2ff9']
self.Controller_Color = '#9D9D9D'
self.images = miniImages()
# Title
self.appName = 'MiniNAM'
self.top = self.winfo_toplevel()
self.top.title( self.appName )
# Menu bar
self.createMenubar()
# Editing canvas
self.cheight, self.cwidth = cheight, cwidth
self.cframe, self.canvas = self.createCanvas()
# Layout
self.cframe.grid( column=1, row=0 )
self.columnconfigure( 1, weight=1 )
self.rowconfigure( 0, weight=1 )
self.pack( expand=True, fill='both' )
# Info boxes
self.aboutBox = None
self.infoBox = None
# Initialize node data
self.nodeBindings = self.createNodeBindings()
self.nodePrefixes = { 'LegacyRouter': 'r', 'LegacySwitch': 's', 'Switch': 's', 'Host': 'h' , 'Controller': 'c'}
self.widgetToItem = {}
self.itemToWidget = {}
self.Nodes = []
# intfdata is [{"node":"-1", 'color': None, "type":"-1", "interface": "-1", "mac":"-1", "ip": "-1", "dgw":"-1", "link": "-1", "TXP":0, "RXP":0, "TXB":0, "RXB":0}]
self.intfData = []
# Initialize link tool
self.link = self.linkWidget = None
# Selection support
self.selection = None
# Keyboard and Popup bindings
self.bind( '<Control-q>', lambda event: self.quit() )
self.focus()
self.canvas.bind('<Button-1>', self.setFocus)
self.hostPopup = Menu(self.top, tearoff=0, takefocus=1)
self.hostPopup.add_command(label='Host Options', font=self.font)
self.hostPopup.add_separator()
self.hostPopup.add_command(label='Terminal', font=self.font, command=self.xterm )
self.hostPopup.bind("<FocusOut>", self.popupFocusOut)
self.legacyRouterPopup = Menu(self.top, tearoff=0, takefocus=1)
self.legacyRouterPopup.add_command(label='Router Options', font=self.font)
self.legacyRouterPopup.add_separator()
self.legacyRouterPopup.add_command(label='Terminal', font=self.font, command=self.xterm )
self.legacyRouterPopup.bind("<FocusOut>", self.popupFocusOut)
self.switchPopup = Menu(self.top, tearoff=0, takefocus=1)
self.switchPopup.add_command(label='Switch Options', font=self.font)
self.switchPopup.add_separator()
self.switchPopup.add_command(label='List bridge details', font=self.font, command=self.listBridge )
self.switchPopup.bind("<FocusOut>", self.popupFocusOut)
self.linkPopup = Menu(self.top, tearoff=0, takefocus=1)
self.linkPopup.add_command(label='Link Options', font=self.font)
self.linkPopup.add_separator()
self.linkPopup.add_command(label='Link Up', font=self.font, command=self.linkUp )
self.linkPopup.add_command(label='Link Down', font=self.font, command=self.linkDown )
self.linkPopup.bind("<FocusOut>", self.popupFocusOut)
# Event handling initalization
self.linkx = self.linky = self.linkItem = None
self.lastSelection = None
# Model initialization
self.packetImage = []
self.flowQueues = {}
self.PLACEMENT = {'block': SwitchBinPlacer, 'random': RandomPlacer}
self.links = {}
self.cli = None
#Setting up values when MiniNAM class is called from a script
self.nodelocations = locations
self.options = None
self.args = None
self.validate = None
self.net = net
self.active = True
#Setup network if MiniNAM is called from CLI
if self.net is None:
self.parseArgs()
self.setup()
self.begin()
if self.options.test == 'cli':
self.startCLI()
#Exit if network wasn't created properly
if self.net is None:
error('Network does not exist. Do not use net(stop) in your script if you want GUI to load.')
sys.exit()
#Start siniffing packets on Mininet interfaces
self.sniff = Thread( target=self.sniff )
self.sniff.daemon = True
self.sniff.start()
#Start CLI thread if requested
if self.appPrefs['startCLI'] == 1:
self.startCLI()
#Gather topology info and create nodes
self.TopoInfo()
self.createNodes()
# Place window at bottom
self.top.geometry("%dx%d%+d%+d" % (self.cwidth, self.cheight, 1, 1000))
# Close window gracefully
Wm.wm_protocol( self.top, name='WM_DELETE_WINDOW', func=self.quit )
#Set the logo for MiniNAM
logo = self.images['Logo']
self.top.tk.call('wm', 'iconphoto', self.top._w, logo)
# Arguments and Network
def custom( self, _option, _opt_str, value, _parser ):
"Parse custom file and add params."
files = []
if os.path.isfile( value ):
# Accept any single file (including those with commas)
files.append( value )
else:
# Accept a comma-separated list of filenames
files += value.split(',')
for fileName in files:
customs = {}
if os.path.isfile( fileName ):
execfile( fileName, customs, customs )
for name, val in customs.iteritems():
self.setCustom( name, val )
else:
raise Exception( 'could not find custom file: %s' % fileName )
def setCustom( self, name, value ):
"Set custom parameters for Mininet."
if name.upper() == 'NET':
info('*** Loading network from custom file ***\n')
self.net = value
elif name in ( 'topos', 'switches', 'hosts', 'controllers' ):
# Update dictionaries
param = name.upper()
try:
globals()[ param ].update( value )
globals()[str(param + '_TYPES')].append( value.keys()[0])
except:
pass
elif name == 'validate':
# Add custom validate function
self.validate = value
elif name == 'locations':
self.nodelocations = value
else:
# Add or modify global variable or class
globals()[ name ] = value
def configs( self, _option, _opt_str, value, _parser ):
"Load custom configs."
fileName = value
if not os.path.isfile(fileName):
print('Could not find config file: %s. Loading default preferences and filters.' % fileName)
return
f = open(fileName, 'r')
loadedPrefs = self.convertJsonUnicode(json.load(f))
# Load application preferences
if 'preferences' in loadedPrefs:
self.appPrefs = dict(self.appPrefs.items() + loadedPrefs['preferences'].items())
# Load application filters
if 'filters' in loadedPrefs:
self.appFilters = dict(self.appFilters.items() + loadedPrefs['filters'].items())
f.close()
def setNat( self, _option, opt_str, value, parser ):
"Set NAT option(s)"
assert self # satisfy pylint
parser.values.nat = True
# first arg, first char != '-'
if parser.rargs and parser.rargs[ 0 ][ 0 ] != '-':
value = parser.rargs.pop( 0 )
_, args, kwargs = splitArgs( opt_str + ',' + value )
parser.values.nat_args = args
parser.values.nat_kwargs = kwargs
else:
parser.values.nat_args = []
parser.values.nat_kwargs = {}
def addDictOption(self, opts, choicesDict, default, name, **kwargs):
"""Convenience function to add choices dicts to OptionParser.
opts: OptionParser instance
choicesDict: dictionary of valid choices, must include default
default: default choice key
name: long option name
kwargs: additional arguments to add_option"""
helpStr = ('|'.join(sorted(choicesDict.keys())) +
'[,param=value...]')
helpList = ['%s=%s' % (k, v.__name__)
for k, v in choicesDict.items()]
helpStr += ' ' + (' '.join(helpList))
params = dict(type='string', default=default, help=helpStr)
params.update(**kwargs)
opts.add_option('--' + name, **params)
def parseArgs( self ):
"""Parse command-line args and return options object.
returns: opts parse options dict"""
desc = ( "The %prog utility creates Mininet network from the\n"
"command line, loads a GUI with the created topology and\n"
"displays any network traffic generated." )
usage = ( '%prog [options]\n'
'(type %prog -h for details)' )
opts = OptionParser( description=desc, usage=usage )
opts.add_option('--config', action='callback',
callback=self.configs,
type='string',
help='load custom preferences from .config file'
)
opts.add_option('--custom', action='callback',
callback=self.custom,
type='string',
help='read custom classes, params or network (with net as name) from .py file(s)'
)
self.addDictOption( opts, SWITCHES, SWITCHDEF, 'switch' )
self.addDictOption( opts, HOSTS, HOSTDEF, 'host' )
self.addDictOption( opts, CONTROLLERS, [], 'controller', action='append' )
self.addDictOption( opts, LINKS, LINKDEF, 'link' )
self.addDictOption( opts, TOPOS, TOPODEF, 'topo' )
opts.add_option( '--clean', '-c', action='store_true',
default=False, help='clean and exit' )
# optional tests to run
TESTS = ['cli', 'build', 'pingall', 'pingpair', 'iperf', 'all', 'iperfudp', 'none']
opts.add_option( '--test', type='choice', choices=TESTS,
default=TESTS[ -1 ],
help='|'.join( TESTS ) )
opts.add_option( '--xterms', '-x', action='store_true',
default=False, help='spawn xterms for each node' )
opts.add_option( '--ipbase', '-i', type='string', default='10.0.0.0/8',
help='base IP address for hosts' )
opts.add_option( '--mac', action='store_true',
default=False, help='automatically set host MACs' )
opts.add_option( '--arp', action='store_true',
default=False, help='set all-pairs ARP entries' )
opts.add_option( '--verbosity', '-v', type='choice',
choices=LEVELS.keys(), default = 'info',
help = '|'.join( LEVELS.keys() ) )
opts.add_option( '--innamespace', action='store_true',
default=False, help='sw and ctrl in namespace?' )
opts.add_option( '--listenport', type='int', default=6634,
help='base port for passive switch listening' )
opts.add_option( '--nolistenport', action='store_true',
default=False, help="don't use passive listening " +
"port")
opts.add_option( '--pre', type='string', default=None,
help='CLI script to run before tests' )
opts.add_option( '--post', type='string', default=None,
help='CLI script to run after tests' )
opts.add_option( '--pin', action='store_true',
default=False, help="pin hosts to CPU cores "
"(requires --host cfs or --host rt)" )
opts.add_option( '--nat', action='callback', callback=self.setNat,
help="adds a NAT to the topology that"
" connects Mininet hosts to the physical network."
" Warning: This may route any traffic on the machine"
" that uses Mininet's"
" IP subnet into the Mininet network."
" If you need to change"
" Mininet's IP subnet, see the --ipbase option." )
opts.add_option( '--version', action='callback', callback=version,
help='prints the version and exits' )
opts.add_option( '--cluster', type='string', default=None,
metavar='server1,server2...',
help=( 'run on multiple servers (experimental!)' ) )
opts.add_option( '--placement', type='choice',
choices=self.PLACEMENT.keys(), default='block',
metavar='block|random',
help=( 'node placement for --cluster '
'(experimental!) ' ) )
self.options, self.args = opts.parse_args()
# We don't accept extra arguments after the options
if self.args:
opts.print_help()
sys.exit()
def setup( self ):
"Setup and validate environment."
lg.setLogLevel( self.options.verbosity )
def begin( self ):
"Create and run mininet."
if self.options.cluster:
servers = self.options.cluster.split( ',' )
for server in servers:
ClusterCleanup.add( server )
if self.options.clean:
cleanup()
sys.exit()
if not self.options.controller:
# Update default based on available controllers
CONTROLLERS[ 'default' ] = findController()
self.options.controller = [ 'default' ]
if not CONTROLLERS[ 'default' ]:
self.options.controller = [ 'none' ]
if self.options.switch == 'default':
info( '*** No default OpenFlow controller found '
'for default switch!\n' )
info( '*** Falling back to OVS Bridge\n' )
self.options.switch = 'ovsbr'
elif self.options.switch not in ( 'ovsbr', 'lxbr' ):
raise Exception( "Could not find a default controller "
"for switch %s" %
self.options.switch )
topo = buildTopo( TOPOS, self.options.topo )
switch = customClass( SWITCHES, self.options.switch )
host = customClass( HOSTS, self.options.host )
controller = [ customClass( CONTROLLERS, c )
for c in self.options.controller ]
if self.options.switch == 'user' and self.options.link == 'default':
# Using TCULink with UserSwitch
# Use link configured correctly for UserSwitch
self.options.link = 'tcu'
link = customClass( LINKS, self.options.link )
if self.validate:
self.validate( self.options )
ipBase = self.options.ipbase
xterms = self.options.xterms
mac = self.options.mac
arp = self.options.arp
pin = self.options.pin
listenPort = None
if not self.options.nolistenport:
listenPort = self.options.listenport
# Handle inNamespace, cluster options
inNamespace = self.options.innamespace
cluster = self.options.cluster
if inNamespace and cluster:
print("Please specify --innamespace OR --cluster")
sys.exit()
Net = MininetWithControlNet if inNamespace else Mininet
if cluster:
warn( '*** WARNING: Experimental cluster mode!\n'
'*** Using RemoteHost, RemoteOVSSwitch, RemoteLink\n' )
host, switch, link = RemoteHost, RemoteOVSSwitch, RemoteLink
Net = partial( MininetCluster, servers=servers,
placement=self.PLACEMENT[ self.options.placement ] )
self.net = Net( topo=topo,
switch=switch, host=host, controller=controller,
link=link,
ipBase=ipBase,
inNamespace=inNamespace,
xterms=xterms, autoSetMacs=mac,
autoStaticArp=arp, autoPinCpus=pin,
listenPort=listenPort )
if self.options.ensure_value( 'nat', False ):
nat = self.net.addNAT( *self.options.nat_args,
**self.options.nat_kwargs )
nat.configDefault()
self.net.start()
def runTest( self ):
cluster = self.options.cluster
cli = ClusterCLI if cluster else CLI
if self.options.pre:
cli(self.net, script=self.options.pre)
test = self.options.test
ALTSPELLING = {'pingall': 'pingAll',
'pingpair': 'pingPair',
'iperfudp': 'iperfUdp',
'iperfUDP': 'iperfUdp'}