-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathcommands.py
More file actions
1983 lines (1688 loc) · 67.9 KB
/
Copy pathcommands.py
File metadata and controls
1983 lines (1688 loc) · 67.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# pylint: disable=unused-argument,line-too-long
import glob
import json
import operator
import os
import pexpect
import re
import requests
import shlex
import subprocess
import time
from behave import step # pylint: disable=no-name-in-module
import nmci
@step('Autocomplete "{cmd}" in bash and execute')
def autocomplete_command(context, cmd):
bash = nmci.pexpect.pexpect_spawn("bash")
bash.send(cmd)
bash.send("\t")
time.sleep(1)
bash.send("\r\n")
time.sleep(1)
bash.sendeof()
@step('Check noted values "{i1}" and "{i2}" are the same')
def check_same_noted_values(context, i1, i2):
assert (
context.noted[i1].strip() == context.noted[i2].strip()
), f"Noted values: {context.noted[i1].strip()} != {context.noted[i2].strip()} !"
@step('Check noted values "{i1}" and "{i2}" are not the same')
def check_different_noted_values(context, i1, i2):
assert (
context.noted[i1].strip() != context.noted[i2].strip()
), f"Noted values: {context.noted[i1].strip()} == {context.noted[i2].strip()} !"
@step('Check noted value "{i2}" difference from "{i1}" is "{operator_kw}" "{dif}"')
def check_dif_in_values_temp(context, i1, i2, operator_kw, dif):
real_dif = int(context.noted[i2].strip()) - int(context.noted[i1].strip())
assert compare_values(operator_kw.lower(), real_dif, int(dif)), (
f'The difference between "{i2}" and "{i1}" is '
f'"|{context.noted[i2].strip()}-{context.noted[i1].strip()}| = {real_dif}", '
f'which is not "{operator_kw}" {dif}'
)
@step('Check noted value is within "{r_min}" to "{r_max}" range')
@step('Check noted value "{index}" is within "{r_min}" to "{r_max}" range')
def check_noted_value_in_range(context, r_min, r_max, index="noted-value"):
assert (
int(r_min) <= int(context.noted[index]) <= int(r_max)
), f'Noted value "{context.noted[index]}" is not within range: "{r_min}"-"{r_max}"'
# ===================================================================
# COMMAND EXECUTION
# ===================================================================
@step('Execute "{command}"')
def execute_command(context, command):
command = nmci.misc.str_replace_dict(command, context.noted)
nmci.process.run_stdout(
command,
shell=True,
ignore_returncode=False,
ignore_stderr=True,
as_bytes=True,
timeout=None,
)
def get_reproducer_command_v(rname, options):
cmd = nmci.util.base_dir("contrib/reproducers", rname)
assert os.access(
cmd, os.X_OK
), f'Reproducer "{rname}" not found in "./contrib/reproducers/"'
args = [cmd]
if options:
args += list(shlex.split(options))
return args
def get_reproducer_command(rname, options):
return " ".join(shlex.quote(a) for a in get_reproducer_command_v(rname, options))
@step('Execute reproducer "{rname}"')
@step('Execute reproducer "{rname}" with options "{options}"')
@step('Execute reproducer "{rname}" for "{number}" times')
@step('Execute reproducer "{rname}" with options "{options}" for "{number}" times')
def execute_reproducer(context, rname, options="", number=1):
orig_nm_pid = nmci.nmutil.nm_pid()
argv = get_reproducer_command_v(rname, options)
# Emebed reproducer file
nmci.embed.embed_file_if_exists(rname, argv[0])
nm_pid_refresh_count = getattr(context, "nm_pid_refresh_count", 0)
for i in range(int(number)):
nmci.process.run_stdout(argv, timeout=180, ignore_stderr=True)
if nm_pid_refresh_count < 1:
curr_nm_pid = nmci.nmutil.nm_pid()
assert (
curr_nm_pid == orig_nm_pid
), f"NM crashed as original pid was {orig_nm_pid} but now is {curr_nm_pid}"
# log mem after each repro exec in stable_mem tests
if hasattr(context, "nm_valgrind_proc"):
nmci.nmutil.nm_size_kb()
@step('Execute "{command}" without waiting for process to finish')
def execute_command_nowait(context, command):
nmci.pexpect.pexpect_service(command, shell=True)
@step('Execute "{command}" without output redirect')
def execute_command_noout(context, command):
nmci.process.run(command, stdout=None, stderr=None)
@step('Execute "{command}" for "{number}" times')
def execute_multiple_times(context, command, number):
orig_nm_pid = nmci.nmutil.nm_pid()
i = 0
while i < int(number):
nmci.process.run(command, shell=True)
curr_nm_pid = nmci.nmutil.nm_pid()
assert (
curr_nm_pid == orig_nm_pid
), f"NM crashed as original pid was {orig_nm_pid} but now is {curr_nm_pid}"
i += 1
# ===================================================================
# PROCESS MANAGEMENT
# ===================================================================
@step('Terminate "{process}"')
@step('Terminate "{process}" with signal "{signal}"')
@step('Terminate all processes named "{process}"')
@step('Terminate all processes named "{process}" with signal "{signal}"')
def pkill_process(context, process, signal="TERM"):
pids = " ".join(nmci.process.run_stdout(f"pgrep {process}").split("\n"))
nmci.process.run_stdout(f"/usr/bin/kill -{signal} {pids}")
ticks = 25 # 5 seconds
while ticks > 0:
# This works for multiple pids, because kill would return 0
# if it could signal *any* of the pids
if (
nmci.process.run(f"/usr/bin/kill -0 {pids}", ignore_stderr=True).returncode
== 1
):
return True
ticks = ticks - 1
time.sleep(0.2)
raise Exception(f"Not all processed {pids} terminated on time")
@step('"{command}" fails')
def wait_for_process(context, command):
assert nmci.process.run(command, ignore_stderr=True, shell=True).returncode != 0
time.sleep(0.1)
@step("Restore hostname from the noted value")
def restore_hostname(context):
nmci.process.run(f"hostname {context.noted['noted-value']}", shell=True)
time.sleep(0.5)
@step('Hostname is visible in log "{log}"')
@step('Hostname is visible in log "{log}" in "{seconds}" seconds')
def hostname_visible(context, log, seconds=1):
seconds = int(seconds)
orig_seconds = seconds
cmd = f"grep $(hostname -s) '{log}'"
while seconds > 0:
if nmci.process.run(cmd, shell=True).returncode == 0:
return True
seconds = seconds - 1
time.sleep(1)
raise Exception(f"Hostname not visible in log in {orig_seconds} seconds")
@step('Hostname is not visible in log "{log}"')
@step('Hostname is not visible in log "{log}" for full "{seconds}" seconds')
def hostname_not_visible(context, log, seconds=1):
seconds = int(seconds)
orig_seconds = seconds
cmd = f"grep $(hostname -s) '{log}'"
while seconds > 0:
if nmci.process.run(cmd, shell=True).returncode != 0:
return True
seconds = seconds - 1
time.sleep(1)
raise Exception(f"Hostname visible in log after {orig_seconds - seconds} seconds")
# ===================================================================
# NAMESERVER AND DOMAIN MANAGEMENT
# ===================================================================
@step('Nameserver "{server}" is set')
@step('Nameserver "{server}" is set in "{seconds}" seconds')
@step('Domain "{server}" is set')
@step('Domain "{server}" is set in "{seconds}" seconds')
@step('DNS option "{server}" is set')
@step('DNS option "{server}" is set in "{seconds}" seconds')
def get_nameserver_or_domain(context, server, seconds=1):
if (
nmci.process.run(
"systemctl is-active systemd-resolved.service -q", shell=True
).returncode
== 0
):
# We have systemd-resolvd running
cmd = "resolvectl dns; resolvectl domain"
else:
cmd = "cat /etc/resolv.conf"
return check_pattern_command(context, cmd, server, seconds)
@step('Nameserver "{server}" is not set')
@step('Nameserver "{server}" is not set in "{seconds}" seconds')
@step('Domain "{server}" is not set')
@step('Domain "{server}" is not set in "{seconds}" seconds')
@step('DNS option "{server}" is not set')
@step('DNS option "{server}" is not set in "{seconds}" seconds')
def get_nameserver_or_domain_not(context, server, seconds=1):
if nmci.process.systemctl("is-active systemd-resolved.service -q").returncode == 0:
# We have systemd-resolvd running
cmd = "systemd-resolve --status |grep -A 100 Link"
else:
cmd = "cat /etc/resolv.conf"
return check_pattern_command(context, cmd, server, seconds, check_type="not")
# ===================================================================
# NOTED VALUES AND PATTERN MATCHING
# ===================================================================
@step('Noted value contains "{pattern}"')
@step('Noted value "{index}" contains "{pattern}"')
def noted_value_contains(context, pattern, index="noted-value"):
assert (
re.search(pattern, context.noted[index]) is not None
), f"Noted value '{context.noted[index]}' does not match the pattern '{pattern}'!"
@step('Noted value does not contain "{pattern}"')
@step('Noted value "{index}" does not contain "{pattern}"')
def noted_value_does_not_contain(context, pattern, index="noted-value"):
assert (
re.search(pattern, context.noted[index]) is None
), f"Noted value '{context.noted[index]}' does match the pattern '{pattern}'!"
@step('Note the output of "{command}"')
@step('Note the output of "{command}" as value "{index}"')
def note_the_output_as(context, command, index="noted-value"):
if not hasattr(context, "noted"):
context.noted = {}
command = nmci.process.WithShell(command)
context.noted[index] = nmci.process.run_stdout(command, ignore_stderr=True).strip()
@step('Note the number of lines of "{command}"')
@step('Note the number of lines with pattern "{pattern}" of "{command}"')
@step('Note the number of lines of "{command}" as value "{index}"')
@step(
'Note the number of lines with pattern "{pattern}" of "{command}" as value "{index}"'
)
def note_the_output_lines_as(context, command, index="noted-value", pattern=None):
if not hasattr(context, "noted"):
context.noted = {}
out = nmci.process.run_stdout(command, ignore_stderr=True, shell=True)
if pattern is not None:
out = [line for line in out.split("\n") if re.search(pattern, line)]
else:
out = [line for line in out.split("\n") if line]
nmci.embed.embed_data(
"Noted", f"[{index}] counted {len(out)} lines ({out})", fail_only=True
)
context.noted[index] = str(len(out))
# ===================================================================
# PATTERN AND COMMAND CHECKING UTILITIES
# ===================================================================
def check_pattern_command(
context,
command,
pattern,
seconds,
check_type="default",
check_class="default",
timeout=180,
maxread=100000,
):
seconds = float(seconds)
xtimeout = nmci.util.start_timeout(seconds)
# Adjust the poll interval based the timeout. Since the command output gets
# recorded in the test artifacts, we want to keep the number of polls
# reasonable.
if seconds < 60:
interval = 0.5
elif seconds <= 200:
interval = 1
else:
interval = 4
pattern = nmci.misc.str_replace_dict(pattern, getattr(context, "noted", {}))
command = nmci.misc.str_replace_dict(command, getattr(context, "noted", {}))
while xtimeout.loop_sleep(interval):
stdout = nmci.process.run_stdout(
command,
shell=True,
ignore_returncode=True,
ignore_stderr=True,
stderr=subprocess.STDOUT,
timeout=timeout,
)
if check_class == "exact":
ret = 0 if pattern in stdout else 1
elif check_class == "json":
def obj_contains_all(needle, haystack):
"""
Check if needle is "sub-object" of haystack, meaning
needle must be fully contained in haystack,
however haystack can contain someting more.
Corenr case: list - this tries to ignore the order,
but it searches for first match, so beware of generic needles:
[{}, {"a":1}] is not found in [{"a":1}, {}], because
first elements are matched ({} is sub-object of {"a":1}),
however second objects no longer match. So, {} in the needle
is too generic to match and might result in unexpected behaviour.
"""
if isinstance(needle, str) or isinstance(needle, int):
return 0 if needle == haystack else 1
if isinstance(needle, list):
if not isinstance(haystack, list):
return 1
hs = haystack.copy()
for i in needle:
found = False
for j in hs:
if obj_contains_all(i, j) == 0:
hs.remove(j)
found = True
break
if not found:
return 1
return 0
if isinstance(needle, dict):
if not isinstance(haystack, dict):
return 1
for i in needle:
if i in haystack:
r = obj_contains_all(needle[i], haystack[i])
if r != 0:
return r
else:
return 1
return 0
pattern_j = json.loads(pattern)
stdout_j = json.loads(stdout)
ret = obj_contains_all(pattern_j, stdout_j)
else:
ret = (
0
if re.search(pattern, stdout, flags=re.MULTILINE | re.DOTALL)
is not None
else 1
)
if check_type == "default":
if ret == 0:
return True
elif check_type == "not":
if ret != 0:
return True
elif check_type == "full":
assert (
ret == 0
), f'Pattern "{pattern}" disappeared after {nmci.misc.format_duration(xtimeout.elapsed_time())} seconds, output was:\n{stdout}'
elif check_type == "not_full":
assert (
ret != 0
), f'Pattern "{pattern}" appeared after {nmci.misc.format_duration(xtimeout.elapsed_time())} seconds, output was:\n{stdout}'
if check_type == "default":
assert (
False
), f'Did not see the pattern "{pattern}" in {nmci.misc.format_duration(seconds)} seconds, output was:\n{stdout}'
elif check_type == "not":
assert (
False
), f'Did still see the pattern "{pattern}" in {nmci.misc.format_duration(seconds)} seconds, output was:\n{stdout}'
def compare_values(keyword, value1, value2):
func_mapper = {
"at least": operator.ge,
"at most": operator.le,
"exactly": operator.eq,
"more than": operator.gt,
"less than": operator.lt,
"different than": operator.ne,
}
assert keyword in func_mapper, (
f'Invalid operator keyword: "{keyword}", supported operators are:\n '
) + "\n ".join(func_mapper.keys())
return func_mapper[keyword](value1, value2)
def check_lines_command(
context,
command,
condition1,
seconds,
timeout=180,
interval=1,
maxread=100000,
pattern=None,
condition2=None,
):
xtimeout = nmci.util.start_timeout(seconds)
while xtimeout.loop_sleep(interval):
stdout = nmci.process.run_stdout(
command,
shell=True,
ignore_returncode=True,
ignore_stderr=True,
stderr=subprocess.STDOUT,
timeout=timeout,
)
if pattern is not None:
out = [line for line in stdout.split("\n") if re.search(pattern, line)]
pattern_text = f'containing pattern "{pattern}"'
else:
out = [line for line in stdout.split("\n") if line]
pattern_text = ""
ret = compare_values(condition1["op"], len(out), int(condition1["n_lines"]))
if condition2 is not None:
ret &= compare_values(
condition2["op"], len(out), int(condition2["n_lines"])
)
if ret:
return True
assert condition2 is None, (
f"""Command "{command}" {pattern_text} did not return """
f""" "{condition1["op"]}" "{condition1["n_lines"]}" """
f""" and "{condition2["op"]}" "{condition2["n_lines"]}" lines, """
f"""but "{len(out)}", output was:\n"""
) + "\n".join(out)
assert False, (
f"""Command "{command}" {pattern_text} did not return """
f""" "{condition1["op"]}" "{condition1["n_lines"]}" lines, but "{len(out)}", output was:\n"""
) + "\n".join(out)
@step('Noted value is visible with command "{command}"')
@step('Noted value is visible with command "{command}" in "{seconds}" seconds')
def noted_visible_command(context, command, seconds=2):
check_pattern_command(
context, command, context.noted["noted-value"], seconds, check_class="exact"
)
@step('Noted value is not visible with command "{command}"')
@step('Noted value is not visible with command "{command}" in "{seconds}" seconds')
def noted_not_visible_command(context, command, seconds=2):
return check_pattern_command(
context,
command,
context.noted["noted-value"],
seconds,
check_type="not",
check_class="exact",
)
@step('Noted value "{index}" is visible with command "{command}"')
@step(
'Noted value "{index}" is visible with command "{command}" in "{seconds}" seconds'
)
def noted_index_visible_command(context, command, index, seconds=2):
return check_pattern_command(
context, command, context.noted[index], seconds, check_class="exact"
)
@step('Noted value "{index}" is not visible with command "{command}"')
@step(
'Noted value "{index}" is not visible with command "{command}" in "{seconds}" seconds'
)
def noted_index_not_visible_command(context, command, index, seconds=2):
return check_pattern_command(
context,
command,
context.noted[index],
seconds,
check_type="not",
check_class="exact",
)
@step('"{pattern}" is visible with reproducer "{rname}"')
@step('"{pattern}" is visible with reproducer "{rname}" with options "{options}"')
@step('"{pattern}" is visible with reproducer "{rname}" in "{seconds}" seconds')
@step(
'"{pattern}" is visible with reproducer "{rname}" with options "{options}" in "{seconds}" seconds'
)
def pattern_visible_reproducer(context, pattern, rname, options="", seconds=2):
command = get_reproducer_command(rname, options)
return check_pattern_command(context, command, pattern, seconds)
@step('"{pattern}" is not visible with reproducer "{rname}"')
@step('"{pattern}" is not visible with reproducer "{rname}" with options "{options}"')
@step('"{pattern}" is not visible with reproducer "{rname}" in "{seconds}" seconds')
@step(
'"{pattern}" is not visible with reproducer "{rname}" with options "{options}" in "{seconds}" seconds'
)
def pattern_not_visible_reproducer(context, pattern, rname, options="", seconds=2):
command = get_reproducer_command(rname, options)
return check_pattern_command(context, command, pattern, seconds, check_type="not")
@step('"{pattern}" is visible with command "{command}"')
@step('"{pattern}" is visible with command "{command}" in "{seconds}" seconds')
def pattern_visible_command(context, command, pattern, seconds=2):
return check_pattern_command(context, command, pattern, seconds)
@step('"{pattern}" is not visible with command "{command}"')
@step('"{pattern}" is not visible with command "{command}" in "{seconds}" seconds')
def pattern_not_visible_command(context, command, pattern, seconds=2):
return check_pattern_command(context, command, pattern, seconds, check_type="not")
@step('String "{string}" is visible with command "{command}"')
@step('String "{string}" is visible with command "{command}" in "{seconds}" seconds')
def string_visible_command(context, command, string, seconds=2):
return check_pattern_command(context, command, string, seconds, check_class="exact")
@step('String "{string}" is not visible with command "{command}"')
@step(
'String "{string}" is not visible with command "{command}" in "{seconds}" seconds'
)
def string_not_visible_command(context, command, string, seconds=2):
return check_pattern_command(
context, command, string, seconds, check_type="not", check_class="exact"
)
@step('JSON "{string}" is visible with command "{command}"')
@step('JSON "{string}" is visible with command "{command}" in "{seconds}" seconds')
def json_visible_command(context, command, string, seconds=2):
return check_pattern_command(context, command, string, seconds, check_class="json")
@step('JSON "{string}" is not visible with command "{command}"')
@step('JSON "{string}" is not visible with command "{command}" in "{seconds}" seconds')
def json_not_visible_command(context, command, string, seconds=2):
return check_pattern_command(
context, command, string, seconds, check_type="not", check_class="json"
)
@step(
'Noted number of lines with pattern "{pattern}" is visible with command "{command}" in "{seconds}" seconds'
)
@step(
'Noted number of lines "{index}" with pattern "{pattern}" is visible with command "{command}" in "{seconds}" seconds'
)
def noted_lines_visible_command(
context, command, index="noted-value", seconds=2, pattern=None
):
return check_lines_command(
context=context,
command=command,
condition1={"n_lines": context.noted[index], "op": "exactly"},
seconds=seconds,
pattern=pattern,
)
@step(
'"{operator_kw1}" "{n_lines1}" and "{operator_kw2}" "{n_lines2}" lines are visible with command "{command}" in "{seconds}" seconds'
)
@step(
'"{operator_kw1}" "{n_lines1}" and "{operator_kw2}" "{n_lines2}" lines with pattern "{pattern}" are visible with command "{command}" in "{seconds}" seconds'
)
def range_lines_visible_command(
context,
command,
n_lines1,
n_lines2,
operator_kw1,
operator_kw2,
seconds=2,
pattern=None,
):
return check_lines_command(
context=context,
command=command,
condition1={"n_lines": n_lines1, "op": operator_kw1.lower()},
condition2={"n_lines": n_lines2, "op": operator_kw2.lower()},
seconds=seconds,
pattern=pattern,
)
@step('"{operator_kw}" "{n_lines}" lines are visible with command "{command}"')
@step(
'"{operator_kw}" "{n_lines}" lines are visible with command "{command}" in "{seconds}" seconds'
)
@step(
'"{operator_kw}" "{n_lines}" lines with pattern "{pattern}" are visible with command "{command}"'
)
@step(
'"{operator_kw}" "{n_lines}" lines with pattern "{pattern}" are visible with command "{command}" in "{seconds}" seconds'
)
def lines_visible_command(
context, command, n_lines, operator_kw, seconds=2, pattern=None
):
return check_lines_command(
context=context,
command=command,
condition1={"n_lines": n_lines, "op": operator_kw.lower()},
seconds=seconds,
pattern=pattern,
)
@step('"{pattern}" is visible with command "{command}" for full "{seconds}" seconds')
def pattern_visible_with_command_fortime(context, pattern, command, seconds):
return check_pattern_command(context, command, pattern, seconds, check_type="full")
@step(
'"{pattern}" is not visible with command "{command}" for full "{seconds}" seconds'
)
def pattern_not_visible_with_command_fortime(context, pattern, command, seconds):
return check_pattern_command(
context, command, pattern, seconds, check_type="not_full"
)
@step('Noted value is visible with command "{command}" for full "{seconds}" seconds')
@step(
'Noted value "{index}" is visible with command "{command}" for full "{seconds}" seconds'
)
def noted_value_visible_with_command_fortime(
context, command, seconds, index="noted_value"
):
return check_pattern_command(
context, command, context.noted[index], seconds, check_type="full"
)
@step(
'Noted value is not visible with command "{command}" for full "{seconds}" seconds'
)
@step(
'Noted value "{index}" is not visible with command "{command}" for full "{seconds}" seconds'
)
def noted_value_not_visible_with_command_fortime(
context, command, seconds, index="noted_value"
):
return check_pattern_command(
context, command, context.noted[index], seconds, check_type="not_full"
)
@step('"{pattern}" is visible with tab after "{command}"')
def pattern_visible_with_tab_after_command(context, pattern, command):
exp = nmci.pexpect.pexpect_spawn("/bin/bash")
exp.send("bind 'set page-completions Off' ;\n")
exp.send("bind 'set completion-query-items 0' ;\n")
exp.send(command)
exp.sendcontrol("i")
exp.sendcontrol("i")
exp.sendcontrol("i")
exp.sendeof()
assert (
exp.expect([pattern, pexpect.EOF], timeout=5) == 0
), f'pattern {pattern} is not visible with "{command}"'
@step('"{pattern}" is not visible with tab after "{command}"')
def pattern_not_visible_with_tab_after_command(context, pattern, command):
exp = nmci.pexpect.pexpect_spawn("/bin/bash")
exp.send("bind 'set page-completions Off' ;\n")
exp.send("bind 'set completion-query-items 0' ;\n")
exp.send(command)
exp.sendcontrol("i")
exp.sendcontrol("i")
exp.sendcontrol("i")
exp.sendeof()
assert (
exp.expect([pattern, pexpect.EOF, pexpect.TIMEOUT], timeout=5) != 0
), f'pattern {pattern} is visible with "{command}"'
def kill_dnsmasq(label):
"""Kill a running dnsmasq pexpect_service by label.
:param label: identifier used when starting (e.g. "ip4", "testX4")
"""
svc_label = f"dnsmasq_{label}"
for svc in nmci.pexpect.pexpect_service_find_all(
label=svc_label, running_only=True
):
svc.proc.kill(15)
svc.proc.expect([pexpect.EOF, pexpect.TIMEOUT], timeout=10)
@step('Kill dnsmasq for "{label}"')
def kill_dnsmasq_step(context, label):
kill_dnsmasq(label)
def start_dnsmasq(label, namespace=None, options=""):
"""Start dnsmasq as a foreground pexpect_service with automatic cleanup.
:param label: identifier for log/pid files (e.g. "ip4", "ip6", "vlan")
:param namespace: network namespace to run in (e.g. "testX_ns"), or None
:param options: extra dnsmasq arguments (e.g. "--dhcp-range=...")
"""
svc_label = f"dnsmasq_{label}"
log_file = f"/tmp/{svc_label}.log"
pid_file = f"/tmp/{svc_label}.pid"
kill_dnsmasq(label)
cmd = (
f"dnsmasq --keep-in-foreground"
f" --log-facility={log_file}"
f" --pid-file={pid_file}"
f" --conf-file=/dev/null"
f" --no-hosts"
)
if options:
cmd += f" {options}"
if namespace:
cmd = f"ip netns exec {namespace} {cmd}"
nmci.pexpect.pexpect_service(cmd, shell=True, label=svc_label)
nmci.cleanup.add_callback(
callback=lambda: nmci.embed.embed_file_if_exists(
f"{svc_label}.log", log_file, fail_only=True
),
name=f"{svc_label}_log_embed",
)
nmci.cleanup.add_file(log_file)
nmci.cleanup.add_file(pid_file)
@step('Start dnsmasq for "{label}" with options "{options}"')
@step('Start dnsmasq for "{label}" in namespace "{namespace}" with options "{options}"')
def start_dnsmasq_step(context, label, options, namespace=None):
options = nmci.misc.str_replace_dict(options, context.noted)
start_dnsmasq(label, namespace=namespace, options=options)
@step('Run child "{command}"')
def run_child_process(context, command):
command = nmci.misc.str_replace_dict(command, context.noted)
nmci.pexpect.pexpect_service(command, shell=True, label="child")
@step('Run child "{command}" without shell')
def run_child_process_no_shell(context, command):
nmci.pexpect.pexpect_service(command, label="child")
@step("Wait for children")
def wait_for_children(context):
for child in nmci.pexpect.pexpect_service_find_all("child"):
child.proc.wait()
@step('Expect "{pattern}" in children in "{seconds}" seconds')
def expect_children(context, pattern, seconds, proc_action=None):
seconds = float(seconds)
pattern = nmci.misc.str_replace_dict(pattern, context.noted)
for child in nmci.pexpect.pexpect_service_find_all("child", running_only=True):
# print(f"expect in {child.proc.pid} {child.proc.isalive()}")
proc = child.proc
r = proc.expect(
[pattern, nmci.pexpect.EOF, nmci.pexpect.TIMEOUT], timeout=seconds
)
assert (
r != 1
), f"Child {proc.name} exited without '{pattern}' in output:\n{proc.before}"
assert (
r != 2
), f"Child {proc.name} did not output '{pattern}' within {seconds}s:\n{proc.before}"
if proc_action is not None:
proc_action(proc)
@step('Do not expect "{pattern}" in children in "{seconds}" seconds')
def not_expect_children(context, pattern, seconds):
seconds = float(seconds)
pattern = nmci.misc.str_replace_dict(pattern, context.noted)
for child in nmci.pexpect.pexpect_service_find_all("child"):
proc = child.proc
r = proc.expect(
[pattern, nmci.pexpect.EOF, nmci.pexpect.TIMEOUT], timeout=seconds
)
assert (
r != 0
), f"Child {proc.name} has '{pattern}' in output:\n{proc.before}{proc.after}"
@step('Expect "{pattern}" in children in "{seconds}" seconds and kill')
@step(
'Expect "{pattern}" in children in "{seconds}" seconds and kill with signal "{signal}"'
)
def expect_children_kill(context, pattern, seconds, signal=15):
signal = int(signal)
expect_children(context, pattern, seconds, lambda p: p.kill(signal))
@step("Kill children")
@step('Kill children with signal "{signal}"')
def kill_children(context, signal=9):
for child in nmci.pexpect.pexpect_service_find_all("child"):
# print(f"before kill {child.proc.pid} {child.proc.isalive()}")
child.proc.kill(int(signal))
# print(f"after kill {child.proc.pid} {child.proc.isalive()}")
@step("Start following journal")
def start_tailing_journal(context):
context.journal = nmci.pexpect.pexpect_service(
"journalctl --follow -o cat", timeout=180
)
with nmci.util.start_timeout(10) as t:
while t.loop_sleep(0.2):
nmci.process.run_stdout("logger nmci_journal_follow")
if (
context.journal.expect(
["nmci_journal_follow", nmci.pexpect.TIMEOUT], timeout=0.2
)
== 0
):
break
@step('"{content}" is visible in journal')
@step('"{content}" is visible in journal in "{timeout}" seconds')
def find_in_tailing_journal(context, content, timeout=180):
if (
context.journal.expect(
[content, pexpect.TIMEOUT, pexpect.EOF], timeout=float(timeout)
)
== 1
):
raise Exception(
f'Did not see the "{content}" in journal output before timeout ("{timeout}" seconds)'
)
@step('"{content}" is not visible in journal')
@step('"{content}" is not visible in journal in "{timeout}" seconds')
def find_not_in_tailing_journal(context, content, timeout=2):
if (
context.journal.expect(
[content, pexpect.TIMEOUT, pexpect.EOF], timeout=float(timeout)
)
== 0
):
raise Exception(f'"{content}" was found in the journal output.')
@step('Start monitoring "{proc}" CPU usage with threshold "{thr}"')
def start_cpu_proc_monitor(context, proc, thr):
context.proc_mon = getattr(context, "proc_mon", {})
context.proc_mon[proc] = nmci.pexpect.pexpect_service(
f"nmci/helpers/proc_cpu_usage_monitor.py {proc} {thr}"
)
@step('NM was not using more than "{perc}%" of CPU')
def nm_cpu_usage(context, perc):
perc = float(perc)
context.proc_mon["NetworkManager"].kill(10)
context.journal.expect("Average NetworkManager usage: [0-9.]*")
msg = context.journal.after
used_perc = float(msg.split(" ")[-1])
assert used_perc <= perc, f"NM was using {used_perc}% of CPU, threshold {perc}%"
@step('Wait for "{secs}" seconds')
def wait_for_x_seconds(context, secs):
time.sleep(float(secs))
@step('Wait for up to "{secs}" random seconds')
def wait_for_random_seconds(context, secs):
rnd = nmci.util.random_float(3288708979)
secs = float(secs)
secs = secs * rnd
time.sleep(secs)
@step('Look for "{content}" in tailed file')
def find_tailing(context, content):
assert (
context.tail.expect([content, pexpect.TIMEOUT, pexpect.EOF]) != 1
), f'Did not see the "{content}" in tail output before timeout (180s)'
@step('Start tailing file "{archivo}"')
def start_tailing(context, archivo):
context.tail = nmci.pexpect.pexpect_service(f"tail -f {archivo}", timeout=180)
time.sleep(0.3)
@step('Ping "{domain}"')
@step('Ping "{domain}" "{number}" times')
def ping_domain(context, domain, number=2):
if number != 2:
rc = nmci.process.run(
f"ping -q -4 -c {number} {domain}",
timeout=30,
ignore_stderr=True,
).returncode
else:
rc = nmci.process.run(f"curl -s {domain}", timeout=30).returncode
assert rc == 0
@step('Ping "{domain}" from "{device}" device')
def ping_domain_from_device(context, domain, device):
rc = nmci.process.run(
f"ping -4 -c 2 -I {device} {domain}", ignore_stderr=True
).returncode
assert rc == 0
@step('Ping6 "{domain}"')
def ping6_domain(context, domain):
rc = nmci.process.run(
f"ping6 -c 2 {domain}", timeout=30, ignore_stderr=True
).returncode
assert rc == 0
@step('Unable to ping "{domain}"')
def cannot_ping_domain(context, domain):
rc = nmci.process.run(f"curl {domain}", timeout=30, ignore_stderr=True).returncode
assert rc != 0
@step('Unable to ping "{domain}" from "{device}" device')
def cannot_ping_domain_from_device(context, domain, device):
assert (
nmci.process.run(
["ping", "-c", "2", "-I", device, domain],
timeout=30,
ignore_stderr=True,
).returncode
!= 0
)
@step('Unable to ping6 "{domain}"')
def cannot_ping6_domain(context, domain):
assert (