-
Notifications
You must be signed in to change notification settings - Fork 298
/
node_local_test.py
executable file
·6568 lines (5306 loc) · 225 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/env python3
"""Node local test (NLT).
(C) Copyright 2020-2024 Intel Corporation.
SPDX-License-Identifier: BSD-2-Clause-Patent
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 argparse
import copy
import errno
import functools
import json
import os
import pickle # nosec
import pprint
import pwd
import random
import re
import shutil
import signal
import stat
import subprocess # nosec
import sys
import tempfile
import threading
import time
import traceback
import uuid
from os.path import join
import junit_xml
import tabulate
import xattr
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 # pylint: disable=invalid-name
def get_inc_id():
"""Return a unique character"""
global instance_num # pylint: disable=invalid-name
instance_num += 1
return f'{instance_num:04d}'
def umount(path, background=False):
"""Umount dfuse from a given path"""
if background:
cmd = ['fusermount3', '-uz', path]
else:
cmd = ['fusermount3', '-u', path]
ret = subprocess.run(cmd, check=False)
print(f'rc from umount {ret.returncode}')
return ret.returncode
class NLTConf():
"""Helper class for configuration"""
def __init__(self, json_file, args):
with open(json_file, 'r') as ofh:
self._bc = json.load(ofh)
self.agent_dir = None
self.wf = None
self.args = None
self.max_log_size = None
self.valgrind_errors = False
self.log_timer = CulmTimer()
self.compress_timer = 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() is None)
self._compress_procs.append(subprocess.Popen(['nice', '-19', 'bzip2', '--best', filename]))
def flush_bz2(self):
"""Wait for all bzip2 subprocess to finish"""
self.compress_timer.start()
for proc in self._compress_procs:
proc.wait()
self._compress_procs = []
self.compress_timer.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.perf_counter()
def stop(self):
"""Stop the timer, and add elapsed to total"""
self.total += time.perf_counter() - 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_startup = junit_xml.TestCase('Startup', classname=self._class_name('core'))
tc_sanity = junit_xml.TestCase('Sanity', classname=self._class_name('core'))
tc_sanity.add_error_info('NLT exited abnormally')
self.test_suite = junit_xml.TestSuite('Node Local Testing',
test_cases=[tc_startup, tc_sanity])
self._write_test_file()
else:
self.test_suite = None
def _class_name(self, class_name):
"""Return a formatted ID string for class"""
if self._class_id:
return f'NLT.{self._class_id}.{class_name}'
return f'NLT.{class_name}'
def __del__(self):
"""Ensure the file is flushed on exit.
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.test_suite = 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.test_suite:
return
test_case = junit_xml.TestCase(name, classname=self._class_name(test_class),
elapsed_sec=duration, stdout=stdout, stderr=stderr)
if failure:
test_case.add_failure_info(failure, output=output)
self.test_suite.test_cases.append(test_case)
self._write_test_file()
def _write_test_file(self):
"""Write test results to file"""
with open('nlt-junit.xml', 'w') as file:
junit_xml.TestSuite.to_file(file, [self.test_suite], 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(f'Process died with signal {esignal}')
sev = 'ERROR'
mtype = 'Fault injection caused crash'
count += 1
if count == 0:
return
for (sline, smessage) in self.pending:
locs.add(f'{sline.filename}:{sline.lineno}')
symptoms.add(smessage)
preamble = f'Fault injected here caused {count} errors, logfile {log_file}:'
message = f"{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'] = f'{line.get_anon_msg()}\n{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(f'::warning file={line.filename},line={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(f'Closed JSON file {self.filename} with {len(self.issues)} errors')
if self.test_suite:
# This is a controlled shutdown, so wipe the error saying forced exit.
self.test_suite.test_cases[1].errors = []
self.test_suite.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 NLTestFail('build file not found')
return NLTConf(json_file, args)
def get_base_env(clean=False):
"""Return the base set of env vars needed for DAOS"""
if clean:
env = {}
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'
# Enable this to debug memory errors, it has a performance impact but will scan the heap
# for corruption. See DAOS-12735 for why this can cause problems in practice.
# env['MALLOC_CHECK_'] = '3'
# Otherwise max number of contexts will be limited by number of cores
env['CRT_CTX_NUM'] = '32'
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
self.conf = server.conf
# pylint: disable-next=invalid-name
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()
def fetch_containers(self):
"""Query the server and return a list of container objects"""
rc = run_daos_cmd(self._server.conf, ['container', 'list', self.uuid], use_json=True)
data = rc.json
assert data['status'] == 0, rc
assert data['error'] is None, rc
if data['response'] is None:
print('No containers in pool')
return []
containers = []
for cont in data['response']:
containers.append(DaosCont(cont['uuid'], cont['label'], pool=self))
return containers
class DaosCont():
"""Class to store data about daos containers"""
def __init__(self, cont_uuid, label, pool):
self.uuid = cont_uuid
self.label = label
self.pool = pool
if pool is not None:
assert isinstance(self.pool, DaosPool)
# pylint: disable-next=invalid-name
def id(self):
"""Return the container ID (label if set; UUID otherwise)"""
if self.label:
return self.label
return self.uuid
def set_attrs(self, attrs):
"""Set container attributes.
Args:
attrs (dict): Dictionary of attributes to set.
"""
kvs = []
for key, value in attrs.items():
kvs.append(f'{key}:{value}')
cmd = ['container', 'set-attr', self.pool.id(), self.id(), ','.join(kvs)]
rc = run_daos_cmd(self.pool.conf, cmd, show_stdout=True)
print(rc)
assert rc.returncode == 0, rc
def destroy(self, valgrind=True, log_check=True, force=False):
"""Destroy the container
Args:
valgrind (bool, optional): Run the command under valgrind. Defaults to True.
log_check (bool, optional): Run log analysis. Defaults to True.
Raises:
NLTestFail: If Pool was not provided when object created.
"""
destroy_container(self.pool.conf, self.pool.id(), self.id(),
valgrind=valgrind, log_check=log_check, force=force)
class DaosServer():
"""Manage a DAOS server instance"""
def __init__(self, conf, test_class=None, valgrind=False, wf=None, fatal_errors=None,
enable_fi=False):
self.running = False
self._file = __file__.lstrip('./')
self._sp = None
self._fi = enable_fi
self._fi_file = None
self.wf = wf
self.fatal_errors = fatal_errors
self.conf = conf
if test_class:
self._test_class = f'Server.{test_class}'
else:
self._test_class = None
self.valgrind = valgrind
self._agent = None
self.max_start_time = 120
self.max_stop_time = 30
self.stop_sleep_time = 0.5
self.engines = conf.args.engine_count
self.sys_ram_rsvd = conf.args.system_ram_reserved
# pylint: disable=consider-using-with
self.control_log = tempfile.NamedTemporaryFile(prefix='dnt_control_',
suffix='.log',
dir=conf.tmp_dir,
delete=False)
self.helper_log = tempfile.NamedTemporaryFile(prefix='dnt_helper_',
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 = f'dnt_server_{self._test_class}_{engine}_'
self.server_logs.append(tempfile.NamedTemporaryFile(prefix=prefix,
suffix='.log',
dir=conf.tmp_dir,
delete=False))
self.__process_name = 'daos_engine'
if self.valgrind:
self.__process_name = 'memcheck-amd64-'
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
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.fatal_errors is not None:
self.fatal_errors.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.unlink(join(self.agent_dir, 'nlt_agent.yaml'))
os.rmdir(self.agent_dir)
except OSError as error:
print(os.listdir(self.agent_dir))
raise error
def _add_test_case(self, name, 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(name, failure=failure, duration=duration,
test_class=self._test_class)
def _check_timing(self, name, start, max_time):
elapsed = time.perf_counter() - start
if elapsed > max_time:
res = f'{name} failed after {elapsed:.2f}s (max {max_time:.2f}s)'
self._add_test_case(name, 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)
plain_env = os.environ.copy()
if self.valgrind:
valgrind_args = ['--fair-sched=yes',
'--gen-suppressions=all',
'--xml=yes',
'--xml-file=dnt.server.%p.memcheck.xml',
'--num-callers=10',
'--track-origins=yes',
'--leak-check=full']
suppression_file = join('src', 'cart', 'utils', 'memcheck-cart.supp')
if not os.path.exists(suppression_file):
suppression_file = join(self.conf['PREFIX'], 'etc', 'memcheck-cart.supp')
valgrind_args.append(f'--suppressions={os.path.realpath(suppression_file)}')
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(f"export PATH={join(self.conf['PREFIX'], 'bin')}:$PATH\n")
fd.write(f'exec valgrind {" ".join(valgrind_args)} daos_engine "$@"\n')
os.chmod(join(self._io_server_dir.name, 'daos_engine'),
stat.S_IXUSR | stat.S_IRUSR)
plain_env['PATH'] = f'{self._io_server_dir.name}:{plain_env["PATH"]}'
self.max_start_time = 300
self.max_stop_time = 600
self.stop_sleep_time = 10
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['engines'][0]['log_mask'] = self.conf.args.server_debug
scyaml['control_log_file'] = self.control_log.name
scyaml['helper_log_file'] = self.helper_log.name
scyaml['socket_dir'] = self.agent_dir
if self._fi:
# Set D_ALLOC to fail, but do not enable it. This can be changed later via
# the set_fi() method.
faults = {'fault_config': [{'id': 0,
'probability_x': 0,
'probability_y': 100}]}
self._fi_file = tempfile.NamedTemporaryFile(prefix='fi_', suffix='.yaml')
self._fi_file.write(yaml.dump(faults, encoding='utf=8'))
self._fi_file.flush()
server_env['D_FI_CONFIG'] = self._fi_file.name
for (key, value) in server_env.items():
# If server log is set via server_debug then do not also set env settings.
if self.conf.args.server_debug and key in ('DD_MASK', 'DD_SUBSYS', 'D_LOG_MASK'):
continue
scyaml['engines'][0]['env_vars'].append(f'{key}={value}')
if self.sys_ram_rsvd is not None:
scyaml['system_ram_reserved'] = self.sys_ram_rsvd
ref_engine = copy.deepcopy(scyaml['engines'][0])
scyaml['engines'] = []
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'] = ref_engine['targets'] * idx
engine['fabric_iface_port'] += server_port_count * idx
engine['storage'][0]['scm_mount'] = f'{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, 'start', f'--config={self._yaml_file.name}', '--insecure']
# pylint: disable=consider-using-with
self._sp = subprocess.Popen(cmd, env=plain_env)
agent_config = join(self.agent_dir, 'nlt_agent.yaml')
with open(agent_config, 'w') as fd:
agent_data = {
'access_points': scyaml['access_points'],
'control_log_mask': 'NOTICE', # INFO logs every client process connection
}
json.dump(agent_data, fd)
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 and not self.conf.args.client_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.perf_counter()
cmd = ['storage', 'format', '--json']
start_timeout = 0.5
while True:
try:
rc = self._sp.wait(timeout=start_timeout)
print(rc)
res = 'daos server died waiting for start'
self._add_test_case('format', failure=res)
raise NLTestFail(res)
except subprocess.TimeoutExpired:
pass
rc = self.run_dmg(cmd)
data = json.loads(rc.stdout.decode('utf-8'))
print(f'cmd: {cmd} data: {data}')
if data['error'] is None:
break
if 'running system' in data['error']:
break
if start_timeout < 5:
start_timeout *= 2
self._check_timing('format', start, self.max_start_time)
duration = time.perf_counter() - start
self._add_test_case('format', duration=duration)
print(f'Format completion in {duration:.2f} seconds')
self.running = True
# Now wait until the system is up, basically the format to happen.
start_timeout = 0.5
while True:
time.sleep(start_timeout)
if self._check_system_state(['ready', 'joined']):
break
if start_timeout < 5:
start_timeout *= 2
self._check_timing("start", start, self.max_start_time)
duration = time.perf_counter() - start
self._add_test_case('start', duration=duration)
print(f'Server started in {duration:.2f} seconds')
self.fetch_pools()
def _stop_agent(self):
self._agent.send_signal(signal.SIGINT)
ret = self._agent.wait(timeout=5)
print(f'rc from agent is {ret}')
self._agent = None
try:
os.unlink(join(self.agent_dir, 'daos_agent.sock'))
except FileNotFoundError:
pass
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 = f'/proc/{proc_id}/status'
if not os.path.exists(status_file):
continue
with open(status_file, 'r') as fd:
for line in fd.readlines():
try:
key, raw = line.split(':', maxsplit=2)
except ValueError:
continue
value = raw.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 preexisting 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 = f'Incorrect number of engines running ({len(procs)} vs {self.engines})'
entry['message'] = message
self.conf.wf.issues.append(entry)
self._add_test_case('server_stop', failure=message)
start = time.perf_counter()
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 = f'dmg system stop failed with {rc.returncode}'
entry['message'] = msg
self.conf.wf.issues.append(entry)
if not self.valgrind:
assert rc.returncode == 0, rc
while True:
time.sleep(self.stop_sleep_time)
if self._check_system_state(['stopped', 'errored']):
break
self._check_timing("stop", start, self.max_stop_time)
duration = time.perf_counter() - start
self._add_test_case('stop', duration=duration)
print(f'Server stopped in {duration:.2f} seconds')
self._sp.send_signal(signal.SIGTERM)
ret = self._sp.wait(timeout=5)
print(f'rc from server is {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, skip_fi=self._fi)
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(f'running {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"""
# If running as a small system with tmpfs already mounted then this is likely a docker
# container so restricted in size.
if self.conf.args.no_root:
size = 1024 * 2
else:
size = 1024 * 4
rc = self.run_dmg(['pool', 'create', 'NLT', '--scm-size', f'{size}M'])
print(rc)
assert rc.returncode == 0