forked from idaholab/Malcolm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
control.py
executable file
·2468 lines (2218 loc) · 100 KB
/
control.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
# -*- coding: utf-8 -*-
# Copyright (c) 2023 Battelle Energy Alliance, LLC. All rights reserved.
import sys
sys.dont_write_bytecode = True
import argparse
import errno
import fileinput
import getpass
import glob
import gzip
import json
import os
import platform
import re
import secrets
import shutil
import signal
import stat
import string
import tarfile
import time
from malcolm_common import (
AskForPassword,
AskForString,
BoundPath,
ChooseOne,
DetermineYamlFileFormat,
DisplayMessage,
DisplayProgramBox,
DotEnvDynamic,
GetUidGidFromEnv,
KubernetesDynamic,
LocalPathForContainerBindMount,
MainDialog,
MalcolmAuthFilesExist,
MalcolmPath,
MalcolmTmpPath,
OrchestrationFramework,
OrchestrationFrameworksSupported,
PLATFORM_WINDOWS,
posInt,
ProcessLogLine,
PROFILE_HEDGEHOG,
PROFILE_KEY,
PROFILE_MALCOLM,
ScriptPath,
UserInputDefaultsBehavior,
YAMLDynamic,
YesOrNo,
)
from malcolm_utils import (
CountUntilException,
deep_get,
dictsearch,
eprint,
flatten,
EscapeAnsi,
EscapeForCurl,
get_iterable,
get_primary_ip,
LoadStrIfJson,
ParseCurlFile,
pushd,
RemoveEmptyFolders,
run_process,
same_file_or_dir,
str2bool,
which,
)
from malcolm_kubernetes import (
CheckPersistentStorageDefs,
DeleteNamespace,
get_node_hostnames_and_ips,
GetPodNamesForService,
PodExec,
PrintNodeStatus,
PrintPodStatus,
REQUIRED_VOLUME_OBJECTS,
StartMalcolm,
)
from base64 import b64encode
from collections import defaultdict, namedtuple
from subprocess import PIPE, STDOUT, DEVNULL, Popen, TimeoutExpired
from urllib.parse import urlparse
from itertools import chain, groupby
try:
from contextlib import nullcontext
except ImportError:
class nullcontext(object):
def __init__(self, enter_result=None):
self.enter_result = enter_result
def __enter__(self):
return self.enter_result
def __exit__(self, *args):
pass
###################################################################################################
ScriptName = os.path.basename(__file__)
pyPlatform = platform.system()
args = None
dockerBin = None
# dockerComposeBin might be e.g., ('docker', 'compose') or 'docker-compose',
# it will be flattened in run_process
dockerComposeBin = None
dockerComposeYaml = None
kubeImported = None
opensslBin = None
orchMode = None
shuttingDown = [False]
yamlImported = None
dotenvImported = None
MaxAskForValueCount = 100
###################################################################################################
try:
from colorama import init as ColoramaInit, Fore, Back, Style
ColoramaInit()
coloramaImported = True
except Exception:
coloramaImported = False
###################################################################################################
# handle sigint/sigterm and set a global shutdown variable
def shutdown_handler(signum, frame):
global shuttingDown
shuttingDown[0] = True
###################################################################################################
def checkEnvFilesExist():
global args
# first, if the configDir is completely empty, then populate from defaults
defaultConfigDir = os.path.join(MalcolmPath, 'config')
if (
(args.configDir is not None)
and os.path.isdir(args.configDir)
and os.path.isdir(defaultConfigDir)
and (not same_file_or_dir(defaultConfigDir, args.configDir))
and (not os.listdir(args.configDir))
):
for defaultEnvExampleFile in glob.glob(os.path.join(defaultConfigDir, '*.env.example')):
shutil.copy2(defaultEnvExampleFile, args.configDir)
# if a specific config/*.env file doesn't exist, use the *.example.env files as defaults
envExampleFiles = glob.glob(os.path.join(args.configDir, '*.env.example'))
for envExampleFile in envExampleFiles:
envFile = envExampleFile[: -len('.example')]
if not os.path.isfile(envFile):
shutil.copyfile(envExampleFile, envFile)
###################################################################################################
# perform a service-keystore operation in a container
#
# service - the service in the docker-compose YML file
# keystore_args - arguments to pass to the service-keystore binary in the container
# run_process_kwargs - keyword arguments to pass to run_process
#
# returns True (success) or False (failure)
#
def keystore_op(service, dropPriv=False, *keystore_args, **run_process_kwargs):
global args
global dockerBin
global dockerComposeBin
global orchMode
err = -1
results = []
# the opensearch containers all follow the same naming pattern for these executables
keystoreBinProc = f"/usr/share/{service}/bin/{service}-keystore"
uidGidDict = GetUidGidFromEnv(args.configDir)
if (orchMode is OrchestrationFramework.DOCKER_COMPOSE) and (args.composeProfile == PROFILE_MALCOLM):
# if we're using docker-uid-gid-setup.sh to drop privileges as we spin up a container
dockerUidGuidSetup = "/usr/local/bin/docker-uid-gid-setup.sh"
# docker-compose use local temporary path
osEnv = os.environ.copy()
osEnv['TMPDIR'] = MalcolmTmpPath
# open up the docker-compose file and "grep" for the line where the keystore file
# is bind-mounted into the service container (once and only once). the bind
# mount needs to exist in the YML file and the local directory containing the
# keystore file needs to exist (although the file itself might not yet).
# also get PUID and PGID variables from the docker-compose file.
localKeystore = None
localKeystoreDir = None
localKeystorePreExists = False
volumeKeystore = f"/usr/share/{service}/config/{service}.keystore"
volumeKeystoreDir = os.path.dirname(volumeKeystore)
try:
composeFileLines = list()
with open(args.composeFile, 'r') as f:
allLines = f.readlines()
composeFileLines = [
x for x in allLines if re.search(fr'-.*?{service}.keystore\s*:.*{service}.keystore', x)
]
if (len(composeFileLines) == 1) and (len(composeFileLines[0]) > 0):
matches = re.search(
fr'-\s*(?P<localKeystore>.*?{service}.keystore)\s*:\s*.*?{service}.keystore',
composeFileLines[0],
)
if matches:
localKeystore = os.path.realpath(matches.group('localKeystore'))
localKeystoreDir = os.path.dirname(localKeystore)
if (localKeystore is not None) and os.path.isdir(localKeystoreDir):
localKeystorePreExists = os.path.isfile(localKeystore)
dockerCmd = None
# determine if Malcolm is running; if so, we'll use docker-compose exec, other wise we'll use docker run
err, out = run_process(
[dockerComposeBin, '--profile', args.composeProfile, '-f', args.composeFile, 'ps', '-q', service],
env=osEnv,
debug=args.debug,
)
out[:] = [x for x in out if x]
if (err == 0) and (len(out) > 0):
# Malcolm is running, we can use an existing container
# assemble the service-keystore command
dockerCmd = [
dockerComposeBin,
'--profile',
args.composeProfile,
'-f',
args.composeFile,
'exec',
# if using stdin, indicate the container is "interactive", else noop (duplicate --rm)
'-T' if ('stdin' in run_process_kwargs and run_process_kwargs['stdin']) else '',
# execute as UID:GID in docker-compose.yml file
'-u',
f'{uidGidDict["PUID"]}:{uidGidDict["PGID"]}',
# the work directory in the container is the directory to contain the keystore file
'-w',
volumeKeystoreDir,
# the service name
service,
# the executable filespec
keystoreBinProc,
]
else:
# Malcolm isn't running, do 'docker run' to spin up a temporary container to run the ocmmand
# "grep" the docker image out of the service's image: value from the docker-compose YML file
serviceImage = None
composeFileLines = list()
with open(args.composeFile, 'r') as f:
composeFileLines = [
x for x in f.readlines() if f'image: ghcr.io/idaholab/malcolm/{service}' in x
]
if (len(composeFileLines) > 0) and (len(composeFileLines[0]) > 0):
imageLineValues = composeFileLines[0].split()
if len(imageLineValues) > 1:
serviceImage = imageLineValues[1]
if serviceImage is not None:
# assemble the service-keystore command
dockerCmd = [
dockerBin,
'run',
# remove the container when complete
'--rm',
# if using stdin, indicate the container is "interactive", else noop
'-i' if ('stdin' in run_process_kwargs and run_process_kwargs['stdin']) else '',
# if dropPriv, dockerUidGuidSetup will take care of dropping privileges for the correct UID/GID
# if NOT dropPriv, enter with the keystore executable directly
'--entrypoint',
dockerUidGuidSetup if dropPriv else keystoreBinProc,
'--env',
f'PUID={uidGidDict["PUID"]}',
'--env',
f'DEFAULT_UID={uidGidDict["PUID"]}',
'--env',
f'PGID={uidGidDict["PGID"]}',
'--env',
f'DEFAULT_GID={uidGidDict["PGID"]}',
'--env',
f'PUSER_CHOWN={volumeKeystoreDir}',
# rw bind mount the local directory to contain the keystore file to the container directory
'-v',
f'{localKeystoreDir}:{volumeKeystoreDir}:rw',
# the work directory in the container is the directory to contain the keystore file
'-w',
volumeKeystoreDir,
# if dropPriv, execute as root, as docker-uid-gid-setup.sh will drop privileges for us
# if NOT dropPriv, execute as UID:GID in docker-compose.yml file
'-u',
'root' if dropPriv else f'{uidGidDict["PUID"]}:{uidGidDict["PGID"]}',
# the service image name grepped from the YML file
serviceImage,
]
if dropPriv:
# the keystore executable filespec (as we used dockerUidGuidSetup as the entrypoint)
dockerCmd.append(keystoreBinProc)
else:
raise Exception(f'Unable to identify docker image for {service} in {args.composeFile}')
if dockerCmd is not None:
# append whatever other arguments to pass to the executable filespec
if keystore_args:
dockerCmd.extend(list(keystore_args))
dockerCmd[:] = [x for x in dockerCmd if x]
# execute the command, passing through run_process_kwargs to run_process as expanded keyword arguments
err, results = run_process(dockerCmd, env=osEnv, debug=args.debug, **run_process_kwargs)
if (err != 0) or (not os.path.isfile(localKeystore)):
raise Exception(f'Error processing command {service} keystore: {results}')
else:
raise Exception(f'Unable formulate keystore command for {service} in {args.composeFile}')
else:
raise Exception(
f'Unable to identify a unique keystore file bind mount for {service} in {args.composeFile}'
)
except Exception as e:
if err == 0:
err = -1
# don't be so whiny if the "create" failed just because it already existed or a 'remove' failed on a nonexistant item
if (
(not args.debug)
and list(keystore_args)
and (len(list(keystore_args)) > 0)
and (list(keystore_args)[0].lower() in ('create', 'remove'))
and localKeystorePreExists
):
pass
else:
eprint(e)
elif orchMode is OrchestrationFramework.KUBERNETES:
cmd = [keystoreBinProc]
if keystore_args:
cmd.extend(list(keystore_args))
cmd = [x for x in cmd if x]
podsResults = PodExec(
service,
args.namespace,
[x for x in cmd if x],
stdin=run_process_kwargs['stdin']
if ('stdin' in run_process_kwargs and run_process_kwargs['stdin'])
else None,
)
err = 0 if all([deep_get(v, ['err'], 1) == 0 for k, v in podsResults.items()]) else 1
results = list(chain(*[deep_get(v, ['output'], '') for k, v in podsResults.items()]))
if args.debug:
dbgStr = f"{len(podsResults)} pods: {cmd}({run_process_kwargs['stdin'][:80] + bool(run_process_kwargs['stdin'][80:]) * '...' if 'stdin' in run_process_kwargs and run_process_kwargs['stdin'] else ''}) returned {err}: {results}"
eprint(dbgStr)
for podname, podResults in podsResults.items():
dbgStr = f"{podname}: {cmd}({run_process_kwargs['stdin'][:80] + bool(run_process_kwargs['stdin'][80:]) * '...' if 'stdin' in run_process_kwargs and run_process_kwargs['stdin'] else ''}) returned {deep_get(podResults, ['err'], 1)}: {deep_get(podResults, ['output'], 'unknown')}"
eprint(dbgStr)
elif args.composeProfile == PROFILE_HEDGEHOG:
# keystore operation doesn't mean anything in hedgehog mode, just return "Ok"
err = 0
else:
raise Exception(
f'{sys._getframe().f_code.co_name} does not yet support {orchMode} with profile {args.composeProfile}'
)
return (err == 0), results
###################################################################################################
def status():
global args
global dockerComposeBin
global orchMode
if orchMode is OrchestrationFramework.DOCKER_COMPOSE:
# docker-compose use local temporary path
osEnv = os.environ.copy()
osEnv['TMPDIR'] = MalcolmTmpPath
err, out = run_process(
[dockerComposeBin, '--profile', args.composeProfile, '-f', args.composeFile, 'ps', args.service][
: 7 if args.service is not None else -1
],
env=osEnv,
debug=args.debug,
)
if err == 0:
print("\n".join(out))
else:
eprint("Failed to display Malcolm status\n")
eprint("\n".join(out))
elif orchMode is OrchestrationFramework.KUBERNETES:
try:
PrintNodeStatus()
print()
except Exception as e:
if args.debug:
eprint(f'Error getting node status: {e}')
try:
PrintPodStatus(namespace=args.namespace)
print()
except Exception as e:
eprint(f'Error getting {args.namespace} status: {e}')
else:
raise Exception(f'{sys._getframe().f_code.co_name} does not yet support {orchMode}')
###################################################################################################
def printURLs():
global orchMode
if orchMode is OrchestrationFramework.KUBERNETES:
addrs = get_node_hostnames_and_ips(mastersOnly=True)
if not any((addrs['external'], addrs['hostname'])):
addrs = get_node_hostnames_and_ips(mastersOnly=False)
if addrs['external']:
myIp = addrs['external'][0]
elif addrs['hostname']:
myIp = addrs['hostname'][0]
elif addrs['internal']:
myIp = addrs['internal'][0]
else:
myIp = '<cluster IP>'
else:
myIp = get_primary_ip()
print("\nMalcolm services can be accessed via the following URLs:")
print("------------------------------------------------------------------------------")
print(f" - Arkime: https://{myIp}/")
print(f" - OpenSearch Dashboards: https://{myIp}/dashboards/")
print(f" - PCAP upload (web): https://{myIp}/upload/")
if orchMode is not OrchestrationFramework.KUBERNETES:
print(f" - PCAP upload (sftp): sftp://username@{myIp}:8022/files/")
print(f" - NetBox: https://{myIp}/netbox/")
print(f" - Account management: https://{myIp}/auth/")
print(f" - Documentation: https://{myIp}/readme/")
###################################################################################################
def netboxBackup(backupFileName=None):
global args
global dockerComposeBin
global orchMode
backupFileName, backupMediaFileName = None, None
uidGidDict = GetUidGidFromEnv(args.configDir)
if (orchMode is OrchestrationFramework.DOCKER_COMPOSE) and (args.composeProfile == PROFILE_MALCOLM):
# docker-compose use local temporary path
osEnv = os.environ.copy()
osEnv['TMPDIR'] = MalcolmTmpPath
dockerCmd = [
dockerComposeBin,
'--profile',
args.composeProfile,
'-f',
args.composeFile,
'exec',
# disable pseudo-TTY allocation
'-T',
# execute as UID:GID in docker-compose.yml file
'-u',
f'{uidGidDict["PUID"]}:{uidGidDict["PGID"]}',
'netbox-postgres',
'pg_dump',
'-U',
'netbox',
'-d',
'netbox',
]
err, results = run_process(dockerCmd, env=osEnv, debug=args.debug, stdout=True, stderr=False)
if (err != 0) or (len(results) == 0):
raise Exception('Error creating NetBox configuration database backup')
if (backupFileName is None) or (len(backupFileName) == 0):
backupFileName = f"malcolm_netbox_backup_{time.strftime('%Y%m%d-%H%M%S')}.gz"
with gzip.GzipFile(backupFileName, "wb") as f:
f.write(bytes('\n'.join(results), 'utf-8'))
backupFileParts = os.path.splitext(backupFileName)
backupMediaFileName = backupFileParts[0] + ".media.tar.gz"
with tarfile.open(backupMediaFileName, 'w:gz') as t:
t.add(os.path.join(os.path.join(MalcolmPath, 'netbox'), 'media'), arcname='.')
elif orchMode is OrchestrationFramework.KUBERNETES:
if podsResults := PodExec(
service='netbox-postgres',
namespace=args.namespace,
command=[
'pg_dump',
'-U',
'netbox',
'-d',
'netbox',
],
maxPodsToExec=1,
):
podName = next(iter(podsResults))
err = podsResults[podName]['err']
results = podsResults[podName]['output']
else:
err = 1
results = []
if (err != 0) or (len(results) == 0):
raise Exception('Error creating NetBox configuration database backup')
if (backupFileName is None) or (len(backupFileName) == 0):
backupFileName = f"malcolm_netbox_backup_{time.strftime('%Y%m%d-%H%M%S')}.gz"
with gzip.GzipFile(backupFileName, "wb") as f:
f.write(bytes('\n'.join(results), 'utf-8'))
# TODO: can't backup netbox/media directory via kubernetes at the moment
backupMediaFileName = None
else:
raise Exception(
f'{sys._getframe().f_code.co_name} does not yet support {orchMode} with profile {args.composeProfile}'
)
return backupFileName, backupMediaFileName
###################################################################################################
def netboxRestore(backupFileName=None):
global args
global dockerComposeBin
global orchMode
if backupFileName and os.path.isfile(backupFileName):
uidGidDict = GetUidGidFromEnv(args.configDir)
if (orchMode is OrchestrationFramework.DOCKER_COMPOSE) and (args.composeProfile == PROFILE_MALCOLM):
# docker-compose use local temporary path
osEnv = os.environ.copy()
osEnv['TMPDIR'] = MalcolmTmpPath
dockerCmdBase = [
dockerComposeBin,
'--profile',
args.composeProfile,
'-f',
args.composeFile,
'exec',
# disable pseudo-TTY allocation
'-T',
# execute as UID:GID in docker-compose.yml file
'-u',
f'{uidGidDict["PUID"]}:{uidGidDict["PGID"]}',
]
# stop the netbox processes
dockerCmd = dockerCmdBase + [
'netbox',
'supervisorctl',
'stop',
'netbox:*',
]
err, results = run_process(dockerCmd, env=osEnv, debug=args.debug)
if (err != 0) and args.debug:
eprint(f'Error stopping netbox:*: {results}')
# if the netbox_init.py process is still happening, interrupt it
dockerCmd = dockerCmdBase + [
'netbox',
'bash',
'-c',
'pgrep -f /usr/local/bin/netbox_init.py | xargs -r kill',
]
err, results = run_process(dockerCmd, env=osEnv, debug=args.debug)
if (err != 0) and args.debug:
eprint(f'Error interrupting netbox_init.py: {results}')
# drop the existing netbox database
dockerCmd = dockerCmdBase + ['netbox-postgres', 'dropdb', '-U', 'netbox', 'netbox', '--force']
err, results = run_process(dockerCmd, env=osEnv, debug=args.debug)
if ((err != 0) or (len(results) == 0)) and args.debug:
eprint(f'Error dropping NetBox database: {results}')
# create a new netbox database
dockerCmd = dockerCmdBase + ['netbox-postgres', 'createdb', '-U', 'netbox', 'netbox']
err, results = run_process(dockerCmd, env=osEnv, debug=args.debug)
if err != 0:
raise Exception('Error creating new NetBox database')
# make sure permissions are set up right
dockerCmd = dockerCmdBase + [
'netbox-postgres',
'psql',
'-U',
'netbox',
'-c',
'GRANT ALL PRIVILEGES ON DATABASE netbox TO netbox',
]
err, results = run_process(dockerCmd, env=osEnv, debug=args.debug)
if err != 0:
raise Exception('Error setting NetBox database permissions')
# load the backed-up psql dump
dockerCmd = dockerCmdBase + ['netbox-postgres', 'psql', '-U', 'netbox']
with gzip.open(backupFileName, 'rt') as f:
err, results = run_process(dockerCmd, env=osEnv, debug=args.debug, stdin=f.read())
if (err != 0) or (len(results) == 0):
raise Exception('Error loading NetBox database')
# start back up the netbox processes
dockerCmd = dockerCmdBase + [
'netbox',
'supervisorctl',
'start',
'netbox:housekeeping',
'netbox:main',
'netbox:worker',
]
err, results = run_process(dockerCmd, env=osEnv, debug=args.debug)
if (err != 0) and args.debug:
eprint(f'Error starting netbox:*: {results}')
# migrations if needed
dockerCmd = dockerCmdBase + ['netbox', '/opt/netbox/netbox/manage.py', 'migrate']
err, results = run_process(dockerCmd, env=osEnv, debug=args.debug)
if (err != 0) or (len(results) == 0):
raise Exception('Error performing NetBox migration')
# restore media directory
backupFileParts = os.path.splitext(backupFileName)
backupMediaFileName = backupFileParts[0] + ".media.tar.gz"
mediaPath = os.path.join(os.path.join(MalcolmPath, 'netbox'), 'media')
if os.path.isfile(backupMediaFileName) and os.path.isdir(mediaPath):
RemoveEmptyFolders(mediaPath, removeRoot=False)
with tarfile.open(backupMediaFileName) as t:
t.extractall(mediaPath)
elif orchMode is OrchestrationFramework.KUBERNETES:
# if the netbox_init.py process is happening, interrupt it
if podsResults := PodExec(
service='netbox',
namespace=args.namespace,
command=['bash', '-c', 'pgrep -f /usr/local/bin/netbox_init.py | xargs -r kill'],
):
err = 0 if all([deep_get(v, ['err'], 1) == 0 for k, v in podsResults.items()]) else 1
results = list(chain(*[deep_get(v, ['output'], '') for k, v in podsResults.items()]))
else:
err = 1
results = []
if (err != 0) and args.debug:
eprint(f'Error ({err}) interrupting netbox_init.py: {results}')
# drop the existing netbox database
if podsResults := PodExec(
service='netbox-postgres',
namespace=args.namespace,
command=['dropdb', '-U', 'netbox', 'netbox', '--force'],
):
err = 0 if all([deep_get(v, ['err'], 1) == 0 for k, v in podsResults.items()]) else 1
results = list(chain(*[deep_get(v, ['output'], '') for k, v in podsResults.items()]))
else:
err = 1
results = []
if ((err != 0) or (len(results) == 0)) and args.debug:
eprint(f'Error dropping NetBox database: {results}')
# create a new netbox database
if podsResults := PodExec(
service='netbox-postgres',
namespace=args.namespace,
command=['createdb', '-U', 'netbox', 'netbox'],
):
err = 0 if all([deep_get(v, ['err'], 1) == 0 for k, v in podsResults.items()]) else 1
results = list(chain(*[deep_get(v, ['output'], '') for k, v in podsResults.items()]))
else:
err = 1
results = []
if err != 0:
raise Exception(f'Error creating new NetBox database: {results}')
# make sure permissions are set up right
if podsResults := PodExec(
service='netbox-postgres',
namespace=args.namespace,
command=[
'netbox-postgres',
'psql',
'-U',
'netbox',
'-c',
'GRANT ALL PRIVILEGES ON DATABASE netbox TO netbox',
],
):
err = 0 if all([deep_get(v, ['err'], 1) == 0 for k, v in podsResults.items()]) else 1
results = list(chain(*[deep_get(v, ['output'], '') for k, v in podsResults.items()]))
else:
err = 1
results = []
if err != 0:
raise Exception(f'Error setting NetBox database permissions: {results}')
# load the backed-up psql dump
with gzip.open(backupFileName, 'rt') as f:
if podsResults := PodExec(
service='netbox-postgres',
namespace=args.namespace,
command=['psql', '-U', 'netbox'],
stdin=f.read(),
):
err = 0 if all([deep_get(v, ['err'], 1) == 0 for k, v in podsResults.items()]) else 1
results = list(chain(*[deep_get(v, ['output'], '') for k, v in podsResults.items()]))
else:
err = 1
results = []
if (err != 0) or (len(results) == 0):
raise Exception(f'Error loading NetBox database: {results}')
# migrations if needed
if podsResults := PodExec(
service='netbox',
namespace=args.namespace,
command=['/opt/netbox/netbox/manage.py', 'migrate'],
):
err = 0 if all([deep_get(v, ['err'], 1) == 0 for k, v in podsResults.items()]) else 1
results = list(chain(*[deep_get(v, ['output'], '') for k, v in podsResults.items()]))
else:
err = 1
results = []
if (err != 0) or (len(results) == 0):
raise Exception(f'Error performing NetBox migration: {results}')
# TODO: can't restore netbox/media directory via kubernetes at the moment
else:
raise Exception(
f'{sys._getframe().f_code.co_name} does not yet support {orchMode} with profile {args.composeProfile}'
)
###################################################################################################
def logs():
global args
global dockerBin
global dockerComposeBin
global orchMode
global shuttingDown
finishedStartingRegEx = re.compile(r'.+Pipelines\s+running\s+\{.*:non_running_pipelines=>\[\]\}')
osEnv = os.environ.copy()
# use local temporary path
osEnv['TMPDIR'] = MalcolmTmpPath
if orchMode is OrchestrationFramework.DOCKER_COMPOSE:
# increase COMPOSE_HTTP_TIMEOUT to be ridiculously large so docker-compose never times out the TTY doing debug output
osEnv['COMPOSE_HTTP_TIMEOUT'] = '100000000'
err, out = run_process(
[dockerComposeBin, '--profile', args.composeProfile, '-f', args.composeFile, 'ps', args.service][
: 7 if args.service is not None else -1
],
env=osEnv,
debug=args.debug,
)
print("\n".join(out))
cmd = [
dockerComposeBin,
'--profile',
args.composeProfile,
'-f',
args.composeFile,
'logs',
'--tail',
str(args.logLineCount) if args.logLineCount else 'all',
'-f',
args.service,
][: 10 if args.service else -1]
elif orchMode is OrchestrationFramework.KUBERNETES:
if which("stern"):
cmd = [
"stern",
"--kubeconfig",
args.composeFile,
"--only-log-lines",
"--color",
'auto' if coloramaImported else 'never',
"--template",
'{{.Namespace}}/{{color .PodColor .PodName}}/{{color .ContainerColor .ContainerName}} | {{.Message}}{{"\\n"}}'
if args.debug
else '{{color .ContainerColor .ContainerName}} | {{.Message}}{{"\\n"}}',
'--tail',
str(args.logLineCount) if args.logLineCount else '-1',
]
if args.namespace:
cmd.extend(['--namespace', args.namespace])
else:
cmd.append('--all-namespaces')
cmd.append(args.service if args.service else '.*')
else:
raise Exception(
f'{sys._getframe().f_code.co_name} with orchestration mode {orchMode} requires "stern" (https://github.com/stern/stern/releases/latest)'
)
else:
cmd = []
raise Exception(f'{sys._getframe().f_code.co_name} does not yet support {orchMode}')
if cmd:
process = Popen(
list(flatten(cmd)),
env=osEnv,
stdout=PIPE,
stderr=None if args.debug else DEVNULL,
)
while not shuttingDown[0]:
output = process.stdout.readline()
if not output:
if process.poll() is not None:
break
else:
time.sleep(0.5)
elif output := ProcessLogLine(output, debug=args.debug):
print(output)
if (
output
and (args.cmdStart or args.cmdRestart)
and (not args.cmdLogs)
and finishedStartingRegEx.match(output)
):
shuttingDown[0] = True
process.terminate()
try:
process.wait(timeout=5.0)
except TimeoutExpired:
process.kill()
print("\nStarted Malcolm\n")
printURLs()
process.poll()
###################################################################################################
def stop(wipe=False):
global args
global dockerBin
global dockerComposeBin
global dockerComposeYaml
global orchMode
if orchMode is OrchestrationFramework.DOCKER_COMPOSE:
# docker-compose use local temporary path
osEnv = os.environ.copy()
osEnv['TMPDIR'] = MalcolmTmpPath
# if stop.sh is being called with wipe.sh (after the docker-compose file)
# then also remove named and anonymous volumes (not external volumes, of course)
err, out = run_process(
[dockerComposeBin, '--profile', args.composeProfile, '-f', args.composeFile, 'down', '--volumes'][
: 7 if wipe else -1
],
env=osEnv,
debug=args.debug,
)
if err == 0:
eprint("Stopped Malcolm\n")
else:
eprint("Malcolm failed to stop\n")
eprint("\n".join(out))
exit(err)
if wipe:
# there is some overlap here among some of these containers, but it doesn't matter
boundPathsToWipe = (
BoundPath("arkime", "/opt/arkime/logs", True, None, None),
BoundPath("arkime", "/opt/arkime/raw", True, None, None),
BoundPath("filebeat", "/zeek", True, None, None),
BoundPath("file-monitor", "/zeek/logs", True, None, None),
BoundPath("netbox", "/opt/netbox/netbox/media", True, None, ["."]),
BoundPath("netbox-postgres", "/var/lib/postgresql/data", True, None, ["."]),
BoundPath("netbox-redis", "/data", True, None, ["."]),
BoundPath("opensearch", "/usr/share/opensearch/data", True, ["nodes"], None),
BoundPath("pcap-monitor", "/pcap", True, ["processed", "upload"], None),
BoundPath("suricata", "/var/log/suricata", True, None, ["."]),
BoundPath(
"upload",
"/var/www/upload/server/php/chroot/files",
True,
[os.path.join('tmp', 'spool'), "variants"],
None,
),
BoundPath("zeek", "/zeek/extract_files", True, None, None),
BoundPath("zeek", "/zeek/upload", True, None, None),
BoundPath("zeek-live", "/zeek/live", True, ["spool"], None),
BoundPath(
"filebeat",
"/zeek",
False,
["processed", "current", "live"],
["processed", "current", "live"],
),
)
for boundPath in boundPathsToWipe:
localPath = LocalPathForContainerBindMount(
boundPath.service,
dockerComposeYaml,
boundPath.container_dir,
MalcolmPath,
)
if localPath and os.path.isdir(localPath):
# delete files
if boundPath.files:
if args.debug:
eprint(f'Walking "{localPath}" for file deletion')
for root, dirnames, filenames in os.walk(localPath, topdown=True, onerror=None):
for file in filenames:
fileSpec = os.path.join(root, file)
if (os.path.isfile(fileSpec) or os.path.islink(fileSpec)) and (
not file.startswith('.git')
):
try:
os.remove(fileSpec)
except Exception:
pass
# delete whole directories
if boundPath.relative_dirs:
for relDir in get_iterable(boundPath.relative_dirs):
tmpPath = os.path.join(localPath, relDir)
if os.path.isdir(tmpPath):
if args.debug:
eprint(f'Performing rmtree on "{tmpPath}"')
shutil.rmtree(tmpPath, ignore_errors=True)
# cleanup empty directories
if boundPath.clean_empty_dirs:
for cleanDir in get_iterable(boundPath.clean_empty_dirs):
tmpPath = os.path.join(localPath, cleanDir)
if os.path.isdir(tmpPath):
if args.debug:
eprint(f'Performing RemoveEmptyFolders on "{tmpPath}"')
RemoveEmptyFolders(tmpPath, removeRoot=False)
eprint("Malcolm has been stopped and its data cleared\n")
elif orchMode is OrchestrationFramework.KUBERNETES:
deleteResults = DeleteNamespace(
namespace=args.namespace,
deleteRetPerVol=args.deleteRetPerVol,
)
if dictsearch(deleteResults, 'error'):
eprint(
f"Deleting {args.namespace} namespace and its underlying resources returned the following error(s):\n"
)
eprint(deleteResults)
eprint()
else:
eprint(f"The {args.namespace} namespace and its underlying resources have been deleted\n")
if args.debug:
eprint(deleteResults)
eprint()