-
Notifications
You must be signed in to change notification settings - Fork 306
/
Copy pathnode_local_test.py
executable file
·1570 lines (1268 loc) · 48.5 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
"""Test code for dfuse"""
# pylint: disable=too-many-lines
# pylint: disable=too-few-public-methods
import os
import sys
import time
import uuid
import yaml
import json
import signal
import stat
import argparse
import subprocess
import tempfile
import pickle
from collections import OrderedDict
class NLTestFail(Exception):
"""Used to indicate test failure"""
pass
class NLTestNoFi(NLTestFail):
"""Used to indicate Fault injection didn't work"""
pass
class NLTestNoFunction(NLTestFail):
"""Used to indicate a function did not log anything"""
def __init__(self, function):
super().__init__(self)
self.function = function
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):
"""Umount dfuse from a given path"""
cmd = ['fusermount3', '-u', path]
ret = subprocess.run(cmd)
print('rc from umount {}'.format(ret.returncode))
return ret.returncode
class NLT_Conf():
"""Helper class for configuration"""
def __init__(self, bc):
self.bc = bc
self.agent_dir = None
self.wf = None
self.args = None
def set_wf(self, wf):
"""Set the WarningsFactory object"""
self.wf = wf
def set_args(self, args):
"""Set command line args"""
self.args = args
def __getitem__(self, key):
return self.bc[key]
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 reporint are LOW, NORMAL, HIGH, ERROR.
# Errors from this list of functions are known to happen during shutdown
# for the time being, so are downgraded to LOW.
FLAKY_FUNCTIONS = ('ds_pool_child_purge')
def __init__(self, filename):
self._fd = open(filename, 'w')
self.issues = []
self.pending = []
self._running = True
# Save the filename of the object, as __file__ does not
# work in __del__
self._file = __file__.lstrip('./')
self._flush()
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'] = os.path.basename(self._file)
entry['directory'] = os.path.dirname(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)
self.close()
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:
print('Nothing to explain')
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['directory'] = os.path.dirname(line.filename)
entry['fileName'] = os.path.basename(line.filename)
if mtype:
entry['type'] = mtype
else:
entry['type'] = message
if cat:
entry['category'] = cat
entry['lineStart'] = line.lineno
entry['description'] = message
entry['message'] = line.get_anon_msg()
entry['severity'] = sev
if line.function in self.FLAKY_FUNCTIONS and \
entry['severity'] != 'ERROR':
entry['severity'] = 'LOW'
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()
def reset_pending(self):
"""Reset the pending list
Should be called before iterating on each new file, so errors
from previous files aren't attribured 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'] = os.path.basename(self._file)
entry['directory'] = os.path.dirname(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(len(self.issues)))
def load_conf():
"""Load the build config file"""
file_self = os.path.dirname(os.path.abspath(__file__))
json_file = None
while True:
new_file = os.path.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')
ofh = open(json_file, 'r')
conf = json.load(ofh)
ofh.close()
return NLT_Conf(conf)
def get_base_env():
"""Return the base set of env vars needed for DAOS"""
env = os.environ.copy()
env['DD_MASK'] = 'all'
env['DD_SUBSYS'] = 'all'
env['D_LOG_MASK'] = 'DEBUG'
env['FI_UNIVERSE_SIZE'] = '128'
return env
class DaosServer():
"""Manage a DAOS server instance"""
def __init__(self, conf, valgrind=False):
self.running = False
self._sp = None
self.conf = conf
self.valgrind = valgrind
self._agent = None
self.agent_dir = None
server_log_file = tempfile.NamedTemporaryFile(prefix='dnt_server_',
suffix='.log',
delete=False)
self._log_file = server_log_file.name
self.__process_name = 'daos_io_server'
if self.valgrind:
self.__process_name = 'valgrind'
socket_dir = '/tmp/dnt_sockets'
if not os.path.exists(socket_dir):
os.mkdir(socket_dir)
if os.path.exists(self._log_file):
os.unlink(self._log_file)
self._agent_dir = tempfile.TemporaryDirectory(prefix='dnt_agent_')
self.agent_dir = self._agent_dir.name
self._yaml_file = None
self._io_server_dir = None
self._size = os.statvfs('/mnt/daos')
capacity = self._size.f_blocks * self._size.f_bsize
mb = int(capacity / (1024*1024))
self.mb = mb
def __del__(self):
if self.running:
self.stop()
def start(self):
"""Start a DAOS server"""
daos_server = os.path.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.
scfd = open(os.path.join(self_dir, 'nlt_server.yaml'), 'r')
control_log_file = tempfile.NamedTemporaryFile(prefix='dnt_control_',
suffix='.log',
delete=False)
scyaml = yaml.load(scfd)
scyaml['servers'][0]['log_file'] = self._log_file
if self.conf.args.server_debug:
scyaml['servers'][0]['log_mask'] = self.conf.args.server_debug
scyaml['control_log_file'] = control_log_file.name
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()
server_env = get_base_env()
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_')
fd = open(os.path.join(self._io_server_dir.name,
'daos_io_server'), 'w')
fd.write('#!/bin/sh\n')
fd.write('export PATH=$REAL_PATH\n')
fd.write('exec valgrind {} daos_io_server "$@"\n'.format(
' '.join(valgrind_args)))
fd.close()
os.chmod(os.path.join(self._io_server_dir.name, 'daos_io_server'),
stat.S_IXUSR | stat.S_IRUSR)
server_env['REAL_PATH'] = '{}:{}'.format(
os.path.join(self.conf['PREFIX'], 'bin'), server_env['PATH'])
server_env['PATH'] = '{}:{}'.format(self._io_server_dir.name,
server_env['PATH'])
cmd = [daos_server, '--config={}'.format(self._yaml_file.name),
'start', '-t' '4', '--insecure', '-d', self.agent_dir]
server_env['DAOS_DISABLE_REQ_FWD'] = '1'
self._sp = subprocess.Popen(cmd, env=server_env)
agent_config = os.path.join(self_dir, 'nlt_agent.yaml')
agent_bin = os.path.join(self.conf['PREFIX'], 'bin', 'daos_agent')
agent_log_file = tempfile.NamedTemporaryFile(prefix='dnt_agent_',
suffix='.log',
delete=False)
self._agent = subprocess.Popen([agent_bin,
'--config-path', agent_config,
'--insecure',
'--debug',
'--runtime_dir', self.agent_dir,
'--logfile', agent_log_file.name],
env=os.environ.copy())
self.conf.agent_dir = self.agent_dir
self.running = True
# 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 is mounted but empty. It will be remounted and formatted
# /mnt/daos exists and has data in. It will be used as is.
start = time.time()
cmd = ['storage', 'format']
while True:
time.sleep(0.5)
rc = self.run_dmg(cmd)
ready = False
if rc.returncode == 1:
for line in rc.stdout.decode('utf-8').splitlines():
if 'format storage of running instance' in line:
ready = True
if 'format request for already-formatted storage and reformat not specified' in line:
cmd = ['storage', 'format', '--reformat']
if ready:
break
if time.time() - start > 20:
raise Exception("Failed to format")
print('Format completion in {:.2f} seconds'.format(time.time() - start))
# How wait until the system is up, basically the format to happen.
while True:
time.sleep(0.5)
rc = self.run_dmg(['system', 'query'])
ready = False
if rc.returncode == 0:
for line in rc.stdout.decode('utf-8').splitlines():
if line.startswith('status'):
if 'Joined' in line:
ready = True
if ready:
break
if time.time() - start > 20:
raise Exception("Failed to start")
print('Server started in {:.2f} seconds'.format(time.time() - start))
def stop(self):
"""Stop a previously started DAOS server"""
if self._agent:
self._agent.send_signal(signal.SIGINT)
ret = self._agent.wait(timeout=5)
print('rc from agent is {}'.format(ret))
if not self._sp:
return
rc = self.run_dmg(['system', 'stop'])
assert rc.returncode == 0
start = time.time()
while True:
time.sleep(0.5)
rc = self.run_dmg(['system', 'query'])
ready = False
if rc.returncode == 0:
for line in rc.stdout.decode('utf-8').splitlines():
if line.startswith('status'):
if 'Stopped' in line:
ready = True
if 'Stopping' in line:
ready = True
if ready:
break
if time.time() - start > 20:
print('Failed to stop')
break
print('Server stopped in {:.2f} seconds'.format(time.time() - start))
# daos_server does not correctly shutdown daos_io_server yet
# so find and kill daos_io_server directly. This may cause
# a assert in daos_io_server, but at least we can check that.
# call daos_io_server, wait, and then call daos_server.
# When parsing the server logs do not report on memory leaks
# yet, as if it fails then lots of memory won't be freed and
# it's not helpful at this stage to report that.
# TODO: Remove this block when daos_server shutdown works.
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
fd = open(status_file, 'r')
this_proc = False
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:
this_proc = True
break
if not this_proc:
continue
print('Target pid is {}'.format(proc_id))
procs.append(proc_id)
os.kill(int(proc_id), signal.SIGTERM)
time.sleep(5)
self._sp.send_signal(signal.SIGTERM)
ret = self._sp.wait(timeout=5)
print('rc from server is {}'.format(ret))
for proc_id in procs:
try:
os.kill(int(proc_id), signal.SIGKILL)
except ProcessLookupError:
pass
# Show errors from server logs bug suppress memory leaks as the server
# often segfaults at shutdown.
if os.path.exists(self._log_file):
# TODO: Enable memleak checking when server shutdown works.
log_test(self.conf, self._log_file, show_memleaks=False)
self.running = False
return ret
def run_dmg(self, cmd):
"""Run the specified dmg command"""
exe_cmd = [os.path.join(self.conf['PREFIX'], 'bin', 'dmg')]
exe_cmd.append('--insecure')
exe_cmd.extend(cmd)
return subprocess.run(exe_cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
def il_cmd(dfuse, cmd, check_read=True, check_write=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())
log_file = tempfile.NamedTemporaryFile(prefix=prefix,
suffix='.log',
delete=False)
my_env['D_LOG_FILE'] = log_file.name
my_env['LD_PRELOAD'] = os.path.join(dfuse.conf['PREFIX'],
'lib64', 'libioil.so')
my_env['DAOS_AGENT_DRPC_DIR'] = dfuse._daos.agent_dir
ret = subprocess.run(cmd, env=my_env)
print('Logged il to {}'.format(log_file.name))
print(ret)
try:
log_test(dfuse.conf,
log_file.name,
check_read=check_read,
check_write=check_write)
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, logid=None):
# Set this to False to disable valgrind, which will run faster.
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()
self._xml_file = 'dnt.{}.memcheck'.format(self._logid)
cmd = ['valgrind', '--quiet', '--fair-sched=yes']
if self.full_check:
cmd.extend(['--leak-check=full', '--show-leak-kinds=all'])
else:
cmd.extend(['--leak-check=no'])
s_arg = '--suppressions='
cmd.extend(['{}{}'.format(s_arg,
os.path.join('src',
'cart',
'utils',
'memcheck-cart.supp')),
'{}{}'.format(s_arg,
os.path.join('utils',
'memcheck-daos-client.supp'))])
cmd.append('--error-exitcode=42')
cmd.extend(['--xml=yes',
'--xml-file={}'.format(self._xml_file)])
return cmd
def convert_xml(self):
"""Modify the xml file"""
if not self.use_valgrind:
return
fd = open(self._xml_file, 'r')
ofd = open('{}.xml'.format(self._xml_file), 'w')
for line in fd:
if self.src_dir in line:
ofd.write(line.replace(self.src_dir, ''))
else:
ofd.write(line)
os.unlink(self._xml_file)
class DFuse():
"""Manage a dfuse instance"""
instance_num = 0
def __init__(self, daos, conf, pool=None, container=None, path=None):
if path:
self.dir = path
else:
self.dir = '/tmp/dfs_test'
self.pool = pool
self.valgrind_file = None
self.container = container
self.conf = conf
self.cores = None
self._daos = daos
self._sp = None
prefix = 'dnt_dfuse_{}_'.format(get_inc_id())
log_file = tempfile.NamedTemporaryFile(prefix=prefix,
suffix='.log',
delete=False)
self.log_file = log_file.name
self.valgrind = None
if not os.path.exists(self.dir):
os.mkdir(self.dir)
def start(self, v_hint=None):
"""Start a dfuse instance"""
dfuse_bin = os.path.join(self.conf['PREFIX'], 'bin', 'dfuse')
single_threaded = False
caching = False
pre_inode = os.stat(self.dir).st_ino
my_env = get_base_env()
my_env['D_LOG_FILE'] = self.log_file
my_env['DAOS_AGENT_DRPC_DIR'] = self._daos.agent_dir
if self.conf.args.dtx == 'yes':
my_env['DFS_USE_DTX'] = '1'
self.valgrind = ValgrindHelper(v_hint)
if self.conf.args.memcheck == 'no':
self.valgrind.use_valgrind = False
if self.cores:
cmd = ['numactl', '--physcpubind', '0-{}'.format(self.cores - 1)]
else:
cmd = []
cmd.extend(self.valgrind.get_cmd_prefix())
cmd.extend([dfuse_bin, '-s', '0', '-m', self.dir, '-f'])
if single_threaded:
cmd.append('-S')
if caching:
cmd.append('--enable-caching')
if self.pool:
cmd.extend(['--pool', self.pool])
if self.container:
cmd.extend(['--container', self.container])
self._sp = subprocess.Popen(cmd, env=my_env)
print('Started dfuse at {}'.format(self.dir))
print('Log file is {}'.format(self.log_file))
total_time = 0
while os.stat(self.dir).st_ino == pre_inode:
print('Dfuse not started, waiting...')
try:
ret = self._sp.wait(timeout=1)
print('dfuse command exited with {}'.format(ret))
self._sp = None
if os.path.exists(self.log_file):
log_test(self.conf, self.log_file)
raise Exception('dfuse died waiting for start')
except subprocess.TimeoutExpired:
pass
total_time += 1
if total_time > 60:
raise Exception('Timeout starting dfuse')
def _close_files(self):
work_done = False
for fname in os.listdir('/proc/self/fd'):
try:
tfile = os.readlink(os.path.join('/proc/self/fd', fname))
except FileNotFoundError:
continue
if tfile.startswith(self.dir):
print('closing file {}'.format(tfile))
os.close(int(fname))
work_done = True
return work_done
def __del__(self):
if self._sp:
self.stop()
def stop(self):
"""Stop a previously started dfuse instance"""
fatal_errors = False
if not self._sp:
return fatal_errors
print('Stopping fuse')
ret = umount(self.dir)
if ret:
self._close_files()
umount(self.dir)
try:
ret = self._sp.wait(timeout=20)
print('rc from dfuse {}'.format(ret))
if ret != 0:
fatal_errors = True
except subprocess.TimeoutExpired:
self._sp.send_signal(signal.SIGTERM)
fatal_errors = True
self._sp = None
log_test(self.conf, self.log_file)
# Finally, modify the valgrind xml file to remove the
# prefix to the src dir.
self.valgrind.convert_xml()
return fatal_errors
def wait_for_exit(self):
"""Wait for dfuse to exit"""
ret = self._sp.wait()
print('rc from dfuse {}'.format(ret))
self._sp = None
log_test(self.conf, self.log_file)
# Finally, modify the valgrind xml file to remove the
# prefix to the src dir.
self.valgrind.convert_xml()
def get_pool_list():
"""Return a list of valid pool names"""
pools = []
for fname in os.listdir('/mnt/daos'):
if len(fname) != 36:
continue
try:
uuid.UUID(fname)
except ValueError:
continue
pools.append(fname)
return pools
def assert_file_size_fd(fd, size):
"""Verify the file size is as expected"""
my_stat = os.fstat(fd)
print('Checking file size is {} {}'.format(size, my_stat.st_size))
assert my_stat.st_size == size
def assert_file_size(ofd, size):
"""Verify the file size is as expected"""
assert_file_size_fd(ofd.fileno(), size)
def import_daos(server, conf):
"""Return a handle to the pydaos module"""
if sys.version_info.major < 3:
pydir = 'python{}.{}'.format(sys.version_info.major,
sys.version_info.minor)
else:
pydir = 'python{}'.format(sys.version_info.major)
sys.path.append(os.path.join(conf['PREFIX'],
'lib64',
pydir,
'site-packages'))
os.environ['DD_MASK'] = 'all'
os.environ['DD_SUBSYS'] = 'all'
os.environ['D_LOG_MASK'] = 'DEBUG'
os.environ['FI_UNIVERSE_SIZE'] = '128'
os.environ['DAOS_AGENT_DRPC_DIR'] = server.agent_dir
daos = __import__('pydaos')
return daos
def run_daos_cmd(conf, cmd, valgrind=True, fi_file=None, fi_valgrind=False):
"""Run a DAOS command
Run a command, returning what subprocess.run() would.
Enable logging, and valgrind for the command.
"""
vh = ValgrindHelper()
if conf.args.memcheck == 'no':
valgrind = False
if fi_file:
# Turn off Valgrind for the fault injection testing unless it's
# specifically requested (typically if a fault injection results
# in a SEGV/assert), and then if it is turned on then just check
# memory access, not memory leaks.
vh.use_valgrind = fi_valgrind
vh.full_check = False
if not valgrind:
vh.use_valgrind = False
exec_cmd = vh.get_cmd_prefix()
exec_cmd.append(os.path.join(conf['PREFIX'], 'bin', 'daos'))
exec_cmd.extend(cmd)
cmd_env = get_base_env()
prefix = 'dnt_cmd_{}_'.format(get_inc_id())
log_file = tempfile.NamedTemporaryFile(prefix=prefix,
suffix='.log',
delete=False)
if fi_file:
cmd_env['D_FI_CONFIG'] = fi_file
cmd_env['D_LOG_FILE'] = log_file.name
if conf.agent_dir:
cmd_env['DAOS_AGENT_DRPC_DIR'] = conf.agent_dir
rc = subprocess.run(exec_cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
env=cmd_env)
if rc.stderr != '':
print('Stderr from command')
print(rc.stderr.decode('utf-8').strip())
show_memleaks = True
skip_fi = False
if fi_file:
skip_fi = True
fi_signal = None
# A negative return code means the process exited with a signal so do not
# check for memory leaks in this case as it adds noise, right when it's
# least wanted.
if rc.returncode < 0:
show_memleaks = False
fi_signal = -rc.returncode
rc.fi_loc = log_test(conf,
log_file.name,
show_memleaks=show_memleaks,
skip_fi=skip_fi,
fi_signal=fi_signal)
vh.convert_xml()
return rc
def show_cont(conf, pool):
"""Create a container and return a container list"""
cmd = ['container', 'create', '--pool', pool]
rc = run_daos_cmd(conf, cmd)
assert rc.returncode == 0
print('rc is {}'.format(rc))
cmd = ['pool', 'list-containers', '--pool', pool]
rc = run_daos_cmd(conf, cmd)
print('rc is {}'.format(rc))
assert rc.returncode == 0
return rc.stdout.decode('utf-8').strip()
def make_pool(daos):
"""Create a DAOS pool"""
size = int(daos.mb / 4)
rc = daos.run_dmg(['pool',
'create',
'--scm-size',
'{}M'.format(size)])
print(rc)
assert rc.returncode == 0
return get_pool_list()
def run_tests(dfuse):
"""Run some tests"""
path = dfuse.dir
fname = os.path.join(path, 'test_file3')
rc = subprocess.run(['dd', 'if=/dev/zero', 'bs=16k', 'count=64',
'of={}'.format(os.path.join(path, 'dd_file'))])
print(rc)
assert rc.returncode == 0
ofd = open(fname, 'w')
ofd.write('hello')
print(os.fstat(ofd.fileno()))
ofd.flush()
print(os.stat(fname))
assert_file_size(ofd, 5)
ofd.truncate(0)
assert_file_size(ofd, 0)
ofd.truncate(1024*1024)
assert_file_size(ofd, 1024*1024)
ofd.truncate(0)
ofd.seek(0)
ofd.write('simple file contents\n')
ofd.flush()
assert_file_size(ofd, 21)
print(os.fstat(ofd.fileno()))
ofd.close()
ret = il_cmd(dfuse, ['cat', fname], check_write=False)
assert ret.returncode == 0
ofd = os.open(fname, os.O_TRUNC)
assert_file_size_fd(ofd, 0)
os.close(ofd)
symlink_name = os.path.join(path, 'symlink_src')
symlink_dest = 'missing_dest'
os.symlink(symlink_dest, symlink_name)
assert symlink_dest == os.readlink(symlink_name)
def stat_and_check(dfuse, pre_stat):
"""Check that dfuse started"""
post_stat = os.stat(dfuse.dir)
if pre_stat.st_dev == post_stat.st_dev:
raise NLTestFail('Device # unchanged')
if post_stat.st_ino != 1:
raise NLTestFail('Unexpected inode number')
def check_no_file(dfuse):
"""Check that a non-existent file doesn't exist"""
try:
os.stat(os.path.join(dfuse.dir, 'no-file'))
raise NLTestFail('file exists')
except FileNotFoundError:
pass
lp = None
lt = None
def setup_log_test(conf):
"""Setup and import the log tracing code"""
file_self = os.path.dirname(os.path.abspath(__file__))
logparse_dir = os.path.join(file_self,
'../src/tests/ftest/cart/util')
crt_mod_dir = os.path.realpath(logparse_dir)
if crt_mod_dir not in sys.path:
sys.path.append(crt_mod_dir)
global lp
global lt
lp = __import__('cart_logparse')
lt = __import__('cart_logtest')
lt.wf = conf.wf
def log_test(conf,
filename,
show_memleaks=True,
skip_fi=False,
fi_signal=None,
check_read=False,
check_write=False):
"""Run the log checker on filename, logging to stdout"""