forked from daos-stack/daos
-
Notifications
You must be signed in to change notification settings - Fork 0
/
node_local_test.py
executable file
·4295 lines (3508 loc) · 143 KB
/
node_local_test.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/python3
"""
Node local test (NLT).
Test script for running DAOS on a single node over tmpfs and running initial
smoke/unit tests.
Includes support for DFuse with a number of unit tests, as well as stressing
the client with fault injection of D_ALLOC() usage.
"""
# pylint: disable=too-many-lines
import os
from os.path import join
import sys
import time
import uuid
import json
import copy
import signal
import pprint
import stat
import errno
import argparse
import tabulate
import threading
import functools
import traceback
import subprocess #nosec
import junit_xml
import tempfile
import pickle #nosec
import xattr
from collections import OrderedDict
import yaml
class NLTestFail(Exception):
"""Used to indicate test failure"""
class NLTestNoFi(NLTestFail):
"""Used to indicate Fault injection didn't work"""
class NLTestNoFunction(NLTestFail):
"""Used to indicate a function did not log anything"""
def __init__(self, function):
super().__init__(self)
self.function = function
class NLTestTimeout(NLTestFail):
"""Used to indicate that an operation timed out"""
instance_num = 0
def get_inc_id():
"""Return a unique character"""
global instance_num
instance_num += 1
return '{:04d}'.format(instance_num)
def umount(path, bg=False):
"""Umount dfuse from a given path"""
if bg:
cmd = ['fusermount3', '-uz', path]
else:
cmd = ['fusermount3', '-u', path]
ret = subprocess.run(cmd, check=False)
print('rc from umount {}'.format(ret.returncode))
return ret.returncode
class NLTConf():
"""Helper class for configuration"""
def __init__(self, bc, args):
self.bc = bc
self.agent_dir = None
self.wf = None
self.args = None
self.max_log_size = None
self.valgrind_errors = False
self.lt = CulmTimer()
self.lt_compress = CulmTimer()
self.dfuse_parent_dir = tempfile.mkdtemp(dir=args.dfuse_dir,
prefix='dnt_dfuse_')
self.tmp_dir = None
if args.class_name:
self.tmp_dir = join('nlt_logs', args.class_name)
if os.path.exists(self.tmp_dir):
for old_file in os.listdir(self.tmp_dir):
os.unlink(join(self.tmp_dir, old_file))
os.rmdir(self.tmp_dir)
os.makedirs(self.tmp_dir)
self._compress_procs = []
def __del__(self):
self.flush_bz2()
os.rmdir(self.dfuse_parent_dir)
def set_wf(self, wf):
"""Set the WarningsFactory object"""
self.wf = wf
def set_args(self, args):
"""Set command line args"""
self.args = args
# Parse the max log size.
if args.max_log_size:
size = args.max_log_size
if size.endswith('MiB'):
size = int(size[:-3])
size *= (1024 * 1024)
elif size.endswith('GiB'):
size = int(size[:-3])
size *= (1024 * 1024 * 1024)
self.max_log_size = int(size)
def __getitem__(self, key):
return self.bc[key]
def compress_file(self, filename):
"""Compress a file using bz2 for space reasons
Launch a bzip2 process in the background as this is time consuming, and each time
a new process is launched then reap any previous ones which have completed.
"""
# pylint: disable=consider-using-with
self._compress_procs[:] = (proc for proc in self._compress_procs if proc.poll())
self._compress_procs.append(subprocess.Popen(['bzip2', '--best', filename]))
def flush_bz2(self):
"""Wait for all bzip2 subprocess to finish"""
self.lt_compress.start()
for proc in self._compress_procs:
proc.wait()
self._compress_procs = []
self.lt_compress.stop()
class CulmTimer():
"""Class to keep track of elapsed time so we know where to focus performance tuning"""
def __init__(self):
self.total = 0
self._start = None
def start(self):
"""Start the timer"""
self._start = time.time()
def stop(self):
"""Stop the timer, and add elapsed to total"""
self.total += time.time() - self._start
class BoolRatchet():
"""Used for saving test results"""
# Any call to fail() of add_result with a True value will result
# in errors being True.
def __init__(self):
self.errors = False
def fail(self):
"""Mark as failure"""
self.errors = True
def add_result(self, result):
"""Save result, keep record of failure"""
if result:
self.fail()
class WarningsFactory():
"""Class to parse warnings, and save to JSON output file
Take a list of failures, and output the data in a way that is best
displayed according to
https://github.com/jenkinsci/warnings-ng-plugin/blob/master/doc/Documentation.md
"""
# Error levels supported by the reporting are LOW, NORMAL, HIGH, ERROR.
def __init__(self,
filename,
junit=False,
class_id=None,
post=False,
post_error=False,
check=None):
# pylint: disable=consider-using-with
self._fd = open(filename, 'w')
self.filename = filename
self.post = post
self.post_error = post_error
self.check = check
self.issues = []
self._class_id = class_id
self.pending = []
self._running = True
# Save the filename of the object, as __file__ does not
# work in __del__
self._file = __file__.lstrip('./')
self._flush()
if junit:
# Insert a test-case and force it to failed. Save this to file
# and keep it there, until close() method is called, then remove
# it and re-save. This means any crash will result in there
# being a results file with an error recorded.
tc = junit_xml.TestCase('Sanity', classname=self._class_name('core'))
tc.add_error_info('NLT exited abnormally')
test_case = junit_xml.TestCase('Startup', classname=self._class_name('core'))
self.ts = junit_xml.TestSuite('Node Local Testing', test_cases=[test_case, tc])
self._write_test_file()
else:
self.ts = None
def _class_name(self, class_name):
"""Return a formatted ID string for class"""
if self._class_id:
return 'NLT.{}.{}'.format(self._class_id, class_name)
return 'NLT.{}'.format(class_name)
def __del__(self):
"""Ensure the file is flushed on exit, but if it hasn't already
been closed then mark an error"""
if not self._fd:
return
entry = {}
entry['fileName'] = self._file
# pylint: disable=protected-access
entry['lineStart'] = sys._getframe().f_lineno
entry['message'] = 'Tests exited without shutting down properly'
entry['severity'] = 'ERROR'
self.issues.append(entry)
# Do not try and write the junit file here, as that does not work
# during teardown.
self.ts = None
self.close()
def add_test_case(self, name, failure=None, test_class='core', output=None, duration=None,
stdout=None, stderr=None):
"""Add a test case to the results
class and other metadata will be set automatically,
if failure is set the test will fail with the message
provided. Saves the state to file after each update.
"""
if not self.ts:
return
tc = junit_xml.TestCase(name, classname=self._class_name(test_class), elapsed_sec=duration,
stdout=stdout, stderr=stderr)
if failure:
tc.add_failure_info(failure, output=output)
self.ts.test_cases.append(tc)
self._write_test_file()
def _write_test_file(self):
"""Write test results to file"""
with open('nlt-junit.xml', 'w') as f:
junit_xml.TestSuite.to_file(f, [self.ts], prettyprint=True)
def explain(self, line, log_file, esignal):
"""Log an error, along with the other errors it caused
Log the line as an error, and reference everything in the pending
array.
"""
count = len(self.pending)
symptoms = set()
locs = set()
mtype = 'Fault injection'
sev = 'LOW'
if esignal:
symptoms.add('Process died with signal {}'.format(esignal))
sev = 'ERROR'
mtype = 'Fault injection caused crash'
count += 1
if count == 0:
return
for (sline, smessage) in self.pending:
locs.add('{}:{}'.format(sline.filename, sline.lineno))
symptoms.add(smessage)
preamble = 'Fault injected here caused {} errors,' \
' logfile {}:'.format(count, log_file)
message = '{} {} {}'.format(preamble,
' '.join(sorted(symptoms)),
' '.join(sorted(locs)))
self.add(line,
sev,
message,
cat='Fault injection location',
mtype=mtype)
self.pending = []
def add(self, line, sev, message, cat=None, mtype=None):
"""Log an error
Describe an error and add it to the issues array.
Add it to the pending array, for later clarification
"""
entry = {}
entry['fileName'] = line.filename
if mtype:
entry['type'] = mtype
else:
entry['type'] = message
if cat:
entry['category'] = cat
entry['lineStart'] = line.lineno
# Jenkins no longer seems to display the description.
entry['description'] = message
entry['message'] = '{}\n{}'.format(line.get_anon_msg(), message)
entry['severity'] = sev
self.issues.append(entry)
if self.pending and self.pending[0][0].pid != line.pid:
self.reset_pending()
self.pending.append((line, message))
self._flush()
if self.post or (self.post_error and sev in ('HIGH', 'ERROR')):
# https://docs.github.com/en/actions/reference/workflow-commands-for-github-actions
if self.post_error:
message = line.get_msg()
print('::warning file={},line={},::{}, {}'.format(line.filename,
line.lineno,
self.check,
message))
def reset_pending(self):
"""Reset the pending list
Should be called before iterating on each new file, so errors
from previous files aren't attributed to new files.
"""
self.pending = []
def _flush(self):
"""Write the current list to the json file
This is done just in case of crash. This function might get called
from the __del__ method of DaosServer, so do not use __file__ here
either.
"""
self._fd.seek(0)
self._fd.truncate(0)
data = {}
data['issues'] = list(self.issues)
if self._running:
# When the test is running insert an error in case of abnormal
# exit, so that crashes in this code can be identified.
entry = {}
entry['fileName'] = self._file
# pylint: disable=protected-access
entry['lineStart'] = sys._getframe().f_lineno
entry['severity'] = 'ERROR'
entry['message'] = 'Tests are still running'
data['issues'].append(entry)
json.dump(data, self._fd, indent=2)
self._fd.flush()
def close(self):
"""Save, and close the log file"""
self._running = False
self._flush()
self._fd.close()
self._fd = None
print('Closed JSON file {} with {} errors'.format(self.filename,
len(self.issues)))
if self.ts:
# This is a controlled shutdown, so wipe the error saying forced
# exit.
self.ts.test_cases[1].errors = []
self.ts.test_cases[1].error_message = []
self._write_test_file()
def load_conf(args):
"""Load the build config file"""
file_self = os.path.dirname(os.path.abspath(__file__))
json_file = None
while True:
new_file = join(file_self, '.build_vars.json')
if os.path.exists(new_file):
json_file = new_file
break
file_self = os.path.dirname(file_self)
if file_self == '/':
raise Exception('build file not found')
with open(json_file, 'r') as ofh:
conf = json.load(ofh)
return NLTConf(conf, args)
def get_base_env(clean=False):
"""Return the base set of env vars needed for DAOS"""
if clean:
env = OrderedDict()
else:
env = os.environ.copy()
env['DD_MASK'] = 'all'
env['DD_SUBSYS'] = 'all'
env['D_LOG_MASK'] = 'DEBUG'
env['D_LOG_SIZE'] = '5g'
env['FI_UNIVERSE_SIZE'] = '128'
return env
class DaosPool():
"""Class to store data about daos pools"""
def __init__(self, server, pool_uuid, label):
self._server = server
self.uuid = pool_uuid
self.label = label
def id(self):
"""Return the pool ID (label if set; UUID otherwise)"""
if self.label:
return self.label
return self.uuid
def dfuse_mount_name(self):
"""Return the string to pass to dfuse mount
This should be a label if set, otherwise just the
uuid.
"""
return self.id()
class DaosServer():
"""Manage a DAOS server instance"""
def __init__(self, conf, test_class=None, valgrind=False, wf=None, fe=None):
self.running = False
self._file = __file__.lstrip('./')
self._sp = None
self.wf = wf
self.fe = fe
self.conf = conf
if test_class:
self._test_class = 'Server.{}'.format(test_class)
else:
self._test_class = None
self.valgrind = valgrind
self._agent = None
self.engines = conf.args.engine_count
# pylint: disable=consider-using-with
self.control_log = tempfile.NamedTemporaryFile(prefix='dnt_control_',
suffix='.log',
dir=conf.tmp_dir,
delete=False)
self.agent_log = tempfile.NamedTemporaryFile(prefix='dnt_agent_',
suffix='.log',
dir=conf.tmp_dir,
delete=False)
self.server_logs = []
for engine in range(self.engines):
prefix = 'dnt_server_{}_'.format(engine)
lf = tempfile.NamedTemporaryFile(prefix=prefix,
suffix='.log',
dir=conf.tmp_dir,
delete=False)
self.server_logs.append(lf)
self.__process_name = 'daos_engine'
if self.valgrind:
self.__process_name = 'valgrind'
socket_dir = '/tmp/dnt_sockets'
if not os.path.exists(socket_dir):
os.mkdir(socket_dir)
self.agent_dir = tempfile.mkdtemp(prefix='dnt_agent_')
self._yaml_file = None
self._io_server_dir = None
self.test_pool = None
self.network_interface = None
self.network_provider = None
# Detect the number of cores for dfuse and do something sensible, if there are
# more than 32 on the node then use 12, otherwise use the whole node.
num_cores = len(os.sched_getaffinity(0))
if num_cores > 32:
self.dfuse_cores = 12
else:
self.dfuse_cores = None
self.fuse_procs = []
def __enter__(self):
self.start()
return self
def __exit__(self, _type, _value, _traceback):
rc = self.stop(self.wf)
if rc != 0 and self.fe is not None:
self.fe.fail()
return False
def add_fuse(self, fuse):
"""Register a new fuse instance"""
self.fuse_procs.append(fuse)
def remove_fuse(self, fuse):
"""Deregister a fuse instance"""
self.fuse_procs.remove(fuse)
def __del__(self):
if self._agent:
self._stop_agent()
try:
if self.running:
self.stop(None)
except NLTestTimeout:
print('Ignoring timeout on stop')
server_file = join(self.agent_dir, '.daos_server.active.yml')
if os.path.exists(server_file):
os.unlink(server_file)
for log in self.server_logs:
if os.path.exists(log.name):
log_test(self.conf, log.name)
try:
os.rmdir(self.agent_dir)
except OSError as error:
print(os.listdir(self.agent_dir))
raise error
def _add_test_case(self, op, failure=None, duration=None):
"""Add a test case to the server instance
Simply wrapper to automatically add the class
"""
if not self._test_class:
return
self.conf.wf.add_test_case(op,
failure=failure,
duration=duration,
test_class=self._test_class)
def _check_timing(self, op, start, max_time):
elapsed = time.time() - start
if elapsed > max_time:
res = '{} failed after {:.2f}s (max {:.2f}s)'.format(op, elapsed,
max_time)
self._add_test_case(op, duration=elapsed, failure=res)
raise NLTestTimeout(res)
def _check_system_state(self, desired_states):
"""Check the system state for against list
Return true if all members are in a state specified by the
desired_states.
"""
if not isinstance(desired_states, list):
desired_states = [desired_states]
rc = self.run_dmg(['system', 'query', '--json'])
if rc.returncode != 0:
return False
data = json.loads(rc.stdout.decode('utf-8'))
if data['error'] or data['status'] != 0:
return False
members = data['response']['members']
if members is None:
return False
if len(members) != self.engines:
return False
for member in members:
if member['state'] not in desired_states:
return False
return True
def start(self):
"""Start a DAOS server"""
# pylint: disable=consider-using-with
server_env = get_base_env(clean=True)
if self.valgrind:
valgrind_args = ['--fair-sched=yes',
'--xml=yes',
'--xml-file=dnt_server.%p.memcheck.xml',
'--num-callers=2',
'--leak-check=no',
'--keep-stacktraces=none',
'--undef-value-errors=no']
self._io_server_dir = tempfile.TemporaryDirectory(prefix='dnt_io_')
with open(join(self._io_server_dir.name, 'daos_engine'), 'w') as fd:
fd.write('#!/bin/sh\n')
fd.write('export PATH=$REAL_PATH\n')
fd.write('exec valgrind {} daos_engine "$@"\n'.format(' '.join(valgrind_args)))
os.chmod(join(self._io_server_dir.name, 'daos_engine'),
stat.S_IXUSR | stat.S_IRUSR)
server_env['REAL_PATH'] = '{}:{}'.format(
join(self.conf['PREFIX'], 'bin'), server_env['PATH'])
server_env['PATH'] = '{}:{}'.format(self._io_server_dir.name,
server_env['PATH'])
daos_server = join(self.conf['PREFIX'], 'bin', 'daos_server')
self_dir = os.path.dirname(os.path.abspath(__file__))
# Create a server yaml file. To do this open and copy the
# nlt_server.yaml file in the current directory, but overwrite
# the server log file with a temporary file so that multiple
# server runs do not overwrite each other.
with open(join(self_dir, 'nlt_server.yaml'), 'r') as scfd:
scyaml = yaml.safe_load(scfd)
if self.conf.args.server_debug:
scyaml['control_log_mask'] = 'ERROR'
scyaml['engines'][0]['log_mask'] = self.conf.args.server_debug
scyaml['control_log_file'] = self.control_log.name
scyaml['socket_dir'] = self.agent_dir
for (key, value) in server_env.items():
scyaml['engines'][0]['env_vars'].append('{}={}'.format(key, value))
ref_engine = copy.deepcopy(scyaml['engines'][0])
ref_engine['storage'][0]['scm_size'] = int(
ref_engine['storage'][0]['scm_size'] / self.engines)
scyaml['engines'] = []
# Leave some cores for dfuse, and start the daos server after these.
if self.dfuse_cores:
first_core = self.dfuse_cores
else:
first_core = 0
server_port_count = int(server_env['FI_UNIVERSE_SIZE'])
self.network_interface = ref_engine['fabric_iface']
self.network_provider = scyaml['provider']
for idx in range(self.engines):
engine = copy.deepcopy(ref_engine)
engine['log_file'] = self.server_logs[idx].name
engine['first_core'] = first_core + (ref_engine['targets'] * idx)
engine['fabric_iface_port'] += server_port_count * idx
engine['storage'][0]['scm_mount'] = '{}_{}'.format(
ref_engine['storage'][0]['scm_mount'], idx)
scyaml['engines'].append(engine)
self._yaml_file = tempfile.NamedTemporaryFile(
prefix='nlt-server-config-',
suffix='.yaml')
self._yaml_file.write(yaml.dump(scyaml, encoding='utf-8'))
self._yaml_file.flush()
cmd = [daos_server, '--config={}'.format(self._yaml_file.name), 'start', '--insecure']
if self.conf.args.no_root:
cmd.append('--recreate-superblocks')
self._sp = subprocess.Popen(cmd)
agent_config = join(self_dir, 'nlt_agent.yaml')
agent_bin = join(self.conf['PREFIX'], 'bin', 'daos_agent')
agent_cmd = [agent_bin,
'--config-path', agent_config,
'--insecure',
'--runtime_dir', self.agent_dir,
'--logfile', self.agent_log.name]
if not self.conf.args.server_debug:
agent_cmd.append('--debug')
self._agent = subprocess.Popen(agent_cmd)
self.conf.agent_dir = self.agent_dir
# Configure the storage. DAOS wants to mount /mnt/daos itself if not
# already mounted, so let it do that.
# This code supports three modes of operation:
# /mnt/daos is not mounted. It will be mounted and formatted.
# /mnt/daos exists and has data in. It will be used as is.
# /mnt/daos is mounted but empty. It will be used-as is.
# In this last case the --no-root option must be used.
start = time.time()
max_start_time = 120
cmd = ['storage', 'format', '--json']
while True:
try:
rc = self._sp.wait(timeout=0.5)
print(rc)
res = 'daos server died waiting for start'
self._add_test_case('format', failure=res)
raise Exception(res)
except subprocess.TimeoutExpired:
pass
rc = self.run_dmg(cmd)
data = json.loads(rc.stdout.decode('utf-8'))
print('cmd: {} data: {}'.format(cmd, data))
if data['error'] is None:
break
if 'running system' in data['error']:
break
self._check_timing('format', start, max_start_time)
duration = time.time() - start
self._add_test_case('format', duration=duration)
print('Format completion in {:.2f} seconds'.format(duration))
self.running = True
# Now wait until the system is up, basically the format to happen.
while True:
time.sleep(0.5)
if self._check_system_state(['ready', 'joined']):
break
self._check_timing("start", start, max_start_time)
duration = time.time() - start
self._add_test_case('start', duration=duration)
print('Server started in {:.2f} seconds'.format(duration))
self.fetch_pools()
def _stop_agent(self):
self._agent.send_signal(signal.SIGINT)
ret = self._agent.wait(timeout=5)
print('rc from agent is {}'.format(ret))
self._agent = None
def stop(self, wf):
"""Stop a previously started DAOS server"""
for fuse in self.fuse_procs:
print('Stopping server with running fuse procs, cleaning up')
self._add_test_case('server-stop-with-running-fuse', failure=str(fuse))
fuse.stop()
if self._agent:
self._stop_agent()
if not self._sp:
return 0
# Check the correct number of processes are still running at this
# point, in case anything has crashed. daos_server does not
# propagate errors, so check this here.
parent_pid = self._sp.pid
procs = []
for proc_id in os.listdir('/proc/'):
if proc_id == 'self':
continue
status_file = '/proc/{}/status'.format(proc_id)
if not os.path.exists(status_file):
continue
with open(status_file, 'r') as fd:
for line in fd.readlines():
try:
key, v = line.split(':', maxsplit=2)
except ValueError:
continue
value = v.strip()
if key == 'Name' and value != self.__process_name:
break
if key != 'PPid':
continue
if int(value) == parent_pid:
procs.append(proc_id)
break
if len(procs) != self.engines:
# Mark this as a warning, but not a failure. This is currently
# expected when running with pre-existing data because the server
# is calling exec. Do not mark as a test failure for the same
# reason.
entry = {}
entry['fileName'] = self._file
# pylint: disable=protected-access
entry['lineStart'] = sys._getframe().f_lineno
entry['severity'] = 'NORMAL'
message = 'Incorrect number of engines running ({} vs {})'\
.format(len(procs), self.engines)
entry['message'] = message
self.conf.wf.issues.append(entry)
self._add_test_case('server_stop', failure=message)
rc = self.run_dmg(['system', 'stop'])
if rc.returncode != 0:
print(rc)
entry = {}
entry['fileName'] = self._file
# pylint: disable=protected-access
entry['lineStart'] = sys._getframe().f_lineno
entry['severity'] = 'ERROR'
msg = 'dmg system stop failed with {}'.format(rc.returncode)
entry['message'] = msg
self.conf.wf.issues.append(entry)
assert rc.returncode == 0, rc
start = time.time()
max_stop_time = 30
while True:
time.sleep(0.5)
if self._check_system_state('stopped'):
break
self._check_timing("stop", start, max_stop_time)
duration = time.time() - start
self._add_test_case('stop', duration=duration)
print('Server stopped in {:.2f} seconds'.format(duration))
self._sp.send_signal(signal.SIGTERM)
ret = self._sp.wait(timeout=5)
print('rc from server is {}'.format(ret))
self.conf.compress_file(self.agent_log.name)
self.conf.compress_file(self.control_log.name)
for log in self.server_logs:
log_test(self.conf, log.name, leak_wf=wf)
self.server_logs.remove(log)
self.running = False
return ret
def run_dmg(self, cmd):
"""Run the specified dmg command"""
exe_cmd = [join(self.conf['PREFIX'], 'bin', 'dmg')]
exe_cmd.append('--insecure')
exe_cmd.extend(cmd)
print('running {}'.format(exe_cmd))
return subprocess.run(exe_cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
check=False)
def run_dmg_json(self, cmd):
"""Run the specified dmg command in json mode
return data as json, or raise exception on failure
"""
cmd.append('--json')
rc = self.run_dmg(cmd)
print(rc)
assert rc.returncode == 0
assert rc.stderr == b''
data = json.loads(rc.stdout.decode('utf-8'))
assert not data['error']
assert data['status'] == 0
assert data['response']['status'] == 0
return data
def fetch_pools(self):
"""Query the server and return a list of pool objects"""
data = self.run_dmg_json(['pool', 'list'])
# This should exist but might be 'None' so check for that rather than
# iterating.
pools = []
if not data['response']['pools']:
return pools
for pool in data['response']['pools']:
pobj = DaosPool(self,
pool['uuid'],
pool.get('label', None))
pools.append(pobj)
if pobj.label == 'NLT':
self.test_pool = pobj
return pools
def _make_pool(self):
"""Create a DAOS pool"""
size = 1024*2
rc = self.run_dmg(['pool',
'create',
'--label',
'NLT',
'--scm-size',
'{}M'.format(size)])
print(rc)
assert rc.returncode == 0
self.fetch_pools()
def get_test_pool(self):
"""Return a pool uuid to be used for testing
Create a pool as required"""
if self.test_pool is None:
self._make_pool()
return self.test_pool.uuid
def get_test_pool_id(self):
"""Return a pool uuid to be used for testing
Create a pool as required"""
if self.test_pool is None:
self._make_pool()
return self.test_pool.id()
def il_cmd(dfuse, cmd, check_read=True, check_write=True, check_fstat=True):
"""Run a command under the interception library
Do not run valgrind here, not because it's not useful
but the options needed are different. Valgrind handles
linking differently so some memory is wrongly lost that
would be freed in the _fini() function, and a lot of
commands do not free all memory anyway.
"""
my_env = get_base_env()
prefix = 'dnt_dfuse_il_{}_'.format(get_inc_id())
with tempfile.NamedTemporaryFile(prefix=prefix, suffix='.log', delete=False) as log_file:
log_name = log_file.name
my_env['D_LOG_FILE'] = log_name
my_env['LD_PRELOAD'] = join(dfuse.conf['PREFIX'], 'lib64', 'libioil.so')
# pylint: disable=protected-access
my_env['DAOS_AGENT_DRPC_DIR'] = dfuse._daos.agent_dir
my_env['D_IL_REPORT'] = '2'
ret = subprocess.run(cmd, env=my_env, check=False)
print('Logged il to {}'.format(log_name))
print(ret)
if dfuse.caching:
check_fstat = False
try:
log_test(dfuse.conf, log_name, check_read=check_read, check_write=check_write,
check_fstat=check_fstat)
assert ret.returncode == 0
except NLTestNoFunction as error:
print("ERROR: command '{}' did not log via {}".format(' '.join(cmd), error.function))
ret.returncode = 1
return ret
class ValgrindHelper():
"""Class for running valgrind commands
This helps setup the command line required, and
performs log modification after the fact to assist
Jenkins in locating the source code.
"""
def __init__(self, conf, logid=None):
# Set this to False to disable valgrind, which will run faster.
self.conf = conf
self.use_valgrind = True
self.full_check = True
self._xml_file = None
self._logid = logid
self.src_dir = '{}/'.format(os.path.realpath(
os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
def get_cmd_prefix(self):
"""Return the command line prefix"""
if not self.use_valgrind:
return []
if not self._logid:
self._logid = get_inc_id()
with tempfile.NamedTemporaryFile(prefix='dnt.{}.'.format(self._logid), dir='.',
suffix='.memcheck', delete=False) as log_file:
self._xml_file = log_file.name
cmd = ['valgrind', '--fair-sched=yes']
if self.full_check:
cmd.extend(['--leak-check=full', '--show-leak-kinds=all'])
else:
cmd.append('--leak-check=no')
cmd.append('--gen-suppressions=all')
src_suppression_file = join('src', 'cart', 'utils', 'memcheck-cart.supp')
if os.path.exists(src_suppression_file):
cmd.append('--suppressions={}'.format(src_suppression_file))
else:
cmd.append('--suppressions={}'.format(
join(self.conf['PREFIX'], 'etc', 'memcheck-cart.supp')))
cmd.append('--error-exitcode=42')
cmd.extend(['--xml=yes', '--xml-file={}'.format(self._xml_file)])
return cmd