-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathmodule.py
More file actions
6152 lines (4895 loc) · 233 KB
/
module.py
File metadata and controls
6152 lines (4895 loc) · 233 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
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
# This file was originally created for CM Script automations and is now
# modified to make it work for MLCFlow automation.
# This file contains the CM/MLC script execution logic which includes processing the script meta,
# running the dependencies and finally preparing the required environment and running the specified script.
#
# Developed by Grigori Fursin and Arjun Suresh for CM and modified for MLCFlow by Arjun Suresh and Anandhu Sooraj
#
import re
import os
import logging
from mlc.main import Automation
from mlc.main import CacheAction
import mlc.utils as utils
from utils import *
from script.script_utils import *
from script.cache_utils import *
class ScriptAutomation(Automation):
"""
MLC "script" automation actions
(making native scripts more portable, deterministic, reusable and reproducible)
"""
############################################################
def __init__(self, action_object, automation_file, run_args={}):
super().__init__(action_object, "script", automation_file)
self.os_info = {}
self.file_with_cached_state = 'mlc-cached-state.json'
self.logger = self.action_object.logger
self.logger.propagate = False
# Create CacheAction using the same parent as the Script
self.cache_action = CacheAction(self.action_object.parent)
self.tmp_file_env = 'tmp-env'
self.tmp_file_env_all = 'tmp-env-all'
self.tmp_file_run = 'tmp-run'
self.tmp_file_state = 'tmp-state.json'
self.tmp_file_run_state = 'tmp-run-state.json'
self.tmp_file_run_env = 'tmp-run-env.out'
self.tmp_file_ver = 'tmp-ver.out'
self.__version__ = "1.3.2"
self.local_env_keys = ['MLC_VERSION',
'MLC_VERSION_MIN',
'MLC_VERSION_MAX',
'MLC_VERSION_MAX_USABLE',
'MLC_DETECTED_VERSION',
'MLC_INPUT',
'MLC_OUTPUT',
'MLC_OUTBASENAME',
'MLC_OUTDIRNAME',
'MLC_SEARCH_FOLDER_PATH',
'MLC_NAME',
'MLC_EXTRA_CACHE_TAGS',
'MLC_TMP_*',
'MLC_GIT_*',
'MLC_RENEW_CACHE_ENTRY']
self.host_env_keys = [
"USER",
"HOME",
"GH_TOKEN",
"ftp_proxy",
"FTP_PROXY",
"http_proxy",
"HTTP_PROXY",
"https_proxy",
"HTTPS_PROXY",
"no_proxy",
"NO_PROXY",
"socks_proxy",
"SOCKS_PROXY"]
self.input_flags_converted_to_tmp_env = {
'path': {'desc': 'Filesystem path to search for executable', 'default': ''},
'folder': {'desc': 'Folder to search first before other paths', 'default': ''}}
self.input_flags_converted_to_env = {'input': {'desc': 'Input to the script passed using the env key `MLC_INPUT`', 'default': ''},
'output': {'desc': 'Output from the script passed using the env key `MLC_OUTPUT`', 'default': ''},
'outdirname': {'desc': 'The directory to store the script output', 'default': 'cache directory ($HOME/MLC/repos/local/cache/<>) if the script is cacheable or else the current directory'},
'outbasename': {'desc': 'The output file/folder name', 'default': ''},
'search_folder_path': {'desc': 'The folder path where executables of a given script need to be searched. Search is done recursively upto 4 levels.'},
'name': {},
'extra_cache_tags': {'desc': 'Extra cache tags to be added to the cached entry when the script results are saved', 'default': ''},
'skip_compile': {'desc': 'Skip compilation', 'default': False},
'skip_run': {'desc': 'Skip run', 'default': False},
'skip_sudo': {'desc': 'Skip SUDO detection', 'default': False},
'accept_license': {'desc': 'Accept the required license requirement to run the script', 'default': False},
'skip_system_deps': {'desc': 'Skip installing any system dependencies', 'default': False},
'git_ssh': {'desc': 'Use SSH for git repos', 'default': False},
'gh_token': {'desc': 'Github Token', 'default': ''},
'hf_token': {'desc': 'Huggingface Token', 'default': ''},
'verify_ssl': {'desc': 'Verify SSL', 'default': False}
}
self.default_env = run_args.get('default_env', {})
self.env = run_args.get('env', {})
self.state = run_args.get('state', {})
self.const = run_args.get('const', {})
self.const_state = run_args.get('const_state', {})
add_deps_recursive = run_args.get('adr', {})
if not add_deps_recursive:
add_deps_recursive = run_args.get('add_deps_recursive', {})
else:
utils.merge_dicts({'dict1': add_deps_recursive, 'dict2': run_args.get(
'add_deps_recursive', {}), 'append_lists': True, 'append_unique': True})
self.add_deps_recursive = add_deps_recursive
# Recursion spaces needed to format log and print
self.recursion_spaces = run_args.get('recursion_spaces', '')
# Caching selections to avoid asking users again
self.remembered_selections = run_args.get('remembered_selections', [])
self.deps = []
self.run_state = self.init_run_state(
run_args.get('run_state')) # changes for every run call
self.main_script_force_new_cache = run_args.get(
'new', False) # only set for the initial script being called
if self.env.get('MLC_USER_RUN_DIR', '') == '':
current_path = os.path.abspath(os.getcwd())
r = _update_env(self.env, 'MLC_USER_RUN_DIR', current_path)
if r['return'] > 0:
return r
if self.const.get('MLC_USER_RUN_DIR', '') == '':
r = _update_env(
self.const,
'MLC_USER_RUN_DIR',
self.env['MLC_USER_RUN_DIR'])
if r['return'] > 0:
return r
def init_run_state(self, run_state):
run_state = run_state or {}
run_state.setdefault('parent', None)
for f in ['fake_deps', 'cache']:
run_state.setdefault(f, False)
for d in ['input_mapping', 'docker', 'remote_run']:
run_state.setdefault(d, {})
for l in ['deps', 'post_deps', 'prehook_deps', 'posthook_deps',
'new_env_keys', 'new_state_keys', 'file_path_env_keys',
'folder_path_env_keys', 'version_info', 'full_deps']:
run_state.setdefault(l, [])
return run_state
#################################################################
def run(self, i):
"""
Run MLC script
Args:
(MLC input dict):
(out) (str): if 'con', output to console
(artifact) (str): specify MLC script (MLC artifact) explicitly
(tags) (str): tags to find an MLC script (MLC artifact)
(env) (dict): global environment variables (can/will be updated by a given script and dependencies)
(const) (dict): constant environment variable (will be preserved and persistent for a given script and dependencies)
(state) (dict): global state dictionary (can/will be updated by a given script and dependencies)
(const_state) (dict): constant state (will be preserved and persistent for a given script and dependencies)
(add_deps) (dict): {"name": {"tag": "tag(s)"}, "name": {"version": "version_no"}, ...}
(add_deps_recursive) (dict): same as add_deps but is passed recursively onto dependencies as well
(version) (str): version to be added to env.MLC_VERSION to specialize this flow
(version_min) (str): min version to be added to env.MLC_VERSION_MIN to specialize this flow
(version_max) (str): max version to be added to env.MLC_VERSION_MAX to specialize this flow
(version_max_usable) (str): max USABLE version to be added to env.MLC_VERSION_MAX_USABLE
(path) (str): list of paths to be added to env.MLC_TMP_PATH to specialize this flow
(input) (str): converted to env.MLC_INPUT (local env)
(output) (str): converted to env.MLC_OUTPUT (local env)
(outbasename) (str): converted to env.MLC_OUTBASENAME (local env)
(outdirname) (str): converted to env.MLC_OUTDIRNAME (local env)
(extra_cache_tags) (str): converted to env.MLC_EXTRA_CACHE_TAGS and used to add to caching (local env)
(name) (str): taken from env.MLC_NAME and/or converted to env.MLC_NAME (local env)
Added to extra_cache_tags with "name-" prefix .
Useful for python virtual env (to create multiple entries)
(quiet) (bool): if True, set env.MLC_QUIET to "yes" and attempt to skip questions
(the developers have to support it in pre/post processing and scripts)
(skip_cache) (bool): if True, skip caching and run in current directory
(force_cache) (bool): if True, force caching if can_force_cache=true in script meta
(skip_remembered_selections) (bool): if True, skip remembered selections
(uses or sets env.MLC_TMP_SKIP_REMEMBERED_SELECTIONS to "yes")
(new) (bool): if True, skip search for cached and run again
(renew) (bool): if True, rewrite cache entry if exists
(dirty) (bool): if True, do not clean files
(save_env) (bool): if True, save env and state to tmp-env.sh/bat and tmp-state.json
(shell) (bool): if True, save env with cmd/bash and run it
(recursion) (bool): True if recursive call.
Useful when preparing the global bat file or Docker container
to save/run it in the end.
(recursion_spaces) (str, internal): adding ' ' during recursion for debugging
(remembered_selections) (list): remember selections of cached outputs
(print_env) (bool): if True, print aggregated env before each run of a native script
(fake_run) (bool): if True, will run the dependent scripts but will skip the main run script
(prepare) (bool): the same as fake_run
(fake_deps) (bool): if True, will fake run the dependent scripts
(run_state) (dict): Internal run state
(debug_script_tags) (str): if !='', run cmd/bash before executing a native command
inside a script specified by these tags
(debug_script) (bool): if True, debug current script (set debug_script_tags to the tags of a current script)
(debug_uid) (str): if True, set MLC_TMP_DEBUG_UID to this number to enable
remote python debugging of scripts and wrapped apps/tools
(detected_versions) (dict): All the used scripts and their detected_versions
(verbose) (bool): if True, prints all tech. info about script execution (False by default)
(v) (bool): the same as verbose
(time) (bool): if True, print script execution time (or if verbose == True)
(space) (bool): if True, print used disk space for this script (or if verbose == True)
(ignore_script_error) (bool): if True, ignore error code in native tools and scripts
and finish a given MLC script. Useful to test/debug partial installations
(json) (bool): if True, print output as JSON
(j) (bool): if True, print output as JSON
(pause) (bool): if True, pause at the end of the main script (Press Enter to continue)
(repro) (bool): if True, dump mlc-run-script-input.json, mlc-run_script_output.json,
mlc-run-script-state.json, mlc-run-script-info.json
to improve the reproducibility of results
(repro_prefix) (str): if !='', use it to record above files {repro-prefix)-input.json ...
(repro_dir) (str): if !='', use this directory to dump info (default = 'mlc-repro')
(dump_version_info) (bool): dump info about resolved versions of tools in dependencies
(print_deps) (bool): if True, will print the MLC run commands of the direct dependent scripts
(print_readme) (bool): if True, will print README with all MLC steps (deps) to run a given script
(script_call_prefix) (str): how to call script in logs and READMEs (mlcr)
(skip_sys_utils) (bool): if True, set env['MLC_SKIP_SYS_UTILS']='yes'
to skip MLC sys installation
(skip_sudo) (bool): if True, set env['MLC_TMP_SKIP_SUDO']='yes'
to let scripts deal with that
(silent) (bool): if True, attempt to suppress all info if supported
(sets MLC_TMP_SILENT=yes)
(s) (bool): the same as 'silent'
...
Returns:
(MLC return dict):
* return (int): return code == 0 if no error and >0 if error
* (error) (str): error string if return>0
* (skipped) (bool): if true, this script was skipped
* new_env (dict): new environment (delta from a collective script)
* new_state (dict): new state (delta from a collective script)
* env (dict): global env (updated by this script - includes new_env)
* state (dict): global state (updated by this script - includes new_state)
"""
r = self._run(i)
return r
############################################################
def _run(self, i):
# from cmind import utils
import copy
import time
import shutil
# Check if has --help
if i.get('help', False):
return self.help(i)
logger = self.logger
recursion = i.get('recursion', False)
# If first script run, check if can write to current directory
if not recursion and not i.get('skip_write_test', False):
if not can_write_to_current_directory():
return {
'return': 1, 'error': 'Current directory "{}" is not writable - please change it'.format(os.getcwd())}
recursion_int = int(i.get('recursion_int', 0)) + 1
start_time = time.time()
# Check extra input from environment variable MLC_SCRIPT_EXTRA_CMD
# Useful to set up default flags such as the name of virtual enviroment
extra_cli = os.environ.get('MLC_SCRIPT_EXTRA_CMD', '').strip()
if extra_cli != '':
r = convert_args_to_dictionary(extra_cli)
if r['return'] > 0:
return r
mlc_input = r['args_dict']
utils.merge_dicts({'dict1': i,
'dict2': mlc_input,
'append_lists': True,
'append_unique': True})
# Recursion spaces needed to format log and print
self.recursion_spaces = i.get(
'recursion_spaces', self.recursion_spaces)
# Caching selections to avoid asking users again
self.remembered_selections = i.get(
'remembered_selections', self.remembered_selections)
# Get current env and state before running this script and sub-scripts
# env = i.get('env', {})
# state = i.get('state', {})
# const = i.get('const', {})
# const_state = i.get('const_state', {})
self.env = i.get('env', self.env)
self.state = i.get('state', self.state)
self.const = i.get('const', self.const)
self.const_state = i.get('const_state', self.const_state)
self.add_deps_recursive = i.get('adr', self.add_deps_recursive)
if not self.add_deps_recursive:
self.add_deps_recursive = i.get('add_deps_recursive', {})
else:
utils.merge_dicts({'dict1': self.add_deps_recursive, 'dict2': i.get(
'add_deps_recursive', {}), 'append_lists': True, 'append_unique': True})
env = self.env
state = self.state
const = self.const
const_state = self.const_state
add_deps_recursive = self.add_deps_recursive
# Save current env and state to detect new env and state after running
# a given script
saved_env = copy.deepcopy(self.env)
saved_state = copy.deepcopy(self.state)
for key in ["env", "state", "const", "const_state"]:
if i.get("local_" + key):
utils.merge_dicts({'dict1': getattr(self, key),
'dict2': i['local_' + key],
'append_lists': True,
'append_unique': True})
add_deps = i.get('ad', {})
if not add_deps:
add_deps = i.get('add_deps', {})
else:
utils.merge_dicts({'dict1': add_deps, 'dict2': i.get(
'add_deps', {}), 'append_lists': True, 'append_unique': True})
save_env = i.get('save_env', False)
print_env = i.get('print_env', False)
show_time = i.get('time', False)
show_space = i.get('space', False)
if not recursion and show_space:
start_disk_stats = shutil.disk_usage("/")
extra_recursion_spaces = ' ' # if verbose else ''
skip_cache = i.get('skip_cache', False)
force_cache = i.get('force_cache', False)
fake_run = i.get(
'fake_run',
False) if 'fake_run' in i else i.get(
'prepare',
False)
if fake_run:
env['MLC_TMP_FAKE_RUN'] = 'yes'
debug_uid = i.get('debug_uid', '')
if debug_uid != '':
r = _update_env(env, 'MLC_TMP_DEBUG_UID', debug_uid)
if r['return'] > 0:
return r
fake_deps = i.get('fake_deps', False)
if fake_deps:
env['MLC_TMP_FAKE_DEPS'] = 'yes'
if is_true(i.get('skip_sys_utils', '')):
env['MLC_SKIP_SYS_UTILS'] = 'yes'
if is_true(i.get('skip_sudo', '')):
env['MLC_TMP_SKIP_SUDO'] = 'yes'
run_state = self.init_run_state(i.get('run_state'))
# Check verbose and silent
# Get the current log level so that the log levels could be reverted
# after execution of the script and corresponding dependencies
original_logging_level = logger.level
verbose = False
silent = False
if i.get('verbose', '') != '':
verbose = True if is_true(i.get('verbose', '')) else False
elif i.get('v', '') != '':
verbose = True if is_true(i.get('v', '')) else False
elif env.get('MLC_VERBOSE', '') != '':
verbose = True if is_true(env.get('MLC_VERBOSE', '')) else False
if i.get('silent', '') != '':
silent = True if is_true(i.get('silent', '')) else False
elif i.get('s', '') != '':
silent = True if is_true(i.get('s', '')) else False
elif env.get('MLC_SILENT', '') != '':
silent = True if is_true(env.get('MLC_SILENT', '')) else False
if verbose and silent:
logger.warning(
"Both verbose and silent is set to True. Verbose will take precedence.")
silent = False
if silent:
env['MLC_TMP_SILENT'] = 'yes'
logger.setLevel(logging.WARNING)
run_state['tmp_silent'] = True
if verbose:
env['MLC_TMP_VERBOSE'] = 'yes'
run_state['tmp_verbose'] = True
logger.setLevel(logging.DEBUG)
if not env.get('MLC_TMP_SILENT') and not env.get('MLC_TMP_VERBOSE'):
if logger.level == logging.DEBUG:
env['MLC_TMP_VERBOSE'] = "yes"
elif logger.level == logging.DEBUG:
env['MLC_TMP_SILENT'] = "yes"
print_deps = i.get('print_deps', False)
print_versions = i.get('print_versions', False)
print_readme = i.get('print_readme', False)
dump_version_info = i.get('dump_version_info', False)
new_cache_entry = i.get('new', False)
renew = i.get('renew', False)
cmd = i.get('cmd', '')
# Capturing the input command if it is coming from an access function
if not cmd and 'cmd' in i.get('input', ''):
i['cmd'] = i['input']['cmd']
cmd = i['cmd']
debug_script_tags = i.get('debug_script_tags', '')
detected_versions = i.get('detected_versions', {})
ignore_script_error = i.get('ignore_script_error', False)
# Detect current path and record in env for further use in native
# scripts
current_path = os.path.abspath(os.getcwd())
r = _update_env(env, 'MLC_TMP_CURRENT_PATH', current_path)
if r['return'] > 0:
return r
# Check if quiet/non-interactive mode
quiet = i.get(
'quiet',
False) if 'quiet' in i else (
str(env.get(
'MLC_QUIET',
'')).lower() in ["1", "true", "yes", "on"])
if quiet:
env['MLC_QUIET'] = 'yes'
skip_remembered_selections = i.get('skip_remembered_selections', False) if 'skip_remembered_selections' in i \
else (env.get('MLC_SKIP_REMEMBERED_SELECTIONS', '').lower() == 'yes')
if skip_remembered_selections:
env['MLC_SKIP_REMEMBERED_SELECTIONS'] = 'yes'
# Prepare debug info
parsed_script = i.get('parsed_artifact')
parsed_script_alias = parsed_script[0][0] if parsed_script is not None else ''
# Get and cache minimal host OS info to be able to run scripts and
# manage OS environment
if len(self.os_info) == 0:
r = get_host_os_info()
if r['return'] > 0:
return r
self.os_info = r['info']
os_info = self.os_info
# Bat extension for this host OS
bat_ext = os_info['bat_ext']
# Add permanent env from OS (such as MLC_WINDOWS:"yes" on Windows)
env_from_os_info = os_info.get('env', {})
if len(env_from_os_info) > 0:
# env.update(env_from_os_info)
utils.merge_dicts({'dict1': env,
'dict2': env_from_os_info,
'append_lists': True,
'append_unique': True})
# take some env from the user environment
for key in self.host_env_keys:
if os.environ.get(key, '') != '' and env.get(key, '') == '':
env[key] = os.environ[key]
r = self._update_env_from_input(env, i)
if env.get('MLC_OUTDIRNAME', '') != '':
if not os.path.isabs(env['MLC_OUTDIRNAME']):
env['MLC_OUTDIRNAME'] = os.path.abspath(env['MLC_OUTDIRNAME'])
#######################################################################
# Check if we want to skip cache (either by skip_cache or by fake_run)
force_skip_cache = True if skip_cache else False
force_skip_cache = True if fake_run else force_skip_cache
#######################################################################
# Find MLC script(s) based on their tags and variations to get their meta and customize this workflow.
# We will need to decide how to select if more than 1 (such as "get compiler")
#
# Note: this local search function will separate tags and variations
#
# STEP 100 Input: Search sripts by i['tags'] (includes variations starting from _) and/or i['parsed_artifact']
# tags_string = i['tags']
tags_string = i.get('tags', '').strip()
# ii = utils.sub_input(i, self.action_object.cfg['artifact_keys'])
r = get_variation_and_script_tags(tags_string)
if r['return'] > 0:
return r
script_tags = r['script_tags']
variation_tags = r['variation_tags']
r = select_script_and_cache(
self,
i,
script_tags,
variation_tags,
parsed_script_alias,
quiet,
skip_remembered_selections=skip_remembered_selections,
force_cache=force_cache and not self.main_script_force_new_cache,
force_skip_cache=force_skip_cache,
new_cache_entry=new_cache_entry
)
if r['return'] > 0:
return r
script_item = r['script']
cache_list = r['cache_list']
meta = script_item.meta
path = script_item.path
# Check min MLC version requirement
min_mlc_version = meta.get('min_mlc_version', '').strip()
if min_mlc_version != '':
try:
import importlib.metadata
current_mlc_version = importlib.metadata.version("mlc")
comparison = utils.compare_versions(
current_mlc_version, min_mlc_version)
if comparison < 0:
return {'return': 1, 'error': 'This script requires MLC version >= {} while current MLC version is {} - please update using "pip install mlcflow -U"'.format(
min_mlc_version, current_mlc_version)}
except Exception as e:
error = format(e)
# Check path to repo
script_repo_path = script_item.repo.path
script_repo_path_with_prefix = script_item.repo.path
if script_item.repo.meta.get('prefix', '') != '':
script_repo_path_with_prefix = os.path.join(
script_repo_path, script_item.repo.meta['prefix'])
env['MLC_TMP_CURRENT_SCRIPT_REPO_PATH'] = script_repo_path
env['MLC_TMP_CURRENT_SCRIPT_REPO_PATH_WITH_PREFIX'] = script_repo_path_with_prefix
run_state['script_id'] = meta['alias'] + "," + meta['uid']
run_state['script_tags'] = script_tags
run_state['script_variation_tags'] = variation_tags
run_state['script_repo_alias'] = script_item.repo.meta.get(
'alias', '')
run_state['script_repo_git'] = script_item.repo.meta.get(
'git', False)
run_state['cache'] = meta.get('cache', False)
run_state['cache_expiration'] = i.get(
'cache_expiration', meta.get(
'cache_expiration', False))
if not recursion:
run_state['script_entry_repo_to_report_errors'] = meta.get(
'repo_to_report_errors', '')
run_state['script_entry_repo_alias'] = script_item.repo.meta.get(
'alias', '')
run_state['script_entry_repo_git'] = script_item.repo.meta.get(
'git', False)
deps = run_state['deps']
post_deps = run_state['post_deps']
prehook_deps = run_state['prehook_deps']
posthook_deps = run_state['posthook_deps']
input_mapping = run_state['input_mapping']
docker_settings = run_state['docker']
input_mapping = meta.get('input_mapping', {})
input_description = meta.get('input_description', {})
docker_settings = meta.get('docker')
found_script_item = utils.assemble_object(
meta['alias'], meta['uid'])
found_script_tags = meta.get('tags', [])
if i.get('debug_script', False):
debug_script_tags = ','.join(found_script_tags)
logger.debug(self.recursion_spaces +
' - Found script::{} in {}'.format(found_script_item, path))
# STEP 500 output: script_item - unique selected script artifact
# (cache_list) pruned for the unique script if cache is used
# meta - script meta
# path - script path
# found_script_tags [] - all tags of the found script
# HERE WE HAVE ORIGINAL ENV
# STEP 600: Continue updating env
# Add default env from meta to new env if not empty
# (env NO OVERWRITE)
script_item_default_env = meta.get('default_env', {})
for key in script_item_default_env:
env.setdefault(key, script_item_default_env[key])
# STEP 700: Overwrite env with keys from the script input (to allow user friendly CLI)
# IT HAS THE PRIORITY OVER meta['default_env'] and meta['env'] but not over the meta from versions/variations
# (env OVERWRITE - user enforces it from CLI)
# (it becomes const)
if input_mapping:
update_env_from_input_mapping(
env, i, input_mapping, input_description)
update_env_from_input_mapping(
const, i, input_mapping, input_description)
# This mapping is done in docker script
# if docker_input_mapping:
# update_env_from_input_mapping(env, i, docker_input_mapping)
# update_env_from_input_mapping(const, i, docker_input_mapping)
# Update env/state with cost
env.update(const)
utils.merge_dicts({'dict1': state,
'dict2': const_state,
'append_lists': True,
'append_unique': True})
# for update_meta_if_env
r = self.update_state_from_meta(
meta,
run_state,
i)
if r['return'] > 0:
return r
# taking from meta or else deps with same names will be ignored
run_state['deps'] = meta.get('deps', [])
run_state['post_deps'] = meta.get('post_deps', [])
run_state['prehook_deps'] = meta.get('prehook_deps', [])
run_state['posthook_deps'] = meta.get('posthook_deps', [])
deps = run_state['deps']
post_deps = run_state['post_deps']
prehook_deps = run_state['prehook_deps']
posthook_deps = run_state['posthook_deps']
r = self._update_state_from_version(meta, run_state, i)
if r['return'] > 0:
return r
version = r['version']
version_min = r['version_min']
version_max = r['version_max']
version_max_usable = r['version_max_usable']
versions = r['versions']
# STEP 800: Process variations and update env (overwrite from env and update form default_env)
# VARIATIONS HAS THE PRIORITY OVER
# MULTIPLE VARIATIONS (THAT CAN BE TURNED ON AT THE SAME TIME) SHOULD
# NOT HAVE CONFLICTING ENV
# VARIATIONS OVERWRITE current ENV but not input keys (they become
# const)
variations = script_item.meta.get('variations', {})
if version and f"version.{version}" not in variation_tags and (
f"version.{version}" in variations or "version.#" in variations):
logger.debug(
f"version.{version} added as a variation tag from input version")
variation_tags.append(f"version.{version}")
run_state['docker'] = meta.get('docker', {})
r = self._update_state_from_variations(
i,
meta,
variation_tags,
variations,
run_state
)
if r['return'] > 0:
return r
warnings = meta.get('warnings', [])
if len(r.get('warnings', [])) > 0:
warnings += r['warnings']
variation_tags_string = r['variation_tags_string']
explicit_variation_tags = r['explicit_variation_tags']
# STEP 1100: Update deps from input -? is this needed as we update adr
# from meta anyway
r = update_deps_from_input(
deps, post_deps, prehook_deps, posthook_deps, i)
if r['return'] > 0:
return r
r = update_env_with_values(env)
if r['return'] > 0:
return r
if is_true(env.get('MLC_RUN_STATE_DOCKER', False)):
if run_state.get('docker'):
if is_false(run_state['docker'].get('run', True)):
logger.info(
self.recursion_spaces +
' - Skipping script::{} run as we are inside docker'.format(found_script_item))
# restore env and state
for k in list(env.keys()):
del (env[k])
for k in list(state.keys()):
del (state[k])
env.update(saved_env)
state.update(saved_state)
rr = {
'return': 0,
'env': env,
'new_env': {},
'state': state,
'new_state': {},
'deps': []}
return rr
elif is_false(run_state['docker'].get('real_run', True)):
logger.info(
self.recursion_spaces +
' - Doing fake run for script::{} as we are inside docker'.format(found_script_item))
fake_run = True
env['MLC_TMP_FAKE_RUN'] = 'yes'
#######################################################################
# Check extra cache tags
x = env.get('MLC_EXTRA_CACHE_TAGS', '').strip()
extra_cache_tags = [] if x == '' else x.split(',')
if i.get('extra_cache_tags', '') != '':
for x in i['extra_cache_tags'].strip().split(','):
if x != '':
if '<<<' in x:
import re
tmp_values = re.findall(r'<<<(.*?)>>>', str(x))
for tmp_value in tmp_values:
xx = str(env.get(tmp_value, ''))
x = x.replace("<<<" + tmp_value + ">>>", xx)
if x not in extra_cache_tags:
extra_cache_tags.append(x)
if env.get('MLC_NAME', '') != '':
extra_cache_tags.append('name-' + env['MLC_NAME'].strip().lower())
#######################################################################
# Check if need to clean output files
clean_output_files = meta.get('clean_output_files', [])
if len(clean_output_files) > 0:
clean_tmp_files(clean_output_files, self.recursion_spaces)
#######################################################################
# Check if the output of a selected script should be cached
cache = False if i.get(
'skip_cache',
False) else run_state.get(
'cache',
False)
cache = cache or (
i.get(
'force_cache',
False) and meta.get(
'can_force_cache',
False))
# fake run skips run script - should not pollute cache
cache = False if fake_run else cache
cached_uid = ''
cached_tags = []
cached_meta = {}
remove_tmp_tag = False
reuse_cached = False
found_cached = False
cached_path = ''
local_env_keys_from_meta = meta.get('local_env_keys', [])
# For allowing python files in one script to be called from another
if path not in sys.path:
sys.path.insert(0, path)
# Check if has customize.py
path_to_customize_py = os.path.join(path, 'customize.py')
customize_code = None
customize_common_input = {}
if os.path.isfile(path_to_customize_py) and cache:
customize_code = load_customize_with_deps(path_to_customize_py)
customize_common_input = {
'input': i,
'automation': self,
'artifact': script_item,
'customize': script_item.meta.get('customize', {}),
'os_info': os_info,
'recursion_spaces': self.recursion_spaces,
'script_tags': script_tags,
'variation_tags': variation_tags
}
#######################################################################
# Check if script is cached if we need to skip deps from cached entries
this_script_cached = False
#######################################################################
# Check if the output of a selected script should be cached
if cache:
# Checking if any of the found entry in cache_list has
# matching_tags and is a valid cache_entry
r = find_cached_script({'self': self,
'cache_list': cache_list,
'extra_recursion_spaces': extra_recursion_spaces,
'add_deps_recursive': add_deps_recursive,
'script_tags': script_tags,
'found_script_tags': found_script_tags,
'found_script_path': path,
'customize_code': customize_code,
'customize_common_input': customize_common_input,
'variation_tags': variation_tags,
'variation_tags_string': variation_tags_string,
'explicit_variation_tags': explicit_variation_tags,
'version': version,
'version_min': version_min,
'version_max': version_max,
'extra_cache_tags': extra_cache_tags,
'new_cache_entry': new_cache_entry,
'meta': meta,
'env': env,
'state': state,
'const': const,
'const_state': const_state,
'recursion_spaces': self.recursion_spaces,
'skip_remembered_selections': skip_remembered_selections,
'remembered_selections': self.remembered_selections,
'quiet': quiet,
'show_time': show_time,
'logger': self.action_object.logger,
'run_state': self.init_run_state({})
})
if r['return'] > 0:
return r
# Sort by tags to ensure determinism in order (and later add
# versions)
found_cached_scripts = sorted(
r['found_cached_scripts'],
key=lambda x: sorted(
x.meta['tags']))
cached_tags = r['cached_tags']
search_tags = r['search_tags']
num_found_cached_scripts = len(found_cached_scripts)
if num_found_cached_scripts > 0:
selection = 0
# Check if quiet mode
if num_found_cached_scripts > 1:
if quiet:
num_found_cached_scripts = 1
if num_found_cached_scripts > 1:
selection = select_script_item(
found_cached_scripts,
'cached script output',
self.recursion_spaces,
True,
",".join(script_tags),
quiet,
logger)
if selection >= 0:
if not skip_remembered_selections:
# Remember selection
self.remembered_selections.append({'type': 'cache',
'tags': search_tags,
'cached_script': found_cached_scripts[selection]})
else:
num_found_cached_scripts = 0
elif num_found_cached_scripts == 1:
logger.debug(
self.recursion_spaces +
' - Found cached script output: {}'.format(
found_cached_scripts[0].path))
if num_found_cached_scripts > 0:
found_cached = True
# Check chain of dynamic dependencies on other MLC scripts
if len(deps) > 0:
logger.debug(
self.recursion_spaces +
' - Checking dynamic dependencies on other MLC scripts:')
r = self._call_run_deps(deps, self.local_env_keys, local_env_keys_from_meta,
self.recursion_spaces + extra_recursion_spaces,
variation_tags_string, True, debug_script_tags, show_time, extra_recursion_spaces, run_state)
if r['return'] > 0:
return r
logger.debug(
self.recursion_spaces +
' - Processing env after dependencies ...')