Repository navigation
Expand file tree
/
Copy pathcperf.py
More file actions
1985 lines (1833 loc) · 77.1 KB
/
Copy pathcperf.py
File metadata and controls
1985 lines (1833 loc) · 77.1 KB
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/python3
# Copyright (c) 2020-2023 Homa Developers
# SPDX-License-Identifier: BSD-2-Clause OR GPL-2.0+
# This file contains library functions used to run cluster performance
# tests for the Linux kernel implementation of Homa.
import argparse
from collections import defaultdict
import copy
import datetime
import glob
import math
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import os
from pathlib import Path
import platform
import re
import shutil
import subprocess
import sys
import time
import traceback
# Avoid Type 3 fonts (conferences don't tend to like them).
matplotlib.rcParams['pdf.fonttype'] = 42
matplotlib.rcParams['ps.fonttype'] = 42
if platform.system() != "Windows":
import fcntl
# If a server's id appears as a key in this dictionary, it means we
# have started cp_node running on that node. The value of each entry is
# a Popen object that can be used to communicate with the node.
active_nodes = {}
# If a server's id appears as a key in this dictionary, it means we
# have started homa_prio running on that node. The value of each entry is
# a Popen object for the homa_prio instance; if this is terminated, then
# the homa_prio process will end.
homa_prios = {}
# The range of nodes currently running cp_node servers.
server_nodes = range(0,0)
# If a server's id appears as a key in this dictionary it means that we
# have started a log file on that server. Values have no meaning. Used to
# delete old log files the first time a server is started on the node
log_nodes = {}
# Directory containing log files.
log_dir = ''
# Open file (in the log directory) where log messages should be written.
log_file = 0
# Indicates whether we should generate additional log messages for debugging
verbose = False
# The --delete-rtts command-line option.
delete_rtts = False
# The CloudLab node type for this node (e.g. xl170)
node_type = None
# Value of the "--stripped" option.
stripped = False
# Speed of host uplinks.
link_mbps = None
# "Best possible RTT for short messages", depending on CloudLab node type.
# Used to compute slowdowns.
baseline_rtts = {"xl170": 15, "c6620": 25, "c6525-25g": 25, "c6525-100g": 25,
"default": 25}
# Defaults for command-line options; assumes that servers and clients
# share nodes. Individual benchmarks may override some of these values.
# 'None' values will eventually be replaced with values from defaults_25g
# or defaults_100g.
default_defaults = {
'gbps': 0.0,
# Note: very large numbers for client_max hurt Homa throughput with
# unlimited load (throttle queue inserts take a long time).
'client_max': 200,
'client_ports': None,
'log_dir': 'logs/' + time.strftime('%Y%m%d%H%M%S'),
'mtu': 0,
'no_trunc': '',
'protocol': 'homa',
'port_receivers': None,
'port_threads': None,
'seconds': 20,
'server_ports': None,
'tcp_client_ports': None,
'tcp_port_receivers': None,
'tcp_server_ports': None,
'tcp_port_threads': None,
'unsched': 0,
'unsched_boost': 0.0,
'workload': 'w4'
}
# These defaults are used for 25 Gbps networks.
defaults_25g = {
'client_ports': 3,
'port_receivers': 3,
'port_threads': 3,
'server_ports': 3,
'tcp_client_ports': 4,
'tcp_port_receivers': 1,
'tcp_port_threads': 1,
'tcp_server_ports': 8,
}
# These defaults are used for 100 Gbps networks.
defaults_100g = {
'client_ports': 5,
'port_receivers': 3,
'port_threads': 3,
'server_ports': 2,
'tcp_client_ports': 10,
'tcp_port_receivers': 1,
'tcp_port_threads': 1,
'tcp_server_ports': 20,
}
# Maps from CloudLab node type ('xl170', 'c6620', etc.) to defaults
# appropriate for that cluster type.
type_defaults = {
'xl170': defaults_25g,
'c6620': defaults_100g,
'c6525-25g': defaults_25g,
'c6525-100g': defaults_100g
}
# Keys are experiment names, and each value is the digested data for that
# experiment. The digest is itself a dictionary containing some or all of
# the following keys:
# rtts: A dictionary with message lengths as keys; each value is
# a list of the RTTs (in usec) for all messages of that length.
# total_messages: Total number of samples in rtts.
# lengths: Sorted list of message lengths, corresponding to buckets
# chosen for plotting
# cum_frac: Cumulative fraction of all messages corresponding to each length
# counts: Number of RTTs represented by each bucket
# p50: List of 50th percentile rtts corresponding to each length
# p99: List of 99th percentile rtts corresponding to each length
# p999: List of 999th percentile rtts corresponding to each length
# slow_50: List of 50th percentile slowdowns corresponding to each length
# slow_99: List of 99th percentile slowdowns corresponding to each length
# slow_999: List of 999th percentile slowdowns corresponding to each length
# avg_slowdown: Average slowdown across all messages of all sizes
digests = {}
# Keys are filenames, and each value is a dictionary containing data read
# from that file. Within that dictionary, each key is the name of a column
# within the file, and the value is a list of numbers read from the given
# column of the given file.
data_from_files = {}
# Time when this benchmark was run.
date_time = str(datetime.datetime.now())
# Standard colors for plotting
tcp_color = '#00B000'
tcp_color2 = '#5BD15B'
tcp_color3 = '#96E296'
homa_color = '#1759BB'
homa_color2 = '#6099EE'
homa_color3 = '#A6C6F6'
dctcp_color = '#7A4412'
dctcp_color2 = '#CB701D'
dctcp_color3 = '#EAA668'
unloaded_color = '#d62728'
# Default bandwidths to use when running all of the workloads.
load_info = [["w1", 1.4], ["w2", 3.2], ["w3", 14], ["w4", 20], ["w5", 20]]
# PyPlot color circle colors:
pyplot_colors = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd',
'#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf']
def boolean(s):
"""
Used as a "type" in argparse specs; accepts Boolean-looking things.
"""
map = {'true': True, 'yes': True, 'ok': True, "1": True, 'y': True,
't': True, 'false': False, 'no': False, '0': False, 'f': False,
'n': False}
lc = s.lower()
if lc not in map:
raise ValueError("Expected boolean value, got %s" % (s))
return map[lc]
def log(message):
"""
Write the a log message both to stdout and to the cperf log file.
message: The log message to write; a newline will be appended.
"""
global log_file
print(message)
log_file.write("%.9f " % (time.time()))
log_file.write(message)
log_file.write("\n")
def vlog(message):
"""
Log a message, like log, but if verbose logging isn't enabled, then
log only to the cperf log file, not to stdout.
message: The log message to write; a newline will be appended.
"""
global log_file, verbose
if verbose:
print(message)
log_file.write("%.9f " % (time.time()))
log_file.write(message)
log_file.write("\n")
def get_parser(description, usage, defaults = {}):
"""
Returns an ArgumentParser for options that are commonly used in
performance tests.
description: A string describing the overall functionality of this
particular performance test
usage: A command synopsis (passed as usage to ArgumentParser)
defaults: A dictionary whose keys are option names and whose values
are defaults; used to modify the defaults for some of the
options (there is a default default for each option).
"""
# Configure defaults for this particular node type (e.g. network speed)
p = Path("/var/emulab/boot/nodetype")
if p.is_file():
type = p.read_text().strip()
if type in type_defaults:
node_defaults = type_defaults[type]
else:
print("Couldn't find option defaults for node type '%s'; "
"using 100 Gbps defaults" % (type), file=sys.stderr)
node_defaults = defaults_100g
else:
print("Couldn't read node type from /var/emulab/boot/nodetype; "
"using 100 Gbps defaults")
node_defaults = defaults_100g
for key, value in node_defaults.items():
# Only set default if the application hasn't already specified a value
if default_defaults[key] == None:
default_defaults[key] = value
for key in default_defaults:
if not key in defaults:
defaults[key] = default_defaults[key]
parser = argparse.ArgumentParser(description=description + ' The options '
'below may include some that are not used by this particular '
'benchmark', usage=usage, add_help=False,
conflict_handler='resolve')
parser.add_argument('-b', '--gbps', type=float, dest='gbps',
metavar='B', default=defaults['gbps'],
help='Generate a total of B Gbits/sec of bandwidth on the most '
'heavily loaded machines; 0 means run as fast as possible '
'(default: %.2f)' % (defaults['gbps']))
parser.add_argument('--client-max', type=int, dest='client_max',
metavar='count', default=defaults['client_max'],
help='Maximum number of Homa requests each client machine can have '
'outstanding at a time (divided evenly among the Homa ports) '
'(default: %d)' % (defaults['client_max']))
parser.add_argument('--client-ports', type=int, dest='client_ports',
metavar='count', default=defaults['client_ports'],
help='Number of ports on which each client should issue requests '
'(default: %d)' % (defaults['client_ports']))
parser.add_argument('--cperf-log', dest='cperf_log',
metavar='F', default='cperf.log',
help='Name to use for the cperf log file (default: cperf.log)')
parser.add_argument('-d', '--debug', dest='debug', action='store_true',
help='Pause after starting servers to enable debugging setup')
parser.add_argument('--delete-rtts', dest='delete_rtts', action='store_true',
help='Delete .rtt files after reading, in order to save disk space')
parser.add_argument('-h', '--help', action='help',
help='Show this help message and exit')
parser.add_argument('-6', '--ipv6', dest='ipv6', action='store_const',
const='--ipv6', default='',
help='Use IPv6 for communication (default: use IPv4)')
parser.add_argument('-l', '--log-dir', dest='log_dir',
metavar='D', default=defaults['log_dir'],
help='Directory to use for logs and metrics')
parser.add_argument('--mtu', type=int, dest='mtu',
required=False, metavar='M', default=defaults['mtu'],
help='Maximum allowable packet size (0 means use existing, '
'default: %d)' % (defaults['mtu']))
parser.add_argument('-n', '--nodes', type=int, dest='num_nodes',
required=True, metavar='N',
help='Total number of nodes to use in the cluster')
parser.add_argument('--no-homa-prio', dest='no_homa_prio',
action='store_true', default=False,
help='Don\'t run homa_prio on nodes to adjust unscheduled cutoffs')
parser.add_argument('--plot-only', dest='plot_only', action='store_true',
help='Don\'t run experiments; generate plot(s) with existing data')
parser.add_argument('--port-receivers', type=int, dest='port_receivers',
metavar='count', default=defaults['port_receivers'],
help='Number of threads listening for responses on each Homa '
'client port (default: %d)'% (defaults['port_receivers']))
parser.add_argument('--port-threads', type=int, dest='port_threads',
metavar='count', default=defaults['port_threads'],
help='Number of threads listening on each Homa server port '
'(default: %d)'% (defaults['port_threads']))
parser.add_argument('-p', '--protocol', dest='protocol',
choices=['homa', 'tcp', 'dctcp'], default=defaults['protocol'],
help='Transport protocol to use (default: %s)'
% (defaults['protocol']))
parser.add_argument('-s', '--seconds', type=int, dest='seconds',
metavar='S', default=defaults['seconds'],
help='Run each experiment for S seconds (default: %.1f)'
% (defaults['seconds']))
parser.add_argument('--server-ports', type=int, dest='server_ports',
metavar='count', default=defaults['server_ports'],
help='Number of ports on which each server should listen '
'(default: %d)'% (defaults['server_ports']))
parser.add_argument('--set-ids', dest='set_ids', type=boolean,
default=True, metavar="T/F", help="Boolean value: if true, the "
"next_id sysctl parameter will be set on each node in order to "
"avoid conflicting RPC ids on different nodes (default: true)")
parser.add_argument('--skip', dest='skip',
metavar='nodes',
help='List of node numbers not to use in the experiment; can '
' contain ranges, such as "3,5-8,12"')
parser.add_argument('--stripped', dest='stripped', type=boolean,
default=False, metavar="T/F", help='Boolean value: true means '
'Homa has been stripped for upstreaming, which means some '
'facilities are not available (default: false)')
parser.add_argument('--tcp-client-max', dest='tcp_client_max', type=int,
metavar='count', default=0, help="Maximum number of TCP requests "
"that can be outstanding from a client node at once (divided evenly "
"among the TCP ports); if zero, the "
"--client-max option is used for TCP as well (i.e. each protocol "
"can have that many outstanding requests) (default: 0)")
parser.add_argument('--tcp-client-ports', type=int, dest='tcp_client_ports',
metavar='count', default=defaults['tcp_client_ports'],
help='Number of ports on which each TCP client should issue requests '
'(default: %d)'% (defaults['tcp_client_ports']))
parser.add_argument('--tcp-port-receivers', type=int,
dest='tcp_port_receivers', metavar='count',
default=defaults['tcp_port_receivers'],
help='Number of threads listening for responses on each TCP client '
'port (default: %d)'% (defaults['tcp_port_receivers']))
parser.add_argument('--tcp-port-threads', type=int, dest='tcp_port_threads',
metavar='count', default=defaults['tcp_port_threads'],
help='Number of threads listening on each TCP server port '
'(default: %d)'% (defaults['tcp_port_threads']))
parser.add_argument('--tcp-server-ports', type=int, dest='tcp_server_ports',
metavar='count', default=defaults['tcp_server_ports'],
help='Number of ports on which TCP servers should listen '
'(default: %d)'% (defaults['tcp_server_ports']))
parser.add_argument('--tt-freeze', dest='tt_freeze', type=boolean,
default=True, metavar="T/F", help="Boolean value: if true, "
"timetraces will be frozen on all nodes at the end of the "
"Homa benchmark run (default: true)")
parser.add_argument('--unsched', type=int, dest='unsched',
metavar='count', default=defaults['unsched'],
help='If nonzero, homa_prio will always use this number of '
'unscheduled priorities, rather than computing from workload'
'(default: %d)'% (defaults['unsched']))
parser.add_argument('--unsched-boost', type=float, dest='unsched_boost',
metavar='float', default=defaults['unsched'],
help='Increase the number of unscheduled priorities that homa_prio '
'assigns by this (possibly fractional) amount (default: %.2f)'
% (defaults['unsched_boost']))
parser.add_argument('-v', '--verbose', dest='verbose', action='store_true',
help='Enable verbose output in node logs')
parser.add_argument('-w', '--workload', dest='workload',
metavar='W', default=defaults['workload'],
help='Workload to use for benchmark: w1-w5 or number, empty '
'means try each of w1-w5 (default: %s)'
% (defaults['workload']))
return parser
def choose_nodes(options):
"""
Select which nodes to use for clients and servers in the experiment.
options: Contains command-line options that control the node
selection; fields related to nodes will be created or
replaced if they arleady exist.
"""
skips = {}
if options.skip:
for spec in options.skip.split(","):
nodes = spec.split("-")
if len(nodes) == 1:
skips[int(spec)] = 1
elif len(nodes) == 2:
for i in range(int(nodes[0]), int(nodes[1])+1):
skips[i] = 1
else:
raise Exception("Bad skip range '%s': must be either id "
"or id1-id2" % (spec))
nodes = []
id = 0
while len(nodes) != options.num_nodes:
if not id in skips:
nodes.append(id)
id += 1
options.nodes = nodes
options.servers = options.nodes
options.clients = options.nodes
def init(options):
"""
Initialize various global state, such as the log file.
"""
global log_dir, log_file, verbose, delete_rtts, link_mbps
global stripped
log_dir = options.log_dir
if not options.plot_only:
if os.path.exists(log_dir):
shutil.rmtree(log_dir)
os.makedirs(log_dir)
os.makedirs(log_dir + "/reports")
log_file = open("%s/reports/%s" % (log_dir, options.cperf_log), "a")
verbose = options.verbose
vlog("cperf starting at %s" % (date_time))
s = ""
choose_nodes(options)
# Log configuration information, including options here as well
# as Homa's configuration parameters.
opts = vars(options)
for name in sorted(opts.keys()):
if len(s) != 0:
s += ", "
s += ("--%s: %s" % (name, str(opts[name])))
vlog("Options: %s" % (s))
vlog("Homa configuration (node%d):" % (options.nodes[0]))
result = subprocess.run(['ssh', 'node%d' % (options.nodes[0]),
'sysctl', '-a'], capture_output=True, encoding="iso8859-1")
if (result.returncode != 0):
log("sysctl -a on node%d exited with status %d:" %
(options.nodes[0], result.returncode))
log(result.stderr.rstrip())
for line in result.stdout.splitlines():
match = re.match('.*net.homa.([^ ]+) = (.*)', line)
if match:
name = match.group(1)
value = match.group(2)
vlog(" %-20s %s" % (name, value))
if name == 'link_mbps':
link_mbps = float(value)
if link_mbps == None:
link_mbps = 25000
if options.mtu != 0:
log("Setting MTU to %d" % (options.mtu))
do_ssh(["config", "mtu", str(options.mtu)], options.nodes)
if options.delete_rtts:
delete_rtts = True
def wait_output(string, nodes, cmd, time_limit=10.0):
"""
This method waits until a particular string has appeared on the stdout of
each of the nodes in the list given by nodes. If a long time goes by without
the string appearing, an exception is thrown.
string: The value to wait for
nodes: List of node ids from which output is expected
cmd: Used in error messages to indicate the command that failed
time_limit: An error will be generated if this much time goes by without
the desired string appearing
"""
global active_nodes
outputs = []
printed = False
bad_node = -1
for id in nodes:
while len(outputs) <= id:
outputs.append("")
start_time = time.time()
while True:
if time.time() > (start_time + time_limit):
raise Exception("timeout (%.1fs) exceeded for command '%s' on node%d"
% (time_limit, cmd, bad_node))
for id in nodes:
data = active_nodes[id].stdout.read(1000)
if data != None:
print_data = data
if print_data.endswith(string):
print_data = print_data[:(len(data) - len(string))]
if print_data != "":
log("extra output from node%d: '%s'" % (id, print_data))
outputs[id] += data
bad_node = -1
for id in nodes:
if not string in outputs[id]:
bad_node = id
break
if bad_node < 0:
return
if (time.time() > (start_time + time_limit)) and not printed:
log("expected output from node%d not yet received "
"after command '%s': expecting '%s', got '%s'"
% (bad_node, cmd, string, outputs[bad_node]))
printed = True
time.sleep(0.1)
raise Exception("bad output from node%d after command '%s': "
"expected '%s', got '%s'"
% (bad_node, cmd, string, outputs[bad_node]))
def start_nodes(ids, options):
"""
Start up cp_node on a group of nodes. Also starts homa_prio on the
nodes, if protocol is "homa".
ids: List of node ids on which to start cp_node, if it isn't already
running
options: Command-line options that may affect node configuration
"""
global active_nodes, homa_prios, verbose, log_nodes
started = []
for id in ids:
if not id in active_nodes:
vlog("Starting cp_node on node%d" % (id))
node = subprocess.Popen(["ssh", "-o", "StrictHostKeyChecking=no",
"node%d" % (id), "cp_node"], universal_newlines=True,
stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
fl = fcntl.fcntl(node.stdin, fcntl.F_GETFL)
fcntl.fcntl(node.stdin, fcntl.F_SETFL, fl | os.O_NONBLOCK)
fl = fcntl.fcntl(node.stdout, fcntl.F_GETFL)
fcntl.fcntl(node.stdout, fcntl.F_SETFL, fl | os.O_NONBLOCK)
active_nodes[id] = node
started.append(id)
if options.protocol == "homa":
if options.set_ids:
set_sysctl_parameter(".net.homa.next_id",
str(10000000*(id+1)), [id])
if not options.no_homa_prio:
f = open("%s/homa_prio-%d.log" % (log_dir,id), "w")
homa_prios[id] = subprocess.Popen(["ssh", "-o",
"StrictHostKeyChecking=no", "node%d" % (id), "sudo",
"bin/homa_prio", "--interval", "500", "--unsched",
str(options.unsched), "--unsched-boost",
str(options.unsched_boost)], universal_newlines=True,
stdout=f, stderr=subprocess.STDOUT)
f.close
wait_output("% ", started, "ssh")
log_level = "verbose" if verbose else "normal"
command = "log --file node.log --level %s" % (log_level)
for id in started:
if not id in log_nodes:
do_subprocess(["ssh", "-o", "StrictHostKeyChecking=no",
"node%d" % id, "rm", "-f", "node.log"])
log_nodes[id] = 1
active_nodes[id].stdin.write(command + "\n")
active_nodes[id].stdin.flush()
wait_output("% ", started, command)
def stop_nodes():
"""
Exit all of the nodes that are currently active.
"""
global active_nodes, server_nodes, homa_prios
for id, popen in homa_prios.items():
do_subprocess(["ssh", "-o", "StrictHostKeyChecking=no",
"node%d" % id, "sudo", "pkill", "homa_prio"])
try:
popen.wait(5.0)
except subprocess.TimeoutExpired:
log("Timeout killing homa_prio on node%d" % (id))
homa_prios = {}
for id, node in active_nodes.items():
node.stdin.write("exit\n")
try:
node.stdin.flush()
except BrokenPipeError:
log("Broken pipe to node%d" % (id))
for node in active_nodes.values():
node.wait(5.0)
for id in active_nodes:
do_subprocess(["rsync", "-rtvq", "node%d:node.log" % (id),
"%s/node%d.log" % (log_dir, id)])
active_nodes.clear()
server_nodes = range(0,0)
def do_cmd(command, ids, ids2 = []):
"""
Execute a cp_node command on a given group of nodes.
command: A command to execute on each node
ids: List of node ids on which to run the command
ids2: An optional additional list of node ids on which to run the
command; if a node is present in both r and r2, the
command will only be performed once
"""
global active_nodes
nodes = []
for id in ids:
nodes.append(id)
for id in ids2:
if id not in ids:
nodes.append(id)
for id in nodes:
vlog("Command for node%d: %s" % (id, command))
active_nodes[id].stdin.write(command + "\n")
try:
active_nodes[id].stdin.flush()
except BrokenPipeError:
log("Broken pipe to node%d" % (id))
wait_output("% ", nodes, command)
def do_ssh(command, nodes):
"""
Use ssh to execute a particular shell command on a group of nodes.
command: command to execute on each node (a list of argument words)
nodes: specifies ids of the nodes on which to execute the command:
should be a range, list, or other object that supports "in"
"""
vlog("ssh command on nodes %s: %s" % (str(nodes), " ".join(command)))
for id in nodes:
do_subprocess(["ssh", "node%d" % id] + command)
def get_sysctl_parameter(name, node):
"""
Retrieve the value of a particular system parameter using sysctl on
the given node, and return the value as a string.
name: name of the desired configuration parameter
node: node number on which the value should be retrieved
"""
output = do_subprocess(["ssh", "node%d" % node, "sysctl", name])
match = re.match('.*= (.*)', output)
if not match:
raise Exception("Couldn't parse sysctl output: %s" % output)
return match.group(1)
def set_sysctl_parameter(name, value, nodes):
"""
Modify the value of a system parameter on a group of nodes.
name: name of the sysctl configuration parameter to modify
value: desired value for the parameter
nodes: specifies ids of the nodes on which to execute the command:
should be a range, list, or other object that supports "in"
"""
global stripped
if stripped:
vlog("Skipping set of Homa %s parameter to %s on nodes %s (Homa is stripped)"
% (name, value, str(nodes)))
return
vlog("Setting Homa parameter %s to %s on nodes %s" % (name, value,
str(nodes)))
for id in nodes:
do_subprocess(["ssh", "node%d" % id, "sudo", "sysctl",
"%s=%s" % (name, value)])
def get_baseline_rtt():
"""
Return the "best possible" RTT for short messages, for use in computing
slowdowns.
"""
global baseline_rtts
node_type = get_node_type()
if node_type in baseline_rtts:
return baseline_rtts[node_type]
return baseline_rtts["default"]
def get_node_type():
"""
Returns the node type for this machine.
"""
global node_type
if node_type:
return node_type
f = open("/var/emulab/boot/nodetype")
node_type = f.read().strip()
f.close()
return node_type
def do_subprocess(words):
"""
Invoke subprocess.run to run args in a child process and then
check the results. Log any errors that are detected. Returns
stdout from the child (with trailing newlines removed).
words: List of words for the command to run.
"""
result = subprocess.run(words, capture_output=True, universal_newlines=True)
if (result.returncode != 0):
log("Command %s exited with status %d" % (words, result.returncode))
if (result.stderr != ""):
log("Error output from %s: %s" % (words, result.stderr.rstrip()))
return result.stdout.rstrip()
def start_servers(exp, ids, options):
"""
Starts cp_node servers running on a group of nodes
exp: Name of experiment these servers will be part of
ids: A list of node ids on which to start cp_node servers
options: A namespace that must contain at least the following
keys, which will be used to configure the servers:
server_ports
port_threads
protocol
"""
global server_nodes, stripped
stripped = options.stripped
log("Starting servers for %s experiment on nodes %s" % (exp, ids))
if len(server_nodes) > 0:
do_cmd("stop servers", server_nodes)
server_nodes = []
start_nodes(ids, options)
if options.protocol == "homa":
do_cmd("server --ports %d --port-threads %d --protocol %s --exp %s %s"
% (options.server_ports, options.port_threads,
options.protocol, exp, options.ipv6), ids)
else:
do_cmd("server --ports %d --port-threads %d --protocol %s --exp %s %s"
% (options.tcp_server_ports, options.tcp_port_threads,
options.protocol, exp, options.ipv6), ids)
server_nodes = ids
if options.debug:
input("Pausing for debug setup, type <Enter> to continue: ")
def run_experiment(name, clients, options):
"""
Starts cp_node clients running on a group of nodes, lets the clients run
for an amount of time given by options.seconds, and gathers statistics.
name: Identifier for this experiment, which is used in the names
of files created in the log directory.
clients: List of node numbers on which to run clients
options: A namespace that must contain at least the following attributes,
which control the experiment:
client_max
client_ports
gbps
port_receivers
protocol
seconds
server_ports
servers
tcp_client_ports
tcp_server_ports
workload
"""
global active_nodes, stripped
exp_nodes = list(set(options.servers + list(clients)))
start_nodes(clients, options)
nodes = []
log("Starting clients for %s experiment on nodes %s" % (name, clients))
for id in clients:
if options.protocol == "homa":
command = "client --ports %d --port-receivers %d --server-ports %d " \
"--workload %s --servers %s --gbps %.3f --client-max %d " \
"--protocol %s --id %d --exp %s %s" % (
options.client_ports,
options.port_receivers,
options.server_ports,
options.workload,
",".join([str(x) for x in options.servers]),
options.gbps,
options.client_max,
options.protocol,
id,
name,
options.ipv6)
else:
if "no_trunc" in options:
trunc = '--no-trunc'
else:
trunc = ''
client_max = options.tcp_client_max
if not client_max:
client_max = options.client_max
command = "client --ports %d --port-receivers %d --server-ports %d " \
"--workload %s --servers %s --gbps %.3f %s --client-max %d " \
"--protocol %s --id %d --exp %s %s" % (
options.tcp_client_ports,
options.tcp_port_receivers,
options.tcp_server_ports,
options.workload,
",".join([str(x) for x in options.servers]),
options.gbps,
trunc,
client_max,
options.protocol,
id,
name,
options.ipv6)
active_nodes[id].stdin.write(command + "\n")
try:
active_nodes[id].stdin.flush()
except BrokenPipeError:
log("Broken pipe to node%d" % (id))
nodes.append(id)
vlog("Command for node%d: %s" % (id, command))
wait_output("% ", nodes, command, 40.0)
if options.protocol == "homa":
# Wait a bit so that homa_prio can set priorities appropriately
time.sleep(2)
if stripped:
vlog("Skipping initial read of metrics (Homa is stripped)")
else:
vlog("Recording initial metrics")
for id in exp_nodes:
do_subprocess(["ssh", "node%d" % (id), "metrics.py"])
if options.protocol == "tcp" or options.protocol == "dctcp":
log("Waiting for TCP to warm up...")
time.sleep(10)
if not "no_rtt_files" in options:
do_cmd("dump_times /dev/null %s" % (name), clients)
if options.protocol == "homa" and options.tt_freeze:
log("Unfreezing timetraces on %s" % (nodes))
set_sysctl_parameter(".net.homa.action", "10", nodes)
do_cmd("log Starting measurements for %s experiment" % (name),
server_nodes, clients)
log("Starting measurements")
debug_delay = 0
if debug_delay > 0:
time.sleep(debug_delay)
if False and "dctcp" in name:
log("Setting debug info")
do_cmd("debug 2000 3000", clients)
log("Finished setting debug info")
time.sleep(options.seconds - debug_delay)
if options.protocol == "homa" and options.tt_freeze:
log("Freezing timetraces via node%d" % nodes[0])
set_sysctl_parameter(".net.homa.action", "7", nodes[0:1])
do_cmd("log Ending measurements for %s experiment" % (name),
server_nodes, clients)
log("Retrieving data for %s experiment" % (name))
if not "no_rtt_files" in options:
do_cmd("dump_times rtts %s" % (name), clients)
if (options.protocol == "homa"):
if stripped:
vlog("Skipping final read of metrics (Homa is stripped)")
else:
vlog("Recording final metrics from nodes %s" % (exp_nodes))
for id in exp_nodes:
f = open("%s/%s-%d.metrics" % (options.log_dir, name, id), 'w')
subprocess.run(["ssh", "node%d" % (id), "metrics.py"], stdout=f)
f.close()
shutil.copyfile("%s/%s-%d.metrics" %
(options.log_dir, name, options.servers[0]),
"%s/reports/%s-%d.metrics" %
(options.log_dir, name, options.servers[0]))
shutil.copyfile("%s/%s-%d.metrics" %
(options.log_dir, name, clients[0]),
"%s/reports/%s-%d.metrics" %
(options.log_dir, name, clients[0]))
do_cmd("stop senders", clients)
if False and "dctcp" in name:
do_cmd("tt print cp.tt", clients)
# do_ssh(["sudo", "sysctl", ".net.homa.log_topic=3"], clients)
# do_ssh(["sudo", "sysctl", ".net.homa.log_topic=2"], clients)
# do_ssh(["sudo", "sysctl", ".net.homa.log_topic=1"], clients)
do_cmd("stop clients", clients)
if not "no_rtt_files" in options:
for id in clients:
do_subprocess(["rsync", "-rtvq", "node%d:rtts" % (id),
"%s/%s-%d.rtts" % (options.log_dir, name, id)])
def run_experiments(*args):
"""
Run multiple experiments simultaneously and collect statistics.
args: Each argument is a namespace describing an experiment to
run. The namespace must contain the following values:
name: The name of the experiment; used to create files
with the experiment's results.
clients: List of node numbers on which to run clients for the
experiment.
servers: List of node numbers on which to run servers for the
experiment (if the same server is in multiple
experiments, the parameters from the first experiment
are used to start the server).
protocol: tcp or homa
gbps
seconds
workload
For Homa experiments the following values must be present:
client_max
client_ports
port_receivers
server_ports
port_threads
For TCP experiments the following values must be present:
tcp_client_max (or client_max)
tcp_client_ports
tcp_server_ports
There may be additional optional values that used if present.
"""
global active_nodes, stripped
homa_nodes = []
homa_clients = []
homa_servers= []
tcp_nodes = []
# Prefix to use for Homa metrics files
metrics_name = None
for exp in args:
if exp.protocol == "homa":
homa_clients.extend(exp.clients)
homa_nodes.extend(exp.clients)
homa_servers.extend(exp.servers)
homa_nodes.extend(exp.servers)
if not metrics_name:
metrics_name = exp.name
elif exp.protocol == "tcp":
tcp_nodes.extend(exp.clients)
tcp_nodes.extend(exp.servers)
homa_clients = sorted(list(set(homa_clients)))
homa_servers = sorted(list(set(homa_servers)))
homa_nodes = sorted(list(set(homa_nodes)))
tcp_nodes = sorted(list(set(tcp_nodes)))
all_nodes = sorted(list(set(homa_nodes + tcp_nodes)))
# Start servers for all experiments
stop_nodes()
for exp in args:
if exp.servers:
log("Starting servers for %s experiment on nodes %s" % (exp.name,
exp.servers))
start_nodes(exp.servers, exp)
if exp.protocol == "homa":
do_cmd("server --ports %d --port-threads %d --protocol homa "
"--exp %s %s"
% (exp.server_ports, exp.port_threads,
exp.name, exp.ipv6), exp.servers)
else:
do_cmd("server --ports %d --port-threads %d --protocol tcp "
"--exp %s %s"
% (exp.tcp_server_ports, exp.tcp_port_threads,
exp.name, exp.ipv6), exp.servers)
# Start clients for all experiments
for exp in args:
log("Starting clients for %s experiment on nodes %s" % (exp.name,
exp.clients))
start_nodes(exp.clients, exp)
for id in exp.clients:
if exp.protocol == "homa":
command = "client --ports %d --port-receivers %d --server-ports %d " \
"--workload %s --servers %s --gbps %.3f --client-max %d " \
"--protocol homa --id %d --exp %s %s" % (
exp.client_ports,
exp.port_receivers,
exp.server_ports,
exp.workload,
",".join([str(x) for x in exp.servers]),
exp.gbps,
exp.client_max,
id,
exp.name,
exp.ipv6)
else:
client_max = exp.tcp_client_max
if not client_max:
client_max = exp.client_max
command = "client --ports %d --port-receivers %d --server-ports %d " \
"--workload %s --servers %s --gbps %.3f --client-max %d " \
"--protocol tcp --id %d --exp %s %s" % (
exp.tcp_client_ports,
exp.tcp_port_receivers,
exp.tcp_server_ports,
exp.workload,
",".join([str(x) for x in exp.servers]),
exp.gbps,
client_max,
id,
exp.name,
exp.ipv6)
active_nodes[id].stdin.write(command + "\n")
try:
active_nodes[id].stdin.flush()
except BrokenPipeError:
log("Broken pipe to node%d while starting %s client" % (id,
exp.protocol))
vlog("Command for node%d: %s" % (id, command))
wait_output("% ", exp.clients, command, 40.0)
if homa_clients:
# Wait a bit so that homa_prio can set priorities appropriately
time.sleep(2)
if tcp_nodes:
log("Waiting for TCP to warm up...")