-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathdk-installer.py
executable file
·2039 lines (1747 loc) · 65.4 KB
/
dk-installer.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/env python3
import argparse
import contextlib
import dataclasses
import datetime
import ipaddress
import json
import logging
import logging.config
import os
import pathlib
import platform
import re
import secrets
import ssl
import string
import subprocess
import sys
import textwrap
import time
import urllib.request
import urllib.parse
import zipfile
#
# Initial setup
#
MINIKUBE_PROFILE = "dk-observability"
MINIKUBE_KUBE_VER = "v1.29"
NAMESPACE = "datakitchen"
HELM_REPOS = (("datakitchen", "https://datakitchen.github.io/dataops-observability/"),)
HELM_SERVICES = (
"dataops-observability-services",
os.environ.get("HELM_FOLDER", "datakitchen/dataops-") + "observability-services",
)
HELM_APP = (
"dataops-observability-app",
os.environ.get("HELM_FOLDER", "datakitchen/dataops-") + "observability-app",
)
HELM_DEFAULT_TIMEOUT = 10
DOCKER_COMPOSE_FILE = "docker-compose.yml"
DEFAULT_DOCKER_REGISTRY = "docker.io"
DOCKER_NETWORK = "datakitchen-network"
DOCKER_NETWORK_SUBNET = "192.168.60.0/24"
POD_LOG_LIMIT = 10_000
INSTALLER_NAME = pathlib.Path(__file__).name
DEMO_CONFIG_FILE = "demo-config.json"
DEMO_IMAGE = "datakitchen/data-observability-demo:latest"
DEMO_CONTAINER_NAME = "dk-demo"
SERVICES_LABELS = {
"observability-ui": "User Interface",
"event-api": "Event Ingestion API",
"observability-api": "Observability API",
"agent-api": "Agent Heartbeat API",
}
SERVICES_URLS = {
"observability-ui": "{}",
"event-api": "{}/api/events/v1",
"observability-api": "{}/api/observability/v1",
"agent-api": "{}/api/agent/v1",
}
DEFAULT_EXPOSE_PORT = 8082
DEFAULT_OBS_MEMORY = 4096
BASE_API_URL_TPL = "{}/api"
CREDENTIALS_FILE = "dk-{}-credentials.txt"
TESTGEN_COMPOSE_NAME = "testgen"
TESTGEN_LATEST_TAG = "v2"
TESTGEN_DEFAULT_IMAGE = f"datakitchen/dataops-testgen:{TESTGEN_LATEST_TAG}"
TESTGEN_PULL_TIMEOUT = 120
TESTGEN_PULL_RETRIES = 3
TESTGEN_DEFAULT_PORT = 8501
LOG = logging.getLogger()
#
# Utility functions
#
def collect_images_digest(action, images, env=None):
action.run_cmd(
"docker",
"image",
"inspect",
*images,
"--format=DIGEST: {{ index .RepoDigests 0 }} CREATED: {{ .Created }}",
raise_on_non_zero=False,
env=env,
)
def get_recommended_minikube_driver():
if platform.system() == "Darwin" and platform.processor() == "i386":
return "hyperkit"
else:
return "docker"
def collect_user_input(fields: list[str]) -> dict[str, str]:
res = {}
CONSOLE.space()
try:
for field in fields:
while field not in res:
if value := input(f"{CONSOLE.MARGIN}{field.capitalize()!s: >20}: "):
res[field] = value
except KeyboardInterrupt:
print("") # Moving the cursor back to the start
raise AbortAction
finally:
CONSOLE.space()
return res
def generate_password():
characters = string.ascii_letters + string.digits
password = ""
for _ in range(12):
password += secrets.choice(characters)
return password
def write_credentials_file(folder: pathlib.Path, product, lines):
file_path = folder.joinpath(CREDENTIALS_FILE.format(product))
try:
with open(file_path, "w") as file:
file.writelines([f"{text}\n" for text in lines])
except Exception:
pass
else:
CONSOLE.msg(f"(Credentials also written to {file_path.name} file)")
def delete_file(file_path):
LOG.debug("Deleting [%s]", file_path.name)
file_path.unlink(missing_ok=True)
def get_testgen_status(action):
compose_installs = action.run_cmd("docker", "compose", "ls", "--format=json", capture_json=True)
for install in compose_installs:
if install["Name"] == TESTGEN_COMPOSE_NAME:
return install
return {}
def get_testgen_volumes(action):
volumes = action.run_cmd("docker", "volume", "list", "--format=json", capture_json_lines=True)
return [v for v in volumes if "com.docker.compose.project=testgen" in v.get("Labels", "")]
def do_request(url, method="GET", headers=None, params=None, data=None, verify=True):
query_params = ""
if params:
query_params = "?" + urllib.parse.urlencode(params)
request = urllib.request.Request(url + query_params, method=method, headers=headers or {})
if data:
request.data = json.dumps(data).encode()
request.add_header("Content-Type", "application/json")
ssl_context = None
if not verify:
ssl_context = ssl.create_default_context()
ssl_context.check_hostname = False
ssl_context.verify_mode = ssl.CERT_NONE
with urllib.request.urlopen(request, context=ssl_context) as response:
try:
return json.loads(response.read().decode())
except:
return {}
class StreamIterator:
def __init__(self, proc, stream, file_path):
self.proc = proc
self.stream = stream
self.file_path = file_path
self.file = None
self.bytes_written = 0
def __iter__(self):
return self
def __next__(self):
for return_anyway in (False, True):
# We poll the process status before consuming the stream to make sure the StopIteration condition
# is not vulnerable to a race condition.
ret = self.proc.poll()
line = self.stream.readline()
if line:
if not self.file:
self.file = open(self.file_path, "wb")
self.file.write(line)
self.bytes_written += len(line)
return line
if ret is not None and not line:
raise StopIteration
if not return_anyway:
time.sleep(0.1)
return line
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
for _ in iter(self):
pass
if self.file:
self.file.close()
return False
#
# Core building blocks
#
class Console:
MARGIN = " | "
def __init__(self):
self._last_is_space = False
self._partial_msg = ""
def title(self, text):
LOG.info("Console title: [%s]", text)
if not self._last_is_space:
print("")
print(f" == {text}")
print("")
self._last_is_space = True
def space(self):
if not self._last_is_space:
print(self.MARGIN)
self._last_is_space = True
def msg(self, text, skip_logging=False):
if skip_logging:
LOG.info("Console message omitted from the logs")
else:
LOG.info("Console message: [%s]", text)
print(self.MARGIN, end="")
print(text)
self._last_is_space = False
def __enter__(self):
print(self.MARGIN, end="")
return self
def send(self, text):
print(text, end="")
sys.stdout.flush()
self._partial_msg += text
def __exit__(self, exc_type, exc_val, exc_tb):
print("")
LOG.info("Console message: [%s]", self._partial_msg)
self._partial_msg = ""
self._last_is_space = False
return False
CONSOLE = Console()
@dataclasses.dataclass
class Requirement:
name: str
cmd: tuple[str, ...]
def check_availability(self, action, args):
try:
action.run_cmd(*(seg.format(**args.__dict__) for seg in self.cmd))
except CommandFailed:
CONSOLE.msg(f"The installer could not verify that '{self.name}' is available.")
return False
else:
return True
class CommandFailed(Exception):
"""
Raised when a command returns a non-zero exit code.
It's useful to prevent the installer logic from having to check the output of each command
"""
def __init__(self, idx=None, cmd=None, ret_code=None):
self.idx = idx
self.cmd = cmd
self.ret_code = ret_code
class InstallerError(Exception):
"""Should be raised when the root cause could not be addressed and the process is unable to continue."""
class AbortAction(InstallerError):
"""Should be raised when the root cause has been addressed but the process is unable to continue."""
class SkipStep(Exception):
"""Should be raised when a given Step does not need to be executed."""
class Step:
required: bool = True
label = None
def pre_execute(self, action, args):
pass
def execute(self, action, args):
pass
def on_action_success(self, action, args):
pass
def on_action_fail(self, action, args):
pass
def __str__(self):
return self.label or self.__name__
class Action:
_cmd_idx: int = 0
args_cmd: str
args_parser_parents: list = []
requirements: list = []
@contextlib.contextmanager
def init_session_folder(self, prefix):
if platform.system() == 'Windows':
self.data_folder = pathlib.Path.home().joinpath("Documents", "DataKitchenApps")
self.logs_folder = self.data_folder.joinpath("logs")
else:
self.data_folder = pathlib.Path(sys.argv[0]).absolute().parent
self.logs_folder = self.data_folder.joinpath(".dk-installer")
self.data_folder.mkdir(exist_ok=True)
self.logs_folder.mkdir(exist_ok=True)
timestamp = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
self.session_folder = self.logs_folder.joinpath(f"{prefix}-{timestamp}")
self.session_folder.mkdir()
self.session_zip = self.logs_folder.joinpath(f"{self.session_folder.name}.zip")
try:
yield
finally:
with zipfile.ZipFile(self.session_zip, "w") as session_zip:
for session_file in self.session_folder.iterdir():
session_zip.write(session_file, arcname=session_file.relative_to(self.session_zip.parent))
session_file.unlink()
self.session_folder.rmdir()
self.session_folder = None
latest = self.logs_folder.joinpath("latest")
latest.unlink(True)
latest.symlink_to(self.session_zip.relative_to(latest.parent))
@contextlib.contextmanager
def configure_logging(self, debug=False):
file_path = self.session_folder.joinpath("installer_log.txt")
logging.config.dictConfig(
{
"version": 1,
"formatters": {
"file": {"format": "%(asctime)s %(levelname)8s %(message)s"},
"console": {"format": " : %(levelname)8s %(message)s"},
},
"handlers": {
"file": {
"level": "DEBUG",
"class": "logging.FileHandler",
"filename": str(file_path),
"formatter": "file",
},
"console": {
"level": "DEBUG",
"class": "logging.StreamHandler",
"formatter": "console",
},
},
"loggers": {
"": {"handlers": ["file"] + (["console"] if debug else []), "level": "DEBUG"},
},
},
)
try:
yield
finally:
logging.shutdown()
logging.config.dictConfig(
{
"version": 1,
"disable_existing_loggers": True,
"loggers": {
"": {"handlers": [], "level": "DEBUG"},
},
}
)
def _msg_unexpected_error(self):
msg_file_path = self.session_zip.relative_to(pathlib.Path().absolute())
CONSOLE.msg(f"An unexpected error occurred. Please check the logs in {msg_file_path} for details.")
CONSOLE.msg("")
CONSOLE.msg("For assistance, reach out the #support channel on https://data-observability-slack.datakitchen.io/join, attaching the logs.")
CONSOLE.msg("")
def execute_with_log(self, args):
with self.init_session_folder(prefix=f"{args.prod}-{self.args_cmd}"), self.configure_logging(debug=args.debug):
# Collecting basic system information for troubleshooting
LOG.info(
"System info: %s | %s",
platform.system(),
platform.version(),
)
LOG.info(
"Platform info: %s | %s",
platform.platform(),
platform.processor(),
)
LOG.info(
"Python info: %s %s",
platform.python_implementation(),
platform.python_version(),
)
try:
if not all((req.check_availability(self, args) for req in self.requirements)):
CONSOLE.msg("Not all requirements are fulfilled")
raise AbortAction
self.execute(args)
except AbortAction:
raise
except InstallerError:
self._msg_unexpected_error()
raise
except Exception as e:
LOG.exception("Uncaught error: %r", e)
self._msg_unexpected_error()
raise InstallerError from e
except KeyboardInterrupt:
CONSOLE.msg("Processing interrupted. The platform might be left in a inconsistent state.")
raise AbortAction
def get_parser(self, sub_parsers):
parser = sub_parsers.add_parser(self.args_cmd, parents=self.args_parser_parents)
parser.set_defaults(func=self.execute_with_log)
return parser
def execute(self, args):
raise NotImplementedError
def run_cmd(
self,
*cmd,
input=None,
capture_json=False,
capture_json_lines=False,
capture_text=False,
echo=False,
raise_on_non_zero=True,
env=None,
**popen_args,
):
with self.start_cmd(*cmd, raise_on_non_zero=raise_on_non_zero, env=env, **popen_args) as (proc, stdout, stderr):
if input:
proc.stdin.write(input)
proc.stdin.close()
if echo:
for line in stdout:
if line:
CONSOLE.msg(line.decode().strip())
elif capture_text:
return b"".join(stdout).decode()
elif capture_json:
try:
return json.loads(b"".join(stdout).decode())
except json.JSONDecodeError:
LOG.warning("Error decoding JSON from stdout")
return {}
elif capture_json_lines:
json_lines = []
for idx, output_line in enumerate(stdout):
try:
json_lines.append(json.loads(output_line.decode()))
except json.JSONDecodeError:
LOG.warning(f"Error decoding JSON from stdout line #{idx}")
return json_lines
@contextlib.contextmanager
def start_cmd(self, *cmd, raise_on_non_zero=True, env=None, **popen_args):
started = time.time()
self._cmd_idx += 1
cmd_str = " ".join(str(part) for part in cmd)
LOG.debug("Command [%04d]: [%s]", self._cmd_idx, cmd_str)
if isinstance(env, dict):
LOG.debug("Command [%04d] extra ENV: [%s]", self._cmd_idx, ", ".join(env.keys()))
env = {**os.environ, **env}
try:
proc = subprocess.Popen(
cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE, env=env, **popen_args
)
except FileNotFoundError as e:
LOG.error("Command [%04d] failed to find the executable", self._cmd_idx)
raise CommandFailed(self._cmd_idx, cmd, None) from e
slug_cmd = re.sub(r"[^a-zA-Z]+", "-", cmd_str)[:100].strip("-")
def get_stream_iterator(stream_name):
file_name = f"{self._cmd_idx:04d}-{stream_name}-{slug_cmd}.txt"
file_path = self.session_folder.joinpath(file_name)
return StreamIterator(proc, getattr(proc, stream_name), file_path)
try:
with get_stream_iterator("stdout") as stdout_iter, get_stream_iterator("stderr") as stderr_iter:
try:
yield proc, stdout_iter, stderr_iter
finally:
proc.wait()
if raise_on_non_zero and proc.returncode != 0:
raise CommandFailed
# We capture and raise CommandFailed to allow the client code to raise an empty CommandFailed exception
# but still get a contextualized exception at the end
except CommandFailed as e:
raise CommandFailed(self._cmd_idx, cmd, proc.returncode) from e.__cause__
finally:
elapsed = time.time() - started
LOG.info(
"Command [%04d] returned [%d] in [%.3f] seconds. [%d] bytes in STDOUT, [%d] bytes in STDERR",
self._cmd_idx,
proc.returncode,
elapsed,
stdout_iter.bytes_written,
stderr_iter.bytes_written,
)
class MultiStepAction(Action):
steps: list[Step]
label = "Process"
title = ""
intro_text = ""
def execute(self, args):
CONSOLE.title(self.title)
for step in self.steps:
try:
LOG.debug("Running step [%s] pre-execute", step)
step.pre_execute(self, args)
except InstallerError:
raise
except Exception as e:
LOG.exception("Step [%s] pre-execute failed", step)
raise InstallerError from e
CONSOLE.space()
if self.intro_text:
CONSOLE.msg(self.intro_text)
CONSOLE.space()
executed_steps: list[Step] = []
action_fail_exception = None
for step in self.steps:
executed_steps.append(step)
with CONSOLE:
CONSOLE.send(f"{step.label}... ")
try:
if action_fail_exception:
raise SkipStep
LOG.debug("Executing step [%s]", step)
step.execute(self, args)
except SkipStep:
CONSOLE.send("SKIPPED")
continue
except Exception as e:
CONSOLE.send("FAILED")
if step.required:
action_fail_exception = e
else:
LOG.warning(f"Non-required step [%s] failed with: %s", step, e)
else:
CONSOLE.send("OK")
if action_fail_exception:
CONSOLE.title(f"{self.label} FAILED")
else:
CONSOLE.title(f"{self.label} SUCCEEDED")
for step in reversed(executed_steps):
try:
if action_fail_exception is None:
LOG.debug("Running [%s] on-action-success", step)
step.on_action_success(self, args)
else:
LOG.debug("Running [%s] on-action-fail", step)
step.on_action_fail(self, args)
except Exception as e:
LOG.exception("Post-execution of step [%s] failed", step)
if action_fail_exception:
raise action_fail_exception
class Installer:
def __init__(self):
self.parser = argparse.ArgumentParser(description="DataKitchen Installer")
self.parser.add_argument("--debug", action="store_true", help=argparse.SUPPRESS)
self.sub_parsers = self.parser.add_subparsers(help="Products", required=True)
def run(self, def_args):
# def_args has to be None to preserve the argparser behavior when only part of the arguments are used
args = self.parser.parse_args(def_args or None)
if not hasattr(args, "func"):
self.parser.print_usage()
return 2
CONSOLE.title("DataKitchen Data Observability Installer")
try:
args.func(args)
except AbortAction:
return 1
except Exception:
return 2
else:
return 0
def add_product(self, prefix, actions, defaults=None):
prod_parser = self.sub_parsers.add_parser(prefix)
prod_parser.set_defaults(prod=prefix, **(defaults or {}))
prod_sub_parsers = prod_parser.add_subparsers(required=True)
for action in actions:
action.get_parser(prod_sub_parsers)
#
# Common blocks shared by more than one step/action
#
def get_minikube_parser():
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument(
"--profile",
type=str,
action="store",
default=MINIKUBE_PROFILE,
help="Name of the minikube profile that will be started/deleted. Defaults to '%(default)s'",
)
parser.add_argument(
"--namespace",
type=str,
action="store",
default=NAMESPACE,
help="Namespace to be given to the kubernetes resources. Defaults to '%(default)s'",
)
return parser
minikube_parser = get_minikube_parser()
REQ_HELM = Requirement("Helm", ("helm", "version"))
REQ_MINIKUBE = Requirement("minikube", ("minikube", "version"))
REQ_MINIKUBE_DRIVER = Requirement("minikube driver", ("{driver}", "-v"))
REQ_DOCKER = Requirement("Docker", ("docker", "-v"))
REQ_DOCKER_DAEMON = Requirement("Docker daemon process", ("docker", "info"))
REQ_TESTGEN_CONFIG = Requirement(f"TestGen {DOCKER_COMPOSE_FILE}", ("docker", "compose", "config"))
#
# Action and Steps implementations
#
class DockerNetworkStep(Step):
label = "Creating a Docker network"
def execute(self, action, args):
if args.prod == "tg" or args.driver == "docker":
try:
action.run_cmd(
"docker",
"network",
"inspect",
DOCKER_NETWORK,
)
LOG.info(f"Re-using existing Docker network '{DOCKER_NETWORK}'")
raise SkipStep
except CommandFailed:
LOG.info(f"Creating Docker network '{DOCKER_NETWORK}'")
action.run_cmd(
"docker",
"network",
"create",
"--subnet",
DOCKER_NETWORK_SUBNET,
"--gateway",
# IP at index 0 is unavailable
str(ipaddress.IPv4Network(DOCKER_NETWORK_SUBNET)[1]),
DOCKER_NETWORK,
)
else:
raise SkipStep
class MinikubeProfileStep(Step):
label = "Starting a new minikube profile"
def pre_execute(self, action, args):
env_json = action.run_cmd(
"minikube",
"-p",
args.profile,
"status",
"-o",
"json",
capture_json=True,
raise_on_non_zero=False,
)
if "Name" in env_json:
CONSOLE.msg(
"Found a minikube profile with the same name. If a previous attempt to run this installer failed,"
)
CONSOLE.msg(
f"please run `python3 {INSTALLER_NAME} {args.prod} delete --profile={args.profile}` before trying again"
)
CONSOLE.msg("or choose a different profile name.")
CONSOLE.space()
for k, v in env_json.items():
CONSOLE.msg(f"{k:>10}: {v}")
raise AbortAction
def execute(self, action, args):
action.run_cmd(
"minikube",
"start",
f"--memory={args.memory}",
f"--profile={args.profile}",
f"--namespace={args.namespace}",
f"--driver={args.driver}",
f"--kubernetes-version={MINIKUBE_KUBE_VER}",
f"--network={DOCKER_NETWORK}",
# minikube tries to use gateway + 1 by default, but that may be in use by TestGen - so we pass in a static IP at gateway + 4
f"--static-ip={str(ipaddress.IPv4Network(DOCKER_NETWORK_SUBNET)[5])}",
"--embed-certs",
"--extra-config=apiserver.service-node-port-range=1-65535",
"--extra-config=kubelet.allowed-unsafe-sysctls=net.core.somaxconn",
)
def on_action_fail(self, action, args):
if args.debug:
LOG.debug("Skipping deleting the minikube profile on failure because debug is ON")
return
action.run_cmd("minikube", "-p", args.profile, "delete")
def on_action_success(self, action, args):
action.run_cmd("minikube", "profile", args.profile)
class SetupHelmReposStep(Step):
label = "Setting up the helm repositories"
def execute(self, action, args):
if "HELM_FOLDER" in os.environ:
raise SkipStep
for name, url in HELM_REPOS:
action.run_cmd("helm", "repo", "add", name, url, "--force-update")
action.run_cmd("helm", "repo", "update")
class HelmInstallStep(Step):
chart_info: tuple[str, str] = None
values_arg: str = None
def execute(self, action, args):
release, chart_ref = self.chart_info
values_file = getattr(args, self.values_arg) if self.values_arg else None
values = ("--values", values_file) if values_file else ()
action.run_cmd(
"helm",
"install",
release,
chart_ref,
*values,
f"--namespace={args.namespace}",
"--create-namespace",
"--wait",
f"--timeout={args.helm_timeout}m",
)
def on_action_fail(self, action, args):
release, _ = self.chart_info
action.run_cmd("helm", "status", release, "-o", "json", capture_json=True, raise_on_non_zero=False)
pods = action.run_cmd(
"minikube",
"kubectl",
"--profile",
args.profile,
"--",
"--namespace",
args.namespace,
"-l",
f"app.kubernetes.io/instance={release}",
"get",
"pods",
"-o",
"json",
capture_json=True,
)
if POD_LOG_LIMIT:
for pod in pods["items"]:
for container in pod["status"]["containerStatuses"]:
if not container["ready"]:
action.run_cmd(
"minikube",
"kubectl",
"--profile",
args.profile,
"--",
"--namespace",
args.namespace,
"logs",
pod["metadata"]["name"],
"-c",
container["name"],
"--limit-bytes",
str(POD_LOG_LIMIT),
)
class ObsHelmInstallServicesStep(HelmInstallStep):
label = "Installing helm charts for supporting services"
chart_info = HELM_SERVICES
class ObsHelmInstallPlatformStep(HelmInstallStep):
label = "Installing helm charts for Observability platform"
chart_info = HELM_APP
values_arg = "app_values"
def execute(self, action, args):
if args.docker_username and args.docker_password:
action.run_cmd(
"minikube",
"kubectl",
"--profile",
args.profile,
"--",
"--namespace",
args.namespace,
"create",
"secret",
"docker-registry",
"docker-hub-pull-secrets",
"--docker-username",
args.docker_username,
"--docker-password",
args.docker_password,
)
super().execute(action, args)
if not (
args.driver == "docker"
and platform.system()
in [
"Darwin",
"Windows",
]
):
try:
data = action.run_cmd(
"minikube",
"-p",
args.profile,
"service",
"--namespace",
args.namespace,
"list",
"-o",
"json",
capture_json=True,
)
url = [svc["URLs"][0] for svc in data if svc["Name"] == "observability-ui"][0]
except Exception:
pass
else:
action.ctx["base_url"] = url
def on_action_success(self, action, args):
if not action.ctx.get("base_url"):
cmd_args = []
if args.profile != MINIKUBE_PROFILE:
cmd_args.append(f"--profile={args.profile}")
if args.namespace != NAMESPACE:
cmd_args.append(f"--namespace={args.namespace}")
CONSOLE.space()
CONSOLE.msg("Because you are using the docker driver on a Mac or Windows, you have to run")
CONSOLE.msg("the following command in order to be able to access the platform.")
CONSOLE.space()
CONSOLE.msg(f"python3 {INSTALLER_NAME} {args.prod} expose {' '.join(cmd_args)}")
self._collect_images_sha(action, args)
def on_action_fail(self, action, args):
self._collect_images_sha(action, args)
def _collect_images_sha(self, action, args):
images = action.run_cmd("minikube", "-p", args.profile, "image", "list", "--format=json", capture_json=True)
image_repo_tags = [img["repoTags"][0] for img in images]
bash_env = action.run_cmd("minikube", "-p", args.profile, "docker-env", "--shell", "bash", capture_text=True)
env = dict(re.findall(r'export ([\w_]+)="([^"]+)"', bash_env, re.M))
collect_images_digest(action, image_repo_tags, env)
class ObsDataInitializationStep(Step):
label = "Initializing the database"
_user_data = {}
def execute(self, action, args):
self._user_data = {
"name": "Admin",
"email": "[email protected]",
"username": "admin",
"password": generate_password(),
}
action.ctx["init_data"] = action.run_cmd(
"minikube",
"kubectl",
"--profile",
args.profile,
"--",
"--namespace",
args.namespace,
"exec",
"-i",
"deployments/agent-api",
"--",
"/dk/bin/cli",
"init",
"--demo",
"--json",
input=json.dumps(self._user_data).encode(),
capture_json=True,
)
def on_action_success(self, action, args):
info_lines = []
if url := action.ctx.get("base_url"):
for service, label in SERVICES_LABELS.items():
info_lines.append(f"{label:>20}: {SERVICES_URLS[service].format(url)}")
info_lines.append("")
info_lines.extend(
[
f"Username: {self._user_data['username']}",
f"Password: {self._user_data['password']}",
"",
]
)
CONSOLE.space()
for line in info_lines:
CONSOLE.msg(line, skip_logging="Password" in line) if line else CONSOLE.space()
write_credentials_file(action.data_folder, args.prod, info_lines)
class ObsGenerateDemoConfigStep(Step):
label = "Generating the demo configuration"
required = False
def execute(self, action, args):
try:
init_data = action.ctx["init_data"]
except KeyError:
LOG.info("Skipping generating the demo config file because the initialization data is not available")
raise SkipStep
else:
base_url = action.ctx.get("base_url", f"http://host.docker.internal:{DEFAULT_EXPOSE_PORT}")
config = {
"api_key": init_data["service_account_key"],