- Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathinvoke.py
More file actions
Latest commit
executable file
·658 lines (549 loc) · 29.7 KB
/
Copy pathinvoke.py
File metadata and controls
executable file
·658 lines (549 loc) · 29.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
#!/usr/bin/env python3
fromargparseimportArgumentParser
importos
importsys
importsubprocess
importcopy
importjson
fromdatetimeimportdatetime
frompathlibimportPath
invokePyVersion='0.2'
treatAsDirectories= ['outputs', 'output', 'outdir', 'dir']
invokeSpec= {}
currentConfigPath=os.path.curdir
defupdateBenchSpec(origBenchSpec: dict, source: dict, subdirectory=None):
benchSpec=copy.deepcopy(origBenchSpec)
ifisinstance(source['dir'], str):
# If a path is given use it
benchSpec['dir'] =source['dir'] ifos.path.isabs(source['dir']) elseos.path.abspath(benchSpec['dir'] +'/'+source['dir'])
elifsource['dir'] isNoneandsubdirectoryisnotNone:
# If not use the benchmark name as subdirectory
benchSpec['dir'] =os.path.abspath(benchSpec['dir'] +'/'+subdirectory)
ifisinstance(source['exec'], str):
benchSpec['exec'] =source['exec'] ifos.path.isabs(source['exec']) elseos.path.abspath(benchSpec['dir'] +'/'+source['exec'])
ifisinstance(source['stdout'], str):
benchSpec['stdout'] =source['stdout'] ifos.path.isabs(source['stdout']) elseos.path.abspath(benchSpec['dir'] +'/'+source['stdout'])
ifisinstance(source['stdout'], str):
benchSpec['stderr'] =source['stderr'] ifos.path.isabs(source['stderr']) elseos.path.abspath(benchSpec['dir'] +'/'+source['stderr'])
ifisinstance(source['environment'], dict):
benchSpec['environment'] =source['environment'] ifbenchSpec['environment'] isNoneelse {**benchSpec['environment'], **source['environment']}
ifisinstance(source['disabled'], bool):
benchSpec['disabled'] =source['disabled']
forkin ['params', 'precmd', 'postcmd']:
ifisinstance(source[k], str):
benchSpec[k] =source[k]
elifnotsource[k]:
benchSpec[k] =None
returnbenchSpec
defbatchReplace(target, what: dict, wrapper='%'):
ifisinstance(target, dict):
forxintarget:
fork, vinwhat.items():
target[x] =str(target[x]).replace(wrapper+k+wrapper, v)
elifisinstance(target, str):
fork, vinwhat.items():
target=target.replace(wrapper+k+wrapper, v)
returntarget
defensureDictionaryKeys(target: dict, keys: list, default=None):
forkinkeys:
ifknotintarget:
target[k] =default
defloadSpecification(spec: dict):
globalinvokeSpec
globalcurrentConfigPath
ifnotisinstance(invokeSpec, dict):
invokeSpec= {}
# Patching the path of the config file into the specification
# Resolves relative paths inside the speficiation relative to
# the config file.
ifisinstance(spec['specs'], list):
forsinspec['specs']:
if'dir'insandnotos.path.isabs(s['dir']):
s['dir'] =currentConfigPath+'/'+s['dir']
elif'dir'notins:
s['dir'] =currentConfigPath
# merge
forkinspec:
ifisinstance(spec[k], dict):
ifkininvokeSpecandisinstance(invokeSpec[k], dict):
invokeSpec[k] = {**invokeSpec[k], **spec[k]}
else:
invokeSpec[k] =spec[k]
elifisinstance(spec[k], list):
ifkininvokeSpecandisinstance(invokeSpec[k], list):
invokeSpec[k].extend(spec[k])
else:
invokeSpec[k] =spec[k]
else:
invokeSpec[k] =spec[k]
parser=ArgumentParser(description="Invoke and control benchmarks")
parser.add_argument("-c", "--config", help="use this invoke specification", action="append", default=[])
parser.add_argument("-w", "--wrapper", help="Use these invoke wrappers", action="append", default=[])
parser.add_argument("-e", "--environment", help="Use these invoke environments", action="append", default=[])
parser.add_argument("-s", "--suite", help="Invoke these benchmark suites", action="append", default=[])
parser.add_argument("-i", "--input", help="Use these input sets", action="append", default=[])
parser.add_argument("-v", "--variable", help="define varibles e.g. -v var=test", action="append", default=[])
parser.add_argument("-f", "--force", help="ignore benchmark invocations that could not be resolved", action="store_true", default=False)
parser.add_argument("--stdout", help="redirect stdout from benchmark invocation", default=False)
parser.add_argument("--stderr", help="reiderct stderr from benchmark invocation", default=False)
parser.add_argument("--precmd", help="execute this command before each benchmark invocation", default=False)
parser.add_argument("--postcmd", help="execute this command after each benchmark invocation", default=False)
parser.add_argument("--specs", help="Show available benchmarks, suites, wrappers, environments and variables", action="store_true", default=False)
parser.add_argument("--list-benchmarks", help="show a list of specified benchmarks", action="store_true", default=False)
parser.add_argument("--list-suites", help="show a list of specified suites", action="store_true", default=False)
parser.add_argument("--compile", help="compile shell script", action="store_true", default=False)
parser.add_argument("--simulate", help="simulate invocation with verbose output", action="store_true", default=False)
parser.add_argument("--prepare", help="create directories and links", action="store_true", default=False)
parser.add_argument("--verbose", help="verbose output", action="store_true", default=False)
parser.add_argument("--version", help="print version number", action="store_true", default=False)
parser.add_argument("benchmarks", help="Invoke these benchmarks", nargs="*", default=[])
args=parser.parse_args()
ifargs.version:
print(f'invoke.py version {invokePyVersion} -- sourced at https://github.com/bgottschall/pythonTools/blob/master/invoke.py')
exit(0)
ifargs.simulate:
print('Simulating, no invocations or changes to the filesystems will be made!')
args.compile=False
args.prepare=False
ifargs.compile:
args.verbose=False
args.simulate=False
iflen(args.config) ==0:
ifos.path.exists(os.path.curdir+'/'+'invoke.spec.json'):
args.config= [os.path.curdir+'/'+'invoke.spec.json']
elifos.path.exists(os.path.dirname(__file__) +'/'+'invoke.spec.json'):
args.config= [os.path.dirname(__file__) +'/'+'invoke.spec.json']
else:
raiseException('Could not find any invoke specification files!')
forconfiginargs.config:
ifnotos.path.exists(config):
ifargs.force:
ifargs.verbose:
print(f"WARNING: could not find invoke specification {config}", file=sys.stderr)
continue
raiseException(f'Invoke specification {args.config} not found!')
currentConfigPath=os.path.dirname(config)
try:
loadSpecification(json.load(open(config)))
exceptException:
print(f"Could not parse configuration file {config}", file=sys.stderr)
raise
ifnotisinstance(invokeSpec, dict):
raiseException('Invalid invoke specification')
benchmarksAvailable=False
# Sanitize Config to make parsing easier
ensureDictionaryKeys(invokeSpec, ['specs', 'variables', 'wrappers', 'environments', 'suites'])
ifinvokeSpec['specs'] isnotNone:
forspecininvokeSpec['specs']:
ensureDictionaryKeys(spec, ['dir', 'precmd', 'postcmd', 'environment', 'stdout', 'stderr', 'input', 'benchmarks'])
ifspec['benchmarks'] isnotNone:
benchmarksAvailable=benchmarksAvailableorlen(spec['benchmarks']) >0
forbinspec['benchmarks']:
ensureDictionaryKeys(spec['benchmarks'][b], ['disabled', 'dir', 'exec', 'params', 'precmd', 'postcmd', 'stdout', 'stderr', 'environment', 'input'])
ifspec['benchmarks'][b]['inputs'] isnotNone:
foriinspec['benchmarks'][b]['inputs']:
ensureDictionaryKeys(spec['benchmarks'][b]['inputs'][i], ['disabled', 'dir', 'exec', 'params', 'precmd', 'postcmd', 'stdout', 'stderr', 'environment', 'workloads'])
ifspec['benchmarks'][b]['inputs'][i]['workloads'] isnotNone:
forwinspec['benchmarks'][b]['inputs'][i]['workloads']:
ensureDictionaryKeys(w, ['disabled', 'dir', 'exec', 'params', 'precmd', 'postcmd', 'stdout', 'stderr', 'environment'])
ifinvokeSpec['variables'] isNone:
invokeSpec['variables'] = {}
iflen(args.variable) >0:
forvinargs.variable:
vsplit=v.split('=')
invokeSpec['variables'][vsplit[0]] ='='.join(vsplit[1:])
ifargs.list_suites:
ifinvokeSpec['suites'] isNoneorlen(invokeSpec['suites']) ==0:
print('No suites specified!')
else:
forsininvokeSpec['suites']:
print(s)
exit(0)
ifargs.list_benchmarks:
ifnotbenchmarksAvailableorinvokeSpec['specs'] isNone:
print('No benchmarks specified')
else:
iflen(args.suite) >0:
forsinargs.suite:
ifsnotininvokeSpec['suites']:
raiseException(f"Suite '{s}' not found")
forbininvokeSpec['suites'][s]['benchmarks']:
forspecininvokeSpec['specs']:
ifbinspec['benchmarks'] and (notspec['benchmarks'][b]['disabled'] orargs.force):
print(b)
else:
forspecininvokeSpec['specs']:
forbinspec['benchmarks']:
ifnotspec['benchmarks'][b]['disabled'] orargs.force:
print(b)
exit(0)
ifargs.specs:
print(f"{'Benchmark':24s}{'Inputs'}")
print('---')
ifnotbenchmarksAvailableorinvokeSpec['specs'] isNone:
print('No benchmarks specified')
else:
forspecininvokeSpec['specs']:
forbinspec['benchmarks']:
print(f"{b:24s}{', '.join(spec['benchmarks'][b]['inputs'].keys())}{' (disabled)'ifspec['benchmarks'][b]['disabled'] else''}")
print('')
print(f"{'Suite':24s}{'Benchmarks'}")
print('---')
ifinvokeSpec['suites'] isNoneorlen(invokeSpec['suites']) ==0:
print('No suites specified!')
else:
forsininvokeSpec['suites']:
print(f"{s:24s}{', '.join(invokeSpec['suites'][s]['benchmarks'])}")
print('')
print(f"{'Wrapper':24s}{'Definition'}")
print('---')
ifinvokeSpec['wrappers'] isNoneorlen(invokeSpec['wrappers']) ==0:
print('No wrappers specified')
else:
forwininvokeSpec['wrappers']:
print(f"{w:24s}{invokeSpec['wrappers'][w]}")
print('')
print(f"{'Variable':24s}{'Definition'}")
print('---')
ifinvokeSpec['variables'] isNoneorlen(invokeSpec['variables']) ==0:
print('No variables specified')
else:
forvininvokeSpec['variables']:
print(f"{v:24s}{invokeSpec['variables'][v]}")
print('')
print(f"{'Environment':24s}{'Definition'}")
print('---')
ifinvokeSpec['environments'] isNoneorlen(invokeSpec['environments']) ==0:
print('No environments specified')
else:
foreininvokeSpec['environments']:
print(f"{e:24s}{invokeSpec['environments'][e]}")
exit(0)
ifnotbenchmarksAvailable:
raiseException('No benchmarks are specified in the configuration!')
forsuiteinargs.suite:
ifsuitenotininvokeSpec['suites']:
raiseException(f"Suite '{suite}' not found")
ifisinstance(invokeSpec['suites'][suite]['benchmarks'], list):
args.benchmarks.extend(invokeSpec['suites'][suite]['benchmarks'])
else:
args.benchmarks.append(invokeSpec['suites'][suite]['benchmarks'])
# create a unique benchmark selection, no need to invoke a benchmark more than once (no logical for this script)
uniqueBenchmarks=set()
args.benchmarks= [bforbinargs.benchmarksifbnotinuniqueBenchmarksandnotuniqueBenchmarks.add(b)]
deluniqueBenchmarks
iflen(args.benchmarks) ==0:
print('No benchmarks selected for invocation!')
exit(1)
# Make sure its all string
forvininvokeSpec['variables']:
invokeSpec['variables'][v] =str(invokeSpec['variables'][v])
# Lets build the default Invoke CMD line
defaultInvoke=''
iflen(args.wrapper) >0:
forwinargs.wrapper:
ifinvokeSpec['wrappers'] isNoneorwnotininvokeSpec['wrappers']:
raiseException(f"Wrapper '{w}' not found!")
defaultInvoke+=invokeSpec['wrappers'][w]
ifnotdefaultInvoke.endswith(' '):
defaultInvoke+=' '
# Start constructing the environment
globalEnvironment= {}
globalVarEnvironment= {}
iflen(args.environment) >0:
foreinargs.environment:
ifinvokeSpec['environments'] isNoneorenotininvokeSpec['environments']:
raiseException(f"Environment '{e}' not found!")
fork, vininvokeSpec['environments'][e].items():
v=str(v)
ifv.count('%') >=2:
globalVarEnvironment[k] =v
else:
globalEnvironment[k] =v
globalVarEnvironment=batchReplace(globalVarEnvironment, invokeSpec['variables'])
tempDict= {}
fork, vinglobalVarEnvironment.items():
ifv.count('%') <2:
globalEnvironment[k] =v
else:
tempDict[k] =v
globalVarEnvironment=tempDict
ifargs.compile:
shellScript='#!/bin/sh\n'
shellScript+='\n'
shellScript+='PWDPATH="$(pwd -P)"\n'
shellScript+='SCRIPTPATH="$( cd -- "$(dirname "$0")" >/dev/null 2>&1 ; pwd -P )"\n'
shellScript+='\n'
shellScript+='[ "$PWDPATH" != "$SCRIPTPATH" ] && cd "$SCRIPTPATH"\n'
shellScript+='\n'
ifargs.compileandlen(globalEnvironment) >0:
shellScript+='export '
forkinglobalEnvironment:
shellScript+=f'{k}={globalEnvironment[k]} '
shellScript+='\n'
ifargs.simulateandlen(globalEnvironment) >0:
print('/:$ export ', end='')
forkinglobalEnvironment:
print(f'{k}={globalEnvironment[k]} ', end='')
print('')
fordintreatAsDirectories:
ifdininvokeSpec['variables']:
ifnotos.path.exists(invokeSpec['variables'][d]):
ifargs.prepareor (notargs.compileandnotargs.simulate):
try:
Path(invokeSpec['variables'][d]).mkdir(parents=True, exist_ok=True)
exceptException:
pass
elifargs.compile:
shellScript+=f"mkdir -p {invokeSpec['variables'][d]} 2>/dev/null || true\n"
ifargs.simulate:
print(f"/:$ mkdir -p {invokeSpec['variables'][d]} || true")
ifargs.compile:
shellScript+='\n'
invokeCounter=0
failedInvokes= []
outputFiles= []
forbenchmarkinargs.benchmarks:
benchmarkFound=False
forspecIndex, specinenumerate(invokeSpec['specs']):
ifbenchmarknotinspec['benchmarks']:
continue
benchmarkFound=True
subEnvironment= {}
benchSpecL0= {
'dir': spec['dir'] ifspec['dir'] isnotNoneelseos.path.curdir,
'exec': None,
'params': None,
'precmd': spec['precmd'],
'postcmd': spec['postcmd'],
'stdout': spec['stdout'],
'stderr': spec['stderr'],
'environment': {},
'disabled': False,
}
ifisinstance(spec['environment'], dict):
fork, vinspec['environment'].items():
v=str(v)
ifv.count('%') >=2:
v=batchReplace(v, invokeSpec['variables'])
ifv.count('%') >=2:
benchSpecL0['environment'][k] =v
else:
subEnvironment[k] =v
ifargs.compileandlen(subEnvironment) >0:
shellScript+='export '
forkinsubEnvironment:
shellScript+=f'{k}={subEnvironment[k]} '
shellScript+='\n'
ifargs.simulateandlen(subEnvironment) >0:
print('/:$ export ', end='')
forkinsubEnvironment:
print(f'{k}={subEnvironment[k]} ', end='')
print('')
iflen(args.input) ==0:
ifspec['input'] isNone:
ifargs.force:
ifargs.verbose:
print(f'WARNING: specification {specIndex} odes not provide a default input, skipping.', file=sys.stderr)
continue
raiseException(f"Specficiation {specIndex} does not have a default input, please specify one!")
useInputs=spec['input'] ifisinstance(spec['input'], list) else [spec['input']]
else:
useInputs=args.input
benchSpecL1=updateBenchSpec(benchSpecL0, spec['benchmarks'][benchmark], benchmark)
forinputinuseInputs:
ifinputnotinspec['benchmarks'][benchmark]['inputs']:
print(f"WARNING: Could not find input '{input}' for benchmark '{benchmark}', will skip invocation...", file=sys.stderr)
continue
benchSpecL2=updateBenchSpec(benchSpecL1, spec['benchmarks'][benchmark]['inputs'][input], input)
iflen(spec['benchmarks'][benchmark]['inputs'][input]['workloads']) ==0:
print(f"WARNING: no workloads defined for benchmark '{benchmark}', will skip invocation...", file=sys.stderr)
continue
symlinked=False
forworkload, _inenumerate(spec['benchmarks'][benchmark]['inputs'][input]['workloads']):
benchSpec=updateBenchSpec(benchSpecL2, spec['benchmarks'][benchmark]['inputs'][input]['workloads'][workload])
# the %now% variable is replaced by the datetime, if compiling its resolved through the shell
ifbenchSpec['disabled']:
ifargs.force:
print(f"WARNING: ignore disabled flag for benchmark '{benchmark}'", file=sys.stderr)
else:
ifargs.verbose:
print(f"Ignore disabled benchmark '{benchmark}'")
continue
ifbenchSpec['exec'] isNone:
ifargs.force:
ifargs.verbose:
print(f"WARNING: ignored workload {workload} of '{benchmark}' because no executable was defined", file=sys.stderr)
continue
raiseException(f"No executable defined for benchmark '{benchmark}'")
ifbenchSpec['params'] isNone:
benchSpec['params'] =''
ifargs.precmd:
benchSpec['precmd'] =args.precmd
ifargs.postcmd:
benchSpec['postcmd'] =args.postcmd
ifargs.compileand (('%now%'instr(benchSpec)) or ('%now%'indefaultInvoke)):
sDate='${NOW}'
else:
sDate=datetime.now().strftime("%Y-%m-%d_%H%M%S")
replaceVars= {**{'counter': str(invokeCounter), 'workload': str(workload), 'input': str(input), 'benchmark': str(benchmark), 'now': sDate}, **invokeSpec['variables']}
benchSpec['dir'] =batchReplace(benchSpec['dir'], replaceVars)
benchSpec['exec'] =batchReplace(benchSpec['exec'], replaceVars)
execName=os.path.basename(benchSpec['exec'])
benchSpec['exec'] =os.path.relpath(benchSpec['exec'], os.path.curdir)
ifnotos.path.isdir(benchSpec['dir']):
ifargs.verbose:
print(f"Creating directory '{benchSpec['dir']}'")
ifargs.simulate:
print(f"/:$ mkdir -p {benchSpec['dir']}")
else:
Path(benchSpec['dir']).mkdir(parents=True, exist_ok=True)
# Executable is not where it is supposed to be, but one is available in the input directory
ifnotos.path.exists(benchSpec['exec']) andos.path.exists(benchSpec['dir'] +'/'+execName):
ifargs.verbose:
print(f"WARNING: couldn't find {benchSpec['exec']}, will use {benchSpec['dir'] +'/'+execName} instead", file=sys.stderr)
benchSpec['exec'] =benchSpec['dir'] +'/'+execName
ifnotos.path.exists(benchSpec['exec']):
ifargs.force:
ifargs.verbose:
print(f"WARNING: ignored workload {workload} of '{benchmark}' because executable '{benchSpec['exec']}' was not found", file=sys.stderr)
continue
raiseException(f"Could not find executable '{benchSpec['exec']}'")
benchSpec['dir'] =os.path.relpath(benchSpec['dir'], os.path.curdir)
ifargs.compile:
shellScript+=f"# Execute workload {workload} of the '{input}' input of benchmark '{benchmark}'\n"
ifsDate=='${NOW}':
shellScript+='NOW="$(date +\'%Y-%m-%d_%H%M%S\')"\n'
ifargs.verboseandnotargs.prepare:
print(f"Executing benchmark '{benchmark}', input '{input}', workload {workload}")
ifnotos.path.exists(benchSpec['dir'] +'/'+execName):
ifargs.verbose:
print(f"Symlinking '{benchSpec['exec']}' to '{benchSpec['dir'] +'/'+execName}'")
ifargs.simulate:
print(f"/:$ ln -s {os.path.relpath(benchSpec['exec'], benchSpec['dir'])}{benchSpec['dir'] +'/'+execName}")
elifargs.prepareornotargs.compile:
os.symlink(os.path.relpath(benchSpec['exec'], benchSpec['dir']), benchSpec['dir'] +'/'+execName)
else:
shellScript+=f"ln -s {os.path.relpath(benchSpec['exec'], benchSpec['dir'])}{benchSpec['dir'] +'/'+execName}\n"
symlinked=True
elifos.path.realpath(benchSpec['exec']) !=os.path.realpath(benchSpec['dir'] +'/'+execName):
print(f"WARNING: target executable '{benchSpec['dir'] +'/'+execName}' differs from specified executable '{benchSpec['exec']}'", file=sys.stderr)
invokeCmd=defaultInvoke+'./'+execName
iflen(benchSpec['params']) >0:
invokeCmd+=' '+benchSpec['params']
benchSpec['environment'] = {**benchSpec['environment'], **globalVarEnvironment}
replaceVars= {**replaceVars, **{'dir': benchSpec['dir'], 'exec': execName}}
fordintreatAsDirectories:
ifdinreplaceVars:
replaceVars[d] =os.path.abspath(replaceVars[d]) +'/'ifos.path.isabs(replaceVars[d]) elseos.path.relpath(replaceVars[d], benchSpec['dir']) +'/'
# Postprocess the invoke cmd lines after variables
invokeCmd=batchReplace(invokeCmd, replaceVars)
ifisinstance(benchSpec['precmd'], str):
benchSpec['precmd'] =batchReplace(benchSpec['precmd'], replaceVars)
ifisinstance(benchSpec['postcmd'], str):
benchSpec['postcmd'] =batchReplace(benchSpec['postcmd'], replaceVars)
ifargs.stdout:
benchSpec['stdout'] =args.stdoutifos.path.isabs(args.stdout) elseos.path.relpath(args.stdout, benchSpec['dir'])
ifargs.stderr:
benchSpec['stderr'] =args.stderrifos.path.isabs(args.stderr) elseos.path.relpath(args.stderr, benchSpec['dir'])
ifisinstance(benchSpec['stdout'], str):
benchSpec['stdout'] =batchReplace(benchSpec['stdout'], replaceVars)
ifisinstance(benchSpec['stderr'], str):
benchSpec['stderr'] =batchReplace(benchSpec['stderr'], replaceVars)
benchSpec['environment'] =batchReplace(benchSpec['environment'], replaceVars)
ifnotargs.compile:
invokeEnvironment= {**os.environ.copy(), **subEnvironment, **benchSpec['environment'], **globalEnvironment}
ifbenchSpec['stdout'] isnotNone:
# Append to invokeCmd or open it for redirected output
ifargs.compileorargs.simulate:
invokeCmd+=f" >>{benchSpec['stdout']}"
else:
benchSpec['stdout'] =open(benchSpec['stdout'] ifos.path.isabs(benchSpec['stdout']) elsebenchSpec['dir'] +'/'+benchSpec['stdout'], 'a')
ifbenchSpec['stderr'] isnotNone:
# Append to invokeCmd or open it for redirected output
ifargs.compileorargs.simulate:
invokeCmd+=f" 2>>{benchSpec['stderr']}"
else:
benchSpec['stderr'] =open(benchSpec['stderr'] ifos.path.isabs(benchSpec['stderr']) elsebenchSpec['dir'] +'/'+benchSpec['stderr'], 'a')
ifargs.compile:
shellScript+='(\n'
shellScript+=' set -x\n'
shellScript+=f" cd \"{benchSpec['dir']}\"\n"
iflen(benchSpec['environment']) >0:
shellScript+=' export '
forkinbenchSpec['environment']:
shellScript+=f"{k}={benchSpec['environment'][k]} "
shellScript+='\n'
ifargs.simulate:
iflen(benchSpec['environment']) >0:
print(f"{benchSpec['dir']}:$ export ", end='')
forkinbenchSpec['environment']:
print(f"{k}={benchSpec['environment'][k]} ", end='')
print('')
ifargs.verboseandlen(benchSpec['environment']) >0:
print(f"Setting environment to {benchSpec['environment']}")
ifisinstance(benchSpec['precmd'], str):
ifnotargs.prepare:
ifargs.verbose:
print(f"Executing pre invoke command '{benchSpec['precmd']}'")
ifargs.simulate:
print(f"{benchSpec['dir']}:$ {benchSpec['precmd']}")
elifnotargs.prepareandnotargs.compile:
ret=subprocess.call(benchSpec['precmd'], shell=True, cwd=benchSpec['dir'], env=invokeEnvironment)
ifret!=0:
ifargs.verbose:
print(f"Execution failed with return code {ret}")
failedInvokes.append(f"{benchmark}-{input}-{workload}-precmd")
ifargs.compile:
shellScript+=f" {benchSpec['precmd']}\n"
ifnotargs.prepareandargs.verbose:
print(f"Invoke command line '{invokeCmd}'")
ifnotargs.compileandnotargs.simulate:
ifbenchSpec['stdout'] isnotNone:
print(f"Redirect stdout to {benchSpec['stdout'].name}")
ifbenchSpec['stderr'] isnotNone:
print(f"Redirect stderr to {benchSpec['stderr'].name}")
ifargs.simulate:
print(f"{benchSpec['dir']}:$ {invokeCmd}")
elifnotargs.prepareandnotargs.compile:
ret=subprocess.call(invokeCmd, shell=True, cwd=benchSpec['dir'], env=invokeEnvironment, stdout=benchSpec['stdout'], stderr=benchSpec['stderr'])
ifret!=0:
ifargs.verbose:
print(f"Execution failed with return code {ret}")
failedInvokes.append(f"{benchmark}-{input}-{workload}")
ifargs.compile:
shellScript+=f" {invokeCmd}\n"
ifisinstance(benchSpec['postcmd'], str):
ifnotargs.prepare:
ifargs.verbose:
print(f"Executing post invoke command '{benchSpec['postcmd']}'")
ifargs.simulate:
print(f"{benchSpec['dir']}:$ {benchSpec['postcmd']}")
elifnotargs.compile:
ret=subprocess.call(benchSpec['postcmd'], shell=True, cwd=benchSpec['dir'], env=invokeEnvironment)
ifret!=0:
ifargs.verbose:
print(f"Execution failed with return code {ret}")
failedInvokes.append(f"{benchmark}-{input}-{workload}-postcmd")
ifargs.compile:
shellScript+=f" {benchSpec['postcmd']}\n"
invokeCounter+=1
ifargs.compile:
shellScript+=')\n'
ifsymlinkedandnotargs.prepare:
ifargs.verbose:
print("Remove previously created symlink")
ifargs.simulate:
print(f"/:$ rm {benchSpec['dir'] +'/'+execName}")
elifnotargs.compile:
os.unlink(benchSpec['dir'] +'/'+execName)
ifargs.compile:
shellScript+=f"rm {benchSpec['dir'] +'/'+execName}\n"
ifargs.compile:
shellScript+='\n'
ifnotbenchmarkFound:
raiseException(f"Could not find specification for benchmark '{benchmark}'!")
ifargs.compile:
print(shellScript, end='')
iflen(failedInvokes) !=0:
print(f'WARNING: detected {failedInvokes} with an error return code!', file=sys.stderr)