This repository has been archived by the owner on Sep 29, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
install.py
executable file
·1476 lines (1320 loc) · 51 KB
/
install.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 shutil
import venv
import platform
import subprocess
import tempfile
import time
from collections import namedtuple
import logging
import argparse
from typing import Optional, Tuple, Union, List, Dict, Pattern
from pathlib import Path
from threading import Thread
import re
import os
import sys
VENV_NAME: str = "ZoMi_Client"
# Change these if you want to install to a different default location
# You can also specify these locations via CLI
DEFAULT_DATA_DIR = "/opt/zomi/client"
DEFAULT_MODEL_DIR = f"{DEFAULT_DATA_DIR}/models"
DEFAULT_CONFIG_DIR = f"{DEFAULT_DATA_DIR}/conf"
DEFAULT_LOG_DIR = f"{DEFAULT_DATA_DIR}/logs"
DEFAULT_TMP_DIR = f"{tempfile.gettempdir()}/zomi/client"
DEFAULT_IMG_DIR = f"{DEFAULT_DATA_DIR}/images"
DEFAULT_SYSTEM_CREATE_PERMISSIONS = 0o755
# config files will have their permissions adjusted to this
DEFAULT_CONFIG_CREATE_PERMISSIONS = 0o755
REPO_BASE = Path(__file__).parent.parent
EXAMPLES_DIR = Path(__file__).parent
_ENV = {}
THREADS: Dict[str, Thread] = {}
FORBIDDEN_DESTS = ('/*', '/')
_simple_re: Pattern = re.compile(r"(?<!\\)\$([A-Za-z0-9_]+)")
_extended_re: Pattern = re.compile(r"(?<!\\)\$\{([A-Za-z0-9_]+)((:?-)([^}]+))?}")
# Logging
logger = logging.getLogger("install_client")
logger.setLevel(logging.INFO)
log_formatter = logging.Formatter(
"%(asctime)s.%(msecs)04d %(name)s[%(process)s] %(levelname)s %(module)s:%(lineno)d -> %(message)s",
"%m/%d/%y %H:%M:%S",
)
console = logging.StreamHandler(stream=sys.stdout)
console.setFormatter(log_formatter)
logger.addHandler(console)
# Misc.
__dependencies__ = "psutil", "requests", "tqdm", "distro", "venv"
__doc__ = """Install ZoMi Machine Learning Client - Custom"""
# Logic
tst_msg_wrap = "[testing!!]", "[will not actually execute]"
# parse .env file using python-dotenv
def parse_env_file(env_file: Path) -> None:
"""Parse .env file using python-dotenv.
:param env_file: Path to .env file.
:type env_file: Path
:returns: Dict of parsed .env file.
"""
try:
import dotenv
except ImportError:
logger.warning(f"python-dotenv not installed, skipping {env_file}")
else:
global _ENV
dotenv_vals = dotenv.dotenv_values(env_file)
_ENV.update(dotenv_vals)
def test_msg(msg_: str, level: Optional[Union[str, int]] = None):
"""Print test message. Changes stack level to 2 to show caller of test_msg."""
if testing:
logger.warning(f"{tst_msg_wrap[0]} {msg_} {tst_msg_wrap[1]}", stacklevel=2)
else:
if level in ("debug", logging.DEBUG, None):
logger.debug(msg_, stacklevel=2)
elif level in ("info", logging.INFO):
logger.info(msg_, stacklevel=2)
elif level in ("warning", logging.WARNING):
logger.warning(msg_, stacklevel=2)
elif level in ("error", logging.ERROR):
logger.error(msg_, stacklevel=2)
elif level in ("critical", logging.CRITICAL):
logger.critical(msg_, stacklevel=2)
else:
logger.info(msg_, stacklevel=2)
def get_distro() -> namedtuple:
if hasattr(platform, "freedesktop_os_release"):
release_data = platform.freedesktop_os_release()
else:
import distro
release_data = {"ID": distro.id()}
nmd_tpl = namedtuple("Distro", release_data.keys())
return nmd_tpl(**release_data)
def check_imports():
import importlib
ret = True
_missing = []
for imp_name in __dependencies__:
try:
importlib.import_module(imp_name)
except ImportError:
_missing.append(imp_name)
ret = False
else:
logger.debug(f"Found python module dependency: {imp_name}")
if _missing:
logger.error(
f"Missing python module dependencies: {_missing}"
f":: Please install the python package(s)"
)
return ret
def get_web_user() -> Tuple[Optional[str], Optional[str]]:
"""Get the user that runs the web server using psutil library.
:returns: The user that runs the web server.
:rtype: str
"""
import psutil
import grp
# get group name from gid
www_daemon_names = ("httpd", "hiawatha", "apache", "nginx", "lighttpd", "apache2")
hits = []
proc_names = []
for proc in psutil.process_iter():
if any(x.startswith(proc.name()) for x in www_daemon_names):
uname, ugroup = proc.username(), grp.getgrgid(proc.gids().real).gr_name
logger.debug(f"Found web server process: {proc.name()} ({uname}:{ugroup})")
hits.append((uname, ugroup))
proc_names.append(proc.name())
proc_names = list(set(proc_names))
if len(hits) > 1:
import pwd
# sort by uid high to low (only use root if we have to)
hits = sorted(hits, key=lambda x: pwd.getpwnam(x[0]).pw_uid, reverse=True)
logger.warning(
f"Multiple web server processes found ({proc_names}) - The list is sorted to account "
f"for root dropping privileges. Hopefully the first entry is the correct one -> {hits}"
)
if hits:
return hits[0]
return None, None
def parse_cli():
global args
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--venv-only", action="store_true", help="Only create the VENV", dest="venv_only")
parser.add_argument("--mlapi-user", help="API user", type=str, default=None, dest="api_user")
parser.add_argument("--mlapi-pass", help="API password", type=str, default=None, dest="api_pass")
parser.add_argument(
"--route-name", "--mlapi-name",
dest="route_name",
default=None,
type=str,
help="MLAPI route name [Optional]",
)
# address and port as well as the route name
parser.add_argument(
"--route-host", "--mlapi-host",
dest="route_host",
default=None,
type=str,
help="MLAPI host address [Optional]",
)
parser.add_argument(
"--route-port", "--mlapi-port",
dest="route_port",
default=None,
type=str,
help="MLAPI host port [Optional]",
)
parser.add_argument(
"--no-cache-dir",
action="store_true",
dest="no_cache",
help="Do not use cache directory for pip install",
)
parser.add_argument(
"--editable",
action="store_true",
dest="pip_install_editable",
help="Use the --editable flag when installing via pip (a git pull will update "
"the installed package) BE AWARE: you must keep the git source directory intact for this to work",
)
parser.add_argument(
"--zm-portal",
dest="zm_portal",
default=None,
type=str,
help="ZoneMinder portal URL [Optional]",
)
parser.add_argument(
"--zm-api",
dest="zm_api",
default=None,
type=str,
help="ZoneMinder API URL, If this is omitted and --zm-portal "
"is specified, the API URL will be derived from the portal URL (--zm-portal + '/api')",
)
parser.add_argument(
"--zm-user",
dest="zm_user",
default=None,
type=str,
help="ZoneMinder API user [Optional]",
)
parser.add_argument(
"--zm-pass",
dest="zm_pass",
default=None,
type=str,
help="ZoneMinder API password [Optional]",
)
parser.add_argument(
"--config-only",
dest="config_only",
action="store_true",
help="Install config files only, used in conjunction with --secret-only",
)
parser.add_argument(
"--secrets-only",
dest="secrets_only",
action="store_true",
help="Install secrets file only, used in conjunction with --config-only",
)
parser.add_argument(
"--interactive",
"-I",
action="store_true",
dest="interactive",
help="Run in interactive mode",
)
parser.add_argument(
"--install-log",
type=str,
default=f"./zomi-client_install.log",
help="File to write installation logs to",
)
parser.add_argument(
"--env-file", type=Path, help="Path to .env file (requires python-dotenv)"
)
parser.add_argument(
"--dir-data",
help=f"Directory where variable data is held Default: {DEFAULT_DATA_DIR}",
dest="data_dir",
default=DEFAULT_DATA_DIR,
type=Path,
)
parser.add_argument(
"--dir-config",
help=f"Directory where config files are held Default: {DEFAULT_CONFIG_DIR}",
default=DEFAULT_CONFIG_DIR,
type=Path,
dest="config_dir",
)
parser.add_argument(
"--dir-model",
type=str,
help="ML model base directory",
default=DEFAULT_MODEL_DIR,
dest="model_dir",
)
parser.add_argument(
"--dir-image",
"--dir-images",
type=str,
help="Directory where images are stored",
default=DEFAULT_IMG_DIR,
dest="image_dir",
)
parser.add_argument(
"--dir-temp",
"--dir-tmp",
type=Path,
help="Temp files directory",
default=DEFAULT_TMP_DIR,
dest="tmp_dir",
)
parser.add_argument(
"--dir-log",
help=f"Directory where logs will be stored Default: {DEFAULT_LOG_DIR}",
default=DEFAULT_LOG_DIR,
dest="log_dir",
type=Path,
)
parser.add_argument(
"--user",
"-U",
help="User to install as [leave empty to auto-detect what user runs "
"the web server]",
type=str,
dest="system_user",
default="",
)
parser.add_argument(
"--group",
"-G",
help="Group member to install as [leave empty to auto-detect what "
"group member runs the web server]",
type=str,
dest="system_group",
default="",
)
parser.add_argument(
"--debug", "-D", help="Enable debug logging", action="store_true", dest="debug"
)
parser.add_argument(
"--dry-run",
"--test",
"-T",
action="store_true",
dest="test",
help="Run in test mode, no actions are actually executed.",
)
parser.add_argument(
"--system-create-permissions",
help=f"ZoMi ML system octal [0o] file permissions [Default: {oct(DEFAULT_SYSTEM_CREATE_PERMISSIONS)}]",
type=lambda x: int(x, 8),
default=DEFAULT_SYSTEM_CREATE_PERMISSIONS,
)
parser.add_argument(
"--config-create-permissions",
help=f"Config files (client.yml, secrets.yml) octal [0o] file permissions "
f"[Default: {oct(DEFAULT_CONFIG_CREATE_PERMISSIONS)}]",
type=lambda x: int(x, 8),
default=DEFAULT_CONFIG_CREATE_PERMISSIONS,
)
return parser.parse_args()
def chown(path: Path, user: Union[str, int], group: Union[str, int]):
import pwd
import grp
if isinstance(user, str):
user = pwd.getpwnam(user).pw_uid
if isinstance(group, str):
group = grp.getgrnam(group).gr_gid
test_msg(f"chown {user}:{group} {path}")
if not testing:
os.chown(path, user, group)
def chmod(path: Path, mode: int):
test_msg(f"chmod OCTAL: {mode:o} RAW: {mode} => {path}")
if not testing:
os.chmod(path, mode)
def chown_mod(path: Path, user: Union[str, int], group: Union[str, int], mode: int):
chown(path, user, group)
chmod(path, mode)
def create_dir(path: Path, user: Union[str, int], group: Union[str, int], mode: int):
message = (
f"Created directory: {path} with user:group:permission "
f"[{user}:{group}:{mode:o}]"
)
test_msg(message)
if not testing:
path.mkdir(parents=True, exist_ok=True, mode=mode)
chown_mod(path, user, group, mode)
def show_config(cli_args: argparse.Namespace):
logger.info(f"Configuration:")
for key, value in vars(cli_args).items():
if key.endswith("_permissions"):
value = oct(value)
elif key == "models":
value = ", ".join(value)
elif isinstance(value, Path):
value = value.expanduser().resolve().as_posix()
logger.info(f" {key}: {value.__repr__()}")
if args.interactive:
input(
"Press Enter to continue if all looks fine, otherwise use 'Ctrl+C' to exit and edit CLI options..."
)
else:
_msg_ = f"This is a non-interactive{' TEST' if testing else ''} session, continuing with installation... "
if testing:
logger.info(_msg_)
else:
logger.info(f"{_msg_} in 5 seconds, press 'Ctrl+C' to exit")
time.sleep(5)
def do_web_user():
global install_as_user, install_as_group
_group = None
if not install_as_user or not install_as_group:
if not install_as_user:
if interactive:
install_as_user = input("Web server username [Leave blank to try auto-find]: ")
if not install_as_user:
install_as_user, _group = get_web_user()
logger.info(f"Web server user auto-find: {install_as_user}")
else:
install_as_user, _group = get_web_user()
logger.info(f"Web server user auto-find: {install_as_user}")
if not install_as_group:
if interactive:
install_as_group = input("Web server group [Leave blank to try auto-find]: ")
if not install_as_group:
if _group:
install_as_group = _group
else:
_, install_as_group = get_web_user()
logger.info(f"Web server group auto-find: {install_as_group}")
else:
if _group:
install_as_group = _group
else:
_, install_as_group = get_web_user()
logger.info(f"Web server group auto-find: {install_as_group}")
if not install_as_user or not install_as_group:
_missing = ""
_u = "user [--user]"
_g = "group [--group]"
if not install_as_user and install_as_group:
_missing = _u
elif install_as_user and not install_as_group:
_missing = _g
else:
_missing = f"{_u} and {_g}"
_mess = f"Unable to determine web server {_missing}, please specify manually!"
if not testing:
logger.exception(_mess)
sys.exit(1)
else:
test_msg(_mess)
def install_dirs(
dest_dir: Path,
default_dir: str,
dir_type: str,
sub_dirs: Optional[List[str]] = None,
perms: int = 0o755,
):
"""Create directories with sub dirs"""
if sub_dirs is None:
sub_dirs = []
if not dest_dir:
if interactive:
dest_dir = input(
f"Set {dir_type} directory [Leave blank to use default {default_dir}]: "
)
if not dest_dir:
if default_dir:
logger.info(f"Using default {dir_type} directory: {default_dir}")
dest_dir = default_dir
else:
raise ValueError(f"Default {dir_type} directory not set!")
dest_dir = Path(dest_dir)
if dir_type.casefold() == "data":
global data_dir
data_dir = dest_dir
elif dir_type.casefold() == "log":
global log_dir
log_dir = dest_dir
elif dir_type.casefold() == "config":
global cfg_dir
cfg_dir = dest_dir
if not dest_dir.exists():
logger.warning(f"{dir_type} directory {dest_dir} does not exist!")
if interactive:
x = input(f"Create {dir_type} directory [Y/n]?... 'n' will exit! ")
if x.strip().casefold() == "n":
logger.error(f"{dir_type} directory does not exist, exiting...")
sys.exit(1)
create_dir(dest_dir, install_as_user, install_as_group, perms)
else:
test_msg(f"Creating {dir_type} directory...")
create_dir(dest_dir, install_as_user, install_as_group, perms)
else:
logger.warning(f"{dir_type} directory {dest_dir} already exists!")
# create sub-folders
if sub_dirs:
test_msg(
f"Creating {dir_type} sub-folders: {', '.join(sub_dirs).lstrip(',')}"
)
for _sub in sub_dirs:
_path = dest_dir / _sub
create_dir(_path, install_as_user, install_as_group, perms)
def download_file(url: str, dest: Path, user: str, group: str, mode: int):
_mess_ = (
f"Downloading {url}..."
if not testing
else f"TESTING if file exists at -> {url}..."
)
logger.info(_mess_)
import requests
from tqdm.auto import tqdm
import shutil
import functools
try:
r = requests.get(url, stream=True, allow_redirects=True, timeout=5)
if r:
file_size = int(r.headers.get("Content-Length", 0))
dest = dest.expanduser().resolve()
dest.parent.mkdir(parents=True, exist_ok=True)
desc = (
"(Unknown total file size!)"
if file_size == 0
else f"Downloading {url} ..."
)
r.raw.read = functools.partial(
r.raw.read, decode_content=True
) # Decompress if needed
with tqdm.wrapattr(
r.raw, "read", total=file_size, desc=desc, colour="green"
) as r_raw:
do_chown = True
if testing:
do_chown = False
logger.info(
f"TESTING: File exists at the url for {url.split('/')[-1]}"
)
# to keep the progress bar, pipe output to /dev/null
dest = Path("/dev/null")
try:
with dest.open("wb") as f:
shutil.copyfileobj(r_raw, f)
except Exception as e:
logger.error(
f"Failed to open or copy data to destination file ({dest}) => {e}"
)
raise e
else:
logger.info(f"Successfully downloaded {url} to {dest}")
if do_chown:
chown_mod(dest, user, group, mode)
else:
logger.error(f"NO RESPONSE FROM {url} :: Failed to download {url}!")
except requests.exceptions.ConnectionError:
logger.error(f"REQUESTS CONNECTION ERROR :: Failed to download {url}!")
return
except Exception as e:
logger.error(f"Failed to download {url}! EXCEPTION :: {e}")
def copy_file(src: Path, dest: Path, user: str, group: str, mode: int):
"""Copy a file from src to dest, chown and chmod it using user:group and mode."""
__msg = f"Copying {src} to {dest}..."
if not testing:
# Check if the file exists, if so, show a log warning and remove, then copy
import shutil
if dest.exists():
logger.warning(f"File {dest} already exists, removing...")
if dest not in FORBIDDEN_DESTS:
dest.unlink()
else:
raise ValueError(f"Invalid destination file: {dest}")
logger.info(__msg)
shutil.copy(src, dest)
chown_mod(dest, user, group, mode)
else:
test_msg(__msg)
def get_pkg_manager():
distro = get_distro()
binary, prefix = "apt", ["install", "-y"]
if distro.ID in ("debian", "ubuntu", "raspbian"):
pass
elif distro.ID in ("centos", "fedora", "rhel"):
binary = "yum"
elif distro.ID == "fedora":
binary = "dnf"
elif distro.ID in ("arch", "manjaro"):
binary = "pacman"
prefix = ["-S", "--noconfirm"]
elif distro.ID == "gentoo":
binary = "emerge"
prefix = ["-av"]
elif distro.ID == "alpine":
binary = "apk"
prefix = ["add", "-q"]
elif distro.ID == "suse":
binary = "zypper"
elif distro.ID == "void":
binary = "xbps-install"
prefix = ["-y"]
elif distro.ID == "nixos":
binary = "nix-env"
prefix = ["-i"]
elif distro.ID == "freebsd":
binary = "pkg"
elif distro.ID == "openbsd":
binary = "pkg_add"
prefix = []
elif distro.ID == "netbsd":
binary = "pkgin"
elif distro.ID == "solus":
binary = "eopkg"
elif distro.ID == "windows":
binary = "choco"
elif distro.ID == "macos":
binary = "brew"
return binary, prefix
def install_host_dependencies(_type: str):
_type = _type.strip().casefold()
if _type == "secrets":
return
if _type not in ["server", "client"]:
logger.error(f"Invalid type '{_type}'")
else:
inst_binary, inst_prefix = get_pkg_manager()
dependencies = {
"apt": {
"client": {
"binary_names": ["gifsicle", "geos-config"],
"binary_flags": ["--version", "--version"],
"pkg_names": ["gifsicle", "libgeos-dev"],
},
"server": {
"binary_names": [],
"binary_flags": [],
"pkg_names": [],
},
},
"yum": {
"client": {
"binary_names": ["gifsicle", "geos-config"],
"binary_flags": ["--version", "--version"],
"pkg_names": ["gifsicle", "geos-devel"],
},
"server": {
"binary_names": [],
"binary_flags": [],
"pkg_names": [],
},
},
"pacman": {
"client": {
"binary_names": ["gifsicle", "geos-config"],
"binary_flags": ["--version", "--version"],
"pkg_names": ["gifsicle", "geos"],
},
"server": {
"binary_names": [],
"binary_flags": [],
"pkg_names": [],
},
},
"zypper": {
"client": {
"binary_names": ["gifsicle", "geos-config"],
"binary_flags": ["--version", "--version"],
"pkg_names": ["gifsicle", "geos"],
},
"server": {
"binary_names": [],
"binary_flags": [],
"pkg_names": [],
},
},
"dnf": {
"client": {
"binary_names": ["gifsicle", "geos-config"],
"binary_flags": ["--version", "--version"],
"pkg_names": ["gifsicle", "geos-devel"],
},
"server": {
"binary_names": [],
"binary_flags": [],
"pkg_names": [],
},
},
"apk": {
"client": {
"binary_names": ["gifsicle", "geos-config"],
"binary_flags": ["--version", "--version"],
"pkg_names": ["gifsicle", "geos-devel"],
},
"server": {
"binary_names": [],
"binary_flags": [],
"pkg_names": [],
},
},
}
deps = []
deps_cmd = []
if _type == "server":
_msg = "Installing server HOST dependencies..."
test_msg(_msg)
full_deps = zip(
dependencies[inst_binary]["server"]["pkg_names"],
dependencies[inst_binary]["server"]["binary_names"],
dependencies[inst_binary]["server"]["binary_flags"],
)
for _dep, _bin, _flag in full_deps:
deps_cmd.append([_bin, _flag])
deps.append(_dep)
elif _type == "client":
_msg = "Testing for client HOST dependencies..."
test_msg(_msg)
full_deps = zip(
dependencies[inst_binary]["client"]["pkg_names"],
dependencies[inst_binary]["client"]["binary_names"],
dependencies[inst_binary]["client"]["binary_flags"],
)
for _dep, _bin, _flag in full_deps:
deps_cmd.append([_bin, _flag])
deps.append(_dep)
else:
logger.error(f"Invalid type '{_type}'")
return
def test_cmd(cmd_array: List[str], dep_name: str):
logger.debug(
f"Testing if dependency {_dep_name} is installed by running: {' '.join(cmd_array)}"
)
try:
x = subprocess.run(cmd_array, check=True, capture_output=True)
except subprocess.CalledProcessError as proc_err:
logger.error(f"Error while running {cmd_array} -> {proc_err}")
except FileNotFoundError:
logger.error(
f"Failed to locate {cmd_array[0]} please install HOST package: {dep_name}"
)
raise
except Exception as exc_:
logger.error(f"Exception type: {type(exc_)} --- {exc_}")
raise exc_
else:
logger.info(f"{cmd_array[0]} is installed")
logger.debug(f"{cmd_array} output: {x.stdout.decode('utf-8')}")
if deps:
full_deps = zip(deps_cmd, deps)
for _cmd_array, _dep_name in full_deps:
try:
test_cmd(_cmd_array, _dep_name)
except FileNotFoundError:
msg = f"package '{_dep_name}' is not installed, please install it manually!"
if os.geteuid() != 0 and not testing:
logger.warning(
f"You must be root to install host dependencies! {msg}"
)
else:
if testing:
logger.warning(
f"Running as non-root user but this is test mode! continuing to test... "
)
install_cmd = [inst_binary]
install_cmd.extend(inst_prefix)
install_cmd.append(_dep_name)
msg = f"Running HOST package manager installation command: {install_cmd}"
if not interactive:
if not testing:
logger.info(msg)
try:
subprocess.run(
install_cmd,
check=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
except subprocess.CalledProcessError as e:
logger.error(
f"Error installing host dependencies: {e.stdout.decode('utf-8')}"
)
sys.exit(1)
else:
logger.info(
"Host dependencies installed successfully"
)
else:
test_msg(msg)
else:
if not testing:
_install = False
_input = input(
f"Host dependencies are not installed, would you like to install "
f"{' '.join(deps)}? [Y/n]"
)
if _input:
_input = _input.strip().casefold()
if _input == "n":
logger.warning(
"Host dependencies not installed, please install them manually!"
)
else:
_install = True
else:
_install = True
if _install:
logger.debug(f"Running: {install_cmd}")
try:
subprocess.run(
install_cmd,
check=True,
)
except subprocess.CalledProcessError as e:
logger.error(
f"Error installing host dependencies: {e.stdout.decode('utf-8')}"
)
sys.exit(1)
else:
logger.info(
"Host dependencies installed successfully"
)
def main():
# create base dir and sub dirs
install_dirs(
data_dir,
DEFAULT_DATA_DIR,
"Data",
sub_dirs=[
"models",
"push",
"scripts",
"images",
"bin",
"misc",
],
)
# create facial data parent and sub dirs.
install_dirs(
Path(f"{DEFAULT_DATA_DIR}/face_data"),
f"{DEFAULT_DATA_DIR}/face_data",
"Face Data",
sub_dirs=["known", "unknown"],
perms=0o777,
)
# config file and logging dirs
install_dirs(
cfg_dir, DEFAULT_CONFIG_DIR, "Config", sub_dirs=[], perms=cfg_create_mode
)
install_dirs(log_dir, DEFAULT_LOG_DIR, "Log", sub_dirs=[], perms=0o777)
# backup existing config files if this is a re-install
check_backup("secrets")
# rock n roll
do_install()
def check_backup(_inst_type: str) -> None:
files: List[Optional[Path]] = [x for x in cfg_dir.rglob(f"{_inst_type}.*")]
if files:
files = sorted(files, reverse=True)
_target: Optional[Path] = None
backup_num = 1
high = 0
for _file in files:
if _file.name.startswith(f"{_inst_type}"):
if _file.suffix == ".bak":
i = int(_file.stem.split(".")[-1])
logger.debug(f"Found a {_inst_type} backup numbered: {i}")
if i > high:
high = backup_num = i + 1
logger.debug(
f"This backup has a higher number, using it as index: {backup_num = }"
)
elif _file.suffix in (".yml", ".yaml"):
logger.debug(f"found existing {_inst_type} config file: {_file}")
_target = _file
if _target:
file_backup = cfg_dir / f"{_inst_type}.{backup_num}.bak"
logger.debug(
f"Backing up existing {_inst_type} config file: {_target} to {file_backup}"
)
# Backup existing
copy_file(_target, file_backup, install_as_user, install_as_group, cfg_create_mode)
# install new
copy_file(
REPO_BASE / f"configs/example_{_inst_type}.yml",
cfg_dir / f"{_inst_type}.yml",
install_as_user,
install_as_group,
cfg_create_mode,
)
else:
logger.debug(f"No existing {_inst_type} config files found!")
if cfg_dir.is_dir() or testing:
test_msg(
f"Creating {_inst_type} config file from example template...", "info"
)
copy_file(
REPO_BASE / f"configs/example_{_inst_type}.yml",
cfg_dir / f"{_inst_type}.yml",
install_as_user,
install_as_group,
cfg_create_mode,
)
else:
logger.warning(
f"Config directory '{cfg_dir}' does not exist, skipping creation of {_inst_type} config file..."
)
def do_install():
global _ENV
_inst_type: str = "client"
check_backup("client")
install_host_dependencies(_inst_type)
copy_file(
EXAMPLES_DIR / "EventStartCommand.sh",
data_dir / "bin/EventStartCommand.sh",
install_as_user,
install_as_group,
cfg_create_mode,
)
copy_file(
EXAMPLES_DIR / "eventproc.py",
data_dir / "bin/eventproc.py",
install_as_user,
install_as_group,
cfg_create_mode,
)
create_("secrets", cfg_dir / "secrets.yml")
create_(_inst_type, cfg_dir / f"{_inst_type}.yml")
# create a symbolic link to both files in /usr/local/bin
# so that they can be called from anywhere
test_msg(
f"Creating symlinks for event start/stop commands: /usr/local/bin will contain zomi-ESC "
f"(shell helper) and zomi-eventproc (python script)",
"info",
)
if not testing:
# Make sure it does not exist first, it will error if file exists
_dest_esc = Path("/usr/local/bin/zomi-ESC")
_dest_ep = Path("/usr/local/bin/zomi-eventproc")
# if it exists log a message that it is being unlinked then symlinked again with specified user
if _dest_esc.exists():
logger.warning(
f"{_dest_esc} already exists, unlinking and sym-linking again..."
)
if _dest_esc not in FORBIDDEN_DESTS:
_dest_esc.unlink()
else:
raise ValueError(f"Invalid destination file: {_dest_esc} - Please delete the existing file yourself!")
_dest_esc.symlink_to(f"{data_dir}/bin/EventStartCommand.sh")