forked from moonlight200/quic-opensand-evaluation
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathparse.py
executable file
·1211 lines (988 loc) · 47.5 KB
/
parse.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
import json
import multiprocessing as mp
import os.path
import re
import sys
from datetime import datetime
from itertools import islice
from multiprocessing.dummy.connection import Connection
from typing import Dict, List, Optional, Generator, Tuple, Callable
import numpy as np
import pandas as pd
import common
from common import logger
def load_json_file(path: str):
"""
Loads and parses the content of a json file.
:param path:
:return:
"""
if not os.path.isfile(path):
return None
with open(path, 'r') as file:
try:
return json.load(file)
except json.JSONDecodeError as err:
if err.msg != "Extra data":
logger.exception("Failed to load json file '%s'" % path)
return None
# Read only first object from file, ignore extra data
file.seek(0)
json_str = file.read(err.pos)
try:
return json.loads(json_str)
except json.JSONDecodeError:
logger.exception("Failed to read json file '%s'" % path)
return None
def bps_factor(prefix: str):
factor = {'K': 10 ** 3, 'M': 10 ** 6, 'G': 10 ** 9, 'T': 10 ** 12, 'P': 10 ** 15, 'E': 10 ** 18, 'Z': 10 ** 21,
'Y': 10 ** 24}
prefix = prefix.upper()
return factor[prefix] if prefix in factor else 1
def extend_df(df: pd.DataFrame, by: pd.DataFrame, **kwargs) -> pd.DataFrame:
"""
Extends the dataframe containing the data of a single file (by) with the information given in the kwargs so that it
can be appended to the main dataframe (df)
:param df: The main dataframe
:param by: The dataframe to extend by
:param kwargs: Values to use for new columns in by
:return: The extended df
"""
aliases = {
'sat': ['delay', 'orbit'],
'queue': ['queue_overhead_factor'],
}
missing_cols = set(df.columns).difference(set(by.columns))
for col_name in missing_cols:
col_value = np.nan
if col_name in kwargs:
col_value = kwargs[col_name]
elif col_name in aliases:
for alias_col in aliases[col_name]:
if alias_col in kwargs:
col_value = kwargs[alias_col]
break
by[col_name] = col_value
return df.append(by, ignore_index=True)
def fix_dtypes(df: pd.DataFrame) -> pd.DataFrame:
"""
Fix the data types of the columns in a data frame.
:param df: The dataframe to fix
:return:
"""
# Cleanup values
if 'rate' in df:
df['rate'] = df['rate'].apply(
lambda x: np.nan if str(x) == 'nan' else ''.join(c for c in str(x) if c.isdigit() or c == '.'))
if 'loss' in df:
df['loss'] = df['loss'].apply(
lambda x: np.nan if str(x) == 'nan' else float(''.join(c for c in str(x) if c.isdigit() or c == '.')) / 100)
defaults = {
np.int32: -1,
np.str: "",
np.bool: False,
}
dtypes = {
'protocol': np.str,
'pep': np.bool,
'sat': np.str,
'rate': np.int32,
'loss': float,
'queue': np.int32,
'run': np.int32,
'second': np.float32,
'bps': np.float64,
'bytes': np.int32,
'packets_received': np.int32,
'cwnd': np.int32,
'packets_sent': np.int32,
'packets_lost': np.int32,
'con_est': np.float64,
'ttfb': np.float64,
'omitted': np.bool,
'rtt': np.int32,
'seq': np.int32,
'ttl': np.int32,
'rtt_min': np.float32,
'rtt_avg': np.float32,
'rtt_max': np.float32,
'rtt_mdev': np.float32,
'name': np.str,
'cpu_load': np.float32,
'ram_usage': np.float32,
'attenuation': np.int32,
'tbs': np.str,
'qbs': np.str,
'ubs': np.str,
'prime': np.float32,
}
# Set defaults
df = df.fillna({col: defaults.get(dtypes[col], np.nan) for col in dtypes.keys()})
cols = set(df.columns).intersection(dtypes.keys())
return df.astype({col_name: dtypes[col_name] for col_name in cols})
def __mp_function_wrapper(parse_func: Callable[..., any], conn: Connection, *args, **kwargs) -> None:
result = parse_func(*args, **kwargs)
conn.send(result)
conn.close()
def __parse_slice(parse_func: Callable[..., pd.DataFrame], in_dir: str, scenarios: List[Tuple[str, Dict]],
df_cols: List[str], protocol: str, entity: str) -> pd.DataFrame:
"""
Parse a slice of the protocol entity results using the given function.
:param parse_func: The function to parse a single scenario.
:param in_dir: The directory containing the measurement results.
:param scenarios: The scenarios to parse within the in_dir.
:param df_cols: The column names for columns in the resulting dataframe.
:param protocol: The name of the protocol that is being parsed.
:param entity: Then name of the entity that is being parsed.
:return: A dataframe containing the combined results of the specified scenarios.
"""
df_slice = pd.DataFrame(columns=df_cols)
for folder, config in scenarios:
for pep in (False, True):
df = parse_func(in_dir, folder, pep=pep)
if df is not None:
df_slice = extend_df(df_slice, df, protocol=protocol, pep=pep, **config)
else:
logger.warning("No data %s%s %s data in %s", protocol, " (pep)" if pep else "", entity, folder)
return df_slice
def __mp_parse_slices(num_procs: int, parse_func: Callable[..., pd.DataFrame], in_dir: str,
scenarios: Dict[str, Dict], df_cols: List[str], protocol: str, entity: str) -> pd.DataFrame:
"""
Parse all protocol entity results using the given function in multiple processes.
:param num_procs: The number of processes to spawn.
:param parse_func: The function to parse a single scenario.
:param in_dir: The directory containing the measurement results.
:param scenarios: The scenarios to parse within the in_dir.
:param df_cols: The column names for columns in the resulting dataframe.
:param protocol: The name of the protocol that is being parsed.
:param entity: Then name of the entity that is being parsed.
:return:
"""
tasks = [
(
"%s_%s_%d" % (protocol, entity, i),
list(islice(scenarios.items(), i, sys.maxsize, num_procs)),
mp.Pipe()
)
for i in range(num_procs)
]
processes = [
mp.Process(target=__mp_function_wrapper, name=name,
args=(__parse_slice, child_con, parse_func, in_dir, s_slice, df_cols, protocol, entity))
for name, s_slice, (_, child_con) in tasks
]
# Start processes
for p in processes:
p.start()
# Collect results
slice_dfs = [
parent_con.recv()
for _, _, (parent_con, _) in tasks
]
# Wait for processes to finish
for p in processes:
p.join()
return pd.concat(slice_dfs, axis=0, ignore_index=True)
def parse_quic_client(in_dir: str, out_dir: str, scenarios: Dict[str, Dict], config_cols: List[str],
multi_process: bool = False) -> pd.DataFrame:
"""
Parse all quic client results.
:param in_dir: The directory containing the measurement results.
:param out_dir: The directory to save the parsed results to.
:param scenarios: The scenarios to parse within the in_dir.
:param config_cols: The column names for columns taken from the scenario configuration.
:param multi_process: Whether to allow multiprocessing.
:return: A dataframe containing the combined results from all scenarios.
"""
logger.info("Parsing quic client results")
df_cols = [*config_cols, 'run', 'second', 'bps', 'bytes', 'packets_received']
if multi_process:
df_quic_client = __mp_parse_slices(2, __parse_quic_client_from_scenario, in_dir, scenarios,
df_cols, 'quic', 'client')
else:
df_quic_client = __parse_slice(__parse_quic_client_from_scenario, in_dir, [*scenarios.items()],
df_cols, 'quic', 'client')
logger.debug("Fixing quic client data types")
df_quic_client = fix_dtypes(df_quic_client)
logger.info("Saving quic client data")
df_quic_client.to_pickle(os.path.join(out_dir, 'quic_client.pkl'))
with open(os.path.join(out_dir, 'quic_client.csv'), 'w+') as out_file:
df_quic_client.to_csv(out_file)
return df_quic_client
def __parse_quic_client_from_scenario(in_dir: str, scenario_name: str, pep: bool = False) -> pd.DataFrame:
"""
Parse the quic client results in the given scenario.
:param in_dir: The directory containing all measurement results
:param scenario_name: The name of the scenario to parse
:param pep: Whether to parse QUIC or QUIC (PEP) files
:return: A dataframe containing the parsed results of the specified scenario.
"""
logger.debug("Parsing quic%s client files in %s", " (pep)" if pep else "", scenario_name)
df = pd.DataFrame(columns=['run', 'second', 'bps', 'bytes', 'packets_received'])
for file_name in os.listdir(os.path.join(in_dir, scenario_name)):
file_path = os.path.join(in_dir, scenario_name, file_name)
if not os.path.isfile(file_path):
continue
match = re.search(r"^quic%s_(\d+)_client\.txt$" % ("_pep" if pep else "",), file_name)
if not match:
continue
logger.debug("%s: Parsing '%s'", scenario_name, file_name)
run = int(match.group(1))
with open(file_path) as file:
for line in file:
line_match = re.search(
r"^second (\d+(?:\.\d+)?): (\d+(?:\.\d+)?) ([a-zA-Z]?)bit/s, bytes received: (\d+), packets received: (\d+)$",
line.strip()
)
if not line_match:
continue
df = df.append({
'run': run,
'second': float(line_match.group(1)),
'bps': float(line_match.group(2)) * bps_factor(line_match.group(3)),
'bytes': int(line_match.group(4)),
'packets_received': int(line_match.group(5))
}, ignore_index=True)
with_na = len(df.index)
df.dropna(subset=['bps', 'bytes', 'packets_received'], inplace=True)
without_na = len(df.index)
if with_na != without_na:
logger.warning("%s: Dropped %d lines with NaN values", scenario_name, with_na - without_na)
if df.empty:
logger.warning("%s: No quic%s client data found", scenario_name, " (pep)" if pep else "")
return df
def parse_quic_server(in_dir: str, out_dir: str, scenarios: Dict[str, Dict], config_cols: List[str],
multi_process: bool = False) -> pd.DataFrame:
"""
Parse all quic server results.
:param in_dir: The directory containing the measurement results.
:param out_dir: The directory to save the parsed results to.
:param scenarios: The scenarios to parse within the in_dir.
:param config_cols: The column names for columns taken from the scenario configuration.
:param multi_process: Whether to allow multiprocessing.
:return: A dataframe containing the combined results from all scenarios.
"""
logger.info("Parsing quic server results")
df_cols = [*config_cols, 'run', 'second', 'cwnd', 'packets_sent', 'packets_lost']
if multi_process:
df_quic_server = __mp_parse_slices(2, __parse_quic_server_from_scenario, in_dir, scenarios,
df_cols, 'quic', 'server')
else:
df_quic_server = __parse_slice(__parse_quic_server_from_scenario, in_dir, [*scenarios.items()],
df_cols, 'quic', 'server')
logger.debug("Fixing quic server data types")
df_quic_server = fix_dtypes(df_quic_server)
logger.info("Saving quic server data")
df_quic_server.to_pickle(os.path.join(out_dir, 'quic_server.pkl'))
with open(os.path.join(out_dir, 'quic_server.csv'), 'w+') as out_file:
df_quic_server.to_csv(out_file)
return df_quic_server
def __parse_quic_server_from_scenario(in_dir: str, scenario_name: str, pep: bool = False) -> pd.DataFrame:
"""
Parse the quic server results in the given scenario.
:param in_dir: The directory containing all measurement results
:param scenario_name: The name of the scenario to parse
:param pep: Whether to parse QUIC or QUIC (PEP) files
:return: A dataframe containing the parsed results of the specified scenario.
"""
logger.debug("Parsing quic%s server files in %s", " (pep)" if pep else "", scenario_name)
df = pd.DataFrame(columns=['run', 'second', 'cwnd', 'packets_sent', 'packets_lost'])
for file_name in os.listdir(os.path.join(in_dir, scenario_name)):
path = os.path.join(in_dir, scenario_name, file_name)
if not os.path.isfile(path):
continue
match = re.search(r"^quic%s_(\d+)_server\.txt$" % ("_pep" if pep else "",), file_name)
if not match:
continue
logger.debug("%s: Parsing '%s'", scenario_name, file_name)
run = int(match.group(1))
with open(path) as file:
for line in file:
line_match = re.search(
r"^connection \d+ second (\d+(?:\.\d+)?):.*send window: (\d+).*packets sent: (\d+).*packets lost: (\d+)$",
line.strip())
if not line_match:
continue
df = df.append({
'run': run,
'second': float(line_match.group(1)),
'cwnd': int(line_match.group(2)),
'packets_sent': int(line_match.group(3)),
'packets_lost': int(line_match.group(4))
}, ignore_index=True)
with_na = len(df.index)
df.dropna(subset=['cwnd', 'packets_sent', 'packets_lost'], inplace=True)
without_na = len(df.index)
if with_na != without_na:
logger.warning("%s: Dropped %d lines with NaN values", scenario_name, with_na - without_na)
if df.empty:
logger.warning("%s: No quic%s server data found", scenario_name, " (pep)" if pep else "")
return df
def parse_quic_timing(in_dir: str, out_dir: str, scenarios: Dict[str, Dict], config_cols: List[str],
multi_process: bool = False) -> pd.DataFrame:
"""
Parse all quic timing results.
:param in_dir: The directory containing the measurement results.
:param out_dir: The directory to save the parsed results to.
:param scenarios: The scenarios to parse within the in_dir.
:param config_cols: The column names for columns taken from the scenario configuration.
:param multi_process: Whether to allow multiprocessing.
:return: A dataframe containing the combined results from all scenarios.
"""
logger.info("Parsing quic timing results")
df_cols = [*config_cols, 'run', 'con_est', 'ttfb']
df_quic_timing = __parse_slice(__parse_quic_timing_from_scenario, in_dir, [*scenarios.items()],
df_cols, 'quic', 'timing')
logger.debug("Fixing quic timing data types")
df_quic_timing = fix_dtypes(df_quic_timing)
logger.info("Saving quic timing data")
df_quic_timing.to_pickle(os.path.join(out_dir, 'quic_timing.pkl'))
with open(os.path.join(out_dir, 'quic_timing.csv'), 'w+') as out_file:
df_quic_timing.to_csv(out_file)
return df_quic_timing
def __parse_quic_timing_from_scenario(in_dir: str, scenario_name: str, pep: bool = False) -> pd.DataFrame:
"""
Parse the quic timing results in the given scenario.
:param in_dir: The directory containing all measurement results
:param scenario_name: The name of the scenario to parse
:param pep: Whether to parse QUIC or QUIC (PEP) files
:return: A dataframe containing the parsed results of the specified scenario.
"""
logger.debug("Parsing quic%s timing files in %s", " (pep)" if pep else "", scenario_name)
df = pd.DataFrame(columns=['run', 'con_est', 'ttfb'])
for file_name in os.listdir(os.path.join(in_dir, scenario_name)):
file_path = os.path.join(in_dir, scenario_name, file_name)
if not os.path.isfile(file_path):
continue
match = re.search(r"^quic%s_ttfb_(\d+)_client\.txt$" % ("_pep" if pep else "",), file_name)
if not match:
continue
logger.debug("%s: Parsing '%s'", scenario_name, file_name)
run = int(match.group(1))
con_est = None
ttfb = None
with open(file_path) as file:
for line in file:
if line.startswith('connection establishment time:'):
if con_est is not None:
logger.warning("Found duplicate value for con_est in '%s', ignoring", file_path)
else:
con_est = float(line.split(':', 1)[1].strip()[:-2])
elif line.startswith('time to first byte:'):
if ttfb is not None:
logger.warning("Found duplicate value for ttfb in '%s', ignoring", file_path)
else:
ttfb = float(line.split(':', 1)[1].strip()[:-2])
df = df.append({
'run': run,
'con_est': con_est,
'ttfb': ttfb
}, ignore_index=True)
with_na = len(df.index)
df.dropna(subset=['con_est', 'ttfb'], inplace=True)
without_na = len(df.index)
if with_na != without_na:
logger.warning("%s: Dropped %d lines with NaN values", scenario_name, with_na - without_na)
if df.empty:
logger.warning("%s: No quic%s timing data found", scenario_name, " (pep)" if pep else "")
return df
def parse_tcp_client(in_dir: str, out_dir: str, scenarios: Dict[str, Dict], config_cols: List[str],
multi_process: bool = False) -> pd.DataFrame:
"""
Parse all tcp client results.
:param in_dir: The directory containing the measurement results.
:param out_dir: The directory to save the parsed results to.
:param scenarios: The scenarios to parse within the in_dir.
:param config_cols: The column names for columns taken from the scenario configuration.
:param multi_process: Whether to allow multiprocessing.
:return: A dataframe containing the combined results from all scenarios.
"""
logger.info("Parsing tcp client results")
df_cols = [*config_cols, 'run', 'second', 'bps', 'bytes', 'omitted']
if multi_process:
df_tcp_client = __mp_parse_slices(4, __parse_tcp_client_from_scenario, in_dir, scenarios,
df_cols, 'tcp', 'client')
else:
df_tcp_client = __parse_slice(__parse_tcp_client_from_scenario, in_dir, [*scenarios.items()],
df_cols, 'tcp', 'client')
logger.debug("Fixing tcp client data types")
df_tcp_client = fix_dtypes(df_tcp_client)
logger.info("Saving tcp client data")
df_tcp_client.to_pickle(os.path.join(out_dir, 'tcp_client.pkl'))
with open(os.path.join(out_dir, 'tcp_client.csv'), 'w+') as out_file:
df_tcp_client.to_csv(out_file)
return df_tcp_client
def __parse_tcp_client_from_scenario(in_dir: str, scenario_name: str, pep: bool = False) -> pd.DataFrame:
"""
Parse the tcp client results in the given scenario.
:param in_dir: The directory containing all measurement results
:param scenario_name: The name of the scenario to parse
:param pep: Whether to parse TCP or TCP (PEP) files
:return: A dataframe containing the parsed results of the specified scenario.
"""
logger.debug("Parsing tcp%s client files in %s", " (pep)" if pep else "", scenario_name)
df = pd.DataFrame(columns=['run', 'second', 'bps', 'bytes', 'omitted'])
for file_name in os.listdir(os.path.join(in_dir, scenario_name)):
file_path = os.path.join(in_dir, scenario_name, file_name)
if not os.path.isfile(file_path):
continue
match = re.search(r"^tcp%s_(\d+)_client\.json$" % ("_pep" if pep else "",), file_name)
if not match:
continue
logger.debug("%s: Parsing '%s'", scenario_name, file_name)
run = int(match.group(1))
results = load_json_file(file_path)
if results is None:
logger.warning("%s: '%s' has no content", scenario_name, file_path)
continue
for interval in results['intervals']:
if len(interval['streams']) == 0:
logger.warning("%s: SKIPPING interval in '%s' due to small interval time", scenario_name, file_path)
continue
if float(interval['streams'][0]['seconds']) < 0.001:
logger.warning("%s: Skipping interval in '%s' due to small interval time", scenario_name, file_path)
continue
df = df.append({
'run': run,
'second': interval['streams'][0]['end'],
'bps': float(interval['streams'][0]['bits_per_second']),
'bytes': int(interval['streams'][0]['bytes']),
'omitted': bool(interval['streams'][0]['omitted']),
}, ignore_index=True)
with_na = len(df.index)
df.dropna(subset=['bps', 'bytes', 'omitted'], inplace=True)
without_na = len(df.index)
if with_na != without_na:
logger.warning("%s: Dropped %d lines with NaN values", scenario_name, with_na - without_na)
if df.empty:
logger.warning("%s: No tcp%s client data found", scenario_name, " (pep)" if pep else "")
return df
def parse_tcp_server(in_dir: str, out_dir: str, scenarios: Dict[str, Dict], config_cols: List[str],
multi_process: bool = False) -> pd.DataFrame:
"""
Parse all tcp server results.
:param in_dir: The directory containing the measurement results.
:param out_dir: The directory to save the parsed results to.
:param scenarios: The scenarios to parse within the in_dir.
:param config_cols: The column names for columns taken from the scenario configuration.
:param multi_process: Whether to allow multiprocessing.
:return: A dataframe containing the combined results from all scenarios.
"""
logger.info("Parsing tcp server results")
df_cols = [*config_cols, 'run', 'second', 'cwnd', 'bps', 'bytes', 'packets_lost', 'rtt', 'omitted']
if multi_process:
df_tcp_server = __mp_parse_slices(4, __parse_tcp_server_from_scenario, in_dir, scenarios,
df_cols, 'tcp', 'server')
else:
df_tcp_server = __parse_slice(__parse_tcp_server_from_scenario, in_dir, [*scenarios.items()],
df_cols, 'tcp', 'server')
logger.debug("Fixing tcp server data types")
df_tcp_server = fix_dtypes(df_tcp_server)
logger.info("Saving tcp server data")
df_tcp_server.to_pickle(os.path.join(out_dir, 'tcp_server.pkl'))
with open(os.path.join(out_dir, 'tcp_server.csv'), 'w+') as out_file:
df_tcp_server.to_csv(out_file)
return df_tcp_server
def __parse_tcp_server_from_scenario(in_dir: str, scenario_name: str, pep: bool = False) -> pd.DataFrame:
"""
Parse the tcp server results in the given scenario.
:param in_dir: The directory containing all measurement results
:param scenario_name: The name of the scenario to parse
:param pep: Whether to parse TCP or TCP (PEP) files
:return: A dataframe containing the parsed results of the specified scenario.
"""
logger.debug("Parsing tcp%s server files in %s", " (pep)" if pep else "", scenario_name)
df = pd.DataFrame(columns=['run', 'second', 'cwnd', 'bps', 'bytes', 'packets_lost', 'rtt', 'omitted'])
for file_name in os.listdir(os.path.join(in_dir, scenario_name)):
file_path = os.path.join(in_dir, scenario_name, file_name)
if not os.path.isfile(file_path):
continue
match = re.search(r"^tcp%s_(\d+)_server\.json$" % ("_pep" if pep else "",), file_name)
if not match:
continue
logger.debug("%s: Parsing '%s'", scenario_name, file_name)
run = int(match.group(1))
results = load_json_file(file_path)
if results is None:
logger.warning("%s: '%s' has no content", scenario_name, file_path)
continue
for interval in results['intervals']:
if len(interval['streams']) == 0:
logger.warning("%s: SKIPPING interval in '%s' due to small interval time", scenario_name, file_path)
continue
if float(interval['streams'][0]['seconds']) < 0.001:
logger.warning("%s: Skipping interval in '%s' due to small interval time", scenario_name, file_path)
continue
df = df.append({
'run': run,
'second': interval['streams'][0]['end'],
'cwnd': int(interval['streams'][0]['snd_cwnd']),
'bps': float(interval['streams'][0]['bits_per_second']),
'bytes': int(interval['streams'][0]['bytes']),
'packets_lost': int(interval['streams'][0]['retransmits']),
'rtt': int(interval['streams'][0]['rtt']),
'omitted': bool(interval['streams'][0]['omitted']),
}, ignore_index=True)
with_na = len(df.index)
df.dropna(subset=['bps', 'bytes', 'packets_lost'], inplace=True)
without_na = len(df.index)
if with_na != without_na:
logger.warning("%s: Dropped %d lines with NaN values", scenario_name, with_na - without_na)
if df.empty:
logger.warning("%s: No tcp%s server data found", scenario_name, " (pep)" if pep else "")
return df
def parse_tcp_timing(in_dir: str, out_dir: str, scenarios: Dict[str, Dict], config_cols: List[str],
multi_process: bool = False) -> pd.DataFrame:
"""
Parse all tcp timing results.
:param in_dir: The directory containing the measurement results.
:param out_dir: The directory to save the parsed results to.
:param scenarios: The scenarios to parse within the in_dir.
:param config_cols: The column names for columns taken from the scenario configuration.
:param multi_process: Whether to allow multiprocessing.
:return: A dataframe containing the combined results from all scenarios.
"""
logger.info("Parsing tcp timing results")
df_cols = [*config_cols, 'run', 'con_est', 'ttfb']
df_tcp_timing = __parse_slice(__parse_tcp_timing_from_scenario, in_dir, [*scenarios.items()],
df_cols, 'tcp', 'timing')
logger.debug("Fixing tcp timing data types")
df_tcp_timing = fix_dtypes(df_tcp_timing)
logger.info("Saving tcp timing data")
df_tcp_timing.to_pickle(os.path.join(out_dir, 'tcp_timing.pkl'))
with open(os.path.join(out_dir, 'tcp_timing.csv'), 'w+') as out_file:
df_tcp_timing.to_csv(out_file)
return df_tcp_timing
def __parse_tcp_timing_from_scenario(in_dir: str, scenario_name: str, pep: bool = False) -> pd.DataFrame:
"""
Parse the tcp timing results in the given scenario.
:param in_dir: The directory containing all measurement results
:param scenario_name: The name of the scenario to parse
:param pep: Whether to parse TCP or TCP (PEP) files
:return: A dataframe containing the parsed results of the specified scenario.
"""
logger.debug("Parsing tcp%s timing files in %s", " (pep)" if pep else "", scenario_name)
df = pd.DataFrame(columns=['run', 'con_est', 'ttfb'])
for file_name in os.listdir(os.path.join(in_dir, scenario_name)):
path = os.path.join(in_dir, scenario_name, file_name)
if not os.path.isfile(path):
continue
match = re.search(r"^tcp%s_ttfb_(\d+)_client\.txt$" % ("_pep" if pep else "",), file_name)
if not match:
continue
logger.debug("%s: Parsing '%s'", scenario_name, file_name)
run = int(match.group(1))
con_est = None
ttfb = None
with open(path) as file:
for line in file:
if line.startswith('established='):
if con_est is not None:
logger.warning("%s: Found duplicate value for con_est in '%s', ignoring", scenario_name, path)
else:
con_est = float(line.split('=', 1)[1].strip()) * 1000.0
elif line.startswith('ttfb='):
if ttfb is not None:
logger.warning("%s: Found duplicate value for ttfb in '%s', ignoring", scenario_name, path)
else:
ttfb = float(line.split('=', 1)[1].strip()) * 1000.0
df = df.append({
'run': run,
'con_est': con_est,
'ttfb': ttfb
}, ignore_index=True)
with_na = len(df.index)
df.dropna(subset=['con_est', 'ttfb'], inplace=True)
without_na = len(df.index)
if with_na != without_na:
logger.warning("%s: Dropped %d lines with NaN values", scenario_name, with_na - without_na)
if df.empty:
logger.warning("%s: No tcp%s timing data found", scenario_name, " (pep)" if pep else "")
return df
def parse_http(in_dir: str, out_dir: str, scenarios: Dict[str, Dict], config_cols: List[str],
multi_process: bool = False) -> pd.DataFrame:
"""
Parse all http (selenium) timing results.
:param in_dir: The directory containing the measurement results.
:param out_dir: The directory to save the parsed results to.
:param scenarios: The scenarios to parse within the in_dir.
:param config_cols: The column names for columns taken from the scenario configuration.
:param multi_process: Whether to allow multiprocessing.
:return: A dataframe containing the combined results from all scenarios.
"""
logger.info("Parsing http results")
df_cols = [*config_cols, 'run', 'domain', 'connectEnd', 'connectStart', 'responseStart', 'domInteractive', 'loadEventEnd', 'firstPaint', 'firstContentfulPaint', 'domInteractiveNorm', 'loadEventEndNorm']
df_http = __parse_slice(__parse_http, in_dir, [*scenarios.items()],
df_cols, 'http', 'timing')
if len(df_http.index) > 0:
logger.info("Saving http timing data")
df_http.to_pickle(os.path.join(out_dir, 'http.pkl'))
with open(os.path.join(out_dir, 'http.csv'), 'w+') as out_file:
df_http.to_csv(out_file)
else:
return None
return df_http
def __parse_http(in_dir: str, scenario_name: str, pep: bool = False) -> pd.DataFrame:
"""
Parse the http timing results in the given scenario.
:param in_dir: The directory containing all measurement results
:param scenario_name: The name of the scenario to parse
:param pep: Whether to parse TCP or TCP (PEP) files
:return: A dataframe containing the parsed results of the specified scenario.
"""
logger.debug("Parsing http%s timing files in %s", " (pep)" if pep else "", scenario_name)
file_name='http.csv' if pep == False else 'http_pep.csv'
file_path=os.path.join(in_dir, scenario_name, file_name)
if not os.path.isfile(file_path):
logger.warning(f'{file_path} was not found!')
return None
df = pd.read_csv(file_path, delimiter=";")
# Filter metrics with errors out
original_df_count = df['protocol'].count()
df = df[df['error'].isnull()]
df = df[df['nextHopProtocol'].notnull()]
filtered_df_count = df['protocol'].count()
logger.debug(f'{filtered_df_count}/{original_df_count} are valid')
# Calculate normalized metrics
df['domInteractiveNorm']=df.apply(lambda row: row.domInteractive - row.responseStart, axis=1)
df['loadEventEndNorm']=df.apply(lambda row: row.loadEventEnd - row.responseStart, axis=1)
# New normalized fields
df = df.reset_index()
return df
def parse_ping(in_dir: str, out_dir: str, scenarios: Dict[str, Dict], config_cols: List[str],
multi_process: bool = False) -> Tuple[pd.DataFrame, pd.DataFrame]:
"""
Parse all ping results.
:param in_dir: The directory containing the measurement results.
:param out_dir: The directory to save the parsed results to.
:param scenarios: The scenarios to parse within the in_dir.
:param config_cols: The column names for columns taken from the scenario configuration.
:param multi_process: Whether to allow multiprocessing.
:return: Two dataframes containing the combined results from all scenarios, one with the raw data and one with the
summary data.
"""
logger.info("Parsing ping results")
df_ping_raw = pd.DataFrame(columns=[*config_cols, 'seq', 'ttl', 'rtt'])
df_ping_summary = pd.DataFrame(columns=[*config_cols, 'packets_sent', 'packets_received', 'rtt_min',
'rtt_avg', 'rtt_max', 'rtt_mdev'])
for folder, config in scenarios.items():
dfs = __parse_ping_from_scenario(in_dir, folder)
if dfs is not None:
df_ping_raw = extend_df(df_ping_raw, dfs[0], protocol='icmp', pep=False, **config)
df_ping_summary = extend_df(df_ping_summary, dfs[1], protocol='icmp', pep=False, **config)
else:
logger.warning("No data ping data in %s", folder)
logger.debug("Fixing ping data types")
df_ping_raw = fix_dtypes(df_ping_raw)
df_ping_summary = fix_dtypes(df_ping_summary)
logger.info("Saving ping data")
df_ping_raw.to_pickle(os.path.join(out_dir, 'ping_raw.pkl'))
df_ping_summary.to_pickle(os.path.join(out_dir, 'ping_summary.pkl'))
with open(os.path.join(out_dir, 'ping_raw.csv'), 'w+') as out_file:
df_ping_raw.to_csv(out_file)
with open(os.path.join(out_dir, 'ping_summary.csv'), 'w+') as out_file:
df_ping_summary.to_csv(out_file)
return df_ping_raw, df_ping_summary
def __parse_ping_from_scenario(in_dir: str, scenario_name: str) -> Optional[Tuple[pd.DataFrame, pd.DataFrame]]:
"""
Parse the ping results in the given scenario.
:param in_dir: The directory containing all measurement results
:param scenario_name: The name of the scenario to parse
:return: Two dataframes containing the parsed results of the specified scenario, one with the raw data and one with
the summary data.
"""
logger.debug("Parsing ping file in %s", scenario_name)
path = os.path.join(in_dir, scenario_name, "ping.txt")
if not os.path.isfile(path):
logger.warning("%s: No ping data found", scenario_name)
return None
raw_data = []
summary_data = {}
with open(path) as file:
for line in file:
match = re.match(r"^\d+ bytes from .*: icmp_seq=(\d+) ttl=(\d+) time=(\d+) ms", line)
if match:
raw_data.append({
'seq': match.group(1),
'ttl': match.group(2),
'rtt': match.group(3)
})
else:
match = re.search(r"^(\d+) packets transmitted, (\d+) received", line)
if match:
summary_data['packets_sent'] = int(match.group(1))
summary_data['packets_received'] = int(match.group(2))
else:
match = re.search(r"= (\d+(?:\.\d+)?)/(\d+(?:\.\d+)?)/(\d+(?:\.\d+)?)/(\d+(?:\.\d+)?) ms", line)
if match:
summary_data['rtt_min'] = float(match.group(1))
summary_data['rtt_avg'] = float(match.group(2))
summary_data['rtt_max'] = float(match.group(3))
summary_data['rtt_mdev'] = float(match.group(4))
raw_df = pd.DataFrame(raw_data)
summary_df = pd.DataFrame({k: [v] for k, v in summary_data.items()})
with_na = len(raw_df.index)
raw_df.dropna(inplace=True)
without_na = len(raw_df.index)
if with_na != without_na:
logger.warning("%s: Dropped %d lines with NaN values in raw data", scenario_name, with_na - without_na)
with_na = len(summary_df.index)
summary_df.dropna(inplace=True)
without_na = len(summary_df.index)
if with_na != without_na:
logger.warning("%s, Dropped %d lines with NaN values in summary data", scenario_name, with_na - without_na)
return raw_df, summary_df
def parse_log(in_dir: str, out_dir: str, measure_type: common.MeasureType) -> Tuple[pd.DataFrame, pd.DataFrame]:
df_runs = None
df_stats = None
dfs = __parse_log(in_dir, measure_type)
if dfs is not None:
df_runs, df_stats = dfs
else:
logger.warning("No logging data")
if df_runs is None:
df_runs = pd.DataFrame(columns=['name'], index=pd.TimedeltaIndex([], name='time'))
if df_stats is None:
df_stats = pd.DataFrame(columns=['cpu_load', 'ram_usage'], index=pd.TimedeltaIndex([], name='time'))
logger.debug("Fixing log data types")
df_runs = fix_dtypes(df_runs)
df_stats = fix_dtypes(df_stats)
logger.info("Saving ping data")
df_runs.to_pickle(os.path.join(out_dir, 'runs.pkl'))
df_stats.to_pickle(os.path.join(out_dir, 'stats.pkl'))
with open(os.path.join(out_dir, 'runs.csv'), 'w+') as out_file:
df_runs.to_csv(out_file)
with open(os.path.join(out_dir, 'stats.csv'), 'w+') as out_file:
df_stats.to_csv(out_file)
return df_runs, df_stats
def __parse_log(in_dir: str, measure_type: common.MeasureType) -> Optional[Tuple[pd.DataFrame, pd.DataFrame]]:
logger.info("Parsing log file")
path = None
if measure_type == common.MeasureType.OPENSAND:
path = os.path.join(in_dir, "opensand.log")
elif measure_type == common.MeasureType.NETEM:
path = os.path.join(in_dir, "measure.log")
if not os.path.isfile(path):
logger.warning("No log file found")
return None
runs_data = []
stats_data = []
start_time = None
with open(path) as file:
for line in file:
line = '00'.join(line.rsplit(':00', 1))
if start_time is None:
start_time = datetime.strptime(' '.join(line.split(' ', 2)[:2]), "%Y-%m-%d %H:%M:%S%z")
match = re.match(r"^([0-9-+ :]+) \[INFO]: (.* run \d+/\d+)$", line)
if match:
runs_data.append({
'time': datetime.strptime(match.group(1), "%Y-%m-%d %H:%M:%S%z") - start_time,
'name': match.group(2),
})
else:
match = re.search(r"^([0-9-+ :]+) \[STAT]: CPU load \(1m avg\): (\d+(?:\.\d+)?), RAM usage: (\d+)MB$",
line)
if match:
stats_data.append({
'time': datetime.strptime(match.group(1), "%Y-%m-%d %H:%M:%S%z") - start_time,
'cpu_load': match.group(2),
'ram_usage': match.group(3),
})
runs_df = None
if len(runs_data) > 0:
runs_df = pd.DataFrame(runs_data)
runs_df.set_index('time', inplace=True)
stats_df = None
if len(stats_data) > 0:
stats_df = pd.DataFrame(stats_data)
stats_df.set_index('time', inplace=True)
return runs_df, stats_df
def __read_config_from_scenario(in_dir: str, scenario_name: str) -> Dict:
config = {
'name': scenario_name
}
with open(os.path.join(in_dir, scenario_name, 'config.txt'), 'r') as f:
for line in f:
if '=' in line:
key, value = line.split('=', 1)
config[key.strip()] = value.strip()
return config
def __create_config_df(out_dir: str, scenarios: Dict[str, Dict]) -> pd.DataFrame:
df_config = pd.DataFrame(data=[config for config in scenarios.values()])
if not df_config.empty:
df_config.set_index('name', inplace=True)
df_config.sort_index(inplace=True)
logger.info("Saving config data")
df_config.to_pickle(os.path.join(out_dir, 'config.pkl'))
with open(os.path.join(out_dir, 'config.csv'), 'w+') as out_file:
df_config.to_csv(out_file)
return df_config
def parse_auto_detect(in_dir: str, out_dir: str) -> Dict: