-
Notifications
You must be signed in to change notification settings - Fork 192
/
mininet_test_base.py
2870 lines (2600 loc) · 121 KB
/
mininet_test_base.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
#!/usr/bin/env python3
"""Base class for all FAUCET unit tests."""
# pylint: disable=missing-docstring
# pylint: disable=too-many-arguments
from functools import partial
import collections
import copy
import glob
import ipaddress
import json
import os
import random
import re
import shutil
import string
import subprocess
import tempfile
import time
import unittest
import yaml
import netaddr
import requests
from ryu.ofproto import ofproto_v1_3 as ofp
from mininet.link import Intf as HWIntf # pylint: disable=import-error
from mininet.log import error, output # pylint: disable=import-error
from mininet.net import Mininet # pylint: disable=import-error
from mininet.util import dumpNodeConnections, pmonitor # pylint: disable=import-error
from clib import mininet_test_util
from clib import mininet_test_topo
from clib.mininet_test_topo import FaucetLink
from clib.tcpdump_helper import TcpdumpHelper
MAX_TEST_VID = 512
OFPVID_PRESENT = 0x1000
MIN_FLAP_TIME = 1
PEER_BGP_AS = 2**16 + 1
IPV4_ETH = 0x0800
IPV6_ETH = 0x86dd
FPING_ARGS = '-s -T 1 -A'
class FaucetTestBase(unittest.TestCase):
"""Base class for all FAUCET unit tests."""
ONE_GOOD_PING = '1 packets transmitted, 1 received, 0% packet loss'
FAUCET_VIPV4 = ipaddress.ip_interface('10.0.0.254/24')
FAUCET_VIPV4_2 = ipaddress.ip_interface('172.16.0.254/24')
FAUCET_VIPV6 = ipaddress.ip_interface('fc00::1:254/112')
FAUCET_VIPV6_2 = ipaddress.ip_interface('fc01::1:254/112')
OFCTL = 'ovs-ofctl -OOpenFlow13'
VSCTL = 'ovs-vsctl'
OVS_TYPE = 'kernel'
BOGUS_MAC = '01:02:03:04:05:06'
FAUCET_MAC = '0e:00:00:00:00:01'
LADVD = 'ladvd -e lo -f'
ONEMBPS = (1024 * 1024)
DB_TIMEOUT = 5
CONTROLLER_CLASS = mininet_test_topo.FAUCET
DP_NAME = 'faucet-1'
STAT_RELOAD = ''
EVENT_SOCK_HEARTBEAT = ''
CONFIG = ''
CONFIG_GLOBAL = ''
GAUGE_CONFIG_DBS = ''
LOG_LEVEL = 'INFO'
N_UNTAGGED = 0
N_TAGGED = 0
N_EXTENDED = 0
EXTENDED_CLS = None
NUM_DPS = 1
LINKS_PER_HOST = 1
SOFTWARE_ONLY = False
NETNS = False
EVENT_LOGGER_TIMEOUT = 120
FPING_ARGS = FPING_ARGS
FPING_ARGS_SHORT = ' '.join((FPING_ARGS, '-i10 -p100 -t100'))
FPINGS_ARGS_ONE = ' '.join(('fping', FPING_ARGS, '-t100 -c 1'))
RUN_GAUGE = True
REQUIRES_METERS = False
REQUIRES_METADATA = False
_PORT_ACL_TABLE = 0
_VLAN_TABLE = 1
_COPRO_TABLE = 2
_VLAN_ACL_TABLE = 3
_ETH_SRC_TABLE = 4
_IPV4_FIB_TABLE = 5
_IPV6_FIB_TABLE = 6
_VIP_TABLE = 7
_ETH_DST_HAIRPIN_TABLE = 8
_ETH_DST_TABLE = 9
_FLOOD_TABLE = 10
# Standard Gauge port counters.
PORT_VARS = {
'of_port_rx_bytes',
'of_port_tx_bytes',
'of_port_rx_packets',
'of_port_tx_packets',
}
config = None
dpid = None
hw_dpid = None
hardware = 'Open vSwitch'
hw_switch = False
gauge_controller = None
gauge_of_port = None
prom_port = None
net = None
of_port = None
ctl_privkey = None
ctl_cert = None
ca_certs = None
port_map = {}
switch_map = {}
tmpdir = None
net = None
topo = None
cpn_intf = None
cpn_ipv6 = False
config_ports = {}
env = collections.defaultdict(dict)
rand_dpids = set()
event_sock = None
faucet_config_path = None
event_log = None
def __init__(self, name, config, root_tmpdir, ports_sock, max_test_load, port_order=None):
super(FaucetTestBase, self).__init__(name)
self.config = config
self.root_tmpdir = root_tmpdir
self.ports_sock = ports_sock
self.max_test_load = max_test_load
self.port_order = port_order
self.start_time = None
self.dpid_names = None
self.event_log = None
self.prev_event_id = None
def hosts_name_ordered(self):
"""Return hosts in strict name only order."""
return sorted(self.net.hosts, key=lambda host: host.name)
def switches_name_ordered(self):
"""Return switches in strict name only order."""
return sorted(self.net.switches, key=lambda switch: switch.name)
def first_switch(self):
"""Return first switch by name order."""
if not self.switches_name_ordered():
return None
return self.switches_name_ordered()[0]
def rand_dpid(self):
reserved_range = 100
while True:
dpid = random.randint(1, (2**32 - reserved_range)) + reserved_range
if dpid not in self.rand_dpids:
self.rand_dpids.add(dpid)
return str(dpid)
def _set_var(self, controller, var, value):
self.env[controller][var] = value
def _set_var_path(self, controller, var, path):
self._set_var(controller, var, os.path.join(self.tmpdir, path))
def _set_prom_port(self, name='faucet'):
self._set_var(name, 'FAUCET_PROMETHEUS_PORT', str(self.prom_port))
self._set_var(name, 'FAUCET_PROMETHEUS_ADDR', mininet_test_util.LOCALHOSTV6)
def _set_static_vars(self):
if self.event_sock and os.path.exists(self.event_sock):
shutil.rmtree(os.path.dirname(self.event_sock))
self.event_sock = os.path.join(tempfile.mkdtemp(), 'event.sock')
self._set_var('faucet', 'FAUCET_EVENT_SOCK', self.event_sock)
self._set_var('faucet', 'FAUCET_CONFIG_STAT_RELOAD', self.STAT_RELOAD)
self._set_var('faucet', 'FAUCET_EVENT_SOCK_HEARTBEAT', self.EVENT_SOCK_HEARTBEAT)
self._set_var_path('faucet', 'FAUCET_CONFIG', 'faucet.yaml')
self._set_var_path('faucet', 'FAUCET_LOG', 'faucet.log')
self._set_var_path('faucet', 'FAUCET_EXCEPTION_LOG', 'faucet-exception.log')
self._set_var_path('gauge', 'GAUGE_CONFIG', 'gauge.yaml')
self._set_var_path('gauge', 'GAUGE_LOG', 'gauge.log')
self._set_var_path('gauge', 'GAUGE_EXCEPTION_LOG', 'gauge-exception.log')
self.faucet_config_path = self.env['faucet']['FAUCET_CONFIG']
self.gauge_config_path = self.env['gauge']['GAUGE_CONFIG']
self.debug_log_path = os.path.join(
self.tmpdir, 'ofchannel.txt')
self.monitor_stats_file = os.path.join(
self.tmpdir, 'gauge-ports.txt')
self.monitor_state_file = os.path.join(
self.tmpdir, 'gauge-state.txt')
self.monitor_flow_table_dir = os.path.join(
self.tmpdir, 'gauge-flow')
self.monitor_meter_stats_file = os.path.join(
self.tmpdir, 'gauge-meter.txt')
os.mkdir(self.monitor_flow_table_dir)
if self.config is not None:
if 'hw_switch' in self.config:
self.hw_switch = self.config['hw_switch']
if self.hw_switch:
self.dpid = self.config['dpid']
self.cpn_intf = self.config['cpn_intf']
if 'cpn_ipv6' in self.config:
self.cpn_ipv6 = self.config['cpn_ipv6']
self.hardware = self.config['hardware']
if 'ctl_privkey' in self.config:
self.ctl_privkey = self.config['ctl_privkey']
if 'ctl_cert' in self.config:
self.ctl_cert = self.config['ctl_cert']
if 'ca_certs' in self.config:
self.ca_certs = self.config['ca_certs']
dp_ports = self.config['dp_ports']
self.switch_map = dp_ports.copy()
def _set_vars(self):
self._set_prom_port()
self._set_log_level()
def _set_log_level(self, name='faucet'):
self._set_var(name, 'FAUCET_LOG_LEVEL', str(self.LOG_LEVEL))
def _enable_event_log(self, timeout=None):
"""Enable analsis of event log contents by copying events to a local log file"""
assert not self.event_log, 'event_log already enabled'
if not timeout:
timeout = self.EVENT_LOGGER_TIMEOUT
self.event_log = os.path.join(self.tmpdir, 'event.log')
self.prev_event_id = 0
controller = self._get_controller()
sock = self.env['faucet']['FAUCET_EVENT_SOCK']
# Relying on a timeout seems a bit brittle;
# as an alternative we might possibly use something like
# `with popen(cmd...) as proc`to clean up on exceptions
controller.cmd(mininet_test_util.timeout_cmd(
'nc -U %s > %s &' % (sock, self.event_log), timeout))
def _wait_until_matching_event(self, match_func, timeout=30):
"""Return the next matching event from the event sock, else fail"""
assert timeout >= 1
assert self.event_log and os.path.exists(self.event_log)
for _ in range(timeout):
with open(self.event_log) as events:
for event_str in events:
event = json.loads(event_str)
event_id = event['event_id']
if event_id <= self.prev_event_id:
continue
self.prev_event_id = event_id
try:
if match_func(event):
return event
except KeyError:
pass # Allow for easy dict traversal.
time.sleep(1)
self.fail('matching event not found in event stream')
def _read_yaml(self, yaml_path):
with open(yaml_path) as yaml_file:
content = yaml.safe_load(yaml_file.read())
return content
def _get_faucet_conf(self):
return self._read_yaml(self.faucet_config_path)
def _annotate_interfaces_conf(self, yaml_conf):
"""Consistently name interface names/descriptions."""
if 'dps' not in yaml_conf:
return yaml_conf
yaml_conf_remap = copy.deepcopy(yaml_conf)
for dp_key, dp_yaml in yaml_conf['dps'].items():
interfaces_yaml = dp_yaml.get('interfaces', None)
if interfaces_yaml is not None:
remap_interfaces_yaml = {}
for intf_key, orig_intf_conf in interfaces_yaml.items():
intf_conf = copy.deepcopy(orig_intf_conf)
port_no = None
if isinstance(intf_key, int):
port_no = intf_key
number = intf_conf.get('number', port_no)
if isinstance(number, int):
port_no = number
assert isinstance(number, int), '%u %s' % (intf_key, orig_intf_conf)
intf_name = 'b%u' % port_no
intf_conf.update({'name': intf_name, 'description': intf_name})
remap_interfaces_yaml[intf_key] = intf_conf
yaml_conf_remap['dps'][dp_key]['interfaces'] = remap_interfaces_yaml
return yaml_conf_remap
def _write_yaml_conf(self, yaml_path, yaml_conf):
assert isinstance(yaml_conf, dict)
new_conf_str = yaml.dump(yaml_conf).encode()
with tempfile.NamedTemporaryFile(
prefix=os.path.basename(yaml_path),
dir=os.path.dirname(yaml_path),
delete=False) as conf_file_tmp:
conf_file_tmp_name = conf_file_tmp.name
conf_file_tmp.write(new_conf_str)
with open(conf_file_tmp_name, 'rb') as conf_file_tmp:
conf_file_tmp_str = conf_file_tmp.read()
assert new_conf_str == conf_file_tmp_str
if os.path.exists(yaml_path):
shutil.copyfile(yaml_path, '%s.%f' % (yaml_path, time.time()))
os.rename(conf_file_tmp_name, yaml_path)
def _init_faucet_config(self):
faucet_config = '\n'.join((
self.get_config_header(
self.CONFIG_GLOBAL,
self.debug_log_path, self.dpid, self.hardware),
self.CONFIG))
config_vars = {}
for config_var in (self.config_ports, self.port_map):
config_vars.update(config_var)
faucet_config = faucet_config % config_vars
yaml_conf = self._annotate_interfaces_conf(yaml.safe_load(faucet_config))
self._write_yaml_conf(self.faucet_config_path, yaml_conf)
def _init_gauge_config(self):
gauge_config = self.get_gauge_config(
self.faucet_config_path,
self.monitor_stats_file,
self.monitor_state_file,
self.monitor_flow_table_dir)
if self.config_ports:
gauge_config = gauge_config % self.config_ports
self._write_yaml_conf(self.gauge_config_path, yaml.safe_load(gauge_config))
def _test_name(self):
return mininet_test_util.flat_test_name(self.id())
def _tmpdir_name(self):
tmpdir = os.path.join(self.root_tmpdir, self._test_name())
os.mkdir(tmpdir)
return tmpdir
def _controller_lognames(self):
lognames = []
for controller in self.net.controllers:
logname = controller.logname()
if os.path.exists(logname) and os.path.getsize(logname) > 0:
lognames.append(logname)
return lognames
def _wait_load(self, load_retries=120):
for _ in range(load_retries):
load = os.getloadavg()[0]
time.sleep(random.randint(1, 7))
if load < self.max_test_load:
return
output('load average too high %f, waiting' % load)
self.fail('load average %f consistently too high' % load)
def _allocate_config_ports(self):
for port_name in self.config_ports:
self.config_ports[port_name] = None
for config in (self.CONFIG, self.CONFIG_GLOBAL, self.GAUGE_CONFIG_DBS):
if re.search(port_name, config):
port = mininet_test_util.find_free_port(
self.ports_sock, self._test_name())
self.config_ports[port_name] = port
output('allocating port %u for %s' % (port, port_name))
def _allocate_faucet_ports(self):
if self.hw_switch:
self.of_port = self.config['of_port']
else:
self.of_port = mininet_test_util.find_free_port(
self.ports_sock, self._test_name())
self.prom_port = mininet_test_util.find_free_port(
self.ports_sock, self._test_name())
def _allocate_gauge_ports(self):
if self.hw_switch:
self.gauge_of_port = self.config['gauge_of_port']
else:
self.gauge_of_port = mininet_test_util.find_free_port(
self.ports_sock, self._test_name())
def _stop_net(self):
if self.net is not None:
for switch in self.net.switches:
switch.cmd(
self.VSCTL, 'del-controller', switch.name, '|| true')
self.net.stop()
def setUp(self):
self.start_time = time.time()
self.tmpdir = self._tmpdir_name()
self._set_static_vars()
self.topo_class = partial(
mininet_test_topo.FaucetSwitchTopo, port_order=self.port_order,
switch_map=self.switch_map)
if self.hw_switch:
self.hw_dpid = mininet_test_util.str_int_dpid(self.dpid)
self.dpid = self.hw_dpid
else:
self.dpid = self.rand_dpid()
def hostns(self, host):
return '%s' % host.name
def dump_switch_flows(self, switch):
"""Dump switch information to tmpdir"""
for dump_cmd in (
'dump-flows', 'dump-groups', 'dump-meters',
'dump-group-stats', 'dump-ports', 'dump-ports-desc',
'meter-stats'):
switch_dump_name = os.path.join(self.tmpdir, '%s-%s.log' % (switch.name, dump_cmd))
# TODO: occasionally fails with socket error.
switch.cmd('%s %s %s > %s' % (self.OFCTL, dump_cmd, switch.name, switch_dump_name),
success=None)
for other_cmd in ('show', 'list controller', 'list manager'):
other_dump_name = os.path.join(self.tmpdir, '%s.log' % other_cmd.replace(' ', ''))
switch.cmd('%s %s > %s' % (self.VSCTL, other_cmd, other_dump_name))
def tearDown(self, ignore_oferrors=False):
"""Clean up after a test.
ignore_oferrors: return OF errors rather than failing"""
if self.NETNS:
for host in self.hosts_name_ordered()[:1]:
if self.get_host_netns(host):
self.quiet_commands(host, ['ip netns del %s' % self.hostns(host)])
first_switch = self.first_switch()
if first_switch:
self.first_switch().cmd('ip link > %s' % os.path.join(self.tmpdir, 'ip-links.log'))
switch_names = []
for switch in self.net.switches:
switch_names.append(switch.name)
self.dump_switch_flows(switch)
switch.cmd('%s del-br %s' % (self.VSCTL, switch.name))
self._stop_net()
self.net = None
if os.path.exists(self.event_sock):
shutil.rmtree(os.path.dirname(self.event_sock))
mininet_test_util.return_free_ports(
self.ports_sock, self._test_name())
if 'OVS_LOGDIR' in os.environ:
ovs_log_dir = os.environ['OVS_LOGDIR']
if ovs_log_dir and os.path.exists(ovs_log_dir):
for ovs_log in glob.glob(os.path.join(ovs_log_dir, '*.log')):
lines = []
for name in switch_names:
lines.extend(self.matching_lines_from_file(name, ovs_log))
if lines:
switch_ovs_log_name = os.path.join(self.tmpdir, os.path.basename(ovs_log))
with open(switch_ovs_log_name, 'w') as switch_ovs_log:
switch_ovs_log.write('\n'.join(lines))
with open(os.path.join(self.tmpdir, 'test_duration_secs'), 'w') as duration_file:
duration_file.write(str(int(time.time() - self.start_time)))
# Must not be any controller exception.
for exceptionlog in (
self.env['faucet']['FAUCET_EXCEPTION_LOG'], self.env['gauge']['GAUGE_EXCEPTION_LOG']):
self.verify_no_exception(exceptionlog)
oferrors = ''
for logfile in (self.env['faucet']['FAUCET_LOG'], self.env['gauge']['GAUGE_LOG']):
oldlogfile = '.'.join((logfile, 'old'))
if os.path.exists(oldlogfile):
logfile = oldlogfile
# Verify version is logged.
self.assertTrue(
self.matching_lines_from_file(r'^.+version\s+(\S+)$', logfile),
msg='no version logged in %s' % logfile)
# Verify no OFErrors.
oferrors += '\n\n'.join(self.matching_lines_from_file(r'^.+(OFError.+)$', logfile))
if not ignore_oferrors:
self.assertFalse(oferrors, msg=oferrors)
return oferrors
def _block_non_faucet_packets(self):
def _cmd(cmd):
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = p.communicate()
self.assertFalse(stdout, msg='%s: %s' % (stdout, cmd))
self.assertFalse(stderr, msg='%s: %s' % (stderr, cmd))
_cmd('ebtables --f OUTPUT')
for phys_port in self.switch_map.values():
phys_mac = self.get_mac_of_intf(phys_port)
for cmd in (
'ip link set dev %s up' % phys_port,
'ip -4 addr flush dev %s' % phys_port,
'ip -6 addr flush dev %s' % phys_port,
'ebtables -A OUTPUT -s %s -o %s -j DROP' % (phys_mac, phys_port)):
_cmd(cmd)
def _attach_physical_switch(self):
"""Bridge a physical switch into test topology.
We do this for now to enable us to reconnect
virtual ethernet interfaces which may already
exist on emulated hosts and other OVS instances.
(One alternative would be to create a Link() class
that uses the hardware interfaces directly.)
We repurpose the first OvS switch in the topology
as a patch panel that transparently connects the
hardware interfaces to the host/switch veth links."""
switch = self.first_switch()
if not switch:
return
# hw_names are the names of the server hardware interfaces
# that are cabled to the device under test, sorted by OF port number
hw_names = [self.switch_map[port] for port in sorted(self.switch_map)]
hw_macs = set()
# ovs_ports are the (sorted) OF port numbers of the OvS interfaces
# that are already attached to the emulated network.
# The actual tests reorder them according to port_map
ovs_ports = sorted(self.topo.switch_ports[switch.name])
# Patch hardware interfaces through to to OvS interfaces
for hw_name, ovs_port in zip(hw_names, ovs_ports):
# Note we've already removed any Linux IP addresses from hw_name
# and blocked traffic to/from its meaningless MAC
hw_mac = self.get_mac_of_intf(hw_name)
self.assertFalse(hw_mac in hw_macs,
'duplicate hardware MAC %s' % hw_mac)
hw_macs.add(hw_mac)
# Create mininet Intf and attach it to the switch
hw_intf = HWIntf(hw_name, node=switch)
switch.attach(hw_intf)
hw_port = switch.ports[hw_intf]
# Connect hw_port <-> ovs_port
src, dst = hw_port, ovs_port
for flow in (
# Drop anything to or from the meaningless hw_mac
'eth_src=%s,priority=2,actions=drop' % hw_mac,
'eth_dst=%s,priority=2,actions=drop' % hw_mac,
# Forward traffic bidirectionally src <-> dst
'in_port=%u,priority=1,actions=output:%u' % (src, dst),
'in_port=%u,priority=1,actions=output:%u' % (dst, src)):
switch.cmd(self.OFCTL, 'add-flow', switch, flow)
def create_port_map(self, dpid):
"""Return a port map {'port_1': port...} for a dpid in self.topo"""
ports = self.topo.dpid_ports(dpid)
port_map = {'port_%d' % i: port for i, port in enumerate(ports, start=1)}
return port_map
def start_net(self):
"""Start Mininet network."""
controller_intf = 'lo'
controller_ipv6 = False
if self.hw_switch:
controller_intf = self.cpn_intf
controller_ipv6 = self.cpn_ipv6
if not self.port_map:
# Sometimes created in build_net for config purposes, sometimes not
self.port_map = self.create_port_map(self.dpid)
self._block_non_faucet_packets()
self._start_faucet(controller_intf, controller_ipv6)
self.pre_start_net()
if self.hw_switch:
self._attach_physical_switch()
self._wait_debug_log()
for port_no in self._dp_ports():
self.set_port_up(port_no, wait=False)
dumpNodeConnections(self.hosts_name_ordered())
self.reset_all_ipv4_prefix(prefix=24)
def _get_controller(self):
"""Return first controller."""
return self.net.controllers[0]
@staticmethod
def _start_gauge_check():
return None
def _start_check(self):
if not self._wait_controllers_healthy():
return 'not all controllers healthy'
if not self._wait_controllers_connected():
return 'not all controllers connected to switch'
if not self._wait_ofctl_up():
return 'ofctl not up'
if not self.wait_dp_status(1):
return 'prometheus port not up'
if not self._wait_controllers_healthy():
return 'not all controllers healthy after initial switch connection'
if self.config_ports:
for port_name, port in self.config_ports.items():
if port is not None and not port_name.startswith('gauge'):
if not self._get_controller().listen_port(port):
return 'faucet not listening on %u (%s)' % (
port, port_name)
return self._start_gauge_check()
def _start_faucet(self, controller_intf, controller_ipv6):
last_error_txt = ''
assert self.net is None # _start_faucet() can't be multiply called
for _ in range(3):
mininet_test_util.return_free_ports(
self.ports_sock, self._test_name())
self._allocate_config_ports()
self._allocate_faucet_ports()
self._set_vars()
for log in glob.glob(os.path.join(self.tmpdir, '*.log')):
os.remove(log)
self.net = Mininet(
self.topo,
link=FaucetLink,
controller=self.CONTROLLER_CLASS(
name='faucet', tmpdir=self.tmpdir,
controller_intf=controller_intf,
controller_ipv6=controller_ipv6,
env=self.env['faucet'],
ctl_privkey=self.ctl_privkey,
ctl_cert=self.ctl_cert,
ca_certs=self.ca_certs,
ports_sock=self.ports_sock,
prom_port=self.get_prom_port(),
port=self.of_port,
test_name=self._test_name()))
if self.RUN_GAUGE:
self._allocate_gauge_ports()
self._init_gauge_config()
self.gauge_controller = mininet_test_topo.Gauge(
name='gauge', tmpdir=self.tmpdir,
env=self.env['gauge'],
controller_intf=controller_intf,
controller_ipv6=controller_ipv6,
ctl_privkey=self.ctl_privkey,
ctl_cert=self.ctl_cert,
ca_certs=self.ca_certs,
port=self.gauge_of_port)
self.net.addController(self.gauge_controller)
self._init_faucet_config()
self.net.start()
self._wait_load()
last_error_txt = self._start_check()
if last_error_txt is None:
self._config_tableids()
self._wait_load()
if self.NETNS:
# TODO: seemingly can't have more than one namespace.
for host in self.hosts_name_ordered()[:1]:
hostns = self.hostns(host)
if self.get_host_netns(host):
self.quiet_commands(host, ['ip netns del %s' % hostns])
self.quiet_commands(host, ['ip netns add %s' % hostns])
return
self._stop_net()
last_error_txt += '\n\n' + self._dump_controller_logs()
error('%s: %s' % (self._test_name(), last_error_txt))
time.sleep(mininet_test_util.MIN_PORT_AGE)
self.fail(last_error_txt)
def _ofctl_rest_url(self, req):
"""Return control URL for Ryu ofctl module."""
return 'http://[%s]:%u/%s' % (
mininet_test_util.LOCALHOSTV6, self._get_controller().ofctl_port, req)
@staticmethod
def _ofctl(req, params=None):
if params is None:
params = {}
try:
ofctl_result = requests.get(req, params=params).json()
except requests.exceptions.ConnectionError:
return None
return ofctl_result
def _ofctl_up(self):
switches = self._ofctl(self._ofctl_rest_url('stats/switches'))
return isinstance(switches, list) and switches
def _wait_ofctl_up(self, timeout=10):
for _ in range(timeout):
if self._ofctl_up():
return True
time.sleep(1)
return False
def _ofctl_post(self, int_dpid, req, timeout, params=None):
for _ in range(timeout):
try:
ofctl_result = requests.post(
self._ofctl_rest_url(req),
json=params).json()
return ofctl_result[int_dpid]
except (ValueError, TypeError, requests.exceptions.ConnectionError):
# Didn't get valid JSON, try again
time.sleep(1)
continue
return []
def _ofctl_get(self, int_dpid, req, timeout, params=None):
for _ in range(timeout):
ofctl_result = self._ofctl(self._ofctl_rest_url(req), params=params)
try:
return ofctl_result[int_dpid]
except (ValueError, TypeError):
# Didn't get valid JSON, try again
time.sleep(1)
continue
return []
def _portmod(self, int_dpid, port_no, config, mask):
result = requests.post(
self._ofctl_rest_url('stats/portdesc/modify'),
json={'dpid': str(int_dpid), 'port_no': str(port_no),
'config': str(config), 'mask': str(mask)})
# ofctl doesn't use barriers, so cause port_mod to be sent.
self.get_port_stats_from_dpid(int_dpid, port_no)
return result
@staticmethod
def _signal_proc_on_port(host, port, signal):
tcp_pattern = '%s/tcp' % port
fuser_out = host.cmd('fuser %s -k -%u' % (tcp_pattern, signal))
return re.search(r'%s:\s+\d+' % tcp_pattern, fuser_out)
def _get_ofchannel_logs(self):
ofchannel_logs = []
config = self._get_faucet_conf()
for dp_name, dp_config in config['dps'].items():
if 'ofchannel_log' in dp_config:
debug_log = dp_config['ofchannel_log']
ofchannel_logs.append((dp_name, debug_log))
return ofchannel_logs
def _dump_controller_logs(self):
dump_txt = ''
test_logs = glob.glob(os.path.join(self.tmpdir, '*.log'))
for controller in self.net.controllers:
for test_log_name in test_logs:
basename = os.path.basename(test_log_name)
if basename.startswith(controller.name):
with open(test_log_name) as test_log:
dump_txt += '\n'.join((
'',
basename,
'=' * len(basename),
'',
test_log.read()))
break
return dump_txt
def _controllers_healthy(self):
for controller in self.net.controllers:
if not controller.healthy():
return False
if self.event_sock and not os.path.exists(self.event_sock):
error('event socket %s not created\n' % self.event_sock)
return False
return True
def _controllers_connected(self):
for controller in self.net.controllers:
if not controller.connected():
return False
return True
def _wait_controllers_healthy(self, timeout=30):
for _ in range(timeout):
if self._controllers_healthy():
return True
time.sleep(1)
return False
def _wait_controllers_connected(self, timeout=30):
for _ in range(timeout):
if self._controllers_connected():
return True
time.sleep(1)
return False
def _wait_debug_log(self):
"""Require all switches to have exchanged flows with controller."""
ofchannel_logs = self._get_ofchannel_logs()
for _, debug_log in ofchannel_logs:
for _ in range(60):
if (os.path.exists(debug_log) and
os.path.getsize(debug_log) > 0):
return True
time.sleep(1)
return False
def verify_no_exception(self, exception_log_name):
if not os.path.exists(exception_log_name):
return
with open(exception_log_name) as exception_log:
exception_contents = exception_log.read()
self.assertEqual(
'',
exception_contents,
msg='%s log contains %s' % (
exception_log_name, exception_contents))
@staticmethod
def tcpdump_helper(*args, **kwargs):
return TcpdumpHelper(*args, **kwargs).execute()
@staticmethod
def scapy_template(packet, iface, count=1):
return ('python3 -c \"from scapy.all import * ; sendp(%s, iface=\'%s\', count=%u)"' % (
packet, iface, count))
def scapy_base_udp(self, mac, iface, src_ip, dst_ip, dport, sport, count=1, dst=None):
if dst is None:
dst = 'ff:ff:ff:ff:ff:ff'
return self.scapy_template(
('Ether(dst=\'%s\', src=\'%s\', type=%u) / '
'IP(src=\'%s\', dst=\'%s\') / UDP(dport=%s,sport=%s) ' % (
dst, mac, IPV4_ETH, src_ip, dst_ip, dport, sport)),
iface, count)
def scapy_dhcp(self, mac, iface, count=1, dst=None):
if dst is None:
dst = 'ff:ff:ff:ff:ff:ff'
return self.scapy_template(
('Ether(dst=\'%s\', src=\'%s\', type=%u) / '
'IP(src=\'0.0.0.0\', dst=\'255.255.255.255\') / UDP(dport=67,sport=68) / '
'BOOTP(op=1) / DHCP(options=[(\'message-type\', \'discover\'), (\'end\')])') % (
dst, mac, IPV4_ETH),
iface, count)
def scapy_icmp(self, mac, iface, src_ip, dst_ip, count=1, dst=None):
if dst is None:
dst = 'ff:ff:ff:ff:ff:ff'
return self.scapy_template(
('Ether(dst=\'%s\', src=\'%s\', type=%u) / '
'IP(src=\'%s\', dst=\'%s\') / ICMP()') % (
dst, mac, IPV4_ETH, src_ip, dst_ip),
iface, count)
def scapy_dscp(self, src_mac, dst_mac, dscp_value, iface, count=1):
# creates a packet with L2-L4 headers using scapy
return self.scapy_template(
('Ether(dst=\'%s\', src=\'%s\', type=%u) / '
'IP(src=\'0.0.0.0\', dst=\'255.255.255.255\', tos=%s) / UDP(dport=67,sport=68) / '
'BOOTP(op=1)') % (
dst_mac, src_mac, IPV4_ETH, dscp_value),
iface, count)
def scapy_bcast(self, host, count=1):
return self.scapy_dhcp(host.MAC(), host.defaultIntf(), count)
@staticmethod
def pre_start_net():
"""Hook called after Mininet initializtion, before Mininet started."""
return
def get_config_header(self, config_global, debug_log, dpid, hardware):
"""Build v2 FAUCET config header."""
return """
%s
dps:
%s:
ofchannel_log: %s
dp_id: 0x%x
hardware: "%s"
cookie: %u
""" % (config_global, self.DP_NAME, debug_log,
int(dpid), hardware, random.randint(1, 2**64-1))
def get_gauge_watcher_config(self):
return """
port_stats:
dps: ['%s']
type: 'port_stats'
interval: 5
db: 'stats_file'
port_state:
dps: ['%s']
type: 'port_state'
interval: 5
db: 'state_file'
flow_table:
dps: ['%s']
type: 'flow_table'
interval: 5
db: 'flow_dir'
""" % (self.DP_NAME, self.DP_NAME, self.DP_NAME)
def get_gauge_config(self, faucet_config_file,
monitor_stats_file,
monitor_state_file,
monitor_flow_table_dir):
"""Build Gauge config."""
return """
faucet_configs:
- %s
watchers:
%s
dbs:
stats_file:
type: 'text'
file: %s
state_file:
type: 'text'
file: %s
flow_dir:
type: 'text'
path: %s
%s
""" % (faucet_config_file,
self.get_gauge_watcher_config(),
monitor_stats_file,
monitor_state_file,
monitor_flow_table_dir,
self.GAUGE_CONFIG_DBS)
@staticmethod
def get_exabgp_conf(peer, peer_config=''):
return """
neighbor %s {
router-id 2.2.2.2;
local-address %s;
connect %s;
peer-as 1;
local-as %s;
%s
}
""" % (peer, peer, '%(bgp_port)d', PEER_BGP_AS, peer_config)
def get_all_groups_desc_from_dpid(self, dpid, timeout=2):
int_dpid = mininet_test_util.str_int_dpid(dpid)
return self._ofctl_get(
int_dpid, 'stats/groupdesc/%s' % int_dpid, timeout)
def get_all_flows_from_dpid(self, dpid, table_id, timeout=10, match=None):
"""Return all flows from DPID."""
int_dpid = mininet_test_util.str_int_dpid(dpid)
params = {}
params['table_id'] = table_id
if match is not None:
params['match'] = match
return self._ofctl_post(
int_dpid, 'stats/flow/%s' % int_dpid, timeout, params=params)
@staticmethod
def _port_stat(port_stats, port):
if port_stats:
for port_stat in port_stats:
if port_stat['port_no'] == port:
return port_stat
return None
def get_port_stats_from_dpid(self, dpid, port, timeout=2):
"""Return port stats for a port."""
int_dpid = mininet_test_util.str_int_dpid(dpid)
port_stats = self._ofctl_get(
int_dpid, 'stats/port/%s/%s' % (int_dpid, port), timeout)
return self._port_stat(port_stats, port)
def get_port_desc_from_dpid(self, dpid, port, timeout=2):
"""Return port desc for a port."""
int_dpid = mininet_test_util.str_int_dpid(dpid)
port_stats = self._ofctl_get(
int_dpid, 'stats/portdesc/%s/%s' % (int_dpid, port), timeout)
return self._port_stat(port_stats, port)
def get_all_meters_from_dpid(self, dpid):
"""Return all meters from DPID"""
int_dpid = mininet_test_util.str_int_dpid(dpid)
return self._ofctl_get(
int_dpid, 'stats/meterconfig/%s' % int_dpid, timeout=10)
def wait_matching_in_group_table(self, action, group_id, timeout=10):
groupdump = os.path.join(self.tmpdir, 'groupdump-%s.txt' % self.dpid)
for _ in range(timeout):
group_dump = self.get_all_groups_desc_from_dpid(self.dpid, 1)
with open(groupdump, 'w') as groupdump_file:
for group_dict in group_dump:
groupdump_file.write(str(group_dict) + '\n')
if group_dict['group_id'] == group_id:
actions = set(group_dict['buckets'][0]['actions'])
if set([action]).issubset(actions):
return True
time.sleep(1)
return False
# TODO: Should this have meter_confs as well or can we just match meter_ids
def get_matching_meters_on_dpid(self, dpid):
meterdump = os.path.join(self.tmpdir, 'meterdump-%s.log' % dpid)
meter_dump = self.get_all_meters_from_dpid(dpid)
with open(meterdump, 'w') as meterdump_file:
meterdump_file.write(str(meter_dump))
return meterdump
def get_matching_flows_on_dpid(self, dpid, match, table_id, timeout=10,
actions=None, hard_timeout=0, cookie=None,
ofa_match=True):