-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathdk-installer.py
More file actions
executable file
·3665 lines (3169 loc) · 138 KB
/
Copy pathdk-installer.py
File metadata and controls
executable file
·3665 lines (3169 loc) · 138 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
import argparse
import base64
import contextlib
import dataclasses
import datetime
import functools
import hashlib
import io
import ipaddress
import json
import logging
import logging.config
import os
import pathlib
import pdb
import platform
import random
import re
import secrets
import shutil
import signal
import socket
import ssl
import stat
import string
import subprocess
import sys
import tarfile
import textwrap
import time
import urllib.request
import urllib.parse
import webbrowser
import zipfile
import typing
#
# Initial setup
#
REQ_CHECK_TIMEOUT = 30
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"
BASE_API_URL_TPL = "http://host.docker.internal:{}/api"
CREDENTIALS_FILE = "dk-{}-credentials.txt"
TESTGEN_MAJOR_VERSION = "5"
TESTGEN_PYTHON_VERSION = "3.13"
TESTGEN_DEFAULT_IMAGE = f"datakitchen/dataops-testgen:v{TESTGEN_MAJOR_VERSION}"
TESTGEN_PULL_TIMEOUT = 5
TESTGEN_PULL_RETRIES = 3
TESTGEN_DEFAULT_PORT = 8501
TESTGEN_DEFAULT_API_PORT = 8530
TESTGEN_LATEST_VERSIONS_URL = (
"https://dk-support-external.s3.us-east-1.amazonaws.com/testgen-observability/testgen-latest-versions.json"
)
TESTGEN_PIP_PACKAGE = "dataops-testgen"
TESTGEN_COMPOSE_FILE = "docker-compose.yml"
TESTGEN_LOG_FILE_PATH = pathlib.Path.home() / ".testgen" / "logs" / "app.log"
TESTGEN_CONFIG_ENV_PATH = pathlib.Path.home() / ".testgen" / "config.env"
TESTGEN_APP_READY_TIMEOUT = 120
# Seconds TestGen is given to stop. Must exceed TG_JOB_SHUTDOWN_TIMEOUT (default 60s) plus
# the time the process needs to record what stopped, or the scheduler is killed mid-wait and
# a running job is cut instead of stopping at a checkpoint.
TESTGEN_STOP_GRACE_PERIOD = 90
INSTALL_MARKER_FILE = "dk-{}-install.json"
INSTALL_MODE_DOCKER = "docker"
INSTALL_MODE_PIP = "pip"
UV_VERSION = "0.11.7"
UV_RELEASE_URL_TPL = "https://github.com/astral-sh/uv/releases/download/{version}/{asset}"
UV_DOWNLOAD_TIMEOUT = 120
UV_DOWNLOAD_RETRIES = 3
UV_BIN_SUBDIR = "bin"
# To bump UV_VERSION, refresh the SHA256s here from the dist-manifest:
# https://github.com/astral-sh/uv/releases/download/<version>/dist-manifest.json
# See "Bumping uv" in CLAUDE.md.
UV_ASSETS: dict[tuple[str, str], tuple[str, str]] = {
# (platform.system(), platform.machine()) -> (asset_name, sha256)
("Linux", "x86_64"): (
"uv-x86_64-unknown-linux-gnu.tar.gz",
"6681d691eb7f9c00ac6a3af54252f7ab29ae72f0c8f95bdc7f9d1401c23ea868",
),
("Linux", "aarch64"): (
"uv-aarch64-unknown-linux-gnu.tar.gz",
"f2ee1cde9aabb4c6e43bd3f341dadaf42189a54e001e521346dc31547310e284",
),
("Darwin", "x86_64"): (
"uv-x86_64-apple-darwin.tar.gz",
"0a4bc8fcde4974ea3560be21772aeecab600a6f43fa6e58169f9fa7b3b71d302",
),
("Darwin", "arm64"): (
"uv-aarch64-apple-darwin.tar.gz",
"66e37d91f839e12481d7b932a1eccbfe732560f42c1cfb89faddfa2454534ba8",
),
("Windows", "AMD64"): (
"uv-x86_64-pc-windows-msvc.zip",
"fe0c7815acf4fc45f8a5eff58ed3cf7ae2e15c3cf1dceadbd10c816ec1690cc1",
),
("Windows", "ARM64"): (
"uv-aarch64-pc-windows-msvc.zip",
"1387e1c94e15196351196b79fce4c1e6f4b30f19cdaaf9ff85fbd6b046018aa2",
),
}
OBS_LATEST_TAG = "v2"
OBS_DEF_BE_IMAGE = f"datakitchen/dataops-observability-be:{OBS_LATEST_TAG}"
OBS_DEF_UI_IMAGE = f"datakitchen/dataops-observability-ui:{OBS_LATEST_TAG}"
OBS_PULL_TIMEOUT = 5
OBS_PULL_RETRIES = 3
OBS_DEFAULT_PORT = 8082
OBS_SERVICES_URLS = (
("User Interface", "{}:{}/"),
("Event Ingestion API", "{}:{}/api/events/v1"),
("Observability API", "{}:{}/api/observability/v1"),
("Agent Heartbeat API", "{}:{}/api/agent/v1"),
)
MIXPANEL_TOKEN = "4eff51580bc1685b8ffe79ffb22d2704"
MIXPANEL_URL = "https://api.mixpanel.com"
MIXPANEL_TIMEOUT = 3
INSTANCE_ID_FILE = "instance.txt"
DEFAULT_USER_DATA = {
"name": "Admin",
"email": "email@example.com",
"username": "admin",
}
LOG = logging.getLogger()
COMPOSE_VAR_RE = re.compile(r"\$\{(\w+):-([^\}]*)\}")
TESTGEN_PIP_VERSION_RE = re.compile(rf"^{re.escape(TESTGEN_PIP_PACKAGE)}\s+v(\S+)")
#
# Utility functions
#
def get_tg_url(args, port):
protocol = "https" if args.ssl_cert_file and args.ssl_key_file else "http"
return f"{protocol}://localhost:{port}"
def open_app_in_browser(url: str) -> None:
"""Best-effort open the URL in the user's default browser. Silent no-op
on headless / browser-less environments."""
try:
webbrowser.open(url)
except Exception:
LOG.exception("Failed to open browser for %s", url)
def collect_images_digest(action, images, env=None):
if images:
action.run_cmd(
"docker",
"image",
"inspect",
*images,
"--format=DIGEST: {{ index .RepoDigests 0 }} CREATED: {{ .Created }}",
raise_on_non_zero=False,
env=env,
)
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 remove_path(path: pathlib.Path, label: typing.Optional[str] = None) -> bool:
"""Remove a file or directory tree if it exists.
When ``label`` is provided, success/failure is also reported via CONSOLE.
Returns True if something was actually removed.
"""
if not (path.exists() or path.is_symlink()):
return False
LOG.debug("Removing path [%s]", path)
try:
if path.is_dir():
# On Windows, files inside a Postgres data dir are often marked read-only,
# which causes shutil.rmtree to abort partway through. Clear the read-only
# bit and retry from the error callback. shutil.rmtree's `onerror` is
# deprecated in 3.12 and removed in 3.14, replaced by `onexc`; the callback
# signatures differ on the third arg but we ignore it either way.
def _retry(func, p, _exc):
os.chmod(p, stat.S_IWRITE)
func(p)
if sys.version_info >= (3, 12):
shutil.rmtree(path, onexc=_retry)
else:
shutil.rmtree(path, onerror=_retry)
else:
path.unlink()
except OSError:
LOG.exception("Failed to remove %s", path)
if label:
CONSOLE.msg(f"Could not remove {label} ({path}); remove manually if needed.")
return False
if label:
CONSOLE.msg(f"Removed {label} ({path})")
return True
@functools.cache
def get_installer_version():
try:
return hashlib.md5(pathlib.Path(__file__).read_bytes()).hexdigest()
except Exception:
return "N/A"
def resolve_windows_redirected_path(path: pathlib.Path) -> pathlib.Path:
"""If running under Microsoft Store Python, rewrite ``path`` from its
UWP-virtualized form (what Python sees via ``os.environ['LOCALAPPDATA']``)
to the real on-disk path users can navigate to in Explorer/PowerShell.
Returns ``path`` unchanged on non-Windows or non-Store Python.
"""
exe = pathlib.Path(sys.executable)
if "WindowsApps" not in exe.parts:
return path
parts = exe.parent.name.split("_")
if len(parts) < 2:
return path
pfn = f"{parts[0]}_{parts[-1]}"
try:
local_appdata = pathlib.Path(os.environ["LOCALAPPDATA"])
rel = path.relative_to(local_appdata)
except (KeyError, ValueError):
return path
return local_appdata / "Packages" / pfn / "LocalCache" / "Local" / rel
def simplify_path(path: pathlib.Path) -> pathlib.Path:
if platform.system() == "Windows":
path = resolve_windows_redirected_path(path)
try:
return path.relative_to(pathlib.Path().absolute())
except ValueError:
return path
def command_hint(prod: str, subcmd: str, menu_label: str) -> str:
"""Render a user-facing CLI hint. Under the frozen Windows .exe, the user
typically has no Python and runs via the menu, so we point them at the
menu label instead of a command they can't type.
"""
if getattr(sys, "frozen", False):
return f"select '{menu_label}' from the menu"
return f"run `python3 {INSTALLER_NAME} {prod} {subcmd}`"
class InstallMarker:
"""Read/write the TestGen install marker file. Falls back to detecting
a legacy Docker install (compose file + credentials) from before the
marker was introduced.
"""
def __init__(self, data_folder: pathlib.Path, prod: str, compose_file_name: typing.Optional[str] = None):
self._data_folder = data_folder
self._prod = prod
self._compose_file_name = compose_file_name
self.path = data_folder / INSTALL_MARKER_FILE.format(prod)
def read(self) -> typing.Optional[str]:
if self.path.exists():
try:
data = json.loads(self.path.read_text())
except Exception:
LOG.exception("Failed to read install marker at %s", self.path)
else:
install_mode = data.get("install_mode")
if install_mode in (INSTALL_MODE_DOCKER, INSTALL_MODE_PIP):
return install_mode
LOG.warning("Install marker has unexpected install_mode: %r", install_mode)
if (
self._compose_file_name
and (self._data_folder / self._compose_file_name).exists()
and (self._data_folder / CREDENTIALS_FILE.format(self._prod)).exists()
):
LOG.info("No marker present; detected legacy Docker install in %s", self._data_folder)
return INSTALL_MODE_DOCKER
return None
def write(self, mode: str, **extra) -> None:
if mode not in (INSTALL_MODE_DOCKER, INSTALL_MODE_PIP):
raise ValueError(f"Unknown install_mode: {mode}")
now = datetime.datetime.now(datetime.timezone.utc).isoformat()
created_on = now
if self.path.exists():
try:
existing = json.loads(self.path.read_text())
if isinstance(existing.get("created_on"), str):
created_on = existing["created_on"]
except Exception:
LOG.exception("Failed to read existing install marker at %s", self.path)
self.path.write_text(
json.dumps(
{"install_mode": mode, "created_on": created_on, "last_updated_on": now, **extra},
indent=2,
)
)
def unlink(self) -> None:
if self.path.exists():
self.path.unlink()
@contextlib.contextmanager
def stream_iterator(proc: subprocess.Popen, stream_name: str, file_path: pathlib.Path, timeout: float = 1.0):
comm_index, exc_attr = {
"stdout": (0, "output"),
"stderr": (1, "stderr"),
}[stream_name]
buffer = io.TextIOWrapper(io.BytesIO())
def _iter():
proc_exited = False
read_pos = 0
while not proc_exited:
try:
partial = proc.communicate(timeout=timeout)[comm_index]
except subprocess.TimeoutExpired as exc:
partial = getattr(exc, exc_attr)
else:
proc_exited = True
if partial is not None:
buffer.buffer.seek(0)
buffer.buffer.write(partial)
buffer.seek(read_pos)
while True:
try:
line = buffer.readline()
# When some unicode char is incomplete, we skip yielding
except UnicodeDecodeError:
break
# When the line is empty we skip yielding
# When the line is incomplete and the process is still running, we skip yielding
if not line or (not line.endswith(os.linesep) and not proc_exited):
break
yield line.strip(os.linesep)
read_pos = buffer.tell()
iterator = _iter()
try:
yield iterator
finally:
# Making sure all output was consumed before writing the buffer to the file
for _ in iterator:
pass
if buffer.buffer.tell():
file_path.write_bytes(buffer.buffer.getvalue())
#
# Core building blocks
#
class Console:
MARGIN = " | "
def __init__(self):
self._last_is_space = False
self._partial_msg = None
def title(self, text):
LOG.info("Console title: [%s]", text)
# Always blank-line before a title so they are separated from any input() prompts
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 print_log(self, log_path: pathlib.Path) -> None:
with log_path.open() as log_file:
print("")
for line in log_file:
line = line.strip()
if line:
print(line)
print("")
self._last_is_space = True
@contextlib.contextmanager
def start_partial(self):
print(self.MARGIN, end="")
if self._partial_msg is not None:
raise ValueError("Console partial is already started.")
self._partial_msg = ""
try:
yield self.partial
finally:
print("")
LOG.info("Console message: [%s]", self._partial_msg)
self._partial_msg = None
self._last_is_space = False
def partial(self, text):
if self._partial_msg is None:
raise ValueError("Console partial has not been started.")
print(text, end="")
sys.stdout.flush()
self._partial_msg += text
@contextlib.contextmanager
def tee(self, file_path, append=False):
tee_lines = ["" if append else None]
def console_tee(text, skip_logging=False):
tee_lines.append(text)
return self.msg(text, skip_logging=skip_logging)
self.space()
try:
yield console_tee
finally:
self.space()
try:
with open(file_path, "a" if append else "w") as file:
file.writelines([f"{text}\n" for text in tee_lines if text is not None])
except Exception:
LOG.exception("Error tee'ing content to %s", file_path)
CONSOLE = Console()
@dataclasses.dataclass
class Requirement:
key: str
cmd: tuple[typing.Union[str, pathlib.Path], ...]
fail_msg: tuple[str, ...]
label: typing.Optional[str] = None
#: Second way of satisfying the same requirement, tried when ``cmd`` fails.
alt_cmd: typing.Optional[tuple[typing.Union[str, pathlib.Path], ...]] = None
def check_availability(self, action, args, quiet=False):
for cmd in (c for c in (self.cmd, self.alt_cmd) if c is not None):
try:
action.run_cmd_retries(
*(seg.format(**args.__dict__) for seg in cmd),
timeout=REQ_CHECK_TIMEOUT,
retries=1,
)
except CommandFailed:
continue
else:
return True
if not quiet:
CONSOLE.space()
for line in self.fail_msg:
CONSOLE.msg(line.format(**args.__dict__))
return False
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: typing.Union[int, None] = None,
cmd: typing.Union[str, None] = None,
ret_code: typing.Union[int, None] = None,
):
if any((idx, cmd, ret_code)) and not all((idx, cmd)):
raise ValueError(f"{self.__class__.__name__} requires 'idx' and 'cmd' to be set unless all args are 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 AnalyticsWrapper:
def __init__(self, action, args):
self.action = action
self.args = args
def _hash_value(self, value: typing.Union[bytes, str], digest_size: int = 8) -> str:
if isinstance(value, str):
value = value.encode()
return hashlib.blake2b(value, salt=self.get_instance_id().encode(), digest_size=digest_size).hexdigest()
@functools.cache
def get_distinct_id(self):
return self._hash_value(DEFAULT_USER_DATA["username"])
@functools.cache
def get_instance_id(self):
instance_id_file = self.action.logs_folder / INSTANCE_ID_FILE
try:
return instance_id_file.read_text().strip()
except FileNotFoundError:
instance_id = random.randbytes(8).hex()
instance_id_file.write_text(f"{instance_id}\n")
return instance_id
def __enter__(self):
self._start = time.time()
self.additional_properties = {}
self.action.analytics = self
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type is None:
event_name = f"{self.args.prod}-{self.action.args_cmd}"
elif exc_type is AbortAction:
event_name = "aborted"
else:
event_name = "failed"
if self.args.send_analytics_data:
properties = {
"prod": self.args.prod,
"action": self.action.args_cmd,
"elapsed": time.time() - self._start,
"os_version": platform.release(),
"os_arch": platform.machine(),
"$os": platform.system(),
"python_info": f"{platform.python_implementation()} {platform.python_version()}",
"installer_version": get_installer_version(),
"distinct_id": self.get_distinct_id(),
"instance_id": self.get_instance_id(),
**self.additional_properties,
}
error_chain = []
while exc_val is not None:
error_chain.append(f"{exc_type.__name__}: {exc_val}")
exc_val = exc_val.__cause__
if error_chain:
properties["error"] = " caused by ".join(error_chain)
self.send_mp_event(event_name, properties)
return False
def get_ssl_context(self):
ssl_context = ssl.create_default_context()
ssl_context.check_hostname = False
ssl_context.verify_mode = ssl.CERT_NONE
return ssl_context
def send_mp_request(self, endpoint, payload):
post_data = urllib.parse.urlencode({"data": base64.b64encode(json.dumps(payload).encode()).decode()}).encode()
req = urllib.request.Request(f"{MIXPANEL_URL}/{endpoint}", data=post_data, method="POST")
req.add_header("Content-Type", "application/x-www-form-urlencoded")
resp = urllib.request.urlopen(req, context=self.get_ssl_context(), timeout=MIXPANEL_TIMEOUT)
if resp.code != 200:
raise Exception(resp.reason)
def send_mp_event(self, event_name, properties):
track_payload = {
"event": event_name,
"properties": {
"token": MIXPANEL_TOKEN,
**properties,
},
}
try:
self.send_mp_request("track?ip=1", track_payload)
except Exception as e:
LOG.debug("Failed to send analytics event '%s': %s", event_name, e)
else:
LOG.debug(
"Sent analytics event '%s' with properties %s",
event_name,
properties.keys(),
)
class Action:
_cmd_idx: int = 0
args_cmd: str
args_parser_parents: list = []
requirements: list[Requirement] = []
@contextlib.contextmanager
def init_session_folder(self, prefix):
if "Windows" == platform.system():
self.data_folder = pathlib.Path(os.environ["LOCALAPPDATA"], "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",
# Default is locale.getpreferredencoding(), which is
# cp1252 on US Windows — chokes on non-ASCII chars like
# ✓ that the installer prints in prereq status lines.
"encoding": "utf-8",
},
"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 _get_failed_cmd_log_file_path(
self, exception: Exception
) -> typing.Union[tuple[CommandFailed, pathlib.Path], tuple[None, None]]:
while exception:
if isinstance(exception, CommandFailed):
break
else:
exception = exception.__cause__
if exception:
for stream in ("stderr", "stdout"):
try:
(log_file_path,) = self.session_folder.glob(f"{exception.idx:04d}-{stream}-*.txt")
except ValueError:
continue
else:
return exception, log_file_path
return None, None
def _msg_unexpected_error(self, exception: Exception) -> None:
cmd_exception, log_path = self._get_failed_cmd_log_file_path(exception)
if cmd_exception and log_path:
CONSOLE.msg(
f"Command '{cmd_exception.cmd}' failed with code {cmd_exception.ret_code}. See the output below."
)
CONSOLE.print_log(log_path)
else:
root = exception
while root.__cause__ is not None:
root = root.__cause__
if str(root).strip():
CONSOLE.space()
CONSOLE.msg(f"Error: {root}")
msg_file_path = simplify_path(self.session_zip)
CONSOLE.space()
CONSOLE.msg("For assistance, send the logs to open-source-support@datakitchen.io or reach out")
CONSOLE.msg("to the #support channel on https://data-observability-slack.datakitchen.io/join.")
CONSOLE.msg(f"The logs can be found in {msg_file_path}.")
def get_requirements(self, args) -> list[Requirement]:
return self.requirements
def check_requirements(self, args):
missing_reqs = [req.key for req in self.get_requirements(args) if not req.check_availability(self, args)]
if missing_reqs:
self.analytics.additional_properties["missing_requirements"] = missing_reqs
raise AbortAction
# Names of instance attributes that hold per-invocation state. Reset
# before each run so the same Action instance can be re-invoked cleanly
# in menu mode (Windows .exe) without state from the previous run leaking
# into the next. Subclasses extend this tuple with their own attrs.
_per_invocation_attrs: tuple[str, ...] = ("_cmd_idx",)
def _reset_per_invocation_state(self):
for attr in self._per_invocation_attrs:
self.__dict__.pop(attr, None)
def execute_with_log(self, args):
self._reset_per_invocation_state()
with (
self.init_session_folder(prefix=f"{args.prod}-{self.args_cmd}"),
self.configure_logging(debug=args.debug),
AnalyticsWrapper(self, args),
):
# 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(),
)
LOG.info("Installer version: %s", get_installer_version())
try:
self.check_requirements(args)
self.execute(args)
except AbortAction:
raise
except InstallerError as e:
self._msg_unexpected_error(e)
raise
except Exception as e:
LOG.exception("Uncaught error: %r", e)
self._msg_unexpected_error(e)
raise InstallerError from e
except KeyboardInterrupt as e:
# Reset the cursor to column 0 — the terminal echoed `^C` mid-line.
print("")
CONSOLE.msg("Processing interrupted. This may result in an inconsistent application state.")
raise AbortAction from e
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_retries(self, *cmd, timeout, retries, raise_on_non_zero=True, env=None, **popen_args):
cmd_fail_exception = None
while retries > 0:
try:
with self.start_cmd(*cmd, raise_on_non_zero=raise_on_non_zero, env=env, **popen_args) as (proc, *_):
try:
proc.wait(timeout=timeout)
except subprocess.TimeoutExpired as e:
LOG.warning("Command timed out. [%d] remaining attempts", retries - 1)
proc.kill()
raise CommandFailed from e
except CommandFailed as e:
cmd_fail_exception = e
else:
cmd_fail_exception = None
break
finally:
retries -= 1
if cmd_fail_exception and (
isinstance(cmd_fail_exception.__cause__, subprocess.TimeoutExpired) or raise_on_non_zero
):
raise cmd_fail_exception
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)
if echo:
for line in stdout:
if line:
CONSOLE.msg(line)
elif capture_text:
return "\n".join(stdout)
elif capture_json:
try:
return json.loads("".join(stdout))
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))
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, redact=(), **popen_args):
started = time.time()
self._cmd_idx += 1
# Censor secrets before they reach logs
log_str = " ".join(str(part) for part in cmd)
for secret in redact:
if secret:
log_str = log_str.replace(str(secret), "***")
LOG.debug("Command [%04d]: [%s]", self._cmd_idx, log_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, log_str, None) from e
slug_cmd = re.sub(r"[^a-zA-Z]+", "-", log_str)[:100].strip("-")
stdout_path, stderr_path = [
self.session_folder.joinpath(f"{self._cmd_idx:04d}-{stream_name}-{slug_cmd}.txt")
for stream_name in ("stdout", "stderr")
]
try:
try:
with (
stream_iterator(proc, "stdout", stdout_path) as stdout_iter,
stream_iterator(proc, "stderr", stderr_path) as stderr_iter,
):
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, log_str, proc.returncode) from e.__cause__
finally:
elapsed = time.time() - started
LOG.info(
"Command [%04d] returned [%s] in [%.3f] seconds. [%d] bytes in STDOUT, [%d] bytes in STDERR",
self._cmd_idx,
proc.returncode,
elapsed,
stdout_path.stat().st_size if stdout_path.exists() else 0,
stderr_path.stat().st_size if stderr_path.exists() else 0,
)
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.__class__.__name__
class MultiStepAction(Action):
steps: list[type[Step]]
label: str = "Process"
title: str = ""
intro_text: list[str] = []
def __init__(self):
super().__init__()
self.ctx = {}
def _reset_per_invocation_state(self):
super()._reset_per_invocation_state()
self.ctx = {}
def _print_intro_text(self, args):
CONSOLE.space()