-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy path__init__.py
2390 lines (1925 loc) · 80.9 KB
/
__init__.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 python2
#
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""transperf is a tool to experiment with TCP congestion control.
"""
# Update this version number for each tagged release.
__version__ = "0.1.0"
import collections
import copy
import logging
import math
import md5
import numbers
import os
import socket
import sys
from transperf import path
LOG = logging.getLogger('transperf/init')
_BBR = ['bbr', 'bbr2']
# Static port used to store array into convergence metric.
METRIC_NO_PORT = -1
# The time bucket size in seconds used to check convergence.
CONVERGENCE_BUCKET = 1.0
# TODO(soheil): We should be able to override these in command line arguments.
# Names for built-in NetEm data distributions (no data file needed).
DATA_FILE_KEYWORDS = ['uniform', 'normal', 'pareto', 'paretonormal']
ip_modes = {
4: socket.AF_INET,
6: socket.AF_INET6
}
listen_addrs = {
socket.AF_INET: '0.0.0.0',
socket.AF_INET6: '::',
}
def parse_ip_map(hosts_file):
"""Read hosts file and return a map from hostname to IP."""
ip_map = {}
LOG.info('parse_ip_map: hosts_file=%s', hosts_file)
try:
lines = open(hosts_file).readlines()
for line in lines:
splits = line.rstrip('\r\n').split()
if len(splits) == 2:
ip, host = splits
ip_map[host] = ip
else:
LOG.info('Invalid input line: [%s]', line)
except IOError:
LOG.info('Could not open hosts_file [%s]', hosts_file)
return ip_map
def _type_error(actual, expected):
"""Returns a ValueError that the actual type is not the expected type."""
msg = 'invalid type: %s is not in %s' % (actual.__name__,
[t.__name__ for t in expected])
return ValueError(msg)
def assert_type(ins, *args):
"""Asserts that instance is of one of the expected types.
Args:
ins: The instance.
*args: The expected type.
Raises:
ValueError: If the ins is not an instance of exp_t.
"""
for exp_t in args:
if isinstance(ins, exp_t):
return
raise _type_error(type(ins), args)
def make_iterable(val):
"""If val is not an iterable, it puts the val in a list.
Args:
val: The value.
Returns:
Returns the value if it is iterable, otherwise returns a list that
contains the value.
"""
if isinstance(val, collections.Iterable) and not isinstance(val,
basestring):
return val
return [val]
DEFAULT_CC_PARAMS = {
'bbr': 'flags=0x1,debug_with_printk=1',
'bbr2': 'flags=0x1,debug_with_printk=1',
}
class Burst(object):
"""Represents a burst from netperf.
Attributes:
wait: Inter-burst wait in seconds (can be float) between two rounds.
rounds: How many rounds of repeated request/response to send.
repeat: How many requests and responses send back-to-back per round.
req: Request size.
res: Response size.
"""
def __init__(self, wait, rounds, repeat, req, res):
self.wait = wait
self.rounds = rounds
self.repeat = repeat
self.req = req
self.res = res
def __str__(self):
return 'w%s_r%s_rep%s_req%s_res%s' % (
self.wait, self.rounds, self.repeat, self.req, self.res)
def pretty_str(self):
return 'burst(wait=%s,rounds=%s,repeat=%s,req=%s,res=%s)' % (
self.wait, self.rounds, self.repeat, self.req, self.res)
def burst(wait=-1, rounds=-1, repeat=-1, req=-1, res=-1):
"""Creates a burst specification.
Works only when netperf is compiled with --enable-intervals.
For example, burst(wait=1, rounds=2, repeat=10, req=2000, res=1) will:
1) send 10 back to back 2KB requests and wait to get all 1B reponses.
2) send 10 back to back 2KB requests and wait to get all 1B reponses.
3) sleep for 1sec minus the time spent in 1 and 2.
4) goto 1.
Args:
wait: Inter-burst wait in seconds (can be float) between two rounds.
rounds: How many rounds of repeated request/response to send.
repeat: How many requests and responses send back-to-back per round.
req: Request size.
res: Response size.
Returns:
An object that represents the given burst.
"""
return Burst(wait, rounds, repeat, req, res)
class Tool(object):
"""Represents a tool to run a connection with.
Attributes:
binaries: The name of binaries required to run this tool.
default_path: Default path to run the binaries if not locally available.
paths: A dictionary containing the paths for binaries.
options_dict: Dictionary containing options for tool or None.
"""
def __init__(self, binaries, default_path='', options=None):
self.binaries = binaries
self.default_path = default_path
self.options_dict = options if isinstance(options, dict) else {}
self.paths = dict()
# First look within the binaries resolved by transperf.path. If not
# present, look in the (possibly-per-container) /home/transperf, $PWD,
# or otherwise use the system $PATH.
for binary in binaries:
# First transperf.path
self.paths[binary] = path.resolve_binary_path_for_cmd(binary)
if self.paths[binary] is not None:
continue
# Fallback will be the system path.
self.paths[binary] = binary
# But before falling back, check the (maybe containerized) transperf
# home and current working directory.
for base in [path.get_transperf_home(), os.getcwd()]:
full_path = os.path.join(base, binary)
LOG.info('Checking: %s for existence of %s', full_path, binary)
if os.path.exists(full_path):
LOG.info('Found %s for %s', full_path, binary)
self.paths[binary] = full_path
break
LOG.info('After resolving binaries: paths=%s', str(self.paths))
def sender_cmd(self, conn_, host, port, dur, sender_addr):
"""Returns the command to run the sender connection.
Args:
conn_: Sender connection object.
host: Receiver host.
port: Port to use for this connection.
dur: Duration of experiment.
sender_addr: Address of the sender.
"""
pass
def receiver_cmds(self, senders_port_to_addr, till_start_sec):
"""Returns the receiver commands for this tool.
Args:
senders_port_to_addr: Dict of sender port to address.
till_start_sec: Time till exp start time in second.
"""
# TODO(soheil): add control port.
pass
def throughput(self, output):
"""Returns the throughput out of the tool output."""
pass
def binary_path(self, binary):
"""Returns the binary path depending the system settings."""
return self.paths.get(binary)
def name(self):
"""Returns the name of the tool."""
pass
class Netperf(Tool):
"""Represents netperf (www.netperf.org)."""
def __init__(self):
super(Netperf, self).__init__(binaries=['netperf', 'netserver'])
self.__np_stats = [
'THROUGHPUT',
'THROUGHPUT_UNITS',
'LOCAL_TRANSPORT_RETRANS',
'LOCAL_BYTES_SENT',
]
def sender_cmd(self, conn_, host, port, dur, sender_addr):
binary_path = self.binary_path('netperf')
# connection's duration overrides the experiment duration.
if conn_.dur:
dur = conn_.dur
# If dur is not positive, we cannot run "netperf -l 0/-n" since it will
# run forever. Instead, we run a simple echo that outputs we cannot run
# netperf. This ensures that shell.bg returns a process and
# it outputs useful debug information.
if dur <= 0 and conn_.size <= 0:
return 'echo "cannot run netperf with duration of %s"' % (dur)
# connection's size overrides both connection and experiment durations.
if conn_.size > 0:
dur = -conn_.size
if conn_.upload:
type_args = '-t TCP_MAERTS'
elif conn_.burst and conn_.burst.res:
type_args = '-t TCP_RR'
else:
type_args = ''
burst_args = ''
if conn_.burst:
burst_args = '-w %s' % (1000 * conn_.burst.wait)
if conn_.burst.rounds >= 1:
burst_args += ' -b %s' % conn_.burst.rounds
reqres_args = ('-b %s -r "%s,%s"' % (conn_.burst.repeat,
conn_.burst.req,
conn_.burst.res)
) if conn_.burst else ''
return ('%s %s -H %s -l "%d" %s -- -k "%s" -d send -g -K %s '
'-P %d %s') % (binary_path, type_args, host, dur, burst_args,
','.join(self.__np_stats), conn_.cc, port,
reqres_args)
def receiver_cmds(self, senders_port_to_addr, till_start_sec):
binary_path = self.binary_path('netserver')
ip_mode = self.options_dict.get('ip_mode', '-6')
assert ip_mode in ['-4', '-6']
return ['%s %s -- -g' % (binary_path, ip_mode)]
def throughput(self, output):
for line in output.split('\n'):
if line.startswith('THROUGHPUT='):
return line[len('THROUGHPUT='):]
return ''
def name(self):
return 'netperf'
def __str__(self):
return self.name()
# Supported benchmarking tools in transperf.
NETPERF = Netperf()
TOOLS = {
NETPERF.name(): NETPERF,
}
class Conn(object):
"""Represents a set of connections with one specific congestion control.
Attributes:
cc: The name of the congestion control algorithm.
num: The number of connection of this type.
start: The initial delay before starting the connection in seconds.
dur: The duration of the connection in seconds.
size: The number of bytes to send on the connection.
burst: The connection burst specification (None means an stream).
params: The parameters of the CC kernel module.
sender: The sender machine index.
upload: Whether the connection sends in the opposite direction.
tool: The tool to run for tests.
"""
def __init__(self, cc, num, start, dur, size, burst,
params, sender, upload, tool):
assert_type(cc, basestring)
assert_type(num, int)
assert_type(start, int, float)
assert_type(sender, int)
assert_type(size, int)
assert_type(tool, basestring, Tool)
assert start >= 0, 'connection start time must be positive'
assert dur >= 0, 'connection duration must be positive'
self.cc = cc
self.num = num
self.start = start
self.dur = dur
self.size = size
self.burst = burst
if cc in DEFAULT_CC_PARAMS and DEFAULT_CC_PARAMS[cc] not in params:
self.params = DEFAULT_CC_PARAMS[cc] + ',' + params
else:
self.params = params
self.sender = sender
self.upload = upload
if isinstance(tool, basestring):
self.tool = TOOLS.get(tool)
else:
self.tool = tool
def burst_tuple(self):
"""Returns the tuple representing the burst."""
return (self.burst.wait, self.burst.rounds, self.burst.repeat,
self.burst.req, self.burst.res) if self.burst else None
def __str__(self):
# TODO(soheil): We can later use this notation in the config files as an
# alternative of using conn().
if self.num > 1:
s = '%s%ss' % (self.num, self.cc)
else:
s = self.cc
if self.sender:
s += '@%s' % self.sender
if self.start:
s += ':%s' % self.start
if self.dur:
s += '-%s' % self.dur
if self.size:
s += 's%s' % md5.md5(str(self.size)).hexdigest()[:8]
if self.burst:
s += 'b%s' % md5.md5(str(self.burst)).hexdigest()[:8]
if self.params:
s += 'p%s' % md5.md5(self.params).hexdigest()[:8]
if self.upload:
s += 'up'
if self.tool:
s += 't%s' % self.tool
return s
def pretty_str(self):
"""Returns a prettified representation of this connection."""
burst_str = self.burst.pretty_str() if self.burst else 'None'
return ('conn(cc="%s",num=%s,sender=%s,start=%s,dur=%s,size=%s,'
'burst=%s,params=%s,upload=%s,tool=%s)') % (
self.cc, self.num, self.sender, self.start, self.dur,
self.size, burst_str, self.params, self.upload, self.tool)
def conn(cc, num=1, start=0, dur=0, size=0,
burst=None, params='', sender=0, upload=False, tool=NETPERF):
"""Creates a connection.
Args:
cc: The name of the congestion control algorithm.
num: The number of connection of this type.
start: The initial delay before starting the connection in seconds.
dur: The duration of the connection in seconds.
size: The number of bytes to send on the connection.
burst: The connection burst specification (None means an stream).
params: The parameters of the CC kernel module.
sender: The index of the sender machine.
upload: Whether the connection sends in the opposite direction.
tool: The tool to run for tests.
Returns:
An object that represents the given connection.
"""
return Conn(cc, num, start, dur, size, burst, params, sender, upload, tool)
class Conns(object):
"""Represents a set of Conns that are run together in the same experiment.
Attributes:
conn_list: The list of connection sets.
nsenders: The number of sender machines required for conn_list.
nconns: The number of connections.
"""
def __init__(self, conn_list):
if not conn_list:
raise ValueError('conn_list cannot be empty')
for i, c in enumerate(conn_list):
if isinstance(c, basestring):
conn_list[i] = conn(cc=c)
senders = dict()
autoselect = 0
max_sender = 0
self.nconns = 0
for c in conn_list:
assert_type(c, Conn)
self.nconns += c.num
# Count each -1 as one sender.
if c.sender < 0:
autoselect += 1
continue
senders[c.sender] = True
max_sender = max(c.sender, max_sender)
self.conn_list = conn_list
self.nsenders = len(senders) + autoselect
if max_sender != self.nsenders - 1:
raise RuntimeError('There is a gap in the senders used in a conn')
def __nonzero__(self):
return len(self.conn_list)
def __str__(self):
return '+'.join([str(c) for c in self.conn_list])
def pretty_str(self):
"""Returns the prettified representation of this connection set."""
return 'conns(%s)' % (', '.join([c.pretty_str()
for c in self.conn_list]))
def conns(*args):
"""Creates an instance of Conns.
Args:
*args: This only accepts instances of Conn and strings.
Returns:
An object that represents the given connection.
"""
for c in args:
assert_type(c, basestring, Conn)
return Conns(list(args))
class Bandwidth(object):
"""Represents a temporal bandwidth (a bw valid for a specific duration).
Attributes:
downlink: The downlink bandwidth in Mbps.
uplink: The uplink bandwidth in Mbps. If 0, downlink is used.
dur: The duration of this bandwidth in seconds. Zero means for
ever. Note that this value is relative and the exact time that this
bandwidth is enforced based on the previous bandwidths used in the
experiment.
"""
def __init__(self, downlink, uplink, dur):
assert_type(downlink, int, float)
assert_type(uplink, int, float)
assert_type(dur, int)
self.downlink = downlink
self.uplink = uplink if uplink else downlink
self.dur = dur
def __nonzero__(self):
return bool(self.downlink or self.uplink or self.dur)
def __str__(self):
rate = ('%s' % self.downlink if self.downlink == self.uplink else
'%s_%s' % (self.downlink, self.uplink))
if self.dur:
return '%s@%s' % (rate, self.dur)
return '%s' % rate
def pretty_str(self):
"""Returns the pretified representation of this bandwidth."""
if not self:
return 'UNLIMITED_BW'
return 'bw(downlink=%s,uplink=%s,dur=%s)' % (self.downlink, self.uplink,
self.dur)
class VarBandwidth(object):
"""Represents a variable bandwidth.
Attributes:
bws: The sequence of bandwidths.
"""
def __init__(self, bws):
for i, w in enumerate(bws):
if isinstance(w, int) or isinstance(w, float):
bws[i] = bw(w)
self.bws = bws
def __str__(self):
return '_'.join([str(w) for w in self.bws])
def pretty_str(self):
"""Represents a prettified representation of the variable BW."""
return 'var_bw(%s)' % ', '.join(bw.pretty_str() for bw in self.bws)
def bw(downlink, uplink=0, dur=0):
"""Creates a Bandwidth instance with the given rates and duration.
Args:
downlink: The rate in Mbps for downlink.
uplink: The rate in Mbps for uplink. If 0, downlink is used for uplink.
dur: The duration in seconds.
Returns:
The Bandwidth instance.
"""
return Bandwidth(downlink, uplink, dur)
def var_bw(*args):
"""Returns a variable bandwidth object using args."""
return VarBandwidth(list(args))
UNLIMITED_BW = bw(0)
class Distribution(object):
"""Represents a probably distribution function.
Attributes:
mean: mean value (middle of the distribution)
var: jitter value. With no data file, the value is distributed
uniformly in [mean-var, mean+var]. If the file is present, then
the value varies between (mean - var * min(norm_table)) and
(mean + var * max(norm_table)), according to the cumulative
distribution function in the table. Here, the "norm_table" value
is any 16-bit integer from the data file divided by 8096, so
its maximum range is [-4, 4]. If the data file is a normal
distribution and "var" is the standard deviation, that means it
can cover +/- 4 stddev lengths. However, if values in the data
file range [0, 8096], then "var" is more like a scaling factor,
and the distribution will range just [mean, mean+var].
data_file: data file in the format that NetEm expects (16-bit ints in
ASCII format). Usually generated by NetEm maketable.c utility.
"""
def __init__(self, mean, var, data_file=None):
if float(var) < 0:
raise ValueError('var is negative')
self.mean = float(mean)
self.var = float(var)
self.data_file = data_file
def __str__(self):
if self.data_file:
return '%f+/-%f:%s' % (self.mean, self.var, self.data_file)
else:
return '[%f,%f]' % (self.mean - self.var, self.mean + self.var)
def pretty_str(self):
"""Represents a prettified representation of the Distribution."""
if self.data_file:
return 'distribution(mean=%f,var=%f,data_file=%s)' % (
self.mean, self.var, self.data_file)
else:
return 'uniform_distribution([%f,%f])' % (
self.mean - self.var, self.mean + self.var)
def netem_dist_name(self):
"""Returns the distribution name to pass to netem if available."""
if not self.data_file:
return None
return os.path.splitext(os.path.basename(self.data_file))[0]
def serialize(self):
"""Returns data that can be sent over XmlRpc for this object."""
return {'mean': self.mean, 'var': self.var, 'data_file': self.data_file}
@classmethod
def deserialize(cls, data):
"""Uses data from serialize() to construct an identical object."""
return cls(**data)
def uniform_distribution(min_, max_):
"""Creates a uniform Distribution instance in range [min_, max_].
Args:
min_: Min value of the uniform range.
max_: Max value of the uniform range.
Returns:
The Distribution instance.
Raises:
ValueError: If max_ < min_.
"""
if max_ < min_:
raise ValueError('max_ cannot be smaller than min_')
return Distribution((max_ + min_) / 2.0, (max_ - min_) / 2.0)
def distribution(mean, var, data_file):
"""Creates a non-uniform Distribution instance based on the arguments.
Distributions are used in NetEm for the delay and slot models, to
specify something other than a uniform probability. Values in data_file
represent a cumulative distribution function scaled according to
((x / 8192 * var) + mean). Values must be in the range +/-32767
(16-bit integer) and the middle value (0) is typically the mean,
but it doesn't have to be. If the values span 0-8192, for example,
then the mean is just an offset and the var is a scale for the overall
range.
The data_file can also be "normal" or other *.dist files in /usr/lib/tc
that come along with the standard installation for NetEm.
Args:
mean: offset for the distribution range.
var: scale for the distribution range.
data_file: data file generated by NetEm maketable.c utility.
Raises:
ValueError: If var < 0.
Returns:
The Distribution instance.
"""
if var < 0:
raise ValueError('var is negative')
return Distribution(mean, var, data_file)
class RTT(object):
"""Represents a round trip time.
Attributes:
val: The RTT value in milliseconds.
dur: The duration of this RTT in seconds.
var: The inbound variation in RTT in milliseconds.
out_var: The outbound variation in RTT in milliseconds.
in_dist: Distribution of values for inbound part of RTT in msec.
out_dist: Distribution of values for outbound part of RTT in msec.
sender: The sender which this RTT value applies to.
"""
def __init__(self, val, dur, var, out_var, in_dist, out_dist, sender):
self.dur = dur
self.sender = sender
self.in_dist = in_dist
self.out_dist = out_dist
# Make sure that inputs are not over-specified.
if in_dist and out_dist:
total_val = in_dist.mean + out_dist.mean
if val and total_val != val:
raise ValueError("RTT value '%s' does not agree with "
"inbound/outbound distributions" % val)
val = total_val
if in_dist:
if var and var != in_dist.var:
raise ValueError("RTT var '%s' does not agree with "
"in_dist distribution" % var)
var = in_dist.var
if out_dist:
if out_var and out_var != out_dist.var:
raise ValueError("RTT out_var '%s' does not agree with "
"out_dist distribution" % out_var)
out_var = out_dist.var
# Capture overall RTT characteristics.
self.val = val
self.var = var
self.out_var = out_var
def __nonzero__(self):
return bool(self.val or self.dur or self.var or
self.in_dist or self.out_dist)
def __str__(self):
s = '%s' % self.val
if self.dur:
s += ':%s' % self.dur
if self.in_dist:
s += 'in(%s)' % self.in_dist
elif self.var:
s += 'v%s' % self.var
if self.out_dist:
s += 'out(%s)' % self.out_dist
elif self.out_var:
s += 'o%s' % self.out_var
if self.sender:
s += '@%s' % self.sender
return s
def pretty_str(self):
"""Represents a prettified representation of the RTT."""
if not self:
return 'NO_DELAY'
return ('rtt(%s,dur=%s,var=%s,out_var=%s,'
'in_dist=%s,out_dist=%s,sender=%s)' % (
self.val, self.dur, self.var, self.out_var,
self.in_dist, self.out_dist, self.sender))
def serialize(self):
"""Returns data that can be sent over XmlRpc for this object."""
return {
'val': self.val,
'dur': self.dur,
'var': self.var,
'out_var': self.out_var,
'in_dist': self.in_dist.serialize() if self.in_dist else None,
'out_dist': self.out_dist.serialize() if self.out_dist else None,
'sender': self.sender,
}
@classmethod
def deserialize(cls, data):
"""Uses data from serialize() to construct an identical object."""
if 'in_dist' in data and data['in_dist']:
data['in_dist'] = Distribution.deserialize(data['in_dist'])
if 'out_dist' in data and data['out_dist']:
data['out_dist'] = Distribution.deserialize(data['out_dist'])
return cls(**data)
def rtts_of_sender(self, sender):
"""Returns the RTT seqeuence of the given sender."""
if self.sender != 0 and self.sender != sender:
raise ValueError('invalid sender passed to fixed rtt %s' % sender)
c = copy.deepcopy(self)
c.sender = sender
return [c]
def get_data_files(self):
"""Returns a list of data files embedded in this RTT model."""
files = []
for d in [self.in_dist, self.out_dist]:
if d and d.data_file:
files.append(d.data_file)
return files
class MixedRTT(object):
"""Represents round trip times that are different for each sender.
Attributes:
rtts: The dictionary of senders to their RTTs. There must be only 1 RTT
per sender. If no RTT is provided for a specific sender we reuse
the RTT of sender 0.
dur: The duration that this mixed RTT is valid in seconds.
"""
def __init__(self, rtts, dur):
"""Initializes the MixedRTT.
Args:
rtts: The list of RTTs. There must be only one RTT per sender.
dur: The duration that this mixed RTT is valid in seconds.
Raises:
ValueError: If any parameter is invalid.
"""
rtt_dict = dict()
for t in rtts:
assert_type(t, RTT, int)
if isinstance(t, int) or isinstance(t, float):
t = rtt(t)
if rtt_dict.get(t.sender):
raise ValueError('duplicate RTT value for %s' % t.sender)
rtt_dict[t.sender] = t
if 0 not in rtt_dict:
raise ValueError('no RTT provided for sender 0')
self.rtts = rtt_dict
self.dur = dur
def rtts_of_sender(self, sender):
"""Returns the RTT of the sender."""
srtt = self.rtts.get(sender)
if srtt:
srtt = copy.deepcopy(srtt)
else:
srtt = copy.deepcopy(self.rtts[0])
srtt.dur = self.dur
return [srtt]
def get_data_files(self):
"""Returns a list of data files embedded in this RTT model."""
return sum([rtt_.get_data_files() for rtt_ in self.rtts.values()], [])
def __str__(self):
senders_str = ':::'.join([str(t) for _, t in self.rtts.iteritems()])
return '%s:@:%s' % (senders_str, self.dur)
def pretty_str(self):
"""Returns a pretty representation of the mixed RTT."""
return 'mixed_rtt(%s, dur=%s)' % (', '.join([t.pretty_str() for _, t in
self.rtts.iteritems()]),
self.dur)
class VarRTT(object):
"""Represents a round trip time that changes over time.
Attributes:
rtts: The list of RTTs. All RTTs except the last one must have a
duration.
"""
def __init__(self, rtts):
for i, t in enumerate(rtts):
assert_type(t, MixedRTT, RTT, int)
if isinstance(t, int) or isinstance(t, float):
rtts[i] = rtt(t)
for t in rtts[:-1]:
if not t.dur:
raise ValueError('in a var RTT, all RTTs except the last'
'one must have a duration')
self.rtts = rtts
def rtts_of_sender(self, sender):
"""Returns the sequence of RTTs of the given sender."""
for t in self.rtts:
for st in t.rtts_of_sender(sender):
yield st
def get_data_files(self):
"""Returns a list of data files embedded in this RTT model."""
return sum([rtt_.get_data_files() for rtt_ in self.rtts], [])
def __str__(self):
return '_'.join([str(rtt_) for rtt_ in self.rtts])
def pretty_str(self):
"""Returns a pretty representation of the variable RTT."""
return 'var_rtt(%s)' % ', '.join([rtt_.pretty_str()
for rtt_ in self.rtts])
def rtt(val=None, dur=0, var=0, out_var=0, in_dist=None, out_dist=None,
sender=0):
"""Creates an RTT instance.
Args:
val: Is the round trip time in milliseconds.
dur: The duration of this RTT in seconds.
var: The variation in inbound RTT.
out_var: The variation in outbound RTT.
in_dist: Distribution of values for inbound part of RTT in msec.
out_dist: Distribution of values for outbound part of RTT in msec.
sender: The sender which this RTT applies to.
Returns:
An object that represents the given RTT.
Raises:
ValueError: No overall RTT or in/out dist values (empty definition).
"""
if val is None and (in_dist is None or out_dist is None):
raise ValueError('must specify val or in_dist/out_dist for rtt')
return RTT(val, dur, var, out_var, in_dist, out_dist, sender)
def mixed_rtt(*args, **kwargs):
"""Creates different rtts for each sender sender.
For example:
mixed_rtt(rtt(100, sender=0), rtt(10, sender=1))
Can be mixed with var_rtt:
var_rtt(
mixed_rtt(rtt(100, sender=0), rtt(10, sender=1), dur=100),
rtt(10)
)
Args:
*args: The list of RTTs.
**kwargs: only accepts "dur" which is the duration for which this
mixed_rtt is valid.
Raises:
ValueError: If any parameter is invalid.
Returns:
An object that represents the given RTT.
"""
if not kwargs:
return MixedRTT(args, dur=0)
if len(kwargs) == 1 and 'dur' in kwargs:
return MixedRTT(args, dur=kwargs['dur'])
raise ValueError('invalid named parameters passed to mixed_rtt')
def var_rtt(*args):
"""Creates a variable RTT.
Args:
*args: A list of RTTs and MixedRTTs
Returns:
An object that represents the given RTTs.
"""
return VarRTT(list(args))
NO_DELAY = rtt(0)
class Slot(object):
"""Represents a time slot configuration of netem for one direction.
Attributes:
dist: Distribution of slot interval in msec. Required.
max_bytes: Max number of bytes delivered per slot. Ignored when 0.
max_pkts: Max number of pkts delivered per slot. Ignored when 0.
"""
def __init__(self, dist, max_bytes, max_pkts):
assert_type(dist, Distribution)
assert_type(max_bytes, int)
assert_type(max_pkts, int)
if not dist.data_file:
if dist.mean < 0:
raise ValueError(
'Distribution mean < 0 for uniform. mean:%f' % dist.mean)
if dist.var < 0:
raise ValueError(
'Distribution var < 0 for uniform. var:%f' % dist.var)
if dist.mean - dist.var < 0:
raise ValueError(
'Distribution mean - var < 0 for uniform. mean:%f var:%f' %
(dist.mean, dist.var))
if max_bytes < 0:
raise ValueError('max_bytes < 0: %d' % max_bytes)
if max_pkts < 0:
raise ValueError('max_pkts < 0: %d' % max_pkts)
self.dist = dist
self.max_bytes = max_bytes