forked from tohojo/flent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
runners.py
2583 lines (2152 loc) · 97.2 KB
/
runners.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
# -*- coding: utf-8 -*-
#
# runners.py
#
# Author: Toke Høiland-Jørgensen (toke@toke.dk)
# Date: 16 October 2012
# Copyright (c) 2012-2016, Toke Høiland-Jørgensen
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from __future__ import absolute_import, division, print_function, unicode_literals
import hashlib
import hmac
import math
import os
import re
import shlex
import signal
import socket
import subprocess
import sys
import tempfile
import threading
import time
from datetime import datetime
from calendar import timegm
from threading import Event
from flent import util, transformers
from flent.build_info import DATA_DIR
from flent.util import classname, ENCODING, Glob, normalise_host
from flent.loggers import get_logger
try:
import ujson as json
except ImportError:
import json
mswindows = (sys.platform == "win32")
try:
from defusedxml.xmlrpc import monkey_patch
monkey_patch()
del monkey_patch
XML_DEFUSED = True
except ImportError:
XML_DEFUSED = False
try:
# python 2
import xmlrpclib as xmlrpc
except ImportError:
import xmlrpc.client as xmlrpc
logger = get_logger(__name__)
if mswindows:
def _handle_exitstatus(sts):
raise NotImplementedError(
"Subprocess management currently doesn't work on Windows")
else:
# helper function from subprocess module
def _handle_exitstatus(sts, _WIFSIGNALED=os.WIFSIGNALED,
_WTERMSIG=os.WTERMSIG, _WIFEXITED=os.WIFEXITED,
_WEXITSTATUS=os.WEXITSTATUS):
# This method is called (indirectly) by __del__, so it cannot
# refer to anything outside of its local scope."""
if _WIFSIGNALED(sts):
return -_WTERMSIG(sts)
elif _WIFEXITED(sts):
return _WEXITSTATUS(sts)
else:
# Should never happen
raise RuntimeError("Unknown child exit status!")
class ParseError(Exception):
pass
class RunnerCheckError(Exception):
pass
def get(name):
cname = classname(name, "Runner")
if cname not in globals():
raise RuntimeError("Runner not found: '%s'" % name)
return globals()[cname]
MARKING_MAP = {'AF11': 0x28,
'AF12': 0x30,
'AF13': 0x38,
'AF21': 0x48,
'AF22': 0x50,
'AF23': 0x58,
'AF31': 0x68,
'AF32': 0x70,
'AF33': 0x78,
'AF41': 0x88,
'AF42': 0x90,
'AF43': 0x98,
'CS0': 0x00,
'CS1': 0x20,
'CS2': 0x40,
'CS3': 0x60,
'CS4': 0x80,
'CS5': 0xa0,
'CS6': 0xc0,
'CS7': 0xe0,
'EF': 0xb8}
class RunnerBase(object):
transformed_metadata = []
def __init__(self, name, settings, idx=None, start_event=None,
finish_event=None, kill_event=None, parent=None,
watchdog_timer=None, **kwargs):
super(RunnerBase, self).__init__()
self.name = name
self.settings = settings
self.idx = idx
self.test_parameters = {}
self._raw_values = []
self._result = []
self.command = None
self.returncode = 0
self.out = self.err = ''
self._parent = parent
self.result = None
self.start_event = start_event
self.kill_event = kill_event or Event()
self.finish_event = finish_event or Event()
self.watchdog_timer = watchdog_timer
self._watchdog = None
self._child_runners = []
self._pickled = False
self.metadata = {'RUNNER': self.__class__.__name__, 'IDX': idx}
self.runner_args = kwargs
def __getstate__(self):
state = {}
for k, v in self.__dict__.items():
if k not in ('start_event', 'kill_event', 'finish_event',
'kill_lock', 'stdout', 'stderr') \
and not k.startswith("_"):
state[k] = v
state['_pickled'] = True
return state
def check(self):
pass
# Emulate threading interface to fit into aggregator usage.
def start(self):
if self._pickled:
raise RuntimeError("Attempt to run a pickled runner")
for c in self._child_runners:
c.start()
self.start_watchdog()
s = super(RunnerBase, self)
if hasattr(s, 'start'):
s.start()
logger.debug("Started %s idx %d ('%s')", self.__class__.__name__,
self.idx, self.name)
def join(self, timeout=None):
s = super(RunnerBase, self)
if hasattr(s, 'join'):
s.join(timeout)
for c in self._child_runners:
c.join(timeout)
def is_alive(self):
alive = []
s = super(RunnerBase, self)
if hasattr(s, "is_alive"):
alive.append(s.is_alive())
alive.extend([c.is_alive() for c in self._child_runners])
return any(alive)
def kill(self, graceful=False):
for c in self._child_runners:
c.kill(graceful)
self.kill_event.set()
def run(self):
if self.start_event is not None:
self.start_event.wait()
self._run()
self.finish_event.set()
if self._watchdog:
self._watchdog.kill()
logger.debug("%s %s finished", self.__class__.__name__,
self.name, extra={'runner': self})
def start_watchdog(self):
if self._watchdog or not self.watchdog_timer:
return
logger.debug("%s: Starting watchdog with timeout %d",
self.name, self.watchdog_timer)
self._watchdog = TimerRunner(self.watchdog_timer,
name="Watchdog [%s]" % self.name,
idx=self.idx,
settings=self.settings,
start_event=self.start_event,
kill_event=self.kill_event,
parent=self)
self.kill_event = self._watchdog.finish_event
self._watchdog.start()
def add_child(self, cls, **kwargs):
logger.debug("%s: Adding child %s", self.name, cls.__name__)
c = cls(name="%s :: child %d" % (self.name, len(self._child_runners)),
settings=self.settings,
idx=self.idx,
start_event=self.start_event,
kill_event=self.kill_event,
parent=self, **kwargs)
c.check()
self._child_runners.append(c)
return c
@property
def child_results(self):
for c in self._child_runners:
res = c.result
if res and hasattr(res, 'items'):
yield res
def get_raw_values(self):
if not self._child_runners:
return self._raw_values
vals = list(self._raw_values)
for c in self._child_runners:
vals.extend(c.raw_values)
return sorted(vals, key=lambda v: v['t'])
def set_raw_values(self, val):
self._raw_values = val
raw_values = property(get_raw_values, set_raw_values)
class DelegatingRunner(RunnerBase):
@property
def child_results(self):
return iter([])
def get_metadata(self):
md = {}
for c in self._child_runners:
md.update(c.metadata)
return md
def set_metadata(self, val):
pass
metadata = property(get_metadata, set_metadata)
def _combine(self, vals):
if not vals:
return vals
if hasattr(vals[0], 'keys'):
r = {}
for v in vals:
if v:
r.update(v)
else:
r = []
for v in vals:
if v:
r.extend(v)
return r
def get_result(self):
return self._combine([c.result for c in self._child_runners])
def set_result(self, val):
pass
result = property(get_result, set_result)
def _run(self):
for c in self._child_runners:
c.join()
class TimerRunner(RunnerBase, threading.Thread):
def __init__(self, timeout, **kwargs):
super(TimerRunner, self).__init__(**kwargs)
self.timeout = timeout
self.command = 'Timeout after %f seconds' % self.timeout
def _run(self):
self.kill_event.wait(self.timeout)
logger.debug("%s %s: timer expired", self.__class__.__name__,
self.name, extra={'runner': self})
class FileMonitorRunner(RunnerBase, threading.Thread):
def __init__(self, filename, length, interval, delay, **kwargs):
super(FileMonitorRunner, self).__init__(**kwargs)
self.filename = filename
self.length = length
self.interval = interval
self.delay = delay
self.metadata['FILENAME'] = self.filename
self.command = 'File monitor for %s' % self.filename
def _run(self):
if self.delay:
self.kill_event.wait(self.delay)
if not self.kill_event.is_set():
start_time = current_time = time.time()
result = []
# Add an extra interval to comparison to avoid getting one too few
# samples due to small time differences.
while current_time < start_time + self.length + self.interval \
and not self.kill_event.is_set():
try:
with open(self.filename, 'r') as fp:
val = fp.read()
self.out += val
try:
val = float(val)
result.append((current_time, val))
except ValueError:
val = val.strip()
self._raw_values.append({'t': current_time, 'val': val})
except IOError as e:
self.err += "Error opening file {}: {}\n".format(
self.filename, e)
finally:
self.kill_event.wait(self.interval)
current_time = time.time()
if result:
self.result = result
else:
self.returncode = 1
class ProcessRunner(RunnerBase, threading.Thread):
"""Default process runner for any process."""
silent = False
silent_exit = False
supports_remote = True
_env = {}
def __init__(self, delay=0, remote_host=None, units=None, **kwargs):
super(ProcessRunner, self).__init__(**kwargs)
self.delay = delay
self.remote_host = normalise_host(remote_host)
self.units = units
self.killed = False
self.pid = None
self.returncode = None
self.kill_lock = threading.Lock()
self.test_parameters = {}
self.stdout = None
self.stderr = None
self.command = None
def check(self):
if self.command is None:
raise RunnerCheckError("No command set for %s" %
self.__class__.__name__)
if self.units:
self.metadata['UNITS'] = self.units
# Rudimentary remote host capability. Note that this is modifying the
# final command, so all the find_* stuff must match on the local and
# remote hosts. I.e. the same binaries must exist in the same places.
if self.remote_host:
if not self.supports_remote:
raise RunnerCheckError(
"%s (idx %d) does not support running on remote hosts." % (
self.__class__.__name__, self.idx))
self.command = "ssh %s '%s'" % (self.remote_host, self.command)
self.metadata['REMOTE_HOST'] = self.remote_host
self.args = shlex.split(self.command)
self.metadata['COMMAND'] = self.command
def handle_usr2(self, signal, frame):
if self.start_event is not None:
self.start_event.set()
def fork(self):
# Use named temporary files to avoid errors on double-delete when
# running on Windows/cygwin.
try:
self.stdout = tempfile.NamedTemporaryFile(
prefix="flent-", delete=False)
self.stderr = tempfile.NamedTemporaryFile(
prefix="flent-", delete=False)
except OSError as e:
if e.errno == 24:
raise RuntimeError(
"Unable to create temporary files because too many "
"files are open. Try increasing ulimit.")
else:
raise RuntimeError("Unable to create temporary files: %s" % e)
pid = os.fork()
if pid == 0:
os.dup2(self.stdout.fileno(), 1)
os.dup2(self.stderr.fileno(), 2)
self.stdout.close()
self.stderr.close()
signal.signal(signal.SIGTERM, signal.SIG_DFL)
try:
if self.start_event is not None:
signal.signal(signal.SIGUSR2, self.handle_usr2)
self.start_event.wait()
signal.signal(signal.SIGUSR2, signal.SIG_DFL)
time.sleep(self.delay)
except:
os._exit(0)
env = dict(os.environ)
env.update(self._env)
prog = self.args[0]
os.execvpe(prog, self.args, env)
else:
logger.debug("Forked %s as pid %d", self.args[0], pid)
self.pid = pid
def kill(self, graceful=False):
super(ProcessRunner, self).kill(graceful)
if graceful:
# Graceful shutdown is done on a best-effort basis, and may results
# in some errors from the test tools. We don't print these, since
# they are expected.
self.silent = True
else:
with self.kill_lock:
self.killed = True
self.cleanup_tmpfiles()
if self.pid is not None:
sig = signal.SIGINT if graceful else signal.SIGTERM
logger.debug("Sending signal %d to pid %d.", sig, self.pid)
try:
os.kill(self.pid, sig)
except OSError:
pass
def cleanup_tmpfiles(self):
for f in self.stdout, self.stderr:
if f is not None:
try:
f.close()
except OSError:
pass
try:
os.unlink(f.name)
except OSError:
pass
def is_killed(self):
with self.kill_lock:
return self.killed
def start(self):
if mswindows:
raise RuntimeError(
"Process management currently doesn't work on Windows, "
"so running tests is not possible.")
logger.debug("Forking to run command %s", self.command)
self.fork()
super(ProcessRunner, self).start()
def run(self):
"""Runs the configured job. If a delay is set, wait for that many
seconds, then open the subprocess, wait for it to finish, and collect
the last word of the output (whitespace-separated)."""
if self.start_event is not None:
self.start_event.wait()
try:
os.kill(self.pid, signal.SIGUSR2)
except OSError:
pass
if self.kill_event is None:
pid, sts = os.waitpid(self.pid, 0)
else:
pid, sts = os.waitpid(self.pid, os.WNOHANG)
while (pid, sts) == (0, 0):
self.kill_event.wait(1)
if self.kill_event.is_set():
self.silent_exit = True
logger.debug("%s %s killed by kill event",
self.__class__.__name__,
self.name, extra={'runner': self})
try:
logger.debug("Sending SIGINT to pid %d", self.pid)
os.kill(self.pid, signal.SIGINT)
time.sleep(0.5)
logger.debug("Sending SIGTERM to pid %d", self.pid)
os.kill(self.pid, signal.SIGTERM)
except OSError:
pass
pid, sts = os.waitpid(self.pid, os.WNOHANG)
self.finish_event.set()
self.returncode = _handle_exitstatus(sts)
# Even with locking, kill detection is not reliable; sleeping seems to
# help. *sigh* -- threading.
time.sleep(0.2)
if self.is_killed():
return
self.stdout.seek(0)
self.out += self.stdout.read().decode(ENCODING)
try:
# Close and remove the temporary file. This might fail, but we're
# going to assume that is okay.
filename = self.stdout.name
self.stdout.close()
os.unlink(filename)
except OSError:
pass
self.stderr.seek(0)
self.err += self.stderr.read().decode(ENCODING)
try:
filename = self.stderr.name
self.stderr.close()
os.unlink(filename)
except OSError:
pass
if self.returncode and not (self.silent or self.silent_exit):
logger.warning("Program exited non-zero.",
extra={'runner': self})
self.result = self.parse(self.out, self.err)
if not self.result and not self.silent:
logger.warning("Command produced no valid data.",
extra={'runner': self})
logger.debug("%s %s finished", self.__class__.__name__,
self.name, extra={'runner': self})
def parse(self, output, error=""):
"""Default parser returns the last (whitespace-separated) word of
output as a float."""
return float(output.split()[-1].strip())
def run_simple(self, args, kill=None, errmsg=None):
if self.remote_host:
args = ['ssh', self.remote_host, ' '.join(args)]
if kill:
kill = max(kill, 1)
try:
proc = subprocess.run(args, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, timeout=kill)
out = proc.stdout.decode(ENCODING)
err = proc.stderr.decode(ENCODING)
ret = proc.returncode
except subprocess.TimeoutExpired as e:
out = e.stdout.decode(ENCODING) if e.stdout else ""
err = e.stderr.decode(ENCODING) if e.stderr else ""
ret = 1
if ret != 0 and errmsg:
raise RunnerCheckError(errmsg.format(err=err))
return out, err
def _get_marking(self, marking):
mk = marking.upper()
if mk in MARKING_MAP:
mkval = MARKING_MAP[mk]
elif mk in self.settings.MARKING_NAMES:
mkval = self.settings.MARKING_NAMES[mk]
else:
try:
mkval = util.parse_int(marking)
except ValueError:
raise RuntimeError("Invalid marking: %s" % marking)
return "0x%x" % mkval
def parse_marking(self, marking, fmtstr, paired=False):
"""Convert netperf-style textual marking specs into integers"""
if marking is not None:
try:
mk = marking.split(",")
if paired and len(mk) > 1:
return fmtstr.format("{},{}".format(self._get_marking(mk[0]),
self._get_marking(mk[1])))
return fmtstr.format(self._get_marking(mk[0]))
except (AttributeError, KeyError):
return fmtstr.format(self.marking)
return ""
DefaultRunner = ProcessRunner
class SilentProcessRunner(ProcessRunner):
silent = True
def parse(self, output, error=""):
return None
class DitgRunner(ProcessRunner):
"""Runner for D-ITG with a control server."""
supports_remote = False
transformers = {'delay': transformers.s_to_ms,
'jitter': transformers.s_to_ms,
'bitrate': transformers.identity,
'loss': transformers.identity}
def __init__(self, test_args, host, length, interval,
local_bind=None, control_host=None, **kwargs):
super(DitgRunner, self).__init__(**kwargs)
if not control_host:
control_host = self.settings.CONTROL_HOST or self.settings.HOST
control_host = normalise_host(control_host)
if not local_bind and self.settings.LOCAL_BIND:
local_bind = self.settings.LOCAL_BIND[0]
self.proxy = xmlrpc.ServerProxy("http://%s:%s"
% (control_host,
self.settings.DITG_CONTROL_PORT),
allow_none=True)
self.ditg_secret = self.settings.DITG_CONTROL_SECRET
self.test_args = test_args
self.length = length
self.host = normalise_host(host)
self.interval = interval
self.local_bind = local_bind
def check(self):
try:
# We want to request a test that is long enough to keep the server
# alive for the duration of the whole test, even though we may not
# start ITGSend until after a delay
length = max(self.length, self.settings.TOTAL_LENGTH)
interval = int(self.interval * 1000)
hm = hmac.new(self.ditg_secret.encode(
'UTF-8'), digestmod=hashlib.sha256)
hm.update(str(length).encode('UTF-8'))
hm.update(str(interval).encode('UTF-8'))
params = self.proxy.request_new_test(length, interval,
hm.hexdigest(), True)
if params['status'] != 'OK':
if 'message' in params:
raise RunnerCheckError(
"Unable to request D-ITG test. "
"Control server reported error: %s" % params['message'])
else:
raise RunnerCheckError(
"Unable to request D-ITG test. "
"Control server reported an unspecified error.")
self.test_id = params['test_id']
self.out += "Test ID: %s\n" % self.test_id
except (xmlrpc.Fault, socket.error) as e:
raise RunnerCheckError(
"Error while requesting D-ITG test: '%s'. "
"Is the control server listening (see man page)?" % e)
itgsend = util.which("ITGSend", fail=RunnerCheckError)
# We put placeholders in the command string to be filled out by string
# format expansion by the runner once it has communicated with the control
# server and obtained the port values.
self.command = "{binary} -Sdp {signal_port} -t {length} {local_bind} " \
"-a {dest_host} -rp {dest_port} {args}".format(
binary=itgsend,
length=int(self.length * 1000),
dest_host=self.host,
local_bind="-sa {0} -Ssa {0}".format(
self.local_bind) if self.local_bind else "",
args=self.test_args,
signal_port=params['port'],
dest_port=params['port'] + 1)
super(DitgRunner, self).check()
def parse(self, output, error=""):
data = ""
utc_offset = 0
results = {}
try:
# The control server has a grace period after the test ends, so we
# don't know exactly when the test results are going to be ready. We
# assume that it will be within ten seconds.
for i in range(10):
res = self.proxy.get_test_results(self.test_id)
if res['status'] == 'OK':
data = res['data']
self.out += data
utc_offset = res['utc_offset']
break
time.sleep(1)
if res['status'] != 'OK':
if 'message' in res:
self.err += "Error while getting results. " \
"Control server reported error: %s.\n" \
% res['message']
else:
self.err += "Error while getting results. " \
"Control server reported unknown error.\n"
except xmlrpc.Fault as e:
self.err += "Error while getting results: %s.\n" % e
# D-ITG *should* output about 50 bytes of data per data point. However,
# sometimes it runs amok and outputs megabytes of erroneous data. So, if
# the length of the data is more than ten times the expected value,
# abort rather than try to process the data.
if len(data) > (self.length / self.interval) * 500:
self.err += "D-ITG output too much data (%d bytes).\n" % len(data)
return results
if 'raw' in res:
self.parse_raw(res['raw'])
for line in data.splitlines():
if not line.strip():
continue
parts = [float(i) for i in line.split()]
timestamp = parts.pop(0) + utc_offset
for i, n in enumerate(('bitrate', 'delay', 'jitter', 'loss')):
if n not in results:
results[n] = []
results[n].append([timestamp, self.transformers[n](parts[i])])
return results
def parse_raw(self, data):
raw_values = []
for line in data.splitlines():
parts = re.split(r">?\s*", line)
vals = dict(zip(parts[::2], parts[1::2]))
times = {}
for v in ('txTime', 'rxTime'):
t, microsec = vals[v].split(".")
h, m, s = t.split(":")
# FIXME: This is definitely going to break if a test is run
# around midnight
dt = datetime.utcnow().replace(hour=int(h),
minute=int(m),
second=int(s),
microsecond=int(microsec))
times[v] = float(timegm(dt.timetuple())) + dt.microsecond / 10**6
raw_values.append({
't': times['rxTime'],
'val': 1000.0 * (times['rxTime'] - times['txTime']),
'seq': int(vals['Seq']),
'size': int(vals['Size'])
})
self.raw_values = raw_values
class NetperfDemoRunner(ProcessRunner):
"""Runner for netperf demo mode."""
transformed_metadata = ('MEAN_VALUE',)
output_vars = 'THROUGHPUT,LOCAL_CONG_CONTROL,REMOTE_CONG_CONTROL,' \
'TRANSPORT_MSS,LOCAL_TRANSPORT_RETRANS,' \
'REMOTE_TRANSPORT_RETRANS,LOCAL_SOCKET_TOS,' \
'REMOTE_SOCKET_TOS,DIRECTION,ELAPSED_TIME,PROTOCOL,' \
'LOCAL_SEND_SIZE,LOCAL_RECV_SIZE,' \
'REMOTE_SEND_SIZE,REMOTE_RECV_SIZE,' \
'LOCAL_BYTES_SENT,LOCAL_BYTES_RECVD,' \
'REMOTE_BYTES_SENT,REMOTE_BYTES_RECVD'
netperf = {}
_env = {"DUMP_TCP_INFO": "1"}
def __init__(self, test, length, host, bytes=None, **kwargs):
self.test = test
self.length = length
self.host = normalise_host(host)
self.bytes = bytes
super(NetperfDemoRunner, self).__init__(**kwargs)
def parse(self, output, error=""):
"""Parses the interim result lines and returns a list of (time,value)
pairs."""
result = []
raw_values = []
lines = output.strip().splitlines()
avg_dur = None
alpha = 0.5
data_dict = {}
# We use the -k output option for netperf, so we will get data in
# KEY=VALUE lines. The interim points will be NETPERF_*[id] lines,
# end-of-test data points will be straight KEY=VAL lines
for line in lines:
line = line.strip()
try:
k, v = line.split("=", 1)
if k.endswith(']'):
k, i = k.split('[', 1)
i = i[:-1]
if k not in data_dict:
data_dict[k] = []
data_dict[k].append(v)
else:
if k in data_dict:
logger.warning("Duplicate key in netperf results: %s", k)
data_dict[k] = v
except ValueError:
pass
# TCP_INFO values are output to stderr
for line in error.strip().splitlines():
line = line.strip()
if line.startswith("tcpi"):
parts = line.split()
data_dict.update(dict(zip(parts[::2], parts[1::2])))
try:
for dur, t, value in zip(data_dict['NETPERF_INTERVAL'],
data_dict['NETPERF_ENDING'],
data_dict['NETPERF_INTERIM_RESULT']):
dur = float(dur)
t = float(t)
value = float(value)
if self.test == 'UDP_RR':
value = transformers.rr_to_ms(value)
# Calculate an EWMA of the netperf sampling duration and exclude
# data points from a sampling period that is more than an order
# of magnitude higher or lower than this average; these are
# probably the result of netperf spitting out a measurement at
# the end of a run after having lost the measurement flow during
# the run, or a very short interval giving a very high bandwidth
# measurement
if avg_dur is None:
avg_dur = dur
if dur < avg_dur * 10.0 and dur > avg_dur / 10.0:
raw_values.append({'dur': dur, 't': t, 'val': value})
result.append([t, value])
avg_dur = alpha * avg_dur + (1.0 - alpha) * dur
try:
# The THROUGHPUT key contains the mean value even for UDP_RR tests
self.metadata['MEAN_VALUE'] = float(data_dict['THROUGHPUT'])
if self.test == 'UDP_RR':
self.metadata['MEAN_VALUE'] = transformers.rr_to_ms(self.metadata['MEAN_VALUE'])
self.metadata['ELAPSED_TIME'] = float(data_dict.get('ELAPSED_TIME', 0))
self.metadata['UPSTREAM_TOS'] = int(data_dict.get('LOCAL_SOCKET_TOS', 0),
base=0)
self.metadata['DOWNSTREAM_TOS'] = int(data_dict.get(
'REMOTE_SOCKET_TOS', 0), base=0)
if data_dict['PROTOCOL'] == 'TCP':
self.metadata['TCP_MSS'] = int(data_dict.get('TRANSPORT_MSS',
0))
if data_dict['DIRECTION'] == 'Send':
self.metadata['CONG_CONTROL'] = data_dict.get(
'LOCAL_CONG_CONTROL')
self.metadata['TCP_RETRANSMIT'] = data_dict.get(
'LOCAL_TRANSPORT_RETRANS')
self.metadata['SEND_SIZE'] = int(data_dict.get(
'LOCAL_SEND_SIZE', -1))
self.metadata['RECV_SIZE'] = int(data_dict.get(
'REMOTE_RECV_SIZE', -1))
self.metadata['BYTES_SENT'] = int(data_dict.get(
'LOCAL_BYTES_SENT', -1))
self.metadata['BYTES_RECVD'] = int(data_dict.get(
'REMOTE_BYTES_RECVD', -1))
self.metadata['DATA_TOS'] = self.metadata['UPSTREAM_TOS']
else:
self.metadata['CONG_CONTROL'] = data_dict.get(
'REMOTE_CONG_CONTROL')
self.metadata['TCP_RETRANSMIT'] = int(data_dict.get(
'REMOTE_TRANSPORT_RETRANS', 0))
self.metadata['SEND_SIZE'] = int(data_dict.get(
'REMOTE_SEND_SIZE', -1))
self.metadata['RECV_SIZE'] = int(data_dict.get(
'LOCAL_RECV_SIZE', -1))
self.metadata['BYTES_SENT'] = int(data_dict.get(
'REMOTE_BYTES_SENT', -1))
self.metadata['BYTES_RECVD'] = int(data_dict.get(
'LOCAL_BYTES_RECVD', -1))
self.metadata['DATA_TOS'] = self.metadata['DOWNSTREAM_TOS']
for k in data_dict.keys():
if k.startswith("tcpi"):
self.metadata[k.upper()] = int(data_dict[k])
except KeyError as e:
logger.warning("Missing required netperf metadata: %s", e.args[0])
except KeyError:
pass # No valid data
self.raw_values = raw_values
return result
def check(self):
args = self.runner_args.copy()
if self.test.lower() == 'omni':
raise RunnerCheckError("Use of netperf 'omni' test is not supported")
args.setdefault('ip_version', self.settings.IP_VERSION)
args.setdefault('interval', self.settings.STEP_SIZE)
args.setdefault('control_host', self.settings.CONTROL_HOST or self.host)
args.setdefault('control_port', self.settings.NETPERF_CONTROL_PORT)
args.setdefault('local_bind',
self.settings.LOCAL_BIND[0]
if self.settings.LOCAL_BIND else "")
args.setdefault('control_local_bind',
self.settings.CONTROL_LOCAL_BIND or args['local_bind'])
args.setdefault('extra_args', "")
args.setdefault('extra_test_args', "")
args.setdefault('format', "")
args.setdefault('marking', "")
args.setdefault('cong_control',
self.settings.TEST_PARAMETERS.get('tcp_cong_control', ''))
args.setdefault('socket_timeout', self.settings.SOCKET_TIMEOUT)
args.setdefault('send_size',
self.settings.SEND_SIZE[0]
if self.settings.SEND_SIZE else "")
args.setdefault('test_payload', self.settings.TEST_PAYLOAD)
if self.settings.SWAP_UPDOWN:
if self.test == 'TCP_STREAM':
self.test = 'TCP_MAERTS'
elif self.test == 'TCP_MAERTS':
self.test = 'TCP_STREAM'
if self.netperf and not self.remote_host:
netperf = self.netperf
else:
nperf = util.which('netperf', fail=RunnerCheckError,
remote_host=self.remote_host)
# Try to figure out whether this version of netperf supports the -e