-
Notifications
You must be signed in to change notification settings - Fork 239
/
base.py
2570 lines (2317 loc) · 100 KB
/
base.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2018 Iguazio
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import enum
import getpass
import http
import traceback
import typing
import uuid
from abc import ABC, abstractmethod
from ast import literal_eval
from base64 import b64encode
from copy import deepcopy
from datetime import datetime, timedelta, timezone
from os import environ
from typing import Dict, List, Optional, Tuple, Union
import IPython
import requests.exceptions
from kubernetes.client.rest import ApiException
from nuclio.build import mlrun_footer
from sqlalchemy.orm import Session
import mlrun.errors
import mlrun.utils.helpers
import mlrun.utils.regex
from mlrun.api import schemas
from mlrun.api.constants import LogSources
from mlrun.api.db.base import DBInterface
from mlrun.utils.helpers import generate_object_uri, verify_field_regex
from ..config import config, is_running_as_api
from ..datastore import store_manager
from ..db import RunDBError, get_or_set_dburl, get_run_db
from ..errors import err_to_str
from ..execution import MLClientCtx
from ..k8s_utils import get_k8s_helper
from ..kfpops import mlrun_op, write_kfpmeta
from ..lists import RunList
from ..model import (
BaseMetadata,
HyperParamOptions,
ImageBuilder,
ModelObj,
RunObject,
RunTemplate,
)
from ..secrets import SecretsStore
from ..utils import (
dict_to_json,
dict_to_yaml,
enrich_image_url,
get_in,
get_parsed_docker_registry,
get_ui_url,
is_ipython,
logger,
normalize_name,
now_date,
update_in,
)
from .constants import PodPhases, RunStates
from .funcdoc import update_function_entry_points
from .generators import get_generator
from .utils import RunError, calc_hash, results_to_iter
run_modes = ["pass"]
spec_fields = [
"command",
"args",
"image",
"mode",
"build",
"entry_points",
"description",
"workdir",
"default_handler",
"pythonpath",
"disable_auto_mount",
"allow_empty_resources",
]
class RuntimeClassMode(enum.Enum):
"""
Runtime class mode
Currently there are two modes:
1. run - the runtime class is used to run a function
2. build - the runtime class is used to build a function
The runtime class mode is used to determine what should be the name of the runtime class, each runtime might have a
different name for each mode and some might not have both modes.
"""
run = "run"
build = "build"
class FunctionStatus(ModelObj):
def __init__(self, state=None, build_pod=None):
self.state = state
self.build_pod = build_pod
class FunctionSpec(ModelObj):
_dict_fields = spec_fields
def __init__(
self,
command=None,
args=None,
image=None,
mode=None,
build=None,
entry_points=None,
description=None,
workdir=None,
default_handler=None,
pythonpath=None,
disable_auto_mount=False,
):
self.command = command or ""
self.image = image or ""
self.mode = mode
self.args = args or []
self.rundb = None
self.description = description or ""
self.workdir = workdir
self.pythonpath = pythonpath
self._build = None
self.build = build
self.default_handler = default_handler
# TODO: type verification (FunctionEntrypoint dict)
self.entry_points = entry_points or {}
self.disable_auto_mount = disable_auto_mount
self.allow_empty_resources = None
@property
def build(self) -> ImageBuilder:
return self._build
@build.setter
def build(self, build):
self._build = self._verify_dict(build, "build", ImageBuilder)
def enrich_function_preemption_spec(self):
pass
def validate_service_account(self, allowed_service_accounts):
pass
class BaseRuntime(ModelObj):
kind = "base"
_is_nested = False
_is_remote = False
_dict_fields = ["kind", "metadata", "spec", "status", "verbose"]
def __init__(self, metadata=None, spec=None):
self._metadata = None
self.metadata = metadata
self.kfp = None
self._spec = None
self.spec = spec
self._db_conn = None
self._secrets = None
self._k8s = None
self._is_built = False
self.is_child = False
self._status = None
self.status = None
self._is_api_server = False
self.verbose = False
self._enriched_image = False
def set_db_connection(self, conn, is_api=False):
if not self._db_conn:
self._db_conn = conn
self._is_api_server = is_api
@property
def metadata(self) -> BaseMetadata:
return self._metadata
@metadata.setter
def metadata(self, metadata):
self._metadata = self._verify_dict(metadata, "metadata", BaseMetadata)
@property
def spec(self) -> FunctionSpec:
return self._spec
@spec.setter
def spec(self, spec):
self._spec = self._verify_dict(spec, "spec", FunctionSpec)
@property
def status(self) -> FunctionStatus:
return self._status
@status.setter
def status(self, status):
self._status = self._verify_dict(status, "status", FunctionStatus)
def _get_k8s(self):
return get_k8s_helper()
def set_label(self, key, value):
self.metadata.labels[key] = str(value)
return self
@property
def uri(self):
return self._function_uri()
def is_deployed(self):
return True
def _is_remote_api(self):
db = self._get_db()
if db and db.kind == "http":
return True
return False
def _use_remote_api(self):
if (
self._is_remote
and not self._is_api_server
and self._get_db()
and self._get_db().kind == "http"
):
return True
return False
def _enrich_on_client_side(self):
self.try_auto_mount_based_on_config()
self._fill_credentials()
def _enrich_on_server_side(self):
pass
def _enrich_on_server_and_client_sides(self):
"""
enrich function also in client side and also on server side
"""
pass
def _enrich_function(self):
"""
enriches the function based on the flow state we run in (sdk or server)
"""
if self._use_remote_api():
self._enrich_on_client_side()
else:
self._enrich_on_server_side()
self._enrich_on_server_and_client_sides()
def _function_uri(self, tag=None, hash_key=None):
return generate_object_uri(
self.metadata.project,
self.metadata.name,
tag=tag or self.metadata.tag,
hash_key=hash_key,
)
def _ensure_run_db(self):
self.spec.rundb = self.spec.rundb or get_or_set_dburl()
def _get_db(self):
self._ensure_run_db()
if not self._db_conn:
if self.spec.rundb:
self._db_conn = get_run_db(self.spec.rundb, secrets=self._secrets)
return self._db_conn
# This function is different than the auto_mount function, as it mounts to runtimes based on the configuration.
# That's why it's named differently.
def try_auto_mount_based_on_config(self):
pass
def validate_and_enrich_service_account(
self, allowed_service_account, default_service_account
):
pass
def _fill_credentials(self):
"""
If access key is not mask (starts with secret prefix) then fill $generate so that the API will handle filling
of the credentials.
We rely on the HTTPDB to send the access key session through the request header and that the API will mask
the access key, that way we won't even store any plain access key in the function.
"""
if self.metadata.credentials.access_key and (
# if contains secret reference or $generate then no need to overwrite the access key
self.metadata.credentials.access_key.startswith(
mlrun.model.Credentials.secret_reference_prefix
)
or self.metadata.credentials.access_key.startswith(
mlrun.model.Credentials.generate_access_key
)
):
return
self.metadata.credentials.access_key = (
mlrun.model.Credentials.generate_access_key
)
def run(
self,
runspec: RunObject = None,
handler=None,
name: str = "",
project: str = "",
params: dict = None,
inputs: Dict[str, str] = None,
out_path: str = "",
workdir: str = "",
artifact_path: str = "",
watch: bool = True,
schedule: Union[str, schemas.ScheduleCronTrigger] = None,
hyperparams: Dict[str, list] = None,
hyper_param_options: HyperParamOptions = None,
verbose=None,
scrape_metrics: bool = None,
local=False,
local_code_path=None,
auto_build=None,
param_file_secrets: Dict[str, str] = None,
returns: Optional[List[Union[str, Dict[str, str]]]] = None,
) -> RunObject:
"""
Run a local or remote task.
:param runspec: run template object or dict (see RunTemplate)
:param handler: pointer or name of a function handler
:param name: execution name
:param project: project name
:param params: input parameters (dict)
:param inputs: Input objects to pass to the handler. Type hints can be given so the input will be parsed
during runtime from `mlrun.DataItem` to the given type hint. The type hint can be given
in the key field of the dictionary after a colon, e.g: "<key> : <type_hint>".
:param out_path: default artifact output path
:param artifact_path: default artifact output path (will replace out_path)
:param workdir: default input artifacts path
:param watch: watch/follow run log
:param schedule: ScheduleCronTrigger class instance or a standard crontab expression string
(which will be converted to the class using its `from_crontab` constructor),
see this link for help:
https://apscheduler.readthedocs.io/en/3.x/modules/triggers/cron.html#module-apscheduler.triggers.cron
:param hyperparams: dict of param name and list of values to be enumerated e.g. {"p1": [1,2,3]}
the default strategy is grid search, can specify strategy (grid, list, random)
and other options in the hyper_param_options parameter
:param hyper_param_options: dict or :py:class:`~mlrun.model.HyperParamOptions` struct of
hyper parameter options
:param verbose: add verbose prints/logs
:param scrape_metrics: whether to add the `mlrun/scrape-metrics` label to this run's resources
:param local: run the function locally vs on the runtime/cluster
:param local_code_path: path of the code for local runs & debug
:param auto_build: when set to True and the function require build it will be built on the first
function run, use only if you dont plan on changing the build config between runs
:param param_file_secrets: dictionary of secrets to be used only for accessing the hyper-param parameter file.
These secrets are only used locally and will not be stored anywhere
:param returns: List of log hints - configurations for how to log the returning values from the handler's run
(as artifacts or results). The list's length must be equal to the amount of returning objects. A
log hint may be given as:
* A string of the key to use to log the returning value as result or as an artifact. To specify
The artifact type, it is possible to pass a string in the following structure:
"<key> : <type>". Available artifact types can be seen in `mlrun.ArtifactType`. If no
artifact type is specified, the object's default artifact type will be used.
* A dictionary of configurations to use when logging. Further info per object type and artifact
type can be given there. The artifact key must appear in the dictionary as "key": "the_key".
:return: run context object (RunObject) with run metadata, results and status
"""
mlrun.utils.helpers.verify_dict_items_type("Inputs", inputs, [str], [str])
if self.spec.mode and self.spec.mode not in run_modes:
raise ValueError(f'run mode can only be {",".join(run_modes)}')
self._enrich_function()
run = self._create_run_object(runspec)
if local:
return self._run_local(
run,
schedule,
local_code_path,
project,
name,
workdir,
handler,
params,
inputs,
returns,
artifact_path,
)
run = self._enrich_run(
run,
handler,
project,
name,
params,
inputs,
returns,
hyperparams,
hyper_param_options,
verbose,
scrape_metrics,
out_path,
artifact_path,
workdir,
)
if is_local(run.spec.output_path):
logger.warning(
"artifact path is not defined or is local,"
" artifacts will not be visible in the UI"
)
if self.kind not in ["", "local", "handler", "dask"]:
raise ValueError(
"absolute artifact_path must be specified"
" when running remote tasks"
)
db = self._get_db()
if not self.is_deployed():
if self.spec.build.auto_build or auto_build:
logger.info(
"Function is not deployed and auto_build flag is set, starting deploy..."
)
self.deploy(skip_deployed=True, show_on_failure=True)
else:
raise RunError(
"function image is not built/ready, set auto_build=True or use .deploy() method first"
)
if self.verbose:
logger.info(f"runspec:\n{run.to_yaml()}")
if "V3IO_USERNAME" in environ and "v3io_user" not in run.metadata.labels:
run.metadata.labels["v3io_user"] = environ.get("V3IO_USERNAME")
if not self.is_child:
self._store_function(run, run.metadata, db)
# execute the job remotely (to a k8s cluster via the API service)
if self._use_remote_api():
return self._submit_job(run, schedule, db, watch)
elif self._is_remote and not self._is_api_server and not self.kfp:
logger.warning(
"warning!, Api url not set, " "trying to exec remote runtime locally"
)
execution = MLClientCtx.from_dict(
run.to_dict(),
db,
autocommit=False,
is_api=self._is_api_server,
store_run=False,
)
self._verify_run_params(run.spec.parameters)
# create task generator (for child runs) from spec
task_generator = get_generator(
run.spec, execution, param_file_secrets=param_file_secrets
)
if task_generator:
# verify valid task parameters
tasks = task_generator.generate(run)
for task in tasks:
self._verify_run_params(task.spec.parameters)
# post verifications, store execution in db and run pre run hooks
execution.store_run()
self._pre_run(run, execution) # hook for runtime specific prep
last_err = None
# If the runtime is nested, it means the hyper-run will run within a single instance of the run.
# So while in the API, we consider the hyper-run as a single run, and then in the runtime itself when the
# runtime is now a local runtime and therefore `self._is_nested == False`, we run each task as a separate run by
# using the task generator
if task_generator and not self._is_nested:
# multiple runs (based on hyper params or params file)
runner = self._run_many
if hasattr(self, "_parallel_run_many") and task_generator.use_parallel():
runner = self._parallel_run_many
results = runner(task_generator, execution, run)
results_to_iter(results, run, execution)
result = execution.to_dict()
result = self._update_run_state(result, task=run)
else:
# single run
try:
resp = self._run(run, execution)
if watch and mlrun.runtimes.RuntimeKinds.is_watchable(self.kind):
state, _ = run.logs(True, self._get_db())
if state not in ["succeeded", "completed"]:
logger.warning(f"run ended with state {state}")
result = self._update_run_state(resp, task=run)
except RunError as err:
last_err = err
result = self._update_run_state(task=run, err=err)
self._post_run(result, execution) # hook for runtime specific cleanup
return self._wrap_run_result(result, run, schedule=schedule, err=last_err)
def _wrap_run_result(
self, result: dict, runspec: RunObject, schedule=None, err=None
):
# if the purpose was to schedule (and not to run) nothing to wrap
if schedule:
return
if result and self.kfp and err is None:
write_kfpmeta(result)
# show ipython/jupyter result table widget
results_tbl = RunList()
if result:
results_tbl.append(result)
else:
logger.info("no returned result (job may still be in progress)")
results_tbl.append(runspec.to_dict())
uid = runspec.metadata.uid
project = runspec.metadata.project
if is_ipython and config.ipython_widget:
results_tbl.show()
print()
ui_url = get_ui_url(project, uid)
if ui_url:
ui_url = f' or <a href="{ui_url}" target="_blank">click here</a> to open in UI'
IPython.display.display(
IPython.display.HTML(
f"<b> > to track results use the .show() or .logs() methods {ui_url}</b>"
)
)
elif not (self.is_child and is_running_as_api()):
project_flag = f"-p {project}" if project else ""
info_cmd = f"mlrun get run {uid} {project_flag}"
logs_cmd = f"mlrun logs {uid} {project_flag}"
logger.info(
"To track results use the CLI", info_cmd=info_cmd, logs_cmd=logs_cmd
)
ui_url = get_ui_url(project, uid)
if ui_url:
logger.info("Or click for UI", ui_url=ui_url)
if result:
run = RunObject.from_dict(result)
logger.info(f"run executed, status={run.status.state}")
if run.status.state == "error":
if self._is_remote and not self.is_child:
logger.error(f"runtime error: {run.status.error}")
raise RunError(run.status.error)
return run
return None
def _get_db_run(self, task: RunObject = None):
if self._get_db() and task:
project = task.metadata.project
uid = task.metadata.uid
iter = task.metadata.iteration
try:
return self._get_db().read_run(uid, project, iter=iter)
except RunDBError:
return None
if task:
return task.to_dict()
def _generate_runtime_env(self, runobj: RunObject):
runtime_env = {
"MLRUN_EXEC_CONFIG": runobj.to_json(),
"MLRUN_DEFAULT_PROJECT": runobj.metadata.project
or self.metadata.project
or config.default_project,
}
if runobj.spec.verbose:
runtime_env["MLRUN_LOG_LEVEL"] = "DEBUG"
if config.httpdb.api_url:
runtime_env["MLRUN_DBPATH"] = config.httpdb.api_url
if self.metadata.namespace or config.namespace:
runtime_env["MLRUN_NAMESPACE"] = self.metadata.namespace or config.namespace
return runtime_env
def _run_local(
self,
runspec,
schedule,
local_code_path,
project,
name,
workdir,
handler,
params,
inputs,
returns,
artifact_path,
):
if schedule is not None:
raise mlrun.errors.MLRunInvalidArgumentError(
"local and schedule cannot be used together"
)
# allow local run simulation with a flip of a flag
command = self
if local_code_path:
project = project or self.metadata.project
name = name or self.metadata.name
command = local_code_path
return mlrun.run_local(
runspec,
command,
name,
self.spec.args,
workdir=workdir,
project=project,
handler=handler,
params=params,
inputs=inputs,
artifact_path=artifact_path,
mode=self.spec.mode,
allow_empty_resources=self.spec.allow_empty_resources,
returns=returns,
)
def _create_run_object(self, runspec):
# TODO: Once implemented the `Runtime` handlers configurations (doc strings, params type hints and returning
# log hints, possible parameter values, etc), the configured type hints and log hints should be set into
# the `RunObject` from the `Runtime`.
if runspec:
runspec = deepcopy(runspec)
if isinstance(runspec, str):
runspec = literal_eval(runspec)
if not isinstance(runspec, (dict, RunTemplate, RunObject)):
raise ValueError(
"task/runspec is not a valid task object," f" type={type(runspec)}"
)
if isinstance(runspec, RunTemplate):
runspec = RunObject.from_template(runspec)
if isinstance(runspec, dict) or runspec is None:
runspec = RunObject.from_dict(runspec)
return runspec
def _enrich_run(
self,
runspec,
handler,
project_name,
name,
params,
inputs,
returns,
hyperparams,
hyper_param_options,
verbose,
scrape_metrics,
out_path,
artifact_path,
workdir,
):
runspec.spec.handler = (
handler or runspec.spec.handler or self.spec.default_handler or ""
)
if runspec.spec.handler and self.kind not in ["handler", "dask"]:
runspec.spec.handler = runspec.spec.handler_name
def_name = self.metadata.name
if runspec.spec.handler_name:
short_name = runspec.spec.handler_name
for separator in ["#", "::", "."]:
# drop paths, module or class name from short name
if separator in short_name:
short_name = short_name.split(separator)[-1]
def_name += "-" + short_name
runspec.metadata.name = normalize_name(
name or runspec.metadata.name or def_name
)
verify_field_regex(
"run.metadata.name", runspec.metadata.name, mlrun.utils.regex.run_name
)
runspec.metadata.project = (
project_name
or runspec.metadata.project
or self.metadata.project
or config.default_project
)
runspec.spec.parameters = params or runspec.spec.parameters
runspec.spec.inputs = inputs or runspec.spec.inputs
runspec.spec.returns = returns or runspec.spec.returns
runspec.spec.hyperparams = hyperparams or runspec.spec.hyperparams
runspec.spec.hyper_param_options = (
hyper_param_options or runspec.spec.hyper_param_options
)
runspec.spec.verbose = verbose or runspec.spec.verbose
if scrape_metrics is None:
if runspec.spec.scrape_metrics is None:
scrape_metrics = config.scrape_metrics
else:
scrape_metrics = runspec.spec.scrape_metrics
runspec.spec.scrape_metrics = scrape_metrics
runspec.spec.input_path = (
workdir or runspec.spec.input_path or self.spec.workdir
)
if self.spec.allow_empty_resources:
runspec.spec.allow_empty_resources = self.spec.allow_empty_resources
spec = runspec.spec
if spec.secret_sources:
self._secrets = SecretsStore.from_list(spec.secret_sources)
# update run metadata (uid, labels) and store in DB
meta = runspec.metadata
meta.uid = meta.uid or uuid.uuid4().hex
runspec.spec.output_path = out_path or artifact_path or runspec.spec.output_path
if not runspec.spec.output_path:
if runspec.metadata.project:
if (
mlrun.pipeline_context.project
and runspec.metadata.project
== mlrun.pipeline_context.project.metadata.name
):
runspec.spec.output_path = (
mlrun.pipeline_context.project.spec.artifact_path
or mlrun.pipeline_context.workflow_artifact_path
)
if not runspec.spec.output_path and self._get_db():
try:
# not passing or loading the DB before the enrichment on purpose, because we want to enrich the
# spec first as get_db() depends on it
project = self._get_db().get_project(runspec.metadata.project)
# this is mainly for tests, so we won't need to mock get_project for so many tests
# in normal use cases if no project is found we will get an error
if project:
runspec.spec.output_path = project.spec.artifact_path
except mlrun.errors.MLRunNotFoundError:
logger.warning(
f"project {project_name} is not saved in DB yet, "
f"enriching output path with default artifact path: {config.artifact_path}"
)
if not runspec.spec.output_path:
runspec.spec.output_path = config.artifact_path
if runspec.spec.output_path:
runspec.spec.output_path = runspec.spec.output_path.replace(
"{{run.uid}}", meta.uid
)
runspec.spec.output_path = mlrun.utils.helpers.fill_artifact_path_template(
runspec.spec.output_path, runspec.metadata.project
)
return runspec
def _submit_job(self, run: RunObject, schedule, db, watch):
if self._secrets:
run.spec.secret_sources = self._secrets.to_serial()
try:
resp = db.submit_job(run, schedule=schedule)
if schedule:
logger.info(f"task scheduled, {resp}")
return
except (requests.HTTPError, Exception) as err:
logger.error(f"got remote run err, {err_to_str(err)}")
if isinstance(err, requests.HTTPError):
self._handle_submit_job_http_error(err)
result = None
# if we got a schedule no reason to do post_run stuff (it purposed to update the run status with error,
# but there's no run in case of schedule)
if not schedule:
result = self._update_run_state(task=run, err=err_to_str(err))
return self._wrap_run_result(result, run, schedule=schedule, err=err)
if resp:
txt = get_in(resp, "status.status_text")
if txt:
logger.info(txt)
# watch is None only in scenario where we run from pipeline step, in this case we don't want to watch the run
# logs too frequently but rather just pull the state of the run from the DB and pull the logs every x seconds
# which ideally greater than the pull state interval, this reduces unnecessary load on the API server, as
# running a pipeline is mostly not an interactive process which means the logs pulling doesn't need to be pulled
# in real time
if (
watch is None
and self.kfp
and config.httpdb.logs.pipelines.pull_state.mode == "enabled"
):
state_interval = int(
config.httpdb.logs.pipelines.pull_state.pull_state_interval
)
logs_interval = int(
config.httpdb.logs.pipelines.pull_state.pull_logs_interval
)
run.wait_for_completion(
show_logs=True,
sleep=state_interval,
logs_interval=logs_interval,
raise_on_failure=False,
)
resp = self._get_db_run(run)
elif watch or self.kfp:
run.logs(True, self._get_db())
resp = self._get_db_run(run)
return self._wrap_run_result(resp, run, schedule=schedule)
@staticmethod
def _handle_submit_job_http_error(error: requests.HTTPError):
# if we receive a 400 status code, this means the request was invalid and the run wasn't created in the DB.
# so we don't need to update the run state and we can just raise the error.
# more status code handling can be added here if needed
if error.response.status_code == http.HTTPStatus.BAD_REQUEST.value:
raise mlrun.errors.MLRunBadRequestError(
f"Bad request to mlrun api: {error.response.text}"
)
def _store_function(self, runspec, meta, db):
db_str = "self" if self._is_api_server else self.spec.rundb
logger.info(f"starting run {meta.name} uid={meta.uid} DB={db_str}")
meta.labels["kind"] = self.kind
if "owner" not in meta.labels:
meta.labels["owner"] = environ.get("V3IO_USERNAME") or getpass.getuser()
if runspec.spec.output_path:
runspec.spec.output_path = runspec.spec.output_path.replace(
"{{run.user}}", meta.labels["owner"]
)
if db and self.kind != "handler":
struct = self.to_dict()
hash_key = db.store_function(
struct, self.metadata.name, self.metadata.project, versioned=True
)
runspec.spec.function = self._function_uri(hash_key=hash_key)
def _get_cmd_args(self, runobj: RunObject):
extra_env = self._generate_runtime_env(runobj)
if self.spec.pythonpath:
extra_env["PYTHONPATH"] = self.spec.pythonpath
args = []
command = self.spec.command
code = (
self.spec.build.functionSourceCode if hasattr(self.spec, "build") else None
)
if runobj.spec.handler and self.spec.mode == "pass":
raise ValueError('cannot use "pass" mode with handler')
if code:
extra_env["MLRUN_EXEC_CODE"] = code
load_archive = self.spec.build.load_source_on_run and self.spec.build.source
need_mlrun = code or load_archive or self.spec.mode != "pass"
if need_mlrun:
args = ["run", "--name", runobj.metadata.name, "--from-env"]
if runobj.spec.handler:
args += ["--handler", runobj.spec.handler]
if self.spec.mode:
args += ["--mode", self.spec.mode]
if self.spec.build.origin_filename:
args += ["--origin-file", self.spec.build.origin_filename]
if load_archive:
if code:
raise ValueError("cannot specify both code and source archive")
args += ["--source", self.spec.build.source]
if self.spec.workdir:
# set the absolute/relative path to the cloned code
args += ["--workdir", self.spec.workdir]
if command:
args += [command]
if self.spec.args:
if not command:
# * is a placeholder for the url argument in the run CLI command,
# where the code is passed in the `MLRUN_EXEC_CODE` meaning there is no "actual" file to execute
# until the run command will create that file from the env param.
args += ["*"]
args = args + self.spec.args
command = "mlrun"
else:
command = command.format(**runobj.spec.parameters)
if self.spec.args:
args = [arg.format(**runobj.spec.parameters) for arg in self.spec.args]
extra_env = [{"name": k, "value": v} for k, v in extra_env.items()]
return command, args, extra_env
def _pre_run(self, runspec: RunObject, execution):
pass
def _post_run(self, results, execution):
pass
def _run(self, runobj: RunObject, execution) -> dict:
pass
def _run_many(self, generator, execution, runobj: RunObject) -> RunList:
results = RunList()
num_errors = 0
tasks = generator.generate(runobj)
for task in tasks:
try:
self.store_run(task)
resp = self._run(task, execution)
resp = self._update_run_state(resp, task=task)
run_results = resp["status"].get("results", {})
if generator.eval_stop_condition(run_results):
logger.info(
f"reached early stop condition ({generator.options.stop_condition}), stopping iterations!"
)
results.append(resp)
break
except RunError as err:
task.status.state = "error"
error_string = err_to_str(err)
task.status.error = error_string
resp = self._update_run_state(task=task, err=error_string)
num_errors += 1
if num_errors > generator.max_errors:
logger.error("too many errors, stopping iterations!")
results.append(resp)
break
results.append(resp)
return results
def store_run(self, runobj: RunObject):
if self._get_db() and runobj:
project = runobj.metadata.project
uid = runobj.metadata.uid
iter = runobj.metadata.iteration
self._get_db().store_run(runobj.to_dict(), uid, project, iter=iter)
def _store_run_dict(self, rundict: dict):
if self._get_db() and rundict:
project = get_in(rundict, "metadata.project", "")
uid = get_in(rundict, "metadata.uid")
iter = get_in(rundict, "metadata.iteration", 0)
self._get_db().store_run(rundict, uid, project, iter=iter)
def _update_run_state(
self,
resp: dict = None,
task: RunObject = None,
err=None,
) -> dict:
"""update the task state in the DB"""
was_none = False
if resp is None and task:
was_none = True
resp = self._get_db_run(task)
if not resp:
self.store_run(task)
return task.to_dict()
if task.status.status_text:
update_in(resp, "status.status_text", task.status.status_text)
if resp is None:
return None
if not isinstance(resp, dict):
raise ValueError(f"post_run called with type {type(resp)}")
updates = None
last_state = get_in(resp, "status.state", "")
kind = get_in(resp, "metadata.labels.kind", "")
if last_state == "error" or err: