-
Notifications
You must be signed in to change notification settings - Fork 40
/
kubernetes_manager.go
1909 lines (1696 loc) · 64.9 KB
/
kubernetes_manager.go
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
/*
* Copyright (c) 2021 - present Kurtosis Technologies Inc.
* All Rights Reserved.
*/
package kubernetes_manager
import (
"bytes"
"context"
"encoding/json"
"fmt"
"github.com/kurtosis-tech/stacktrace"
"github.com/sirupsen/logrus"
"golang.org/x/crypto/ssh/terminal"
"io"
apiv1 "k8s.io/api/core/v1"
rbacv1 "k8s.io/api/rbac/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
applyconfigurationsv1 "k8s.io/client-go/applyconfigurations/core/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/kubernetes/scheme"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/remotecommand"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"time"
)
const (
podWaitForAvailabilityTimeout = 15 * time.Minute
podWaitForAvailabilityTimeBetweenPolls = 500 * time.Millisecond
podWaitForTerminationTimeout = 5 * time.Minute
podWaitForTerminationTimeBetweenPolls = 500 * time.Millisecond
// This is a container "reason" (machine-readable string) indicating that the container has some issue with
// pulling the image (usually, a typo in the image name or the image doesn't exist)
// Pods in this state don't really recover on their own
imagePullBackOffContainerReason = "ImagePullBackOff"
containerStatusLineBulletPoint = " - "
// Kubernetes unfortunately doesn't have a good way to get the exit code out, so we have to parse it out of a string
expectedTerminationMessage = "command terminated with exit code"
shouldAllocateStdinOnPodExec = false
shouldAllocatedStdoutOnPodExec = true
shouldAllocatedStderrOnPodExec = true
shouldAllocateTtyOnPodExec = false
successExecCommandExitCode = 0
// This is the owner string we'll use when updating fields
fieldManager = "kurtosis"
shouldFollowContainerLogsWhenPrintingPodInfo = false
shouldAddTimestampsWhenPrintingPodInfo = true
listOptionsTimeoutSeconds int64 = 10
contextDeadlineExceeded = "context deadline exceeded"
)
// We'll try to use the nicer-to-use shells first before we drop down to the lower shells
var commandToRunWhenCreatingUserServiceShell = []string{
"sh",
"-c",
`if command -v 'bash' > /dev/null; then
echo "Found bash on container; creating bash shell..."; bash;
else
echo "No bash found on container; dropping down to sh shell..."; sh;
fi`,
}
var (
globalDeletePolicy = metav1.DeletePropagationForeground
globalDeleteOptions = metav1.DeleteOptions{
TypeMeta: metav1.TypeMeta{
Kind: "",
APIVersion: "",
},
GracePeriodSeconds: nil,
Preconditions: nil,
OrphanDependents: nil,
PropagationPolicy: &globalDeletePolicy,
DryRun: nil,
}
globalCreateOptions = metav1.CreateOptions{
TypeMeta: metav1.TypeMeta{
Kind: "",
APIVersion: "",
},
DryRun: nil,
// We need every object to have this field manager so that the Kurtosis objects can all seamlessly modify Kubernetes resources
FieldManager: fieldManager,
FieldValidation: "",
}
)
type KubernetesManager struct {
// The underlying K8s client that will be used to modify the K8s environment
kubernetesClientSet *kubernetes.Clientset
// Underlying restClient configuration
kuberneteRestConfig *rest.Config
}
func int64Ptr(i int64) *int64 { return &i }
func NewKubernetesManager(kubernetesClientSet *kubernetes.Clientset, kuberneteRestConfig *rest.Config) *KubernetesManager {
return &KubernetesManager{
kubernetesClientSet: kubernetesClientSet,
kuberneteRestConfig: kuberneteRestConfig,
}
}
// ---------------------------Services------------------------------------------------------------------------------
// CreateService creates a k8s service in the specified namespace. It connects pods to the service according to the pod labels passed in
func (manager *KubernetesManager) CreateService(ctx context.Context, namespace string, name string, serviceLabels map[string]string, serviceAnnotations map[string]string, matchPodLabels map[string]string, serviceType apiv1.ServiceType, ports []apiv1.ServicePort) (*apiv1.Service, error) {
servicesClient := manager.kubernetesClientSet.CoreV1().Services(namespace)
objectMeta := metav1.ObjectMeta{
Name: name,
GenerateName: "",
Namespace: "",
SelfLink: "",
UID: "",
ResourceVersion: "",
Generation: 0,
CreationTimestamp: metav1.Time{
Time: time.Time{},
},
DeletionTimestamp: nil,
DeletionGracePeriodSeconds: nil,
Labels: serviceLabels,
Annotations: serviceAnnotations,
OwnerReferences: nil,
Finalizers: nil,
ManagedFields: nil,
}
// Figure out selector api
// There must be a better way
serviceSpec := apiv1.ServiceSpec{
Ports: ports,
Selector: matchPodLabels, // these labels are used to match with the Pod
ClusterIP: "",
ClusterIPs: nil,
Type: serviceType,
ExternalIPs: nil,
SessionAffinity: "",
LoadBalancerIP: "",
LoadBalancerSourceRanges: nil,
ExternalName: "",
ExternalTrafficPolicy: "",
HealthCheckNodePort: 0,
PublishNotReadyAddresses: false,
SessionAffinityConfig: nil,
IPFamilies: nil,
IPFamilyPolicy: nil,
AllocateLoadBalancerNodePorts: nil,
LoadBalancerClass: nil,
InternalTrafficPolicy: nil,
}
service := &apiv1.Service{
TypeMeta: metav1.TypeMeta{
Kind: "",
APIVersion: "",
},
ObjectMeta: objectMeta,
Spec: serviceSpec,
Status: apiv1.ServiceStatus{
LoadBalancer: apiv1.LoadBalancerStatus{
Ingress: nil,
},
Conditions: nil,
},
}
serviceResult, err := servicesClient.Create(ctx, service, globalCreateOptions)
if err != nil {
return nil, stacktrace.Propagate(err, "Failed to create service '%s' in namespace '%s'", name, namespace)
}
return serviceResult, nil
}
func (manager *KubernetesManager) RemoveService(ctx context.Context, service *apiv1.Service) error {
namespace := service.Namespace
serviceName := service.Name
servicesClient := manager.kubernetesClientSet.CoreV1().Services(namespace)
if err := servicesClient.Delete(ctx, serviceName, globalDeleteOptions); err != nil {
return stacktrace.Propagate(err, "Failed to delete service '%s' with delete options '%+v' in namespace '%s'", serviceName, globalDeleteOptions, namespace)
}
return nil
}
func (manager *KubernetesManager) UpdateService(
ctx context.Context,
namespaceName string,
serviceName string,
// We use a configurator, rather than letting the user pass in their own ServiceApplyConfiguration, so that we ensure
// they use the constructor (and don't do struct instantiation and forget to add the namespace, object name, etc. which
// would result in removing the object name)
updateConfigurator func(configuration *applyconfigurationsv1.ServiceApplyConfiguration),
) (*apiv1.Service, error) {
updatesToApply := applyconfigurationsv1.Service(serviceName, namespaceName)
updateConfigurator(updatesToApply)
servicesClient := manager.kubernetesClientSet.CoreV1().Services(namespaceName)
applyOpts := metav1.ApplyOptions{
TypeMeta: metav1.TypeMeta{
Kind: "",
APIVersion: "",
},
DryRun: nil,
Force: false,
FieldManager: fieldManager,
}
result, err := servicesClient.Apply(ctx, updatesToApply, applyOpts)
if err != nil {
return nil, stacktrace.Propagate(err, "Failed to update service '%v' in namespace '%v'", serviceName, namespaceName)
}
return result, nil
}
func (manager *KubernetesManager) GetServicesByLabels(ctx context.Context, namespace string, serviceLabels map[string]string) (*apiv1.ServiceList, error) {
servicesClient := manager.kubernetesClientSet.CoreV1().Services(namespace)
listOptions := metav1.ListOptions{ //nolint:exhaustruct
TypeMeta: metav1.TypeMeta{
Kind: "",
APIVersion: "",
},
LabelSelector: labels.SelectorFromSet(serviceLabels).String(),
FieldSelector: "",
Watch: false,
AllowWatchBookmarks: false,
ResourceVersion: "",
ResourceVersionMatch: "",
TimeoutSeconds: int64Ptr(listOptionsTimeoutSeconds),
Limit: 0,
Continue: "",
}
serviceResult, err := servicesClient.List(ctx, listOptions)
if err != nil {
return nil, stacktrace.Propagate(err, "Failed to list services with labels '%+v' in namespace '%s'", serviceLabels, namespace)
}
// Only return objects not tombstoned by Kubernetes
var servicesNotMarkedForDeletionList []apiv1.Service
for _, service := range serviceResult.Items {
deletionTimestamp := service.GetObjectMeta().GetDeletionTimestamp()
if deletionTimestamp == nil {
servicesNotMarkedForDeletionList = append(servicesNotMarkedForDeletionList, service)
}
}
servicesNotMarkedForDeletionserviceList := apiv1.ServiceList{
Items: servicesNotMarkedForDeletionList,
TypeMeta: serviceResult.TypeMeta,
ListMeta: serviceResult.ListMeta,
}
return &servicesNotMarkedForDeletionserviceList, nil
}
// ---------------------------Volumes------------------------------------------------------------------------------
// TODO Delete this after 2022-08-01 if we're still not using PersistentVolumeClaims
/*
func (manager *KubernetesManager) CreatePersistentVolumeClaim(
ctx context.Context,
namespace string,
persistentVolumeClaimName string,
persistentVolumeClaimLabels map[string]string,
persistentVolumeClaimAnnotations map[string]string,
volumeSizeInMegabytes uint,
storageClassName string,
) (*apiv1.PersistentVolumeClaim, error) {
volumeClaimsClient := manager.kubernetesClientSet.CoreV1().PersistentVolumeClaims(namespace)
volumeSizeInMegabytesStr := strconv.FormatUint(uint64(volumeSizeInMegabytes), uintToIntStringConversionBase)
quantity, err := resource.ParseQuantity(volumeSizeInMegabytesStr + binaryMegabytesSuffix)
if err != nil {
return nil, stacktrace.Propagate(err, "Failed to parse volume size in megabytes %d", volumeSizeInMegabytes)
}
persistentVolumeClaim := &apiv1.PersistentVolumeClaim{
ObjectMeta: metav1.ObjectMeta{
Name: persistentVolumeClaimName,
Labels: persistentVolumeClaimLabels,
Namespace: namespace,
},
Spec: apiv1.PersistentVolumeClaimSpec{
AccessModes: []apiv1.PersistentVolumeAccessMode{
defaultPersistentVolumeClaimAccessMode,
},
StorageClassName: &storageClassName,
Resources: apiv1.ResourceRequirements{
Requests: map[apiv1.ResourceName]resource.Quantity{
apiv1.ResourceStorage: quantity,
},
},
},
}
if _, err := volumeClaimsClient.Create(ctx, persistentVolumeClaim, globalCreateOptions); err != nil {
return nil, stacktrace.Propagate(err, "Failed to create persistent volume claim with name '%s' in namespace '%s'", persistentVolumeClaimName, namespace)
}
// Wait for the PVC to become bound and return that object (which will have VolumeName filled out)
result, err := manager.waitForPersistentVolumeClaimBinding(ctx, namespace, persistentVolumeClaimName)
if err != nil {
return nil, stacktrace.Propagate(err, "An error occurred waiting for persistent volume claim '%v' get bound in namespace '%v'", persistentVolumeClaim.GetName(), persistentVolumeClaim.GetNamespace())
}
return result, nil
}
func (manager *KubernetesManager) RemovePersistentVolumeClaim(ctx context.Context, volumeClaim *apiv1.PersistentVolumeClaim) error {
namespace := volumeClaim.Namespace
name := volumeClaim.Name
volumeClaimsClient := manager.kubernetesClientSet.CoreV1().PersistentVolumeClaims(namespace)
if err := volumeClaimsClient.Delete(ctx, name, globalDeleteOptions); err != nil {
return stacktrace.Propagate(err, "Failed to delete persistent volume claim with name '%s' with delete options '%+v' in namespace '%s'", name, globalDeleteOptions, namespace)
}
return nil
}
func (manager *KubernetesManager) GetPersistentVolumeClaim(ctx context.Context, namespace string, persistentVolumeClaimName string) (*apiv1.PersistentVolumeClaim, error) {
persistentVolumeClaimsClient := manager.kubernetesClientSet.CoreV1().PersistentVolumeClaims(namespace)
volumeClaim, err := persistentVolumeClaimsClient.Get(ctx, persistentVolumeClaimName, metav1.GetOptions{})
if err != nil {
return nil, stacktrace.Propagate(err, "Failed to get persistent volume claim with name '%s' in namespace '%s'", persistentVolumeClaimName, namespace)
}
deletionTimestamp := volumeClaim.GetObjectMeta().GetDeletionTimestamp()
if deletionTimestamp != nil {
return nil, stacktrace.Propagate(err, "Persistent volume claim with name '%s' in namespace '%s' has been marked for deletion", persistentVolumeClaimName, namespace)
}
return volumeClaim, nil
}
// TODO Make return type an actual list
func (manager *KubernetesManager) GetPersistentVolumeClaimsByLabels(ctx context.Context, namespace string, persistentVolumeClaimLabels map[string]string) (*apiv1.PersistentVolumeClaimList, error) {
persistentVolumeClaimsClient := manager.kubernetesClientSet.CoreV1().PersistentVolumeClaims(namespace)
listOptions := metav1.ListOptions{
LabelSelector: labels.SelectorFromSet(persistentVolumeClaimLabels).String(),
}
persistentVolumeClaimsResult, err := persistentVolumeClaimsClient.List(ctx, listOptions)
if err != nil {
return nil, stacktrace.Propagate(err, "Failed to get persistent volume claim with labels '%+v' in namespace '%s'", persistentVolumeClaimLabels, namespace)
}
// Only return objects not tombstoned by Kubernetes
var persistentVolumeClaimsNotMarkedForDeletionList []apiv1.PersistentVolumeClaim
for _, persistentVolumeClaim := range persistentVolumeClaimsResult.Items {
deletionTimestamp := persistentVolumeClaim.GetObjectMeta().GetDeletionTimestamp()
if deletionTimestamp == nil {
persistentVolumeClaimsNotMarkedForDeletionList = append(persistentVolumeClaimsNotMarkedForDeletionList, persistentVolumeClaim)
}
}
persistentVolumeClaimsNotMarkedForDeletionpersistentVolumeClaimList := apiv1.PersistentVolumeClaimList{
Items: persistentVolumeClaimsNotMarkedForDeletionList,
TypeMeta: persistentVolumeClaimsResult.TypeMeta,
ListMeta: persistentVolumeClaimsResult.ListMeta,
}
return &persistentVolumeClaimsNotMarkedForDeletionpersistentVolumeClaimList, nil
}
*/
// ---------------------------namespaces------------------------------------------------------------------------------
func (manager *KubernetesManager) CreateNamespace(
ctx context.Context,
name string,
namespaceLabels map[string]string,
namespaceAnnotations map[string]string,
) (*apiv1.Namespace, error) {
namespaceClient := manager.kubernetesClientSet.CoreV1().Namespaces()
namespace := &apiv1.Namespace{
TypeMeta: metav1.TypeMeta{
Kind: "",
APIVersion: "",
},
ObjectMeta: metav1.ObjectMeta{
Name: name,
GenerateName: "",
Namespace: "",
SelfLink: "",
UID: "",
ResourceVersion: "",
Generation: 0,
CreationTimestamp: metav1.Time{
Time: time.Time{},
},
DeletionTimestamp: nil,
DeletionGracePeriodSeconds: nil,
Labels: namespaceLabels,
Annotations: namespaceAnnotations,
OwnerReferences: nil,
Finalizers: nil,
ManagedFields: nil,
},
Spec: apiv1.NamespaceSpec{
Finalizers: nil,
},
Status: apiv1.NamespaceStatus{
Phase: "",
Conditions: nil,
},
}
namespaceResult, err := namespaceClient.Create(ctx, namespace, globalCreateOptions)
if err != nil {
return nil, stacktrace.Propagate(err, "Failed to create namespace with name '%s'", name)
}
return namespaceResult, nil
}
func (manager *KubernetesManager) UpdateNamespace(
ctx context.Context,
namespaceName string,
// We use a configurator, rather than letting the user pass in their own NamespaceApplyConfiguration, so that we ensure
// they use the constructor (and don't do struct instantiation and forget to add the object name, etc. which
// would result in removing the object name)
updateConfigurator func(configuration *applyconfigurationsv1.NamespaceApplyConfiguration),
) (*apiv1.Namespace, error) {
updatesToApply := applyconfigurationsv1.Namespace(namespaceName)
updateConfigurator(updatesToApply)
namespaceClient := manager.kubernetesClientSet.CoreV1().Namespaces()
applyOpts := metav1.ApplyOptions{
TypeMeta: metav1.TypeMeta{
Kind: "",
APIVersion: "",
},
DryRun: nil,
Force: true, //We need to use force to avoid conflict errors
FieldManager: fieldManager,
}
result, err := namespaceClient.Apply(ctx, updatesToApply, applyOpts)
if err != nil {
return nil, stacktrace.Propagate(err, "Failed to update namespace '%v' ", namespaceName)
}
return result, nil
}
func (manager *KubernetesManager) RemoveNamespace(ctx context.Context, namespace *apiv1.Namespace) error {
name := namespace.Name
namespaceClient := manager.kubernetesClientSet.CoreV1().Namespaces()
if err := namespaceClient.Delete(ctx, name, globalDeleteOptions); err != nil {
return stacktrace.Propagate(err, "Failed to delete namespace with name '%s' with delete options '%+v'", name, globalDeleteOptions)
}
return nil
}
func (manager *KubernetesManager) GetNamespace(ctx context.Context, name string) (*apiv1.Namespace, error) {
namespaceClient := manager.kubernetesClientSet.CoreV1().Namespaces()
namespace, err := namespaceClient.Get(ctx, name, metav1.GetOptions{
TypeMeta: metav1.TypeMeta{
Kind: "",
APIVersion: "",
},
ResourceVersion: "",
})
if err != nil {
return nil, stacktrace.Propagate(err, "Failed to get namespace with name '%s'", name)
}
deletionTimestamp := namespace.GetObjectMeta().GetDeletionTimestamp()
if deletionTimestamp != nil {
return nil, stacktrace.Propagate(err, "Namespace with name '%s' has been marked for deletion", namespace)
}
return namespace, nil
}
func (manager *KubernetesManager) GetNamespacesByLabels(ctx context.Context, namespaceLabels map[string]string) (*apiv1.NamespaceList, error) {
namespaceClient := manager.kubernetesClientSet.CoreV1().Namespaces()
listOptions := metav1.ListOptions{ //nolint:exhaustruct
TypeMeta: metav1.TypeMeta{
Kind: "",
APIVersion: "",
},
LabelSelector: labels.SelectorFromSet(namespaceLabels).String(),
FieldSelector: "",
Watch: false,
AllowWatchBookmarks: false,
ResourceVersion: "",
ResourceVersionMatch: "",
TimeoutSeconds: int64Ptr(listOptionsTimeoutSeconds),
Limit: 0,
Continue: "",
}
namespaces, err := namespaceClient.List(ctx, listOptions)
if err != nil {
return nil, stacktrace.Propagate(err, "Failed to list namespaces with labels '%+v'", namespaceLabels)
}
// Only return objects not tombstoned by Kubernetes
var namespacesNotMarkedForDeletionList []apiv1.Namespace
for _, namespace := range namespaces.Items {
deletionTimestamp := namespace.GetObjectMeta().GetDeletionTimestamp()
if deletionTimestamp == nil {
namespacesNotMarkedForDeletionList = append(namespacesNotMarkedForDeletionList, namespace)
}
}
namespacesNotMarkedForDeletionnamespaceList := apiv1.NamespaceList{
Items: namespacesNotMarkedForDeletionList,
TypeMeta: namespaces.TypeMeta,
ListMeta: namespaces.ListMeta,
}
return &namespacesNotMarkedForDeletionnamespaceList, nil
}
// ---------------------------service accounts------------------------------------------------------------------------------
func (manager *KubernetesManager) CreateServiceAccount(ctx context.Context, name string, namespace string, labels map[string]string) (*apiv1.ServiceAccount, error) {
client := manager.kubernetesClientSet.CoreV1().ServiceAccounts(namespace)
serviceAccount := &apiv1.ServiceAccount{
TypeMeta: metav1.TypeMeta{
Kind: "",
APIVersion: "",
},
ObjectMeta: metav1.ObjectMeta{
Name: name,
GenerateName: "",
Namespace: "",
SelfLink: "",
UID: "",
ResourceVersion: "",
Generation: 0,
CreationTimestamp: metav1.Time{
Time: time.Time{},
},
DeletionTimestamp: nil,
DeletionGracePeriodSeconds: nil,
Labels: labels,
Annotations: nil,
OwnerReferences: nil,
Finalizers: nil,
ManagedFields: nil,
},
Secrets: nil,
ImagePullSecrets: []apiv1.LocalObjectReference{
{
Name: "kurtosis-image",
},
},
AutomountServiceAccountToken: nil,
}
serviceAccountResult, err := client.Create(ctx, serviceAccount, globalCreateOptions)
if err != nil {
return nil, stacktrace.Propagate(err, "Failed to create service account with name '%s' in namespace '%v'", name, namespace)
}
return serviceAccountResult, nil
}
func (manager *KubernetesManager) GetServiceAccountsByLabels(ctx context.Context, namespace string, serviceAccountsLabels map[string]string) (*apiv1.ServiceAccountList, error) {
client := manager.kubernetesClientSet.CoreV1().ServiceAccounts(namespace)
opts := metav1.ListOptions{ //nolint:exhaustruct
TypeMeta: metav1.TypeMeta{
Kind: "",
APIVersion: "",
},
LabelSelector: labels.SelectorFromSet(serviceAccountsLabels).String(),
FieldSelector: "",
Watch: false,
AllowWatchBookmarks: false,
ResourceVersion: "",
ResourceVersionMatch: "",
TimeoutSeconds: int64Ptr(listOptionsTimeoutSeconds),
Limit: 0,
Continue: "",
}
serviceAccounts, err := client.List(ctx, opts)
if err != nil {
return nil, stacktrace.Propagate(err, "Expected to be able to get service accounts with labels '%+v', instead a non-nil error was returned", serviceAccountsLabels)
}
// Only return objects not tombstoned by Kubernetes
var serviceAccountsNotMarkedForDeletionList []apiv1.ServiceAccount
for _, serviceAccount := range serviceAccounts.Items {
deletionTimestamp := serviceAccount.GetObjectMeta().GetDeletionTimestamp()
if deletionTimestamp == nil {
serviceAccountsNotMarkedForDeletionList = append(serviceAccountsNotMarkedForDeletionList, serviceAccount)
}
}
serviceAccountsNotMarkedForDeletionserviceAccountList := apiv1.ServiceAccountList{
Items: serviceAccountsNotMarkedForDeletionList,
TypeMeta: serviceAccounts.TypeMeta,
ListMeta: serviceAccounts.ListMeta,
}
return &serviceAccountsNotMarkedForDeletionserviceAccountList, nil
}
func (manager *KubernetesManager) RemoveServiceAccount(ctx context.Context, serviceAccount *apiv1.ServiceAccount) error {
name := serviceAccount.Name
namespace := serviceAccount.Namespace
client := manager.kubernetesClientSet.CoreV1().ServiceAccounts(namespace)
deleteOptions := metav1.DeleteOptions{
TypeMeta: metav1.TypeMeta{
Kind: "",
APIVersion: "",
},
GracePeriodSeconds: nil,
Preconditions: nil,
OrphanDependents: nil,
PropagationPolicy: nil,
DryRun: nil,
}
if err := client.Delete(ctx, name, deleteOptions); err != nil {
return stacktrace.Propagate(err, "Failed to delete service account with name '%s' in namespace '%v'", name, namespace)
}
return nil
}
// ---------------------------roles------------------------------------------------------------------------------
func (manager *KubernetesManager) CreateRole(ctx context.Context, name string, namespace string, rules []rbacv1.PolicyRule, labels map[string]string) (*rbacv1.Role, error) {
client := manager.kubernetesClientSet.RbacV1().Roles(namespace)
role := &rbacv1.Role{
TypeMeta: metav1.TypeMeta{
Kind: "",
APIVersion: "",
},
ObjectMeta: metav1.ObjectMeta{
Name: name,
GenerateName: "",
Namespace: "",
SelfLink: "",
UID: "",
ResourceVersion: "",
Generation: 0,
CreationTimestamp: metav1.Time{
Time: time.Time{},
},
DeletionTimestamp: nil,
DeletionGracePeriodSeconds: nil,
Labels: labels,
Annotations: nil,
OwnerReferences: nil,
Finalizers: nil,
ManagedFields: nil,
},
Rules: rules,
}
roleResult, err := client.Create(ctx, role, globalCreateOptions)
if err != nil {
return nil, stacktrace.Propagate(err, "Failed to create role with name '%s' in namespace '%v' and rules '%+v'", name, namespace, rules)
}
return roleResult, nil
}
func (manager *KubernetesManager) GetRolesByLabels(ctx context.Context, namespace string, rolesLabels map[string]string) (*rbacv1.RoleList, error) {
client := manager.kubernetesClientSet.RbacV1().Roles(namespace)
opts := metav1.ListOptions{ //nolint:exhaustruct
TypeMeta: metav1.TypeMeta{
Kind: "",
APIVersion: "",
},
LabelSelector: labels.SelectorFromSet(rolesLabels).String(),
FieldSelector: "",
Watch: false,
AllowWatchBookmarks: false,
ResourceVersion: "",
ResourceVersionMatch: "",
TimeoutSeconds: int64Ptr(listOptionsTimeoutSeconds),
Limit: 0,
Continue: "",
}
roles, err := client.List(ctx, opts)
if err != nil {
return nil, stacktrace.Propagate(err, "Expected to be able to get roles with labels '%+v', instead a non-nil error was returned", rolesLabels)
}
// Only return objects not tombstoned by Kubernetes
var rolesNotMarkedForDeletionList []rbacv1.Role
for _, role := range roles.Items {
deletionTimestamp := role.GetObjectMeta().GetDeletionTimestamp()
if deletionTimestamp == nil {
rolesNotMarkedForDeletionList = append(rolesNotMarkedForDeletionList, role)
}
}
rolesNotMarkedForDeletionroleList := rbacv1.RoleList{
Items: rolesNotMarkedForDeletionList,
TypeMeta: roles.TypeMeta,
ListMeta: roles.ListMeta,
}
return &rolesNotMarkedForDeletionroleList, nil
}
func (manager *KubernetesManager) RemoveRole(ctx context.Context, role *rbacv1.Role) error {
name := role.Name
namespace := role.Namespace
client := manager.kubernetesClientSet.RbacV1().Roles(namespace)
deleteOptions := metav1.DeleteOptions{
TypeMeta: metav1.TypeMeta{
Kind: "",
APIVersion: "",
},
GracePeriodSeconds: nil,
Preconditions: nil,
OrphanDependents: nil,
PropagationPolicy: nil,
DryRun: nil,
}
if err := client.Delete(ctx, name, deleteOptions); err != nil {
return stacktrace.Propagate(err, "Failed to delete role with name '%s' in namespace '%v'", name, namespace)
}
return nil
}
// --------------------------- Role Bindings ------------------------------------------------------------------------------
func (manager *KubernetesManager) CreateRoleBindings(ctx context.Context, name string, namespace string, subjects []rbacv1.Subject, roleRef rbacv1.RoleRef, labels map[string]string) (*rbacv1.RoleBinding, error) {
client := manager.kubernetesClientSet.RbacV1().RoleBindings(namespace)
roleBinding := &rbacv1.RoleBinding{
TypeMeta: metav1.TypeMeta{
Kind: "",
APIVersion: "",
},
ObjectMeta: metav1.ObjectMeta{
Name: name,
GenerateName: "",
Namespace: "",
SelfLink: "",
UID: "",
ResourceVersion: "",
Generation: 0,
CreationTimestamp: metav1.Time{
Time: time.Time{},
},
DeletionTimestamp: nil,
DeletionGracePeriodSeconds: nil,
Labels: labels,
Annotations: nil,
OwnerReferences: nil,
Finalizers: nil,
ManagedFields: nil,
},
Subjects: subjects,
RoleRef: roleRef,
}
roleBindingResult, err := client.Create(ctx, roleBinding, globalCreateOptions)
if err != nil {
return nil, stacktrace.Propagate(err, "Failed to create role binding with name '%s', subjects '%+v' and role ref '%v'", name, subjects, roleRef)
}
return roleBindingResult, nil
}
func (manager *KubernetesManager) GetRoleBindingsByLabels(ctx context.Context, namespace string, roleBindingsLabels map[string]string) (*rbacv1.RoleBindingList, error) {
client := manager.kubernetesClientSet.RbacV1().RoleBindings(namespace)
opts := metav1.ListOptions{ //nolint:exhaustruct
TypeMeta: metav1.TypeMeta{
Kind: "",
APIVersion: "",
},
LabelSelector: labels.SelectorFromSet(roleBindingsLabels).String(),
FieldSelector: "",
Watch: false,
AllowWatchBookmarks: false,
ResourceVersion: "",
ResourceVersionMatch: "",
TimeoutSeconds: int64Ptr(listOptionsTimeoutSeconds),
Limit: 0,
Continue: "",
}
roleBindings, err := client.List(ctx, opts)
if err != nil {
return nil, stacktrace.Propagate(err, "Expected to be able to get role bindings with labels '%+v', instead a non-nil error was returned", roleBindingsLabels)
}
// Only return objects not tombstoned by Kubernetes
var roleBindingsNotMarkedForDeletionList []rbacv1.RoleBinding
for _, roleBinding := range roleBindings.Items {
deletionTimestamp := roleBinding.GetObjectMeta().GetDeletionTimestamp()
if deletionTimestamp == nil {
roleBindingsNotMarkedForDeletionList = append(roleBindingsNotMarkedForDeletionList, roleBinding)
}
}
roleBindingsNotMarkedForDeletionroleBindingList := rbacv1.RoleBindingList{
Items: roleBindingsNotMarkedForDeletionList,
TypeMeta: roleBindings.TypeMeta,
ListMeta: roleBindings.ListMeta,
}
return &roleBindingsNotMarkedForDeletionroleBindingList, nil
}
func (manager *KubernetesManager) RemoveRoleBindings(ctx context.Context, roleBinding *rbacv1.RoleBinding) error {
name := roleBinding.Name
namespace := roleBinding.Namespace
client := manager.kubernetesClientSet.RbacV1().RoleBindings(namespace)
deleteOptions := metav1.DeleteOptions{
TypeMeta: metav1.TypeMeta{
Kind: "",
APIVersion: "",
},
GracePeriodSeconds: nil,
Preconditions: nil,
OrphanDependents: nil,
PropagationPolicy: nil,
DryRun: nil,
}
if err := client.Delete(ctx, name, deleteOptions); err != nil {
return stacktrace.Propagate(err, "Failed to delete role bindings with name '%s' in namespace '%v'", name, namespace)
}
return nil
}
// ---------------------------cluster roles------------------------------------------------------------------------------
func (manager *KubernetesManager) CreateClusterRoles(ctx context.Context, name string, rules []rbacv1.PolicyRule, labels map[string]string) (*rbacv1.ClusterRole, error) {
client := manager.kubernetesClientSet.RbacV1().ClusterRoles()
clusterRole := &rbacv1.ClusterRole{
TypeMeta: metav1.TypeMeta{
Kind: "",
APIVersion: "",
},
ObjectMeta: metav1.ObjectMeta{
Name: name,
GenerateName: "",
Namespace: "",
SelfLink: "",
UID: "",
ResourceVersion: "",
Generation: 0,
CreationTimestamp: metav1.Time{
Time: time.Time{},
},
DeletionTimestamp: nil,
DeletionGracePeriodSeconds: nil,
Labels: labels,
Annotations: nil,
OwnerReferences: nil,
Finalizers: nil,
ManagedFields: nil,
},
Rules: rules,
AggregationRule: nil,
}
clusterRoleResult, err := client.Create(ctx, clusterRole, globalCreateOptions)
if err != nil {
return nil, stacktrace.Propagate(err, "Failed to create cluster role with name '%s' with rules '%+v'", name, rules)
}
return clusterRoleResult, nil
}
func (manager *KubernetesManager) GetClusterRolesByLabels(ctx context.Context, clusterRoleLabels map[string]string) (*rbacv1.ClusterRoleList, error) {
client := manager.kubernetesClientSet.RbacV1().ClusterRoles()
opts := metav1.ListOptions{ //nolint:exhaustruct
TypeMeta: metav1.TypeMeta{
Kind: "",
APIVersion: "",
},
LabelSelector: labels.SelectorFromSet(clusterRoleLabels).String(),
FieldSelector: "",
Watch: false,
AllowWatchBookmarks: false,
ResourceVersion: "",
ResourceVersionMatch: "",
TimeoutSeconds: int64Ptr(listOptionsTimeoutSeconds),
Limit: 0,
Continue: "",
}
clusterRoles, err := client.List(ctx, opts)
if err != nil {
return nil, stacktrace.Propagate(err, "Expected to be able to get cluster roles with labels '%+v', instead a non-nil error was returned", clusterRoleLabels)
}
// Only return objects not tombstoned by Kubernetes
var clusterRolesNotMarkedForDeletionList []rbacv1.ClusterRole
for _, clusterRole := range clusterRoles.Items {
deletionTimestamp := clusterRole.GetObjectMeta().GetDeletionTimestamp()
if deletionTimestamp == nil {
clusterRolesNotMarkedForDeletionList = append(clusterRolesNotMarkedForDeletionList, clusterRole)
}
}
clusterRolesNotMarkedForDeletionclusterRoleList := rbacv1.ClusterRoleList{
Items: clusterRolesNotMarkedForDeletionList,
TypeMeta: clusterRoles.TypeMeta,
ListMeta: clusterRoles.ListMeta,
}
return &clusterRolesNotMarkedForDeletionclusterRoleList, nil
}
func (manager *KubernetesManager) RemoveClusterRole(ctx context.Context, clusterRole *rbacv1.ClusterRole) error {
name := clusterRole.Name
client := manager.kubernetesClientSet.RbacV1().ClusterRoles()
deleteOptions := metav1.DeleteOptions{
TypeMeta: metav1.TypeMeta{
Kind: "",
APIVersion: "",
},
GracePeriodSeconds: nil,
Preconditions: nil,
OrphanDependents: nil,
PropagationPolicy: nil,
DryRun: nil,
}
if err := client.Delete(ctx, name, deleteOptions); err != nil {
return stacktrace.Propagate(err, "Failed to delete cluster role with name '%s'", name)
}
return nil
}
// --------------------------- Cluster Role Bindings ------------------------------------------------------------------------------
func (manager *KubernetesManager) CreateClusterRoleBindings(ctx context.Context, name string, subjects []rbacv1.Subject, roleRef rbacv1.RoleRef, labels map[string]string) (*rbacv1.ClusterRoleBinding, error) {
client := manager.kubernetesClientSet.RbacV1().ClusterRoleBindings()
clusterRoleBinding := &rbacv1.ClusterRoleBinding{
TypeMeta: metav1.TypeMeta{
Kind: "",
APIVersion: "",
},
ObjectMeta: metav1.ObjectMeta{
Name: name,
GenerateName: "",
Namespace: "",
SelfLink: "",
UID: "",
ResourceVersion: "",
Generation: 0,
CreationTimestamp: metav1.Time{
Time: time.Time{},
},
DeletionTimestamp: nil,
DeletionGracePeriodSeconds: nil,
Labels: labels,
Annotations: nil,
OwnerReferences: nil,
Finalizers: nil,
ManagedFields: nil,
},
Subjects: subjects,
RoleRef: roleRef,
}
clusterRoleBindingResult, err := client.Create(ctx, clusterRoleBinding, globalCreateOptions)
if err != nil {
return nil, stacktrace.Propagate(err, "Failed to create cluster role binding with name '%s', subjects '%+v' and role ref '%v'", name, subjects, roleRef)
}
return clusterRoleBindingResult, nil
}
func (manager *KubernetesManager) GetClusterRoleBindingsByLabels(ctx context.Context, clusterRoleBindingsLabels map[string]string) (*rbacv1.ClusterRoleBindingList, error) {
client := manager.kubernetesClientSet.RbacV1().ClusterRoleBindings()
opts := metav1.ListOptions{ //nolint:exhaustruct
TypeMeta: metav1.TypeMeta{
Kind: "",