forked from cisagov/Malcolm
-
Notifications
You must be signed in to change notification settings - Fork 54
/
malcolm_kubernetes.py
872 lines (792 loc) · 33.5 KB
/
malcolm_kubernetes.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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) 2023 Battelle Energy Alliance, LLC. All rights reserved.
import base64
import glob
import os
from concurrent.futures import ThreadPoolExecutor, as_completed
from collections import defaultdict
from itertools import chain
from io import StringIO
from malcolm_common import (
DotEnvDynamic,
KubernetesDynamic,
MalcolmPath,
PROFILE_HEDGEHOG,
PROFILE_MALCOLM,
YAMLDynamic,
)
from malcolm_utils import (
deep_get,
dictsearch,
eprint,
get_iterable,
file_contents,
remove_suffix,
tablify,
LoadStrIfJson,
val2bool,
)
###################################################################################################
MALCOLM_IMAGE_PREFIX = 'ghcr.io/idaholab/malcolm/'
MALCOLM_DOTFILE_SECRET_KEY = 'K8S_SECRET'
MALCOLM_CONFIGMAPS = {
'etc-nginx': [
{
'secret': True,
'path': os.path.join(MalcolmPath, os.path.join('nginx', 'nginx_ldap.conf')),
},
{
'secret': False,
'path': os.path.join(MalcolmPath, os.path.join('nginx', 'nginx.conf')),
},
],
'var-local-catrust': [
{
'secret': False,
'path': os.path.join(MalcolmPath, os.path.join('nginx', 'ca-trust')),
},
],
'etc-nginx-certs': [
{
'secret': True,
'path': os.path.join(MalcolmPath, os.path.join('nginx', 'certs')),
},
],
'etc-nginx-certs-pem': [
{
'secret': False,
'path': os.path.join(MalcolmPath, os.path.join(os.path.join('nginx', 'certs'), 'dhparam.pem')),
},
],
'etc-nginx-auth': [
{
'secret': True,
'path': os.path.join(MalcolmPath, os.path.join('nginx', 'htpasswd')),
},
],
'opensearch-curlrc': [
{
'secret': True,
'path': os.path.join(MalcolmPath, '.opensearch.primary.curlrc'),
},
{
'secret': True,
'path': os.path.join(MalcolmPath, '.opensearch.secondary.curlrc'),
},
],
'opensearch-keystore': [
{
'secret': True,
'path': os.path.join(MalcolmPath, os.path.join('opensearch', 'opensearch.keystore')),
},
],
'logstash-certs': [
{
'secret': True,
'path': os.path.join(MalcolmPath, os.path.join('logstash', 'certs')),
},
],
'logstash-maps': [
{
'secret': False,
'path': os.path.join(MalcolmPath, os.path.join('logstash', 'maps')),
},
],
'logstash-keystore': [
{
'secret': True,
'path': os.path.join(MalcolmPath, os.path.join('logstash', 'logstash.keystore')),
},
],
'yara-rules': [
{
'secret': False,
'path': os.path.join(MalcolmPath, os.path.join('yara', 'rules')),
},
],
'suricata-rules': [
{
'secret': False,
'path': os.path.join(MalcolmPath, os.path.join('suricata', 'rules')),
},
],
'filebeat-certs': [
{
'secret': True,
'path': os.path.join(MalcolmPath, os.path.join('filebeat', 'certs')),
},
],
'netbox-netmap-json': [
{
'secret': False,
'path': os.path.join(MalcolmPath, 'net-map.json'),
},
],
'netbox-config': [
{
'secret': False,
'path': os.path.join(MalcolmPath, os.path.join('netbox', 'config')),
},
],
'netbox-preload': [
{
'secret': False,
'path': os.path.join(MalcolmPath, os.path.join('netbox', 'preload')),
},
],
'htadmin-config': [
{
'secret': False,
'path': os.path.join(MalcolmPath, os.path.join('htadmin', 'config.ini')),
},
{
'secret': True,
'path': os.path.join(MalcolmPath, os.path.join('htadmin', 'metadata')),
},
],
}
# the PersistentVolumes themselves aren't used directly,
# so we only need to define the PersistentVolumeClaims
REQUIRED_VOLUME_OBJECTS = defaultdict(lambda: dict)
REQUIRED_VOLUME_OBJECTS[PROFILE_MALCOLM] = {
'pcap-claim': 'PersistentVolumeClaim',
'zeek-claim': 'PersistentVolumeClaim',
'suricata-claim': 'PersistentVolumeClaim',
'config-claim': 'PersistentVolumeClaim',
'runtime-logs-claim': 'PersistentVolumeClaim',
'opensearch-claim': 'PersistentVolumeClaim',
'opensearch-backup-claim': 'PersistentVolumeClaim',
}
REQUIRED_VOLUME_OBJECTS[PROFILE_HEDGEHOG] = {
'pcap-claim': 'PersistentVolumeClaim',
'zeek-claim': 'PersistentVolumeClaim',
'suricata-claim': 'PersistentVolumeClaim',
'config-claim': 'PersistentVolumeClaim',
'runtime-logs-claim': 'PersistentVolumeClaim',
}
MALCOLM_PROFILES_CONTAINERS = defaultdict(lambda: list)
MALCOLM_PROFILES_CONTAINERS[PROFILE_MALCOLM] = [
'api',
'arkime',
'dashboards',
'dashboards-helper',
'filebeat',
'file-monitor',
'freq',
'htadmin',
'logstash',
'netbox',
'netbox-postgres',
'netbox-redis-cache',
'netbox-redis',
'nginx-proxy',
'opensearch',
'pcap-capture',
'pcap-monitor',
'suricata-live',
'suricata-offline',
'upload',
'zeek-live',
'zeek-offline',
]
MALCOLM_PROFILES_CONTAINERS[PROFILE_HEDGEHOG] = [
'arkime',
'file-monitor',
'filebeat',
'pcap-capture',
'pcap-monitor',
'suricata-live',
'suricata-offline',
'zeek-live',
'zeek-offline',
]
###################################################################################################
def _nanocore_to_millicore(n):
n = int(n[:-1])
return str(round(n / 1000000, 2)) + 'm'
def _core_to_millicore(n):
n = int(n)
return str(n * 1000) + 'm'
def _percent_cpu(tcpu, ccpu):
tcpu = float(tcpu[:-1])
ccpu = float(ccpu[:-1])
return str(round((ccpu / tcpu) * 100, 2)) + '%'
def _to_gibibyte_or_mebibyte(n):
if n[-2:] == 'Ki':
n = float(n[:-2])
if str(round(n * 0.000000953674316, 2)).split('.')[0] == '0':
return str(round(n * 0.0009765625, 2)) + 'Mi'
return str(round(n * 0.000000953674316, 2)) + 'Gi'
elif n[-2:] == 'Mi' or n[-2:] == 'Gi':
return n
def load_node_list():
nodes = []
if (
(kubeImported := KubernetesDynamic())
and (stats_api := kubeImported.client.CustomObjectsApi())
and (node_stats := stats_api.list_cluster_custom_object("metrics.k8s.io", "v1beta1", "nodes"))
):
for stat in node_stats['items']:
nodes.append(stat['metadata']['name'])
return nodes
def node_stats(node):
node_dict = {}
if kubeImported := KubernetesDynamic():
k8s_api = kubeImported.client.CoreV1Api()
api_response = k8s_api.read_node_status(node)
stats_api = kubeImported.client.CustomObjectsApi()
node_stats = stats_api.list_cluster_custom_object("metrics.k8s.io", "v1beta1", "nodes/{}".format(node))
field_selector = 'spec.nodeName=' + node
pods = k8s_api.list_pod_for_all_namespaces(watch=False, field_selector=field_selector)
node_dict[node] = [
api_response.metadata.name,
','.join(list(set([x.address for x in api_response.status.addresses if not x.type.endswith('IP')]))),
','.join(list(set([x.address for x in api_response.status.addresses if x.type.endswith('IP')]))),
api_response.spec.provider_id.split('/')[-1],
api_response.metadata.labels['node.kubernetes.io/instance-type'],
_core_to_millicore(api_response.status.capacity['cpu']),
_nanocore_to_millicore(node_stats['usage']['cpu']),
_percent_cpu(
_core_to_millicore(api_response.status.capacity['cpu']),
_nanocore_to_millicore(node_stats['usage']['cpu']),
),
_to_gibibyte_or_mebibyte(api_response.status.capacity['memory']),
_to_gibibyte_or_mebibyte(node_stats['usage']['memory']),
_to_gibibyte_or_mebibyte(api_response.status.capacity['ephemeral-storage']),
len(pods.items),
]
return node_dict
def pod_stats(node, namespace):
pod_dict = {}
if kubeImported := KubernetesDynamic():
k8s_api = kubeImported.client.CoreV1Api()
stats_api = kubeImported.client.CustomObjectsApi()
field_selector = 'spec.nodeName=' + node
if namespace:
pods = k8s_api.list_namespaced_pod(namespace, watch=False, field_selector=field_selector)
else:
pods = k8s_api.list_pod_for_all_namespaces(watch=False, field_selector=field_selector)
for pod in pods.items:
pod_name = pod.metadata.name
namespace = pod.metadata.namespace
phase = pod.status.phase
pod_ip = pod.status.pod_ip
if not pod.metadata.owner_references:
pod_kind = None
else:
pod_kind = pod.metadata.owner_references[0].kind
worker_node = pod.spec.node_name
try:
cpu = 0
mem = 0
cpu_mem = stats_api.get_namespaced_custom_object(
"metrics.k8s.io", "v1beta1", namespace, "pods", pod_name
)
for c in cpu_mem['containers']:
if c['usage']['cpu'] == '0':
pass
else:
cpu = +int(c['usage']['cpu'][:-1])
cpu = str(cpu) + 'n'
cpu = _nanocore_to_millicore(cpu)
for m in cpu_mem['containers']:
mem = +int(m['usage']['memory'][:-2])
mem = str(mem) + 'Ki'
mem = _to_gibibyte_or_mebibyte(mem)
except kubeImported.client.rest.ApiException as x:
if x.status == 404:
cpu = 'Not Found'
mem = 'Not Found'
container_name = []
if not pod.status.container_statuses:
container_name = None
container_image = None
else:
for container in range(len(pod.status.container_statuses)):
container_name.append(
'{}:{}'.format(
pod.status.container_statuses[container].name,
pod.status.container_statuses[container].restart_count,
)
)
container_image = []
for container in range(len(pod.status.container_statuses)):
container_image.append(
pod.status.container_statuses[container].image.replace(MALCOLM_IMAGE_PREFIX, '')
)
pod_dict[pod_name] = [
pod_name,
namespace,
phase,
pod_ip,
pod_kind,
worker_node,
cpu,
mem,
','.join(container_name),
','.join(container_image),
]
if namespace:
del pod_dict[pod_name][1]
return pod_dict
def get_node_hostnames_and_ips(mastersOnly=False):
result = {}
result['hostname'] = list()
result['external'] = list()
result['internal'] = list()
if (
(kubeImported := KubernetesDynamic())
and (k8s_api := kubeImported.client.CoreV1Api())
and (
node_stats := kubeImported.client.CustomObjectsApi().list_cluster_custom_object(
"metrics.k8s.io", "v1beta1", "nodes"
)
)
):
for stat in node_stats['items']:
if (not mastersOnly) or any(
[
val2bool(deep_get(stat, ['metadata', 'labels', l], default=False))
for l in ('node-role.kubernetes.io/control-plane', 'node-role.kubernetes.io/master')
]
):
api_response = k8s_api.read_node_status(stat['metadata']['name'])
result['hostname'].extend(
(list(set([x.address for x in api_response.status.addresses if not x.type.endswith('IP')])))
)
result['external'].extend(
(list(set([x.address for x in api_response.status.addresses if x.type.endswith('ExternalIP')])))
)
result['internal'].extend(
(list(set([x.address for x in api_response.status.addresses if x.type.endswith('InternalIP')])))
)
result['hostname'] = list(set(result['hostname']))
result['external'] = list(set(result['external']))
result['internal'] = list(set(result['internal']))
return result
def GetPodNamesForService(service, namespace):
podsNames = []
if namespace and (kubeImported := KubernetesDynamic()) and (client := kubeImported.client.CoreV1Api()):
podsNames = [
x.metadata.name
for x in client.list_namespaced_pod(
namespace,
watch=False,
label_selector=f'name={service}-deployment',
).items
]
return podsNames
def PodExec(
service,
namespace,
command,
stdout=True,
stderr=True,
stdin=None,
timeout=180,
maxPodsToExec=1,
):
results = {}
if namespace and (kubeImported := KubernetesDynamic()) and (client := kubeImported.client.CoreV1Api()):
podsNames = GetPodNamesForService(service, namespace)
for podName in podsNames[:maxPodsToExec]:
retcode = -1
output = []
try:
while True:
resp = client.read_namespaced_pod(
name=podName,
namespace=namespace,
)
if resp.status.phase != 'Pending':
break
resp = kubeImported.stream.stream(
client.connect_get_namespaced_pod_exec,
podName,
namespace,
command=get_iterable(command),
stdout=stdout,
stderr=stderr,
stdin=stdin is not None,
tty=False,
_preload_content=False,
)
rawOutput = StringIO('')
rawErrput = StringIO('')
stdinRemaining = (
list(chain(*[i.split('\n') for i in list(get_iterable(stdin))])) if (stdin is not None) else []
)
counter = 0
while resp.is_open() and (counter <= timeout):
resp.update(timeout=0 if stdinRemaining else 1)
counter += 0 if stdinRemaining else 1
if stdout and resp.peek_stdout():
rawOutput.write(resp.read_stdout())
if stderr and resp.peek_stderr():
rawErrput.write(resp.read_stderr())
if stdinRemaining:
resp.write_stdin(stdinRemaining.pop(0) + "\n")
if stdout and resp.peek_stdout():
rawOutput.write(resp.read_stdout())
if stderr and resp.peek_stderr():
rawErrput.write(resp.read_stderr())
output.extend(rawOutput.getvalue().split('\n'))
output.extend(rawErrput.getvalue().split('\n'))
err = None
if yamlImported := YAMLDynamic():
err = yamlImported.safe_load(resp.read_channel(kubeImported.stream.ws_client.ERROR_CHANNEL))
if not err:
err = {}
err['status'] = 'Success'
if deep_get(err, ['status'], None) == 'Success':
retcode = 0
elif deep_get(err, ['reason'], None) == 'NonZeroExitCode':
retcodes = [
int(deep_get(x, ['message'], 1))
for x in deep_get(err, ['details', 'causes'], [{'reason': 'ExitCode', 'message': '1'}])
if (deep_get(x, ['reason'], None) == 'ExitCode')
]
retcode = retcodes[0] if len(retcodes) > 0 else 1
else:
# can't parse, but it's a failure
retcode = 1
resp.close()
except kubeImported.client.rest.ApiException as x:
if x.status != 404:
if retcode == 0:
retcode = 1
output.extend(str(x))
results[podName] = {}
results[podName]['err'] = retcode
results[podName]['output'] = output
return results
def PrintNodeStatus():
node_list = load_node_list()
with ThreadPoolExecutor() as executor:
futures = []
for node in node_list:
futures.append(executor.submit(node_stats, node))
node_summary = {}
for future in as_completed(futures):
a = future.result()
node_summary.update(a)
statusRows = [
[
'Node Name',
'Hostname',
'IP',
'Provider ID',
'Instance Type',
'Total CPU',
'CPU Usage',
'Percent CPU',
'Total Memory',
'Memory Usage',
'Total Storage',
'Current Pods',
],
]
for node in node_summary:
statusRows.append([str(x) for x in node_summary[node]])
tablify(statusRows)
def PrintPodStatus(namespace=None):
node_list = load_node_list()
with ThreadPoolExecutor() as executor:
futures = []
for node in node_list:
futures.append(executor.submit(pod_stats, node, namespace))
pod_summary = {}
for future in as_completed(futures):
a = future.result()
pod_summary.update(a)
statusRows = [
[
'Pod Name',
'Namespace',
'State',
'Pod IP',
'Pod Kind',
'Worker Node',
'CPU Usage',
'Memory Usage',
'Container Name:Restarts',
'Container Image',
],
]
if namespace:
del statusRows[0][1]
for pod in pod_summary:
statusRows.append([str(x) for x in pod_summary[pod]])
tablify(statusRows)
def DeleteNamespace(namespace, deleteRetPerVol=False):
results_dict = defaultdict(dict)
if namespace:
if kubeImported := KubernetesDynamic():
k8s_api = kubeImported.client.CoreV1Api()
manualDeletePersistentVolumes = []
if deleteRetPerVol:
# If indicated, manually delete PersistentVolumes with "Retain" reclaim policy
# - https://kubernetes.io/docs/concepts/storage/persistent-volumes/#retain
# get a list of PersistentVolumes to delete after the delete_namespace
# 1. from list_namespaced_persistent_volume_claim
# 2. from list_persistent_volume with the "namespace=XXXXXXX" label
manualDeletePersistentVolumes = [
x.spec.volume_name
for x in k8s_api.list_namespaced_persistent_volume_claim(
watch=False,
namespace=namespace,
).items
]
manualDeletePersistentVolumes.extend(
[
x.metadata.name
for x in k8s_api.list_persistent_volume(
label_selector=f'namespace={namespace}',
).items
if x.spec.persistent_volume_reclaim_policy == 'Retain'
]
)
# filter (ensuring we only ended up with "Retain" PersistentVolumes) and dedupe
manualDeletePersistentVolumes = list(
chain(
*[
[
x.metadata.name
for x in k8s_api.list_persistent_volume(
field_selector=f'metadata.name={name}',
).items
if x.spec.persistent_volume_reclaim_policy == 'Retain'
]
for name in set(manualDeletePersistentVolumes)
]
)
)
# delete the namespace, which should delete the resources belonging to it
try:
results_dict[namespace]['delete_namespace'] = k8s_api.delete_namespace(
namespace,
propagation_policy='Foreground',
)
except kubeImported.client.rest.ApiException as x:
if x.status != 404:
results_dict[namespace]['error'] = LoadStrIfJson(str(x))
if not results_dict[namespace]['error']:
results_dict[namespace]['error'] = str(x)
# If indicated, manually delete each PersistentVolume with "Retain" reclaim policy identified above
if manualDeletePersistentVolumes:
results_dict[namespace]['delete_persistent_volume'] = dict()
for name in manualDeletePersistentVolumes:
try:
results_dict[namespace]['delete_persistent_volume'][name] = k8s_api.delete_persistent_volume(
name=name
)
except kubeImported.client.rest.ApiException as x:
if x.status != 404:
if 'error' not in results_dict[namespace]['delete_persistent_volume']:
results_dict[namespace]['delete_persistent_volume']['error'] = dict()
results_dict[namespace]['delete_persistent_volume']['error'][name] = LoadStrIfJson(str(x))
if not results_dict[namespace]['delete_persistent_volume']['error'][name]:
results_dict[namespace]['delete_persistent_volume']['error'][name] = str(x)
return results_dict
def StartMalcolm(namespace, malcolmPath, configPath, profile=PROFILE_MALCOLM):
if not namespace:
namespace = 'malcolm'
results_dict = defaultdict(dict)
if (
os.path.isdir(malcolmPath)
and os.path.isdir(configPath)
and (kubeImported := KubernetesDynamic())
and (dotenvImported := DotEnvDynamic())
and (yamlImported := YAMLDynamic())
and (client := kubeImported.client.CoreV1Api())
and (apiClient := kubeImported.client.ApiClient())
):
# create the namespace
try:
results_dict['create_namespace']['result'] = client.create_namespace(
kubeImported.client.V1Namespace(metadata=kubeImported.client.V1ObjectMeta(name=namespace))
).metadata
except kubeImported.client.rest.ApiException as x:
if x.status != 409:
results_dict['create_namespace']['error'] = LoadStrIfJson(str(x))
if not results_dict['create_namespace']['error']:
results_dict['create_namespace']['error'] = str(x)
# create configmaps from files
results_dict['create_namespaced_config_map']['result'] = dict()
results_dict['create_namespaced_secret']['result'] = dict()
for configMapName, configMapFiles in MALCOLM_CONFIGMAPS.items():
for isSecret in (True, False):
resultsEntry = 'create_namespaced_secret' if isSecret else 'create_namespaced_config_map'
mapFiles = [x['path'] for x in configMapFiles if (x.get('secret', False) is isSecret)]
if mapFiles:
try:
dataMap = {}
binaryDataMap = {}
for fname in mapFiles:
if os.path.isfile(fname):
contents = file_contents(
fname,
binary_fallback=True,
)
if hasattr(contents, 'decode'):
binaryDataMap[os.path.basename(fname)] = base64.b64encode(contents).decode('utf-8')
else:
dataMap[os.path.basename(fname)] = contents
elif os.path.isdir(fname):
for subfname in glob.iglob(
os.path.join(os.path.join(fname, '**'), '*'), recursive=True
):
if os.path.isfile(subfname):
contents = file_contents(
subfname,
binary_fallback=True,
)
if hasattr(contents, 'decode'):
binaryDataMap[os.path.basename(subfname)] = base64.b64encode(
contents
).decode('utf-8')
else:
dataMap[os.path.basename(subfname)] = contents
metadata = kubeImported.client.V1ObjectMeta(
name=configMapName,
namespace=namespace,
)
if isSecret:
results_dict[resultsEntry]['result'][configMapName] = client.create_namespaced_secret(
namespace=namespace,
body=kubeImported.client.V1Secret(
metadata=metadata,
string_data=dataMap if dataMap else {},
data=binaryDataMap if binaryDataMap else {},
),
).metadata
else:
results_dict[resultsEntry]['result'][configMapName] = client.create_namespaced_config_map(
namespace=namespace,
body=kubeImported.client.V1ConfigMap(
metadata=metadata,
data=dataMap if dataMap else {},
binary_data=binaryDataMap if binaryDataMap else {},
),
).metadata
except kubeImported.client.rest.ApiException as x:
if x.status != 409:
if 'error' not in results_dict[resultsEntry]:
results_dict[resultsEntry]['error'] = dict()
results_dict[resultsEntry]['error'][os.path.basename(configMapName)] = LoadStrIfJson(str(x))
if not results_dict[resultsEntry]['error'][os.path.basename(configMapName)]:
results_dict[resultsEntry]['error'][os.path.basename(configMapName)] = str(x)
# create configmaps (or secrets, given a K8S_SECRET key) from .env files
results_dict['create_namespaced_config_map_from_env_file']['result'] = dict()
results_dict['create_namespaced_secret_from_env_file']['result'] = dict()
for envFileName in glob.iglob(os.path.join(configPath, '*.env'), recursive=False):
if os.path.isfile(envFileName):
try:
values = dotenvImported.dotenv_values(envFileName)
isSecret = val2bool(values.pop(MALCOLM_DOTFILE_SECRET_KEY, False))
metadata = kubeImported.client.V1ObjectMeta(
name=remove_suffix(os.path.basename(envFileName), '.env') + '-env'
)
if isSecret:
resultsEntry = 'create_namespaced_secret_from_env_file'
results_dict[resultsEntry]['result'][metadata.name] = client.create_namespaced_secret(
namespace=namespace,
body=kubeImported.client.V1Secret(
metadata=metadata,
string_data=values if values else {},
),
).metadata
else:
resultsEntry = 'create_namespaced_config_map_from_env_file'
results_dict[resultsEntry]['result'][metadata.name] = client.create_namespaced_config_map(
namespace=namespace,
body=kubeImported.client.V1ConfigMap(
metadata=metadata,
data=values if values else {},
),
).metadata
except kubeImported.client.rest.ApiException as x:
if x.status != 409:
if 'error' not in results_dict[resultsEntry]:
results_dict[resultsEntry]['error'] = dict()
results_dict[resultsEntry]['error'][os.path.basename(envFileName)] = LoadStrIfJson(str(x))
if not results_dict[resultsEntry]['error'][os.path.basename(envFileName)]:
results_dict[resultsEntry]['error'][os.path.basename(envFileName)] = str(x)
# apply manifests
results_dict['create_from_yaml']['result'] = dict()
yamlFiles = sorted(
list(
chain(
*[
glob.iglob(os.path.join(os.path.join(malcolmPath, 'kubernetes'), ftype), recursive=False)
for ftype in ['*.yml', '*.yaml']
]
)
)
)
for yamlName in yamlFiles:
# check to make sure the container in this YAML file belongs to this profile
containerBelongsInProfile = True
with open(yamlName, 'r') as manYamlFile:
if manYamlFileContents := list(yamlImported.safe_load_all(manYamlFile)):
for doc in manYamlFileContents:
if (
containers := [
remove_suffix(x.get('name', ''), '-container')
for x in deep_get(doc, ['spec', 'template', 'spec', 'containers'], [])
]
) and (not all(x in MALCOLM_PROFILES_CONTAINERS[profile] for x in containers)):
containerBelongsInProfile = False
break
# apply the manifests in this YAML file, otherwise skip it
if containerBelongsInProfile:
try:
results_dict['create_from_yaml']['result'][
os.path.basename(yamlName)
] = kubeImported.utils.create_from_yaml(
apiClient,
yamlName,
namespace=namespace,
)
except kubeImported.client.rest.ApiException as x:
if x.status != 409:
if 'error' not in results_dict['create_from_yaml']:
results_dict['create_from_yaml']['error'] = dict()
results_dict['create_from_yaml']['error'][os.path.basename(yamlName)] = LoadStrIfJson(str(x))
if not results_dict['create_from_yaml']['error'][os.path.basename(yamlName)]:
results_dict['create_from_yaml']['error'][os.path.basename(yamlName)] = str(x)
except kubeImported.utils.FailToCreateError as fe:
if [exc for exc in fe.api_exceptions if exc.status != 409]:
if 'error' not in results_dict['create_from_yaml']:
results_dict['create_from_yaml']['error'] = dict()
results_dict['create_from_yaml']['error'][os.path.basename(yamlName)] = LoadStrIfJson(str(fe))
if not results_dict['create_from_yaml']['error'][os.path.basename(yamlName)]:
results_dict['create_from_yaml']['error'][os.path.basename(yamlName)] = str(fe)
return results_dict
def CheckPersistentStorageDefs(namespace, malcolmPath, profile=PROFILE_MALCOLM):
foundObjects = {k: False for (k, v) in REQUIRED_VOLUME_OBJECTS[profile].items()}
if yamlImported := YAMLDynamic():
allYamlContents = []
yamlFiles = sorted(
list(
chain(
*[
glob.iglob(os.path.join(os.path.join(malcolmPath, 'kubernetes'), ftype), recursive=False)
for ftype in ['*.yml', '*.yaml']
]
)
)
)
for yamlName in yamlFiles:
with open(yamlName, 'r') as cf:
allYamlContents.extend(list(yamlImported.safe_load_all(cf)))
for name, kind in REQUIRED_VOLUME_OBJECTS[profile].items():
for doc in allYamlContents:
if (
(doc.get('kind', None) == kind)
and (deep_get(doc, ['metadata', 'namespace']) == namespace)
and (deep_get(doc, ['metadata', 'name']) == name)
):
foundObjects[name] = True
return all([v for k, v in foundObjects.items()])