-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbenchMT
executable file
·3022 lines (2791 loc) · 139 KB
/
benchMT
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
""" benchMT - SETI multi-threaded MB/AP Benchmark Tool
This tool will extract the total number of CPU cores/threads and GPU platforms from the user's
environment and utilize them in running a list of apps/args specified in the benchCFG file.
Using less than the total number of CPU threads can be specified in the command line. This
tool will read a list of MB/AP apps/args from the BenchCFG file and search for the specified
MB/AP apps in the APP_CPU and APP_GPU directories to validate and determine platform. It will
then leverage allocated threads, as specified, to run all benchmark jobs, storing results in
the testData directory. Use the *--help* option to get a description of valid command line
arguments. In support of automation, some command line arguments can be specified as modes in
the BenchCFG file.
By default, a summary list of all jobs will update in the display as the program progresses. If
there are a large number of jobs, then this display may not be useful and the *--display_slots*
option can be used to display the status of each slot as the program progresses. In some cases,
there will be too many slots to display, and the *--display_compact* option can used to further
optimize the progress display.
You may need to use the *--boinc_home* command option to specify the BOINC home directory, which
is required, since boinccmd is used. An alternative BenchCFG file can be specified with the
command line option *--cfg_file filename*.
The *--lsgpu* command option can be used to display information and capability of all installed
GPUs. The *--purge_kernels* can be used to purge all compiled kernels from the *benchMT* working
directory.
All WUs in the WU_test directory will be used in the creation of jobs to be run, unless the
*--std_signals* option is used, in which case, WUs in the WU_std_signal will be used. The
APPS_GPU and APPS_CPU directories can have more apps than are specified to run in the BenchCFG
file, but must contain apps specified in BenchCFG. The APPS_REF directory must contain a single
CPU reference app with a file prefix of "ref-cpu.". The stock CPU app is suggested, as this is
only used to test integrity of the results. Elapsed time analysis is expected to be limited to
apps/arg combinations specified in BenchCFG. The generation of reference results can be skipped
with the *--no_ref* option or forced with the *--force_ref* option. The *--energy* option can be
used if your system has amdgpu drivers with compatible GPUs to give the energy used in running a
task. In order to correctly associate a GPU card number with a BOINC device number, you must
specify this with the *--devmap B:C,B2:C2* option. I know of no robust way to make this mapping
other than manually running each card individually and observing which card is being used. If
you are running an AstroPulse app, you must specify the *--astropulse* option in order for it to
run properly.
The results will be stored in a unique subdir of the testData directory. There is an overall run
log txt file, a psv file useful for importing into an analytics tools, and the sah and stderr
files for each job run. A run name can be specified with the *--run_name* command line option.
This name will be included in the name of the testData subdirectory for the current run.
Copyright (C) 2018 RueiKe
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
__author__ = 'RueiKe'
__copyright__ = 'Copyright (C) 2018 RueiKe'
__credits__ = ['Keith Myers - Testing and Verification',
'Joseph Stateson - Debug and Verification']
__license__ = 'GNU General Public License'
__program_name__ = 'benchMT'
__version__ = 'v2.0.0'
__maintainer__ = 'RueiKe'
__status__ = 'Stable Release'
__docformat__ = 'reStructuredText'
import argparse
import re
import subprocess
import shlex
import socket
import os
import platform
import sys
import time
from datetime import datetime
from uuid import uuid4
import glob
import shutil
from pathlib import Path
# pylint: disable=multiple-statements
# pylint: disable=line-too-long
class ObjDict(dict):
"""
Allow access of dictionary keys by key name.
"""
# pylint: disable=attribute-defined-outside-init
def __getattr__(self, name):
if name in self:
return self[name]
else:
raise AttributeError("No such attribute: " + name)
def __setattr__(self, name, value):
self[name] = value
def __delattr__(self, name):
if name in self:
del self[name]
else:
raise AttributeError("No such attribute: " + name)
class MbConst(ObjDict):
"""
Defines benchMT constants used through out the code.
"""
# pylint: disable=attribute-defined-outside-init
# pylint: disable=too-many-instance-attributes
def __init__(self):
# pylint: disable=attribute-defined-outside-init
super().__init__({'boinc_home': '/home/boinc/BOINC/',
'cpu_app_subdir': 'APPS_CPU/',
'gpu_app_subdir': 'APPS_GPU/',
'ref_app_subdir': 'APPS_REF/',
'ref_results_subdir': 'REF_RESULTS/',
'wu_subdir': 'WU_test/',
'std_signal_subdir': 'WU_std_signal/',
'testdata_subdir': 'testData/',
'workdir_subdir': 'workdir/',
'slots_subdir': 'Slots/',
'command_line_filename': 'BenchCFG',
'boinccmd': 'boinccmd',
'template_file': 'init_data.xml.template',
'coproc_file_name': 'coproc_info.xml',
'wu_cmp': 'rescmpv5_l',
'suspend_args': ['boinccmd --set_gpu_mode never 172800',
'boinccmd --set_run_mode never 172800'],
'resume_args': ['boinccmd --set_gpu_mode never 1',
'boinccmd --set_run_mode never 1'],
'activeWU': 'work_unit.sah',
'activeAPWU': 'in.dat',
'DEBUG': False,
'noBS': False,
'env': None,
# Items required for Energy feature
'card_root': '/sys/class/drm/',
'hwmon_sub': 'hwmon/hwmon',
# System command definitions
'cmd_lspci': None,
'cmd_lshw': None,
'cmd_lscpu': None,
'cmd_clinfo': None,
'cmd_time': None,
'cmd_lsb_release': None,
'cmd_nvidia_smi': None})
def __repr__(self):
return '{} - {} items'.format(self.__class__.__name__, len(self))
def __str__(self):
ret_str = '{'
for k, v in self.items():
pre_str = '' if ret_str == '{' else ', '
k_str = f'\'{k}\'' if isinstance(k, str) else f'{k}'
v_str = f'\'{v}\'' if isinstance(v, str) else f'{v}'
ret_str += '{}{}: {}'.format(pre_str, k_str, v_str)
ret_str += '}'
return ret_str
def print(self):
"""
Print all elements an MB_Const object.
:return: None
:rtype: None
"""
for k, v in self.items():
print('MbConst.{}: [{}]'.format(k, v))
return
MB_CONST = MbConst()
class CfgModes:
"""
Defines benchMT configuration modes.
"""
def __init__(self):
self.modes = {'yes': None,
'run_name': None,
'boinc_home': None,
'noBS': None,
'display_compact': None,
'display_slots': None,
'num_repetitions': None,
'max_threads': None,
'max_gpus': None,
'gpu_devices': None,
'devmap': None,
'std_signals': None,
'no_ref': None,
'force_ref': None,
'energy': None,
'astropulse': None}
self.type = {'yes': bool,
'run_name': str,
'boinc_home': str,
'noBS': bool,
'display_compact': bool,
'display_slots': bool,
'num_repetitions': int,
'max_threads': int,
'max_gpus': int,
'gpu_devices': str,
'devmap': str,
'std_signals': bool,
'no_ref': bool,
'force_ref': bool,
'energy': bool,
'astropulse': bool}
def set_mode(self, mode_name, mode_value):
"""
Set given mode to the specified value.
:param mode_name: Name of the mode to be updated
:type mode_name: str
:param mode_value: Value
:type mode_value: str
:return: True if successful
:rtype: bool
"""
if mode_name not in self.modes:
return False
if mode_name not in self.type:
return False
if self.type[mode_name] is bool:
if mode_value == 'True' or mode_value == 'False':
self.modes[mode_name] = True if mode_value == 'True' else False
return True
elif self.type[mode_name] is int:
if re.fullmatch('[-]*[0-9]+', mode_value):
self.modes[mode_name] = int(mode_value)
return True
elif self.type[mode_name] is str:
self.modes[mode_name] = mode_value
return True
return False
def mode_value(self, mode_name):
"""
Get value for given mode.
:param mode_name:
:type mode_name: str
:return: value
:rtype: Union([str, bool])
"""
if mode_name not in self.modes.keys():
return False
return self.modes[mode_name]
def print(self):
"""
Print modes.
:return: None
:rtype: None
"""
for m, v in self.modes.items():
print('CFG_mode: {} {}'.format(m, str(v)))
class BenchEnv:
"""
benchMT environment parameters.
"""
# pylint: disable=attribute-defined-outside-init
def __init__(self):
# pylint: disable=attribute-defined-outside-init
self._display = {'hostname': 'Hostname: {}', 'run_name': 'Run Name: {}', 'app_mode': 'APP Mode: {}',
'benchMT_version': 'benchMT version: {}', 'platform': 'Platform: {}',
'os_desc': 'OS Description: {}', 'cpu_model': 'CPU Model: {}', 'cpu_mhz': 'CPU MHz: {}',
'total_cpu_cores': 'CPU Cores: {}', 'total_cpu_threads': 'CPU Threads: {}',
'total_gpu_count': 'GPU Count: {}', 'total_gpu_threads': 'GPU Threads: {}',
'gpu_devices': 'Specified GPU Device List: {}', 'devmap': 'Devices Map: {}',
'boinc_dev_list': 'BOINC Device List: {}', 'card_num_list': 'GPU Card Number List: {}',
'gpu_details': 'GPU Details:', 'current_dir': 'Current Dir: {}',
'slots_path': 'Slots Dir: {}', 'time_now': 'TimeNow: {}',
'time_now_short': 'TimeNowShort: {}', 'cpu_app_path': 'CPU App Path: {}',
'gpu_app_path': 'GPU App Path: {}', 'ref_app_path': 'REF App Path: {}',
'ref_results_path': 'Reference Results Path: {}',
'wu_std_signal_path': 'STD Signal WU Path: {}',
'wu_path': 'WU Path: {}', 'testdata_path': 'Test Data Path: {}',
'boinc_home': 'BOINC Home: {}', 'coproc_file': 'Coprocessor Info File: {}',
'repetitions': 'Repetitions: {}', 'allocated_cthreads': 'Allocated CPU Threads: {}',
'allocated_gthreads': 'Allocated GPU Threads: {}', 'mode_yes': '\nMode yes: {}',
'mode_noBS': 'Mode noBS: {}', 'mode_std_signals': 'Mode std_signals: {}',
'mode_display_slots': 'Mode display_slots: {}',
'mode_display_compact': 'Mode display_compact: {}',
'mode_no_ref': 'Mode no_ref: {}', 'mode_force_ref': 'Mode force_ref: {}',
'mode_energy': 'Mode energy: {}', 'mode_astropulse': 'Mode astropulse: {}'}
self.sum_file_ptr = None
self.psv_file_ptr = None
self.prm = ObjDict({'time_now': '',
'time_now_short': '',
'hostname': '',
'platform': '',
'os_desc': '',
'cpu_model': '',
'cpu_mhz': '',
'total_cpu_threads': 0,
'total_cpu_cores': 0,
'specified_max_threads': 0,
'total_gpu_threads': 0,
'total_gpu_count': 0,
'allocated_cthreads': 0,
'allocated_gthreads': 0,
'boinc_dev_list': [],
'card_num_list': [],
'specified_max_gpus': 0,
'gpu_devices': [],
'devmap': {},
'gpu_details': [],
'current_dir': '',
'cpu_app_path': '',
'gpu_app_path': '',
'ref_app_path': '',
'ref_results_path': '',
'wu_path': '',
'wu_std_signal_path': '',
'testdata_path': '',
'slots_path': '',
'command_line_file': '',
'boinccmd': '',
'wucmpcmd': '',
'repetitions': 1,
'summary_path': '',
'run_name': '',
'summary_file': '',
'psv_file': '',
'workdir_path': '',
'lockfile': '',
'mode_devmap': {},
'mode_gpu_devices': [],
'mode_std_signals': False,
'mode_display_slots': False,
'mode_display_compact': False,
'mode_no_ref': False,
'mode_force_ref': False,
'mode_energy': False,
'mode_yes': False,
'mode_noBS': False,
'mode_astropulse': False,
'boinc_home': MB_CONST.boinc_home,
'init_data_template_file': '',
'coproc_file': None})
def process_options(self, args, cfg_modes):
"""
This function takes command line arguments and configuration modes to determine
final operating mode of benchMT. Command line args will over ride config file modes.
:param args: Command line arguments
:param cfg_modes: Config file modes
:return: None
:rtype: None
"""
# mode_yes
if args.yes: self.prm.mode_yes = True
elif cfg_modes.mode_value('yes'): self.prm.mode_yes = True
# mode_force_ref
if args.force_ref: self.prm.mode_force_ref = True
elif cfg_modes.mode_value('force_ref'): self.prm.mode_force_ref = True
# mode_no_ref
if args.no_ref: self.prm.mode_no_ref = True
elif cfg_modes.mode_value('no_ref'): self.prm.mode_no_ref = True
if self.prm.mode_no_ref and self.prm.mode_force_ref:
print('ERROR: --no_ref and --force_ref are mutually exclusive. Exiting...')
sys.exit(-1)
# mode_noBS
if args.noBS: self.prm.mode_noBS = True
elif cfg_modes.mode_value('noBS'): self.prm.mode_noBS = True
# mode_std_signals
if args.std_signals: self.prm.mode_std_signals = True
elif cfg_modes.mode_value('std_signals'): self.prm.mode_std_signals = True
# mode_display_compact
if args.display_compact: self.prm.mode_display_compact = True
elif cfg_modes.mode_value('display_compact'): self.prm.mode_display_compact = True
# mode_display_slots
if args.display_slots: self.prm.mode_display_slots = True
elif cfg_modes.mode_value('display_slots'): self.prm.mode_display_slots = True
# mode_energy
if args.energy: self.prm.mode_energy = True
elif cfg_modes.mode_value('energy'): self.prm.mode_energy = True
# mode_astropulse
if args.astropulse: self.prm.mode_astropulse = True
elif cfg_modes.mode_value('astropulse'): self.prm.mode_astropulse = True
# mode_boinc_home
if args.boinc_home and args.boinc_home.isprintable():
self.prm.boinc_home = args.boinc_home
elif cfg_modes.mode_value('boinc_home'):
if cfg_modes.mode_value('boinc_home') and cfg_modes.mode_value('boinc_home').isprintable():
self.prm.boinc_home = cfg_modes.mode_value('boinc_home')
# mode_run_name
if args.run_name and args.run_name.isprintable():
self.prm.run_name = args.run_name.replace(' ', '').replace('/', '').replace('\\', '')
elif cfg_modes.mode_value('run_name'):
if cfg_modes.mode_value('run_name') and cfg_modes.mode_value('run_name').isprintable():
self.prm.run_name = cfg_modes.mode_value('run_name').replace(' ', '').replace('/', '').replace('\\', '')
# mode_devmap
specified_devmap = {}
self.prm.devmap = {}
devmap_str = ''
if args.devmap:
devmap_str = args.devmap
elif cfg_modes.mode_value('devmap'):
devmap_str = cfg_modes.mode_value('devmap')
if devmap_str:
if re.fullmatch('([0-9]:[0-9],)*([0-9]:[0-9])+', devmap_str):
gdev_items = devmap_str.split(',')
for gi in gdev_items:
gi_items = gi.split(':')
specified_devmap[int(gi_items[0])] = int(gi_items[1])
self.prm.devmap = specified_devmap
else:
print('Invalid devmap arg: [', devmap_str, ']')
# mode_gpu_devices
self.prm.mode_gpu_devices = []
gpu_devices_str = ''
if args.gpu_devices:
gpu_devices_str = args.gpu_devices
elif cfg_modes.mode_value('gpu_devices'):
gpu_devices_str = cfg_modes.mode_value('gpu_devices')
if gpu_devices_str:
if re.fullmatch('([0-9],)*([0-9])+', gpu_devices_str):
gdev_items = gpu_devices_str.split(',')
for gi in gdev_items:
self.prm.mode_gpu_devices.append(int(gi))
else:
print('Invalid gpu_devices arg: [{}]'.format(gpu_devices_str))
# mode_num_repetitions
if args.num_repetitions > 0: self.prm.repetitions = args.num_repetitions
elif cfg_modes.mode_value('num_repetitions'):
if int(cfg_modes.mode_value('num_repetitions')) > 0:
self.prm.repetitions = cfg_modes.mode_value('num_repetitions')
else:
print('CFG: Invalid number of repetitions specified [{}]. Ignoring...'.format(
str(cfg_modes.mode_value('num_repetitions'))))
else:
self.prm.repetitions = 1
# mode_max_threads
self.prm.specified_max_threads = -1
if args.max_threads > 0: self.prm.specified_max_threads = args.max_threads
elif cfg_modes.mode_value('max_threads'):
if cfg_modes.mode_value('max_threads') > 0:
self.prm.specified_max_threads = cfg_modes.mode_value('max_threads')
# mode_max_gpus
self.prm.specified_max_gpus = -1
if args.max_gpus > 0:
self.prm.specified_max_gpus = args.max_gpus
elif cfg_modes.mode_value('max_gpus'):
if cfg_modes.mode_value('max_gpus') > 0:
self.prm.specified_max_gpus = cfg_modes.mode_value('max_gpus')
@staticmethod
def check_env():
"""
Return 0 if all good, -1 if python version issue, -2 if OS issue, -3 if system command issue.
:return: Integer check code
:rtype: int
"""
# Check python version
required_pversion = [3, 6]
(python_major, python_minor, python_patch) = platform.python_version_tuple()
if MB_CONST.DEBUG: print('Using python: {}.{}.{}'.format(python_major, python_minor, python_patch))
if int(python_major) < required_pversion[0]:
print('Using python {}, but {} requires python {}.{} or higher.'.format(python_major, __program_name__,
required_pversion[0],
required_pversion[1]),
file=sys.stderr)
return -1
elif int(python_major) == required_pversion[0] and int(python_minor) < required_pversion[1]:
print('Using python {}.{}.{}, but {} requires python {}.{} or higher.'.format(python_major, python_minor,
python_patch,
__program_name__,
required_pversion[0],
required_pversion[1]),
file=sys.stderr)
return -1
# Check Linux Kernel version
required_kversion = [4, 8]
linux_version = platform.release()
if MB_CONST.DEBUG: print('Using Linux Kernel: {}'.format(linux_version))
if int(linux_version.split('.')[0]) < required_kversion[0]:
print('Using Linux Kernel {}, but {} requires > {}.{}.'.format(linux_version, __program_name__,
required_kversion[0], required_kversion[1]),
file=sys.stderr)
return -2
elif int(linux_version.split('.')[0]) == required_kversion[0] and \
int(linux_version.split('.')[1]) < required_kversion[1]:
print('Using Linux Kernel {}, but {} requires > {}.{}.'.format(linux_version, __program_name__,
required_kversion[0], required_kversion[1]),
file=sys.stderr)
return -2
# Check access/paths to system commands
command_access_fail = False
MB_CONST.cmd_lspci = shutil.which('lspci')
if not MB_CONST.cmd_lspci:
print('OS command [lspci] executable not found.')
command_access_fail = True
MB_CONST.cmd_lshw = shutil.which('lshw')
if not MB_CONST.cmd_lshw:
print('OS command [lshw] executable not found.')
command_access_fail = True
MB_CONST.cmd_lscpu = shutil.which('lscpu')
if not MB_CONST.cmd_lscpu:
print('OS command [lscpu] executable not found.')
command_access_fail = True
MB_CONST.cmd_clinfo = shutil.which('clinfo')
if not MB_CONST.cmd_clinfo:
print('Package addon [clinfo] executable not found. Use sudo apt-get install clinfo to install')
MB_CONST.cmd_time = shutil.which('time')
if not MB_CONST.cmd_time:
print('OS command [time] executable not found.')
command_access_fail = True
MB_CONST.cmd_nvidia_smi = shutil.which('nvidia-smi')
if not MB_CONST.cmd_nvidia_smi:
print('Package addon [nvidia-smi] executable not found.')
MB_CONST.cmd_lsb_release = shutil.which('lsb_release')
if not MB_CONST.cmd_lsb_release:
print('OS command [lsb_release] executable not found.')
command_access_fail = True
if command_access_fail:
return -3
return 0
def set_env(self):
"""
Setup the working environment to run benchmarks
- Get time and system parameters
- Use standard subdirectory and filenames in the MB_CONST class
- Verify all required directories and files exist
:return: True if all files and directories exist, else False
:rtype: bool
"""
valid = True
t = datetime.utcnow()
self.prm.time_now = t.strftime('%c')
self.prm.time_now_short = t.strftime('%m%d_%H%M%S')
self.prm.hostname = socket.gethostname()
self.prm.platform = '{} {}'.format(platform.system(), platform.release())
# Get OS details
if not MB_CONST.cmd_lsb_release:
print('OS Command [lsb_release] not found', file=sys.stderr)
valid = False
else:
cmd_str = '{} -a 2>/dev/null'.format(MB_CONST.cmd_lsb_release)
try:
cmd = subprocess.Popen(cmd_str, shell=True, stdout=subprocess.PIPE)
for line in cmd.stdout:
linestr = line.decode('utf-8').strip()
srch_obj = re.search('Description', linestr)
if srch_obj:
line_items = linestr.split(':')
self.prm.os_desc = line_items[1].strip()
cmd.stdout.close()
break
except (subprocess.CalledProcessError, OSError) as except_err:
print('Warning: {}. can not determine OS'.format(except_err), file=sys.stderr)
self.prm.os_desc = 'UNKNOWN'
# Get CPU details
if not MB_CONST.cmd_lscpu:
print('OS Command [lscpu] not found')
valid = False
else:
cpu_max_mhz = ''
cmd_str = '{} 2>/dev/null'.format(MB_CONST.cmd_lscpu)
try:
cmd = subprocess.Popen(cmd_str, shell=True, stdout=subprocess.PIPE)
for line in cmd.stdout:
linestr = line.decode('utf-8').strip()
srch_obj = re.search('Model name', linestr)
if srch_obj:
line_items = linestr.split(':')
self.prm.cpu_model = line_items[1].strip()
continue
srch_obj = re.search('CPU max MHz', linestr)
if srch_obj:
line_items = linestr.split(':')
cpu_max_mhz = line_items[1].strip()
continue
srch_obj = re.search('CPU MHz', linestr)
if srch_obj:
line_items = linestr.split(':')
cpu_mhz = line_items[1].strip()
continue
if cpu_max_mhz == '':
self.prm.cpu_mhz = int(float(cpu_mhz))
else:
self.prm.cpu_mhz = int(float(cpu_max_mhz))
cmd.stdout.close()
except (subprocess.CalledProcessError, OSError) as except_err:
print('Warning: can not determine CPU details: {}'.format(except_err), file=sys.stderr)
self.prm.cpu_model = 'UNKNOWN'
cpu_max_mhz = 'UNKNOWN'
cpu_mhz = 'UNKNOWN'
# Get CPU details
cmd_str = '{} -e 2>/dev/null | tail -1'.format(MB_CONST.cmd_lscpu)
try:
cmd = subprocess.Popen(cmd_str, shell=True, stdout=subprocess.PIPE)
for line in cmd.stdout:
linestr = line.decode('utf-8').strip()
line_items = linestr.split()
self.prm.total_cpu_threads = int(line_items[0].strip()) + 1
self.prm.total_cpu_cores = int(line_items[3].strip()) + 1
cmd.stdout.close()
except (subprocess.CalledProcessError, OSError) as except_err:
print('Error: can not determine CPU core details: {}'.format(except_err), file=sys.stderr)
valid = False
# Set working directories
self.prm.current_dir = os.getcwd()
self.prm.workdir_path = os.path.join(self.prm.current_dir, MB_CONST.workdir_subdir)
self.prm.cpu_app_path = os.path.join(self.prm.current_dir, MB_CONST.cpu_app_subdir)
self.prm.gpu_app_path = os.path.join(self.prm.current_dir, MB_CONST.gpu_app_subdir)
self.prm.ref_app_path = os.path.join(self.prm.current_dir, MB_CONST.ref_app_subdir)
self.prm.wu_path = os.path.join(self.prm.current_dir, MB_CONST.wu_subdir)
self.prm.wu_std_signal_path = os.path.join(self.prm.current_dir, MB_CONST.std_signal_subdir)
self.prm.testdata_path = os.path.join(self.prm.current_dir, MB_CONST.testdata_subdir)
self.prm.ref_results_path = os.path.join(self.prm.ref_app_path, MB_CONST.ref_results_subdir)
self.prm.slots_path = os.path.join(self.prm.workdir_path, MB_CONST.slots_subdir)
self.prm.lockfile = os.path.join(self.prm.workdir_path, '.benchMTlockfile')
summary_subdir = '{}_benchMT_{}_{}'.format(self.prm.hostname, self.prm.run_name, self.prm.time_now_short)
self.prm.summary_path = os.path.join(self.prm.testdata_path, summary_subdir)
summary_filename = '{}.testlog.{}.txt'.format(self.prm.hostname, self.prm.time_now_short)
self.prm.summary_file = os.path.join(self.prm.summary_path, summary_filename)
psv_filename = '{}.timelog.{}.psv'.format(self.prm.hostname, self.prm.time_now_short)
self.prm.psv_file = os.path.join(self.prm.summary_path, psv_filename)
self.prm.init_data_template_file = os.path.join(self.prm.workdir_path, MB_CONST.template_file)
# Check working directories
if not os.path.isdir(self.prm.workdir_path):
print('benchMT workdir Path [{}] does not exist, making...'.format(self.prm.workdir_path))
os.mkdir(self.prm.workdir_path)
if not os.path.isdir(self.prm.workdir_path):
print('Failed to make benchMT workdir Path [{}]'.format(self.prm.workdir_path))
valid = False
if not os.path.isdir(self.prm.testdata_path):
print('TestData Path [{}] does not exist, making...'.format(self.prm.testdata_path))
os.mkdir(self.prm.testdata_path)
if not os.path.isdir(self.prm.testdata_path):
print('Failed to make TestData Path [{}]'.format(self.prm.testdata_path))
valid = False
if not os.path.isdir(self.prm.cpu_app_path):
print('CPU APP Path [{}] does not exist'.format(self.prm.cpu_app_path))
valid = False
if not os.path.isdir(self.prm.ref_app_path):
print('REFERENCE APP Path [{}] does not exist'.format(self.prm.ref_app_path))
valid = False
if not os.path.isdir(self.prm.ref_results_path):
print('REFERENCE RESULTS Path [{}] does not exist'.format(self.prm.ref_results_path))
valid = False
if not os.path.isdir(self.prm.gpu_app_path):
print('GPU APP Path [{}] does not exist'.format(self.prm.gpu_app_path))
valid = False
if not os.path.isdir(self.prm.wu_path):
print('WU Path [{}] does not exist'.format(self.prm.wu_path))
valid = False
if not os.path.isdir(self.prm.wu_std_signal_path):
print('STD SIGNAL WU Path [{}] does not exist'.format(self.prm.wu_std_signal_path))
valid = False
# Set CFG file location
self.prm.command_line_file = os.path.join(self.prm.current_dir, MB_CONST.command_line_filename)
if not os.path.isfile(self.prm.command_line_file):
print('BenchCFG [{}] does not exist.'.format(self.prm.command_line_file))
valid = False
return valid
def set_env_boinc(self):
"""
Set boinc environment components.
:return: True if all ok
:rtype: bool
"""
valid = True
if not MB_CONST.noBS:
if not os.path.isdir(self.prm.boinc_home):
print('BOINC Home Path [{}] does not exist'.format(self.prm.boinc_home))
print('Please set the correct BOINC Home Path with the --boinc_home command line option')
valid = False
self.prm.wucmpcmd = os.path.join(self.prm.current_dir, MB_CONST.wu_cmp)
if not os.path.isfile(self.prm.wucmpcmd):
print('Results Compare Utility [{}] does not exist'.format(self.prm.wucmpcmd))
valid = False
if not MB_CONST.noBS:
self.prm.coproc_file = os.path.join(self.prm.boinc_home, MB_CONST.coproc_file_name)
if not os.path.isfile(self.prm.coproc_file):
print('coproc_file [{}] does not exist'.format(self.prm.coproc_file))
self.prm.coproc_file = None
self.prm.boinccmd = os.path.join(self.prm.boinc_home, MB_CONST.boinccmd)
if not os.path.isfile(self.prm.boinccmd):
print('boinccmd [{}] does not exist'.format(self.prm.boinccmd))
valid = False
if not os.path.isfile(self.prm.init_data_template_file):
print('init_data.xml_template file [{}] does not exist, creating...'.format(
self.prm.init_data_template_file))
with open(self.prm.init_data_template_file, 'w') as fileptr:
print('<app_init_data>', file=fileptr)
print('<app_name>setiathome_v8</app_name>', file=fileptr)
print('<project_dir>{}</project_dir>'.format(self.prm.workdir_path), file=fileptr)
print('<boinc_dir>{}</boinc_dir>'.format(self.prm.boinc_home), file=fileptr)
print('</app_init_data>', file=fileptr)
return valid
def purge_workdir_cache(self):
"""
Purge openCL kernels from working directory.
:return: None
:rtype: None
"""
if not os.path.isdir(self.prm.workdir_path):
print('benchMT workdir Path [{}] does not exist, can not purge cache...'.format(self.prm.workdir_path))
else:
print('Purging cached kernels from: [{}]'.format(self.prm.workdir_path))
for file_str in glob.glob(os.path.join(self.prm.workdir_path, 'MB_clFFTplan*')):
os.remove(file_str)
print('Removed: {}'.format(file_str))
for file_str in glob.glob(os.path.join(self.prm.workdir_path, 'MultiBeam_Kernels*.cl[0-9,a-z,A-Z]*')):
os.remove(file_str)
print('Removed: {}'.format(file_str))
def makedirs(self):
"""
Check existence of required directories and make if missing
:return: None
:rtype: None
"""
# Check/Make working directories
if not os.path.isdir(self.prm.cpu_app_path):
print('CPU APP Path [{}] does not exist, making...'.format(self.prm.cpu_app_path))
os.mkdir(self.prm.cpu_app_path)
if not os.path.isdir(self.prm.gpu_app_path):
print('GPU APP Path [{}] does not exist, making...'.format(self.prm.gpu_app_path))
os.mkdir(self.prm.gpu_app_path)
if not os.path.isdir(self.prm.ref_app_path):
print('REFERENCE APP Path [{}] does not exist, making...'.format(self.prm.ref_app_path))
os.mkdir(self.prm.ref_app_path)
if not os.path.isdir(self.prm.ref_results_path):
print('REFERENCE RESULTS Path [{}] does not exist, making...'.format(self.prm.ref_results_path))
os.mkdir(self.prm.ref_results_path)
if not os.path.isdir(self.prm.wu_path):
print('WU Path [{}] does not exist, making...'.format(self.prm.wu_path))
os.mkdir(self.prm.wu_path)
if not os.path.isdir(self.prm.wu_std_signal_path):
print('STD SIGNAL WU Path [{}] does not exist, making...'.format(self.prm.wu_std_signal_path))
os.mkdir(self.prm.wu_std_signal_path)
if not os.path.isdir(self.prm.testdata_path):
print('TestData Path [{}] does not exist, making...'.format(self.prm.testdata_path))
os.mkdir(self.prm.testdata_path)
def is_bench_conflict(self):
"""
Return true if there is another instance running. Check lock file for pid
if there is a valid process with that pid, then there is a conflict.
if no conflict, then write current pid to lockfile and return false
:return: True if there is a conflict
:rtype: bool
"""
mypid = os.getpid()
if not os.path.isfile(self.prm.lockfile):
# No lockfile, so assume no conflict
with open(self.prm.lockfile, 'w') as file_ptr:
print(str(mypid), file=file_ptr)
return False
else:
with open(self.prm.lockfile, 'r') as file_ptr:
line = file_ptr.readline().strip()
if line.isdigit():
pid = int(line)
try:
os.kill(pid, 0)
except OSError:
# Not running
with open(self.prm.lockfile, 'w') as file_ptr:
print(str(mypid), file=file_ptr)
return False
return True
@staticmethod
def is_boinc_running():
"""
Check if boinc is running.
:return: True if running
:rtype: bool
"""
cmd_str = 'ps -C boinc -o pid 2>/dev/null'
try:
cmd = subprocess.Popen(cmd_str, shell=True, stdout=subprocess.PIPE)
output = cmd.stdout.read()
cmd.stdout.close()
cmd.wait()
if output.decode('utf-8').strip() == 'PID':
return False
return True
except OSError as except_err:
print('Warning: {}, can not check if boinc is running.'.format(except_err), file=sys.stderr)
return True
def suspend_boinc(self):
"""
Run boinc suspend script
:return: None
:rtype: None
"""
if not self.is_boinc_running():
print('boinc is not running, skip suspend')
return
cwd = os.getcwd()
os.chdir(self.prm.boinc_home)
for cmd_str in MB_CONST.suspend_args:
cmd_str = os.path.join(self.prm.boinc_home, cmd_str)
if MB_CONST.DEBUG: print('Suspend cmd: {}'.format(cmd_str))
try:
cmd = subprocess.Popen(shlex.split(cmd_str), shell=False, stdout=subprocess.PIPE)
while True:
if cmd.poll() is not None:
break
time.sleep(1)
except (subprocess.CalledProcessError, OSError) as except_err:
print('Error: {}, could not execute boinccmd: {}'.format(except_err, cmd_str), file=sys.stderr)
os.chdir(cwd)
time.sleep(1)
def resume_boinc(self):
"""
Run boinc resume script
:return: None
:rtype: None
"""
if not self.is_boinc_running():
print('boinc is not running, skip resume')
return
cwd = os.getcwd()
os.chdir(self.prm.boinc_home)
for cmd_str in MB_CONST.resume_args:
cmd_str = os.path.join(self.prm.boinc_home, cmd_str)
if MB_CONST.DEBUG: print('Resume cmd: {}'.format(cmd_str))
try:
cmd = subprocess.Popen(shlex.split(cmd_str), shell=False, stdout=subprocess.PIPE)
while True:
if cmd.poll() is not None:
break
time.sleep(1)
except (subprocess.CalledProcessError, OSError) as except_err:
print('Error: {}, could not execute {}.'.format(except_err, cmd_str), file=sys.stderr)
os.chdir(cwd)
def print(self, fileptr=sys.stdout):
"""
Print all environment details.
:return: None
:rtype: None
"""
for k, v in self._display.items():
if k == 'app_mode':
appmode = 'AstroPulse' if self.prm.mode_astropulse else 'MultiBeam'
print(v.format(appmode), file=fileptr)
elif k == 'benchMT_version':
print(v.format(__version__), file=fileptr)
elif k == 'run_name' and not self.prm.run_name:
continue
elif k == 'gpu_details':
print('GPU Details:', file=fileptr)
for gpi in self.prm.gpu_details:
print(' {}'.format(gpi), file=fileptr)
else:
print(v.format(self.prm[k]), file=fileptr)
class GpuItem:
"""
Defines a data object that represents a GPU.
"""
def __init__(self, item_id):
self.uuid = item_id
self.card_num = None
self.boinc_device_num = None
self.model = ''
self.vendor = ''
self.card_path = None
self.hwmon_path = None
self.pcie_id = ''
self.driver = ''
self.energy_compatible = False
self.compute_compatible = False
self.ocl_device_name = None
self.ocl_device_version = None
self.ocl_device_index = None
time_0 = datetime.utcnow()
self.energy = {'t0': time_0, 'tn': time_0, 'cumulative': 0.0, 'max_power': 0.0}
self.power = None
def populate(self, pcie_id, gpu_name, vendor, driver_module, card_path, hwmon_path,
energy, compute, ocl_dev, ocl_ver, ocl_index):
"""
Populate elements of a GpuItem.
:param pcie_id: The pcid ID of the GPU.
:type pcie_id: str
:param gpu_name: Model name of the GPU
:type gpu_name: str
:param vendor: The make of the GPU (AMD, NVIDIA, ...)
:type vendor: str
:param driver_module: The name of the driver.
:type driver_module: str
:param card_path: The path to the GPU.
:type card_path: str
:param hwmon_path: Path to the hardware monitor files.
:type hwmon_path: str
:param energy: Energy compatibility flag
:type energy: bool
:param compute: Compute compatibility flag
:type compute: bool
:param ocl_dev: openCL device
:type ocl_dev: str
:param ocl_ver: openCL version
:type ocl_ver: str
:param ocl_index: openCL index
:type ocl_index: str
:return: None
:rtype: None
"""
self.pcie_id = pcie_id
self.model = gpu_name
self.vendor = vendor
self.driver = driver_module
self.card_path = card_path
self.card_num = int(card_path.replace('{}card'.format(MB_CONST.card_root), '').replace('/device', ''))
self.hwmon_path = hwmon_path
self.energy_compatible = energy
self.compute_compatible = compute
self.ocl_device_name = ocl_dev
self.ocl_device_version = ocl_ver
self.ocl_device_index = ocl_index
def print(self):
"""
Print GpuItem.
:return: None
:rtype: None
"""
print('GpuItem: uuid: {}'.format(self.uuid))
print(' pcie_id: {}'.format(self.pcie_id))
print(' model: {}'.format(self.model))
print(' vendor: {}'.format(self.vendor))
print(' driver: {}'.format(self.driver))
print(' openCL Device: {}'.format(self.ocl_device_name))
print(' openCL Version: {}'.format(self.ocl_device_version))
print(' openCL Index: {}'.format(self.ocl_device_index))
print(' card number: {}'.format(self.card_num))
print(' BOINC Device number: {}'.format(self.boinc_device_num))
print(' card path: {}'.format(self.card_path))
print(' hwmon path: {}'.format(self.hwmon_path))
print(' Compute compatible: {}'.format(self.compute_compatible))
print(' Energy compatible: {}'.format(self.energy_compatible))
def reset_energy(self):
"""
Reset energy metrics to time zero state.
:return: None
:rtype: None
.. note:: Energy is stored in kWh.
"""
time_0 = datetime.utcnow()
self.energy.update({'t0': time_0, 'tn': time_0, 'cumulative': 0.0, 'max_power': 0.0})
def get_max_power(self):