-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinstall.py
More file actions
executable file
·1527 lines (1406 loc) · 54.3 KB
/
install.py
File metadata and controls
executable file
·1527 lines (1406 loc) · 54.3 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 platform
import subprocess
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
_simple_re: Pattern = re.compile(r"(?<!\\)\$([A-Za-z0-9_]+)")
_extended_re: Pattern = re.compile(r"(?<!\\)\$\{([A-Za-z0-9_]+)((:?-)([^}]+))?}")
# Change these if you want to install to a different location
DEFAULT_DATA_DIR = "/opt/zm_ml/var/lib/zm_ml"
DEFAULT_CONFIG_DIR = "/opt/zm_ml/etc/zm_ml"
DEFAULT_LOG_DIR = "/opt/zm_ml/var/logs/zm_ml"
DEFAULT_SYSTEM_CREATE_PERMISSIONS = 0o755
# config files will have their permissions adjusted to this
DEFAULT_CONFIG_CREATE_PERMISSIONS = 0o755
# default ML models to install (SEE: available_models{})
DEFAULT_MODELS = ["yolov4", "yolov4_tiny", "yolov7", "yolov7_tiny"]
REPO_BASE = Path(__file__).parent.parent
INSTALL_FILE_DIR = Path(__file__).parent
ZMML_CACHE = REPO_BASE / ".zmml_cache"
INSTALL_TYPE = "client"
_ENV = {}
THREADS: Dict[str, Thread] = {}
# Do not change these unless you know what you are doing
available_models = {
"yolov4": {
"folder": "yolo",
"model": [
# "https://github.com/AlexeyAB/darknet/releases/download/yolov4/yolov4.weights",
"https://github.com/AlexeyAB/darknet/releases/download/yolov4/yolov4_new.weights",
],
"config": [
# "https://raw.githubusercontent.com/AlexeyAB/darknet/master/cfg/yolov4.cfg",
"https://raw.githubusercontent.com/AlexeyAB/darknet/master/cfg/yolov4_new.cfg",
],
},
"yolov4_tiny": {
"folder": "yolo",
"model": [
"https://github.com/AlexeyAB/darknet/releases/download/yolov4/yolov4-tiny.weights"
],
"config": [
"https://raw.githubusercontent.com/AlexeyAB/darknet/master/cfg/yolov4-tiny.cfg"
],
},
"yolov4_p6": {
"folder": "yolo",
"model": [
"https://github.com/AlexeyAB/darknet/releases/download/yolov4/yolov4-p6.weights"
],
"config": [
"https://raw.githubusercontent.com/AlexeyAB/darknet/master/cfg/yolov4-p6.cfg"
],
},
"yolov7": {
"folder": "yolo",
"model": [
"https://github.com/AlexeyAB/darknet/releases/download/yolov4/yolov7.weights"
],
"config": [
"https://raw.githubusercontent.com/AlexeyAB/darknet/master/cfg/yolov7.cfg"
],
},
"yolov7_tiny": {
"folder": "yolo",
"model": [
"https://github.com/AlexeyAB/darknet/releases/download/yolov4/yolov7-tiny.weights"
],
"config": [
"https://raw.githubusercontent.com/AlexeyAB/darknet/master/cfg/yolov7-tiny.cfg"
],
},
"yolov7x": {
"folder": "yolo",
"model": [
"https://github.com/AlexeyAB/darknet/releases/download/yolov4/yolov7x.weights"
],
"config": [
"https://raw.githubusercontent.com/AlexeyAB/darknet/master/cfg/yolov7x.cfg"
],
},
"coral_tpu": {
"folder": "coral_tpu",
"model": [
"https://github.com/google-coral/edgetpu/raw/master/test_data/ssd_mobilenet_v2_coco_quant_postprocess_edgetpu.tflite",
"https://github.com/google-coral/test_data/raw/master/ssdlite_mobiledet_coco_qat_postprocess_edgetpu.tflite",
"https://github.com/google-coral/test_data/raw/master/ssd_mobilenet_v2_face_quant_postprocess_edgetpu.tflite",
"https://github.com/google-coral/test_data/raw/master/tf2_ssd_mobilenet_v2_coco17_ptq_edgetpu.tflite",
"https://github.com/google-coral/test_data/raw/master/efficientdet_lite3_512_ptq_edgetpu.tflite",
],
"config": "https://raw.githubusercontent.com/baudneo/ZM_ML/master/examples/coco-labels-paper.txt",
},
}
# Logging
logger = logging.getLogger("install_zm_ml")
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.
__version__ = "0.0.1a1"
__dependancies__ = "psutil", "requests", "tqdm", "distro"
__doc__ = """Install ZM-ML Server / Client"""
# Logic
tst_msg_wrap = "[testing!!]", "[will not actually execute]"
# parse .env file using pyenv
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
for imp_name in __dependancies__:
try:
importlib.import_module(imp_name)
except ImportError:
_msg = (
f"Missing python module dependency: {imp_name}"
f":: Please install the python package"
)
logger.error(_msg)
print(_msg)
ret = False
else:
logger.debug(f"Found python module dependency: {imp_name}")
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)
) and proc.name() not in proc_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())
if len(hits) >= 1:
if len(hits) > 1:
logger.warning(
f"Multiple web server processes found ({proc_names}), using first one"
)
if hits:
return hits[0]
return None, None
def get_models():
global models, no_models, THREADS
# check models
if no_models:
if INSTALL_TYPE in ["server", "both"]:
logger.info(
" --no-models requested when the server is being installed?"
" Skipping model download..."
)
return
if not models:
logger.info(f"No models specified, using default models {DEFAULT_MODELS}")
if interactive:
x = input(f"Download default models? [Y/n]... ")
if x.casefold() == "n":
logger.info("Skipping model download...")
models = []
else:
models = DEFAULT_MODELS
else:
logger.info("Skipping download of default models...")
if models:
for model in models:
model = model.strip().casefold()
if model not in available_models.keys():
logger.error(
f"Invalid model '{model}' - Allowed models: {', '.join(available_models.keys())}"
)
else:
logger.info(f"Downloading model data: {model}")
model_data = available_models[model]
model_folder = model_dir / model_data["folder"]
cache_folder = ZMML_CACHE / model_data["folder"]
create_dir(cache_folder, ml_user, ml_group, 0o777)
_model = model_data["model"]
_config = model_data["config"]
if _model:
for model_url in model_data["model"]:
model_file = model_folder / Path(model_url).name
if model_file.exists():
if not force_models:
logger.warning(
f"Model file '{model_file}' already exists, skipping..."
)
continue
else:
logger.info(
f"--force-model passed via CLI - Model file '{model_file}' already exists, overwriting..."
)
else:
logger.info(
f"Model file ({model_file}) does not exist, downloading..."
)
# Thread it
THREADS[model_file.name] = Thread(
target=download_file,
args=(
model_url,
model_file,
ml_user,
ml_group,
cfg_create_mode,
),
)
THREADS[model_file.name].start()
if _config:
for config_url in model_data["config"]:
config_file = model_folder / Path(config_url).name
if config_file.exists():
if not force_models:
logger.warning(
f"Config file '{config_file}' already exists, skipping..."
)
continue
else:
logger.info(
f"--force-model passed via CLI - Config file '{config_file}' already exists, overwriting..."
)
THREADS[config_file.name] = Thread(
target=download_file,
args=(
config_url,
config_file,
ml_user,
ml_group,
cfg_create_mode,
),
)
THREADS[config_file.name].start()
def parse_cli():
global args, models
parser = argparse.ArgumentParser(description=__doc__)
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 ommited 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(
"--route-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",
dest="route_host",
default=None,
type=str,
help="MLAPI host address [Optional]",
)
parser.add_argument(
"--route-port",
dest="route_port",
default=None,
type=str,
help="MLAPI host port [Optional]",
)
parser.add_argument(
"--config-only",
dest="config_only",
action="store_true",
help="Install config files only, used in conjunction with --install-type and --secret-only",
)
parser.add_argument(
"--secrets-only",
dest="secrets_only",
action="store_true",
help="Install secrets file only, used in conjunction with --install-type and --config-only",
)
parser.add_argument(
"--interactive",
"-I",
action="store_true",
dest="interactive",
help="Run in interactive mode",
)
parser.add_argument(
"--models-only",
"--only-models",
dest="models_only",
action="store_true",
help="Install models only",
)
parser.add_argument(
"--add-model",
action="append",
dest="models",
help=f"Download model files (can be used several time --add-model yolov4 --add-model yolov7_tiny) Default: {' '.join(DEFAULT_MODELS)}",
default=DEFAULT_MODELS,
choices=available_models.keys(),
)
parser.add_argument(
"--all-models",
action="store_true",
dest="all_models",
help="Download all available model files",
)
parser.add_argument(
"--text-models",
type=str,
dest="text_models",
help="Download model files designated by a comma delimited string of model names [yolov4,yolov7,etc]",
)
parser.add_argument(
"--force-models",
action="store_true",
dest="force_models",
help="Force model installation [Overwrite existing model files]",
)
parser.add_argument(
"--no-models",
dest="no_models",
action="store_true",
help="Do not install models",
)
parser.add_argument(
"--install-type",
choices=["server", "client", "both"],
default="client",
required=True,
dest="install_type",
help="Install candidates",
)
parser.add_argument(
"--install-log",
type=str,
default=f"./zm-ml_install.log",
help="Log 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-config",
help=f"Directory where config files are held Default: {DEFAULT_CONFIG_DIR}",
default="./zmml/conf",
type=Path,
dest="config_dir",
)
parser.add_argument(
"--dir-data",
help=f"Directory where variable data is held Default: {DEFAULT_DATA_DIR}",
dest="data_dir",
default="./zmml/data",
type=Path,
)
parser.add_argument(
"--dir-model",
type=str,
help="ML model base directory",
default="",
dest="model_dir",
)
parser.add_argument(
"--dir-temp",
"--dir-tmp",
type=Path,
help="Temp files directory",
default="./zmml/temp",
dest="tmp_dir",
)
parser.add_argument(
"--dir-log",
help=f"Directory where logs will be stored Default: {DEFAULT_LOG_DIR}",
default="./zmml/log",
dest="log_dir",
type=Path,
)
parser.add_argument(
"--force-install-secrets",
action="store_true",
dest="install_secrets",
help="install default secrets.yml [will use a numbered backup system]",
)
parser.add_argument(
"--user",
"-U",
help="User to install as [leave empty to auto-detect what user runs the web server] (Change if installing server on a remote host)",
type=str,
dest="ml_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] (Change if installing server on a remote host)",
type=str,
dest="ml_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(
"--version", action="version", version=f"%(prog)s {__version__}"
)
parser.add_argument(
"--system-create-permissions",
help=f"ZM 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 (server.yml, client.yml, secrets.yml) octal [0o] file permissions [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):
msg = f"Created directory: {path} with user:group:permission [{user}:{group}:{mode:o}]"
test_msg(msg)
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 ml_user, ml_group
_group = None
if not ml_user or not ml_group:
if not ml_user:
if interactive:
ml_user = input("Web server username [Leave blank to try auto-find]: ")
if not ml_user:
ml_user, _group = get_web_user()
logger.info(f"Web server user auto-find: {ml_user}")
else:
ml_user, _group = get_web_user()
logger.info(f"Web server user auto-find: {ml_user}")
if not ml_group:
if interactive:
ml_group = input("Web server group [Leave blank to try auto-find]: ")
if not ml_group:
if _group:
ml_group = _group
else:
_, ml_group = get_web_user()
logger.info(f"Web server group auto-find: {ml_group}")
else:
if _group:
ml_group = _group
else:
_, ml_group = get_web_user()
logger.info(f"Web server group auto-find: {ml_group}")
if not ml_user or not ml_group:
_missing = ""
_u = "user [--user]"
_g = "group [--group]"
if not ml_user and ml_group:
_missing = _u
elif ml_user and not ml_group:
_missing = _g
else:
_missing = f"{_u} and {_g}"
msg = f"Unable to determine web server {_missing}, EXITING..."
if not testing:
logger.error(msg)
sys.exit(1)
else:
test_msg(msg)
def install_dirs(
dest_dir: Path,
default_dir: str,
dir_type: str,
sub_dirs: Optional[List[str]] = None,
perms: int = 0o755,
):
"""Install directories"""
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, ml_user, ml_group, perms)
else:
test_msg(f"Creating {dir_type} directory...")
create_dir(dest_dir, ml_user, ml_group, perms)
# 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, ml_user, ml_group, perms)
else:
logger.warning(f"{dir_type} directory {dest_dir} already exists!")
def download_file(url: str, dest: Path, user: str, group: str, mode: int):
msg = (
f"Downloading {url}..."
if not testing
else f"TESTING if file exists at :: {url}..."
)
logger.info(msg)
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):
msg = f"Copying {src} to {dest}..."
if not testing:
import shutil
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 e:
logger.error(f"Exception type: {type(e)} --- {e}")
raise e
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, inst_prefix, _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 {' '.join(deps)}? [Y/n]"
)
if _input:
_input = _input.strip().casefold()
if _input == "n":
logger.warning(