-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmlsetup.py
1633 lines (1479 loc) · 52 KB
/
mlsetup.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
#!/usr/bin/python3
import json
import logging
import os
import re
import shutil
import socket
import subprocess
import sys
import urllib.request
from typing import List
import click
import dotenv
logging.basicConfig(level=logging.DEBUG, format="%(levelname)s: %(message)s")
is_dummy_mode = os.environ.get("DUMMY_MODE", "")
default_env_file = "~/.mlrun.env"
scaled_deplyoments = [
"mlrun-api-chief",
"mlrun-db",
"mlrun-jupyter",
"mlrun-ui",
"mpi-operator",
"nuclio-controller",
"nuclio-dashboard",
]
valid_registry_args = [
"kind",
"server",
"username",
"password",
"email",
"url",
"secret",
"push_secret",
]
docker_services = ["jupyter", "milvus", "mysql"]
k8s_services = ["spark", "monitoring", "jupyter", "pipelines"]
service_map = {
"s": "spark-operator",
"m": "kube-prometheus-stack",
"j": "jupyterNotebook",
"p": "pipelines",
}
# auto detect if running inside GitHub Codespaces
is_codespaces = "CODESPACES" in os.environ and "CODESPACE_NAME" in os.environ
class K8sStages:
none = 0
namespace = 1
helm = 2
registry = 3
done = 9
# common options
env_file_opt = click.option(
"--env-file",
"-f",
default="",
help="path to the mlrun .env file (defaults to '~/.mlrun.env')",
)
env_vars_opt = click.option(
"--env-vars",
"-e",
default=[],
multiple=True,
help="additional env vars, e.g. -e AWS_ACCESS_KEY_ID=<key-id>",
)
foreground_opt = click.option(
"--foreground",
is_flag=True,
default=False,
help="run process in the foreground (not as a daemon)",
)
@click.group()
def main():
"""MLRun configuration utility"""
pass
@main.command(context_settings=dict(ignore_unknown_options=True, allow_extra_args=True))
@env_vars_opt
@env_file_opt
@click.option("--tag", help="MLRun version tag")
@click.option("--force-local", is_flag=True, help="force use of local or docker mlrun")
@click.option("--verbose", "-v", is_flag=True, help="verbose log")
@click.option(
"--simulate", is_flag=True, help="simulate install (print commands vs exec)"
)
@click.pass_context
def start(
ctx,
env_vars,
env_file,
tag,
force_local,
verbose,
simulate,
):
"""Start MLRun service, auto detect the best method (local/docker/k8s/remote)"""
extra_args = {}
for i in range(0, len(ctx.args), 2):
if str(ctx.args[i]).startswith("--"):
key = ctx.args[i][2:].replace("-", "_")
value = ctx.args[i + 1]
if key in extra_args.keys():
current_val = extra_args[key]
value = (
current_val + [value]
if isinstance(current_val, list)
else [current_val, value]
)
extra_args[key] = value
config = BaseConfig(env_file, verbose, env_vars_opt=env_vars, simulate=simulate)
current_env_vars = config.get_env()
last_deployment = current_env_vars.get("MLRUN_CONF_LAST_DEPLOYMENT", "")
if not force_local and (
os.environ.get("V3IO_ACCESS_KEY", "") or last_deployment == "remote"
):
dbpath = current_env_vars.get("MLRUN_DBPATH") or os.environ.get(
"MLRUN_DBPATH", ""
)
logging.info(f"detected settings of remote MLRun service at {dbpath}")
return
logging.info(extra_args)
config = K8sConfig.from_config(config)
if config.is_supported():
config.start(tag=tag, **extra_args)
return
config = DockerConfig.from_config(config)
if config.is_supported():
config.start(tag=tag, **extra_args)
return
config = LocalConfig.from_config(config)
config.start(tag=tag, **extra_args)
@main.command()
@env_file_opt
@click.option(
"--deployment", "-d", help="deployment mode: local | docker | kuberenetes"
)
@click.option(
"--cleanup",
"-c",
is_flag=True,
help="delete the specified or default env file",
)
@click.option("--force", "-f", is_flag=True, help="force stop")
@click.option("--verbose", "-v", is_flag=True, help="verbose log")
def stop(env_file, deployment, cleanup, force, verbose):
"""Stop MLRun service which was started using this CLI"""
deployment = deployment or BaseConfig(env_file).get_env().get(
"MLRUN_CONF_LAST_DEPLOYMENT", ""
)
if not deployment:
logging.error(
"cannot determine current deployment type, please specify the -d option"
)
return
config = deployment_modes[deployment](env_file, verbose)
config.stop(force, cleanup)
@main.command()
@env_file_opt
@click.option(
"--deployment", "-d", help="deployment mode: local | docker | kuberenetes"
)
@click.option("--force", "-f", is_flag=True, help="force stop")
@click.option("--verbose", "-v", is_flag=True, help="verbose log")
def uninstall(env_file, deployment, force, verbose):
"""Uninstall and cleanup MLRun service which was started using this CLI"""
deployment = deployment or BaseConfig(env_file).get_env().get(
"MLRUN_CONF_LAST_DEPLOYMENT", ""
)
if not deployment:
logging.error(
"cannot determine current deployment type, please specify the -d option"
)
return
config = deployment_modes[deployment](env_file, verbose)
config.stop(force, True)
@main.command()
@env_file_opt
@click.option(
"--deployment", "-d", help="deployment mode: local | docker | kuberenetes"
)
def pause(env_file, deployment):
"""Scale MLRun deployments to zero
Plese note -
if you want to keep your notebooks between deployments scale save your notebooks in the data folder
"""
deployment = deployment or BaseConfig(env_file).get_env().get(
"MLRUN_CONF_LAST_DEPLOYMENT", ""
)
if not deployment:
print("cannot determine current deployment type, please specify the -d option")
return
config = deployment_modes[deployment](env_file)
config.pause()
@main.command()
@env_file_opt
@click.option(
"--services",
"-s",
default=[],
multiple=True,
help="scale specific services, e.g. -s mlrun-jupyter=0"
f", supported services: {','.join(scaled_deplyoments)}.",
)
@click.option(
"--deployment", "-d", help="deployment mode: local | docker | kuberenetes"
)
def scale(env_file, services, deployment):
"""Scale up MLRun deployments"""
deployment = deployment or BaseConfig(env_file).get_env().get(
"MLRUN_CONF_LAST_DEPLOYMENT", ""
)
if not deployment:
print("cannot determine current deployment type, please specify the -d option")
return
config = deployment_modes[deployment](env_file)
services = _list2dict(services, default_value="1")
config.scale(services)
@main.command()
@click.option(
"--data-volume", "-d", help="host path prefix to the location of db and artifacts"
)
@click.option("--logs-path", "-l", help="logs directory path")
@click.option(
"--artifact-path", "-a", help="default artifact path (if not in the data volume)"
)
@foreground_opt
@click.option("--port", "-p", help="port to listen on", type=int)
@env_vars_opt
@env_file_opt
@click.option("--tag", help="MLRun version tag")
@click.option(
"--conda-env",
help="install and run MLRun API in a the specified conda environment",
type=str,
)
@click.option("--verbose", "-v", is_flag=True, help="verbose log")
def local(
data_volume,
logs_path,
artifact_path,
foreground,
port,
env_vars,
env_file,
tag,
conda_env,
verbose,
):
"""Install MLRun service as a local process (limited, no UI and Nuclio)"""
config = LocalConfig(env_file, verbose, env_vars_opt=env_vars)
config.start(
data_volume,
logs_path,
artifact_path,
foreground,
port,
tag,
conda_env,
)
@main.command()
@click.option(
"--jupyter",
"-j",
is_flag=False,
flag_value=".",
default="",
help="deploy Jupyter container, can provide jupyter image as argument",
)
@click.option(
"--data-volume", "-d", help="host path prefix to the location of db and artifacts"
)
@click.option(
"--volume-mount",
help="container mount path (of the data-volume), when different from host data volume path",
)
@click.option(
"--artifact-path", "-a", help="default artifact path (if not in the data volume)"
)
@foreground_opt
@click.option("--port", "-p", help="MLRun port to listen on", type=int, default="8080")
@env_vars_opt
@env_file_opt
@click.option("--tag", help="MLRun version tag")
@click.option(
"--options",
"-o",
default=[],
multiple=True,
help=f"optional services to enable, supported services: {','.join(docker_services)}",
)
@click.option("--compose-file", help="path to save the generated compose.yaml file")
@click.option("--verbose", "-v", is_flag=True, help="verbose log")
@click.option(
"--simulate", is_flag=True, help="simulate install (print commands vs exec)"
)
def docker(
jupyter,
data_volume,
volume_mount,
artifact_path,
foreground,
port,
env_vars,
env_file,
tag,
options,
compose_file,
verbose,
simulate,
):
"""Deploy mlrun and nuclio services using Docker compose"""
config = DockerConfig(env_file, verbose, env_vars_opt=env_vars, simulate=simulate)
if not config.is_supported(True):
print("use local or remote service options instead")
raise SystemExit(1)
config.start(
jupyter,
data_volume,
volume_mount,
artifact_path,
foreground,
port,
tag,
options,
compose_file,
)
@main.command()
@click.argument("url", type=str, default="", required=True)
@click.option("--username", "-u", help="username (for secure access)")
@click.option("--access-key", "-k", help="access key (for secure access)")
@click.option("--artifact-path", "-p", help="default artifacts path")
@env_file_opt
@env_vars_opt
@click.option("--verbose", "-v", is_flag=True, help="verbose log")
def remote(url, username, access_key, artifact_path, env_file, env_vars, verbose):
"""Connect to remote MLRun service (over Kubernetes)"""
config = RemoteConfig(env_file, verbose, env_vars_opt=env_vars)
config.start(url, username, access_key, artifact_path)
@main.command()
@click.option("--name", "-n", default="mlrun-ce", help="helm deployment name")
@click.option("--namespace", default="mlrun", help="kubernetes namespace")
@click.option(
"--registry-args",
"-r",
default=[],
multiple=True,
help="docker registry args, can be a kind string (local, docker, ..) or a set of key=value args e.g. "
f"-r username=joe -r password=j123 -r [email protected], supported keys: {','.join(valid_registry_args)}",
)
@click.option(
"--options",
"-o",
default=[],
multiple=True,
help=f"optional services to enable, supported services: {','.join(k8s_services)}",
)
@click.option(
"--disable",
"-d",
default=[],
multiple=True,
help=f"optional services to disable, supported services: {','.join(k8s_services)}",
)
@click.option(
"--set",
"-s",
"settings",
default=[],
multiple=True,
help="Additional helm --set commands, accept multiple --set options",
)
@click.option("--external-addr", help="external ip/dns address", type=str)
@click.option("--tag", help="MLRun version tag")
@env_file_opt
@env_vars_opt
@click.option("--verbose", "-v", is_flag=True, help="verbose log")
@click.option(
"--simulate", is_flag=True, help="simulate install (print commands vs exec)"
)
@click.option("--chart-ver", help="MLRun helm chart version")
@click.option("--values-file-path", help="values file path")
@click.option(
"--jupyter",
"-j",
is_flag=False,
flag_value=".",
default="",
help="deploy Jupyter container, can provide jupyter image as argument",
)
def kubernetes(
name,
namespace,
registry_args,
options,
disable,
settings,
external_addr,
tag,
env_file,
env_vars,
verbose,
simulate,
chart_ver,
values_file_path,
jupyter,
):
"""Install MLRun service on Kubernetes"""
config = K8sConfig(env_file, verbose, env_vars_opt=env_vars, simulate=simulate)
if not config.is_supported(True):
print("you can try other mlrun deployment options (local, docker)")
raise SystemExit(1)
config.start(
name,
namespace,
registry_args,
external_addr,
tag,
settings,
options,
disable,
chart_ver,
values_file_path,
jupyter,
)
@main.command()
@click.option("--api", "-a", type=str, help="api service url")
@click.option("--username", "-u", help="username (for secure access)")
@click.option("--access-key", "-k", help="access key (for secure access)")
@click.option("--artifact-path", "-p", help="default artifacts path")
@env_file_opt
@env_vars_opt
def set(api, username, access_key, artifact_path, env_file, env_vars):
"""Set configuration in mlrun default or specified .env file"""
config = BaseConfig(env_file, env_vars_opt=env_vars)
if not os.path.isfile(config.filename):
print(
f".env file {config.filename} not found, creating new and setting configuration"
)
else:
print(f"updating configuration in .env file {config.filename}")
env_dict = {
"MLRUN_DBPATH": api,
"MLRUN_ARTIFACT_PATH": artifact_path,
"V3IO_USERNAME": username,
"V3IO_ACCESS_KEY": access_key,
}
config.set_mlrun_env(env_dict)
@main.command()
@env_file_opt
def get(env_file):
"""Print the local or remote configuration"""
config = BaseConfig(env_file)
if not os.path.isfile(config.filename):
print(f"error, env file {env_file} does not exist")
exit(1)
print(f"Env file {config.filename} content:")
with open(config.filename, "r") as fp:
print(fp.read())
@main.command()
@env_file_opt
def clear(env_file):
"""Delete the default or specified config .env file"""
BaseConfig(env_file).clear_env(True)
@main.command()
def latest():
"""Get the latest MLRun version"""
get_latest_mlrun_tag()
class BaseConfig:
def __init__(self, env_file, verbose=False, env_vars_opt=None, simulate=False):
self.env_file = env_file
self.filename = os.path.expanduser(env_file or default_env_file)
self.verbose = verbose
self.env_vars_opt = env_vars_opt
self.simulate = simulate or is_dummy_mode
self._env_dict = None
@classmethod
def from_config(cls, other_config):
config = cls(
other_config.env_file,
other_config.verbose,
other_config.env_vars_opt,
other_config.simulate,
)
config._env_dict = other_config._env_dict
return config
def get_env(self, refresh=False):
if not self._env_dict or refresh:
self._env_dict = dotenv.dotenv_values(self.filename)
return self._env_dict
def set_env(self, env_vars):
for key, value in env_vars.items():
if value is not None:
dotenv.set_key(self.filename, key, str(value), quote_mode="")
if self.env_vars_opt:
for key, value in _list2dict(self.env_vars_opt).items():
dotenv.set_key(self.filename, key, value, quote_mode="")
if self.env_file:
env_file = self.env_file
# if its not the default file print the usage details
print(
f"to use the {env_file} .env file add MLRUN_ENV_FILE={env_file} to your development environment\n"
f"or call `mlrun.set_env_from_file({env_file}) in the beginning of your code"
)
def clear_env(self, delete_file=None, delete_keys=None):
if os.path.isfile(self.filename):
if delete_file:
print(f"deleting env file {self.filename}")
os.remove(self.filename)
else:
for key in [
"MLRUN_DBPATH",
"MLRUN_CONF_LAST_DEPLOYMENT",
"MLRUN_MOCK_NUCLIO_DEPLOYMENT",
] + (delete_keys or []):
dotenv.unset_key(self.filename, key)
else:
print(f".env file {self.filename} not found")
def do_popen(self, cmd, env=None, interactive=True, stdin=None):
if self.simulate:
print(f"DUMMY: {' '.join(cmd)}")
return 0, "", ""
output = None if interactive else subprocess.PIPE
stdin = None if not stdin else stdin
if self.verbose:
print(cmd)
try:
child = subprocess.Popen(
cmd, env=env, stdin=stdin, stdout=output, stderr=output
)
except FileNotFoundError as exc:
if interactive or self.verbose:
print(str(exc))
return 99, "", ""
returncode = child.wait()
if interactive:
return returncode, "", ""
return (
returncode,
child.stdout.read().decode("utf-8"),
child.stderr.read().decode("utf-8"),
)
def start(self, **kwargs):
pass
def stop(self, force=None, cleanup=None):
pass
def pause(self, **kwargs):
pass
def scale(self, services: dict = None):
pass
def is_supported(self, print_error=False):
return True
class RemoteConfig(BaseConfig):
def start(self, url, username, access_key, artifact_path, env_file, env_vars):
config = {"MLRUN_DBPATH": url, "MLRUN_CONF_LAST_DEPLOYMENT": "remote"}
if artifact_path:
config["V3IO_USERNAME"] = username
if artifact_path:
config["V3IO_ACCESS_KEY"] = access_key
if artifact_path:
config["MLRUN_ARTIFACT_PATH"] = artifact_path
self.set_env(config, env_vars_opt=env_vars)
class LocalConfig(BaseConfig):
@staticmethod
def find_python_exec():
if "python" in sys.executable:
return sys.executable
python_exec = os.environ.get("PYTHON_EXEC")
if python_exec and shutil.which(python_exec):
return python_exec
for executable in ["python3", "python"]:
if shutil.which(executable):
return executable
print(
"Error, python executable was not found or is not accessible, please install it first\n"
"if its installed, specify the python executable path using the PYTHON_EXEC env variable "
)
exit(1)
def start(
self,
data_volume=None,
logs_path=None,
artifact_path=None,
foreground=None,
port=None,
tag=None,
conda_env=None,
**kwargs,
):
env = {"MLRUN_IGNORE_ENV_FILE": "true"}
data_volume = data_volume or os.environ.get("SHARED_DIR", "")
artifact_path = artifact_path or os.environ.get("MLRUN_ARTIFACT_PATH", "")
tag = tag or get_latest_mlrun_tag()
if not port and "COLAB_RELEASE_TAG" in os.environ:
# change default port due to conflict in google colab
port = 8089
self.install_mlrun_api(tag, conda_env)
cmd = [self.find_python_exec(), "-m", "mlrun", "db"]
cmd += ["--update-env", self.filename]
if not foreground:
cmd += ["-b"]
if port is not None:
cmd += ["-p", str(port)]
if data_volume is not None:
cmd += ["-v", data_volume]
env["MLRUN_HTTPDB__LOGS_PATH"] = data_volume.rstrip("/") + "/logs"
if logs_path is not None:
env["MLRUN_HTTPDB__LOGS_PATH"] = logs_path
if self.verbose:
cmd += ["--verbose"]
if artifact_path:
cmd += ["-a", artifact_path]
if conda_env:
cmd = ["conda" "run" "-n", conda_env, "python"] + cmd[1:]
returncode, _, _ = self.do_popen(cmd, env=env)
if returncode != 0:
raise SystemExit(returncode)
# todo: wait to see the db is up
self.set_env(
{
"MLRUN_DBPATH": f"http://localhost:{port or '8080'}",
"MLRUN_MOCK_NUCLIO_DEPLOYMENT": "auto",
"MLRUN_CONF_LAST_DEPLOYMENT": "local",
"MLRUN_STORAGE__ITEM_TO_REAL_PATH": "",
},
)
def stop(self, force=None, cleanup=None):
pid = int(self.get_env().get("MLRUN_CONF_SERVICE_PID", "0"))
if pid and self.pid_exists(pid):
os.kill(pid)
self.clear_env(cleanup)
def install_mlrun_api(self, tag, conda_env=None):
mlrun_env = self.get_env()
installed = mlrun_env.get("MLRUN_CONF_API_IS_INSTALLED")
prefix = [self.find_python_exec()]
if conda_env:
prefix = ["conda" "run" "-n", conda_env, "python"]
if not installed:
# check if mlrun + api packages are installed
returncode, _, _ = self.do_popen(
prefix + ["-c", "import mlrun, apscheduler, uvicorn"], interactive=False
)
installed = returncode == 0
if not installed:
package = "mlrun[api]"
if tag:
package += f"=={tag}"
cmd = ["-m", "pip", "install", package]
returncode, _, err = self.do_popen(prefix + cmd, interactive=False)
if returncode != 0:
print(err)
@staticmethod
def pid_exists(pid):
"""Check whether pid exists in the current process table."""
try:
os.kill(pid, 0)
except OSError:
return False
return True
class DockerConfig(BaseConfig):
def is_supported(self, print_error=False):
for executable in ["docker", "docker-compose"]:
if shutil.which(executable) is None:
if print_error or self.verbose:
print(
f"Error, {executable} executable was not found"
", please make sure it is installed and accessible"
)
return False
docker_runs = self.do_popen(["docker", "ps"])[0] == 0
if not docker_runs and (print_error or self.verbose):
print("docker process failed to execute")
if self.verbose and docker_runs:
print("docker support was detected")
return docker_runs
def start(
self,
jupyter,
data_volume,
volume_mount,
artifact_path,
foreground,
port,
tag,
options,
compose_file,
**kwargs,
):
"""Deploy mlrun and nuclio services using Docker compose"""
print(options)
options = [_partial_match(option, docker_services) for option in options]
if is_codespaces:
volume_mount = volume_mount or "/tmp/mlrun"
data_volume = data_volume or "/mnt/containerTmp/mlrun"
os.makedirs(volume_mount, exist_ok=True)
data_volume = os.path.realpath(
os.path.expanduser(data_volume or "~/mlrun-data")
)
volume_mount = volume_mount or data_volume
docker_volume_mount = _docker_path(volume_mount)
if not is_codespaces:
try:
os.makedirs(data_volume, exist_ok=True)
except PermissionError as exc:
# can be caused if the script runs on another container
print(f"Error making volume {data_volume}, {exc}")
tag = tag or get_latest_mlrun_tag()
compose_file = compose_file or "compose.yaml"
cmd = ["docker-compose", "-f", compose_file, "up"]
if not foreground:
cmd += ["-d"]
compose_body = compose_template + mlrun_api_template
jupyter_image = ""
if not jupyter and "jupyter" in options:
jupyter = "."
if jupyter:
compose_body += jupyter_template
jupyter_image = f"mlrun/jupyter:{tag}" if jupyter == "." else jupyter
logging.info(f"Jupyter container image: {jupyter_image} ")
if "milvus" in options:
compose_body += milvus_template
if "mysql" in options:
compose_body += mysql_template
compose_body += suffix_template
with open(compose_file, "w") as fp:
fp.write(compose_body)
env = os.environ.copy()
conf_env = {}
for key, val in {
"HOST_IP": _get_ip(),
"SHARED_DIR": _docker_path(data_volume), # host dir
"VOLUME_MOUNT": volume_mount, # mounted dir
"MLRUN_PORT": str(port),
"TAG": tag,
"JUPYTER_IMAGE": jupyter_image,
}.items():
print(f"{key}={val}")
if val is not None:
env[key] = val
conf_env[key] = val
path_map = None
if volume_mount != docker_volume_mount:
path_map == f"{docker_volume_mount}::{volume_mount}"
self.set_env(
{
"MLRUN_DBPATH": f"http://localhost:{port}",
"MLRUN_MOCK_NUCLIO_DEPLOYMENT": "",
"MLRUN_CONF_LAST_DEPLOYMENT": "docker",
"MLRUN_CONF_COMPOSE_PATH": os.path.realpath(compose_file),
"MLRUN_CONF_COMPOSE_ENV": json.dumps(conf_env),
"MLRUN_STORAGE__ITEM_TO_REAL_PATH": path_map,
},
)
print(cmd)
returncode, _, _ = self.do_popen(cmd, env=env)
if returncode != 0:
raise SystemExit(returncode)
print()
print(f"MLRun API address: http://localhost:{port} (internal: http://mlrun-api:{port})")
print(
f"MLRun UI address: http://localhost:{os.environ.get('MLRUN_UI_PORT', '8060')}"
)
print(
f"Nuclio UI address: http://localhost:{os.environ.get('NUCLIO_PORT', '8070')}"
)
if jupyter:
print("Jupyter address: http://localhost:8888")
if "milvus" in options:
print("Milvus API address: http://localhost:19530 (internal: http://milvus:19530)")
print("Minio API address: http://localhost:9000 (internal: http://minio:9000)")
if "mysql" in options:
print(f"MySQL connection str:")
print(f" From Containers: {mysql_connection_url}")
print(f" From host: {mysql_connection_url.replace('sqldb', 'localhost')}")
def stop(self, force=None, cleanup=None):
compose_file = self.get_env().get("MLRUN_CONF_COMPOSE_PATH", "")
compose_env = self.get_env().get("MLRUN_CONF_COMPOSE_ENV", "{}")
env = os.environ.copy()
for key, val in json.loads(compose_env).items():
env[key] = val
self.stop_nuclio_containers()
if compose_file:
returncode, _, _ = self.do_popen(
["docker-compose", "-f", compose_file, "down"], env=env
)
if returncode != 0:
self.set_env({"MLRUN_DBPATH": ""}) # disable the DB access
raise SystemExit(returncode)
self.clear_env(cleanup)
def query_containers_by_filter(self, filters: dict) -> List[str]:
cmd = ["docker", "ps", "-q"]
for k, v in filters.items():
cmd.append("-f")
cmd.append(f"{k}={v}")
returncode, out, err = self.do_popen(cmd, interactive=False)
if returncode != 0:
print(err)
return []
containers = out.split()
return containers or []
def stop_nuclio_containers(self):
containers = self.query_containers_by_filter(
filters={"label": "nuclio.io/function-name"}
)
containers += self.query_containers_by_filter(
filters={"name": "nuclio-local-storage-reader"}
)
if not containers:
return
print(f"Stopping nuclio function containers: {' '.join(containers)}")
cmd = ["docker", "stop"] + containers
returncode, _, err = self.do_popen(cmd, interactive=False)
if returncode != 0:
print(err)
class K8sConfig(BaseConfig):
def is_supported(self, print_error=False):
if shutil.which("kubectl") is None:
if print_error or self.verbose:
logging.error(
"Error, kubectl was not found, "
"please make sure Kubernetes is installed and configured"
)
return False
if shutil.which("helm") is None:
if print_error or self.verbose:
logging.error(
"Error, helm was not found, please make sure helm is installed"
" see: https://helm.sh/docs/intro/install/"
)
return False
kubectl_runs = self.do_popen(["kubectl", "version"])[0] == 0
if not kubectl_runs and (print_error or self.verbose):
logging.error("Kubernetes cli (kubectl) is not accessible")
if self.verbose and kubectl_runs:
logging.error("Kubernetes (kubectl) support was detected")
return kubectl_runs
def start(
self,
name="mlrun-ce",
namespace="mlrun",
registry_args=None,
external_addr=None,
tag=None,
settings=None,
options=None,
disable=None,
chart_ver=None,
values_file_path=None,
jupyter="",
**kwargs,
):
logging.info("Start installing MLRun CE")
service_options = self.parse_services(options, enable="true")
service_options += self.parse_services(disable, enable="false")
tag = tag or get_latest_mlrun_tag()
logging.info(f"Using MLRun tag: {tag} ")
logging.info(f"Creating kubernetes namespace {namespace}...")
create_namespace = True
if self.check_k8s_resource_exist("namespace", namespace):
if "MLSETUP_NONINTERACTIVE" not in os.environ:
logging.warning(f"Namespace {namespace} already exists")
text = click.prompt(
"To overwrite the existing namespace press y or Y",
type=str,
default="n",
)
text = text.lower()
if "y" in text:
returncode, out, err = self.do_popen(
["kubectl", "delete", "namespace", namespace], interactive=False
)
if returncode != 0:
logging.error(err)
raise SystemExit(returncode)
else:
create_namespace = False
if create_namespace:
returncode, out, err = self.do_popen(
["kubectl", "create", "namespace", namespace], interactive=True
)
if returncode != 0:
# err = child.stderr.read().decode("utf-8")
if "AlreadyExists" not in err:
logging.error(err)
raise SystemExit(returncode)
env_settings = {
"MLRUN_MOCK_NUCLIO_DEPLOYMENT": "",
"MLRUN_CONF_LAST_DEPLOYMENT": "kubernetes",
"MLRUN_CONF_HELM_DEPLOYMENT": name,
"MLRUN_CONF_K8S_NAMESPACE": namespace,
"MLRUN_CONF_K8S_STAGE": K8sStages.namespace,
}
self.set_env(env_settings)
# Install and update Helm charts
helm_commands = [
["helm", "repo", "add", "mlrun-ce", "https://mlrun.github.io/ce"],
["helm", "repo", "list"],
["helm", "repo", "update"],
]
logging.info("Installing and updating mlrun helm repo")
for command in helm_commands:
returncode, _, _ = self.do_popen(command)
if returncode != 0:
raise SystemExit(returncode)
env_settings["MLRUN_CONF_K8S_STAGE"] = K8sStages.helm
self.set_env(env_settings)