-
Notifications
You must be signed in to change notification settings - Fork 240
/
base.py
2087 lines (1876 loc) · 78.7 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 getpass
import os
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
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
from ..datastore import store_manager
from ..db import RunDBError, get_or_set_dburl, get_run_db
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,
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 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)
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
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 _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 "MLRUN_AUTH_SESSION" in os.environ or "V3IO_ACCESS_KEY" in os.environ:
self.metadata.credentials.access_key = os.environ.get(
"MLRUN_AUTH_SESSION"
) or os.environ.get("V3IO_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,
) -> 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 (dict of key: path)
: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/v3.6.3/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
: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)}')
# Perform auto-mount if necessary - make sure it only runs on client side (when using remote API)
if self._use_remote_api():
self.try_auto_mount_based_on_config()
self.fill_credentials()
if local:
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,
)
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)
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
if "::" in short_name:
short_name = short_name.split("::")[1] # drop class name
def_name += "-" + short_name
runspec.metadata.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
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.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.output_path = out_path or artifact_path or runspec.spec.output_path
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 = runspec.spec.output_path or 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
)
if is_local(runspec.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, use .deploy() method first"
)
if self.verbose:
logger.info(f"runspec:\n{runspec.to_yaml()}")
if "V3IO_USERNAME" in environ and "v3io_user" not in meta.labels:
meta.labels["v3io_user"] = environ.get("V3IO_USERNAME")
if not self.is_child:
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)
# execute the job remotely (to a k8s cluster via the API service)
if self._use_remote_api():
if self._secrets:
runspec.spec.secret_sources = self._secrets.to_serial()
try:
resp = db.submit_job(runspec, schedule=schedule)
if schedule:
logger.info(f"task scheduled, {resp}")
return
if resp:
txt = get_in(resp, "status.status_text")
if txt:
logger.info(txt)
if watch or self.kfp:
runspec.logs(True, self._get_db())
resp = self._get_db_run(runspec)
except Exception as err:
logger.error(f"got remote run err, {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=runspec, err=err)
return self._wrap_run_result(
result, runspec, schedule=schedule, err=err
)
return self._wrap_run_result(resp, runspec, schedule=schedule)
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(
runspec.to_dict(), db, autocommit=False, is_api=self._is_api_server
)
self._pre_run(runspec, execution) # hook for runtime specific prep
# create task generator (for child runs) from spec
task_generator = None
if not self._is_nested:
task_generator = get_generator(spec, execution)
last_err = None
if task_generator:
# 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, runspec)
results_to_iter(results, runspec, execution)
result = execution.to_dict()
else:
# single run
try:
resp = self._run(runspec, execution)
if watch and self.kind not in ["", "handler", "local"]:
state = runspec.logs(True, self._get_db())
if state != "succeeded":
logger.warning(f"run ended with state {state}")
result = self._update_run_state(resp, task=runspec)
except RunError as err:
last_err = err
result = self._update_run_state(task=runspec, err=err)
self._post_run(result, execution) # hook for runtime specific cleanup
return self._wrap_run_result(result, runspec, 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:
ui_url = get_ui_url(project, uid)
ui_url = f"\nor click {ui_url} for UI" if ui_url else ""
project_flag = f"-p {project}" if project else ""
print(
f"to track results use the CLI:\n"
f"info: mlrun get run {uid} {project_flag}\nlogs: mlrun logs {uid} {project_flag}{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:
print(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 _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 command:
args += [command]
command = "mlrun"
if self.spec.args:
args = args + self.spec.args
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"
task.status.error = str(err)
resp = self._update_run_state(task=task, err=err)
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", "")
if last_state == "error" or err:
updates = {"status.last_update": now_date().isoformat()}
updates["status.state"] = "error"
update_in(resp, "status.state", "error")
if err:
update_in(resp, "status.error", str(err))
err = get_in(resp, "status.error")
if err:
updates["status.error"] = str(err)
elif not was_none and last_state != "completed":
updates = {"status.last_update": now_date().isoformat()}
updates["status.state"] = "completed"
update_in(resp, "status.state", "completed")
if self._get_db() and updates:
project = get_in(resp, "metadata.project")
uid = get_in(resp, "metadata.uid")
iter = get_in(resp, "metadata.iteration", 0)
self._get_db().update_run(updates, uid, project, iter=iter)
return resp
def _force_handler(self, handler):
if not handler:
raise RunError(f"handler must be provided for {self.kind} runtime")
def full_image_path(self, image=None, client_version: str = None):
image = image or self.spec.image or ""
image = enrich_image_url(image, client_version)
if not image.startswith("."):
return image
registry, _ = get_parsed_docker_registry()
if registry:
return f"{registry}/{image[1:]}"
namespace_domain = environ.get("IGZ_NAMESPACE_DOMAIN", None)
if namespace_domain is not None:
return f"docker-registry.{namespace_domain}:80/{image[1:]}"
raise RunError("local container registry is not defined")
def as_step(
self,
runspec: RunObject = None,
handler=None,
name: str = "",
project: str = "",
params: dict = None,
hyperparams=None,
selector="",
hyper_param_options: HyperParamOptions = None,
inputs: dict = None,
outputs: dict = None,
workdir: str = "",
artifact_path: str = "",
image: str = "",
labels: dict = None,
use_db=True,
verbose=None,
scrape_metrics=False,
):
"""Run a local or remote task.
:param runspec: run template object or dict (see RunTemplate)
:param handler: name of the function handler
:param name: execution name
:param project: project name
:param params: input parameters (dict)
:param hyperparams: hyper parameters
:param selector: selection criteria for hyper params
:param hyper_param_options: hyper param options (selector, early stop, strategy, ..)
see: :py:class:`~mlrun.model.HyperParamOptions`
:param inputs: input objects (dict of key: path)
:param outputs: list of outputs which can pass in the workflow
:param artifact_path: default artifact output path (replace out_path)
:param workdir: default input artifacts path
:param image: container image to use
:param labels: labels to tag the job/run with ({key:val, ..})
:param use_db: save function spec in the db (vs the workflow file)
:param verbose: add verbose prints/logs
:param scrape_metrics: whether to add the `mlrun/scrape-metrics` label to this run's resources
:return: KubeFlow containerOp
"""
# if self.spec.image and not image:
# image = self.full_image_path()
if use_db:
# if the same function is built as part of the pipeline we do not use the versioned function
# rather the latest function w the same tag so we can pick up the updated image/status
versioned = False if hasattr(self, "_build_in_pipeline") else True
url = self.save(versioned=versioned, refresh=True)
else:
url = None
if runspec is not None:
verify_field_regex(
"run.metadata.name", runspec.metadata.name, mlrun.utils.regex.run_name
)
return mlrun_op(
name,
project,
function=self,
func_url=url,
runobj=runspec,
handler=handler,
params=params,
hyperparams=hyperparams,
selector=selector,
hyper_param_options=hyper_param_options,
inputs=inputs,
outputs=outputs,
job_image=image,
labels=labels,
out_path=artifact_path,
in_path=workdir,
verbose=verbose,
scrape_metrics=scrape_metrics,
)
def with_code(self, from_file="", body=None, with_doc=True):
"""Update the function code
This function eliminates the need to build container images every time we edit the code
:param from_file: blank for current notebook, or path to .py/.ipynb file
:param body: will use the body as the function code
:param with_doc: update the document of the function parameters
:return: function object
"""
if body and from_file:
raise mlrun.errors.MLRunInvalidArgumentError(
"must provide either body or from_file argument. not both"
)
if (not body and not from_file) or (from_file and from_file.endswith(".ipynb")):
from nuclio import build_file
_, _, body = build_file(from_file, name=self.metadata.name)
else:
if from_file:
with open(from_file) as fp:
body = fp.read()
if self.kind == mlrun.runtimes.RuntimeKinds.serving:
body = body + mlrun_footer.format(
mlrun.runtimes.serving.serving_subkind
)
self.spec.build.functionSourceCode = b64encode(body.encode("utf-8")).decode(
"utf-8"
)
if with_doc:
update_function_entry_points(self, body)
return self
def with_requirements(self, requirements: Union[str, List[str]]):
"""add package requirements from file or list to build spec.
:param requirements: python requirements file path or list of packages
:return: function object
"""
if isinstance(requirements, str):
with open(requirements, "r") as fp:
requirements = fp.read().splitlines()
commands = self.spec.build.commands or []
new_command = "python -m pip install " + " ".join(requirements)
# make sure we dont append the same line twice
if new_command not in commands:
commands.append(new_command)
self.spec.build.commands = commands
self.verify_base_image()
return self
def verify_base_image(self):
build = self.spec.build
require_build = build.commands or (
build.source and not build.load_source_on_run
)
if (
self.kind not in mlrun.runtimes.RuntimeKinds.nuclio_runtimes()
and require_build
and self.spec.image
and not self.spec.build.base_image
):
# when the function require build use the image as the base_image for the build
self.spec.build.base_image = self.spec.image
self.spec.image = ""
def export(self, target="", format=".yaml", secrets=None, strip=True):
"""save function spec to a local/remote path (default to./function.yaml)
:param target: target path/url
:param format: `.yaml` (default) or `.json`
:param secrets: optional secrets dict/object for target path (e.g. s3)
:param strip: strip status data
:returns: self
"""
if self.kind == "handler":
raise ValueError(
"cannot export local handler function, use "
+ "code_to_function() to serialize your function"
)
calc_hash(self)
struct = self.to_dict(strip=strip)
if format == ".yaml":
data = dict_to_yaml(struct)
else:
data = dict_to_json(struct)
stores = store_manager.set(secrets)
target = target or "function.yaml"
datastore, subpath = stores.get_or_create_store(target)
datastore.put(subpath, data)
logger.info(f"function spec saved to path: {target}")
return self
def save(self, tag="", versioned=False, refresh=False) -> str:
db = self._get_db()
if not db:
logger.error("database connection is not configured")
return ""
if refresh and self._is_remote_api():
try:
meta = self.metadata
db_func = db.get_function(meta.name, meta.project, meta.tag)
if db_func and "status" in db_func:
self.status = db_func["status"]
if (
self.status.state
and self.status.state == "ready"
and not hasattr(self.status, "nuclio_name")
):
self.spec.image = get_in(db_func, "spec.image", self.spec.image)
except mlrun.errors.MLRunNotFoundError:
pass
tag = tag or self.metadata.tag
obj = self.to_dict()
logger.debug(f"saving function: {self.metadata.name}, tag: {tag}")
hash_key = db.store_function(
obj, self.metadata.name, self.metadata.project, tag, versioned
)
hash_key = hash_key if versioned else None
return "db://" + self._function_uri(hash_key=hash_key, tag=tag)
def to_dict(self, fields=None, exclude=None, strip=False):
struct = super().to_dict(fields, exclude=exclude)
if strip:
if "status" in struct:
del struct["status"]
return struct
def doc(self):
print("function:", self.metadata.name)
print(self.spec.description)
if self.spec.default_handler:
print("default handler:", self.spec.default_handler)
if self.spec.entry_points:
print("entry points:")
for name, entry in self.spec.entry_points.items():
print(f" {name}: {entry.get('doc', '')}")
params = entry.get("parameters")