forked from openshift-kni/eco-goinfra
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpod.go
1359 lines (1010 loc) · 37 KB
/
pod.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
package pod
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"time"
"k8s.io/apimachinery/pkg/runtime/schema"
"github.com/golang/glog"
multus "gopkg.in/k8snetworkplumbingwg/multus-cni.v4/pkg/types"
corev1 "k8s.io/api/core/v1"
k8serrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/httpstream/spdy"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/client-go/kubernetes/scheme"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/remotecommand"
"k8s.io/utils/ptr"
"github.com/openshift-kni/eco-goinfra/pkg/clients"
"github.com/openshift-kni/eco-goinfra/pkg/msg"
)
// Builder provides a struct for pod object from the cluster and a pod definition.
type Builder struct {
// Pod definition, used to create the pod object.
Definition *corev1.Pod
// Created pod object.
Object *corev1.Pod
// Used to store latest error message upon defining or mutating pod definition.
errorMsg string
// api client to interact with the cluster.
apiClient *clients.Settings
}
// AdditionalOptions additional options for pod object.
type AdditionalOptions func(builder *Builder) (*Builder, error)
// NewBuilder creates a new instance of Builder.
func NewBuilder(apiClient *clients.Settings, name, nsname, image string) *Builder {
glog.V(100).Infof(
"Initializing new pod structure with the following params: "+
"name: %s, namespace: %s, image: %s",
name, nsname, image)
if apiClient == nil {
glog.V(100).Infof("The apiClient is empty, pod 'apiClient' cannot be empty")
return nil
}
builder := &Builder{
apiClient: apiClient,
Definition: getDefinition(name, nsname),
}
if name == "" {
glog.V(100).Infof("The name of the pod is empty")
builder.errorMsg = "pod 'name' cannot be empty"
return builder
}
if nsname == "" {
glog.V(100).Infof("The namespace of the pod is empty")
builder.errorMsg = "pod 'namespace' cannot be empty"
return builder
}
if image == "" {
glog.V(100).Infof("The image of the pod is empty")
builder.errorMsg = "pod 'image' cannot be empty"
return builder
}
defaultContainer, err := NewContainerBuilder("test", image, []string{"/bin/bash", "-c", "sleep INF"}).GetContainerCfg()
if err != nil {
glog.V(100).Infof("Failed to define the default container settings")
builder.errorMsg = err.Error()
return builder
}
builder.Definition.Spec.Containers = append(builder.Definition.Spec.Containers, *defaultContainer)
return builder
}
// Pull loads an existing pod into the Builder struct.
func Pull(apiClient *clients.Settings, name, nsname string) (*Builder, error) {
glog.V(100).Infof("Pulling existing pod name: %s namespace:%s", name, nsname)
if apiClient == nil {
glog.V(100).Infof("The apiClient is empty")
return nil, fmt.Errorf("pod 'apiClient' cannot be empty")
}
builder := &Builder{
apiClient: apiClient,
Definition: &corev1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: name,
Namespace: nsname,
},
},
}
if name == "" {
glog.V(100).Infof("The name of the pod is empty")
return nil, fmt.Errorf("pod 'name' cannot be empty")
}
if nsname == "" {
glog.V(100).Infof("The namespace of the pod is empty")
return nil, fmt.Errorf("pod 'namespace' cannot be empty")
}
if !builder.Exists() {
glog.V(100).Infof("Failed to pull pod object %s from namespace %s. Object does not exist",
name, nsname)
return nil, fmt.Errorf("pod object %s does not exist in namespace %s", name, nsname)
}
builder.Definition = builder.Object
return builder, nil
}
// DefineOnNode adds nodeName to the pod's definition.
func (builder *Builder) DefineOnNode(nodeName string) *Builder {
if valid, _ := builder.validate(); !valid {
return builder
}
glog.V(100).Infof("Adding nodeName %s to the definition of pod %s in namespace %s",
nodeName, builder.Definition.Name, builder.Definition.Namespace)
builder.isMutationAllowed("nodeName")
if nodeName == "" {
glog.V(100).Infof("The node name is empty")
builder.errorMsg = "can not define pod on empty node"
return builder
}
builder.Definition.Spec.NodeName = nodeName
return builder
}
// Create makes a pod according to the pod definition and stores the created object in the pod builder.
func (builder *Builder) Create() (*Builder, error) {
if valid, err := builder.validate(); !valid {
return builder, err
}
glog.V(100).Infof("Creating pod %s in namespace %s",
builder.Definition.Name, builder.Definition.Namespace)
var err error
if !builder.Exists() {
builder.Object, err = builder.apiClient.Pods(builder.Definition.Namespace).Create(
context.TODO(), builder.Definition, metav1.CreateOptions{})
}
return builder, err
}
// Delete removes the pod object and resets the builder object.
func (builder *Builder) Delete() (*Builder, error) {
if valid, err := builder.validate(); !valid {
return builder, err
}
glog.V(100).Infof("Deleting pod %s in namespace %s",
builder.Definition.Name, builder.Definition.Namespace)
if !builder.Exists() {
glog.V(100).Infof(
"Pod %s in namespace %s cannot be deleted because it does not exist",
builder.Definition.Name, builder.Definition.Namespace)
builder.Object = nil
return builder, nil
}
err := builder.apiClient.Pods(builder.Definition.Namespace).Delete(
context.TODO(), builder.Object.Name, metav1.DeleteOptions{})
if err != nil {
return builder, fmt.Errorf("can not delete pod: %w", err)
}
builder.Object = nil
return builder, nil
}
// DeleteAndWait deletes the pod object and waits until the pod is deleted.
func (builder *Builder) DeleteAndWait(timeout time.Duration) (*Builder, error) {
if valid, err := builder.validate(); !valid {
return builder, err
}
glog.V(100).Infof("Deleting pod %s in namespace %s and waiting for the defined period until it is removed",
builder.Definition.Name, builder.Definition.Namespace)
builder, err := builder.Delete()
if err != nil {
return builder, err
}
err = builder.WaitUntilDeleted(timeout)
if err != nil {
return builder, err
}
return builder, nil
}
// DeleteImmediate removes the pod immediately and resets the builder object.
func (builder *Builder) DeleteImmediate() (*Builder, error) {
if valid, err := builder.validate(); !valid {
return builder, err
}
glog.V(100).Infof("Immediately deleting pod %s in namespace %s",
builder.Definition.Name, builder.Definition.Namespace)
if !builder.Exists() {
glog.V(100).Infof(
"Pod %s in namespace %s cannot be deleted because it does not exist",
builder.Definition.Name, builder.Definition.Namespace)
builder.Object = nil
return builder, nil
}
err := builder.apiClient.Pods(builder.Definition.Namespace).Delete(
context.TODO(), builder.Object.Name, metav1.DeleteOptions{GracePeriodSeconds: ptr.To(int64(0))})
if err != nil {
return builder, fmt.Errorf("can not immediately delete pod: %w", err)
}
builder.Object = nil
return builder, nil
}
// CreateAndWaitUntilRunning creates the pod object and waits until the pod is running.
func (builder *Builder) CreateAndWaitUntilRunning(timeout time.Duration) (*Builder, error) {
if valid, err := builder.validate(); !valid {
return builder, err
}
glog.V(100).Infof("Creating pod %s in namespace %s and waiting for the defined period until it is ready",
builder.Definition.Name, builder.Definition.Namespace)
builder, err := builder.Create()
if err != nil {
return builder, err
}
err = builder.WaitUntilRunning(timeout)
if err != nil {
return builder, err
}
return builder, nil
}
// WaitUntilRunning waits for the duration of the defined timeout or until the pod is running.
func (builder *Builder) WaitUntilRunning(timeout time.Duration) error {
if valid, err := builder.validate(); !valid {
return err
}
glog.V(100).Infof("Waiting for the defined period until pod %s in namespace %s is running",
builder.Definition.Name, builder.Definition.Namespace)
return builder.WaitUntilInStatus(corev1.PodRunning, timeout)
}
// WaitUntilHealthy waits for the duration of the defined timeout or until the pod is healthy.
// A healthy pod is in running phase and optionally in ready condition.
//
// timeout is the duration to wait for the pod to be healthy
// includeSucceeded when true, implies that pod in succeeded phase is running.
// skipReadinessCheck when false, checks that the podCondition is ready.
// ignoreRestartPolicyNever when true, Ignores failed pods with restart policy set to never.
func (builder *Builder) WaitUntilHealthy(timeout time.Duration, includeSucceeded, skipReadinessCheck,
ignoreRestartPolicyNever bool) error {
statusesChecked := []corev1.PodPhase{corev1.PodRunning}
// Ignore failed pod with restart policy never. This could happen in image pruner or installer pods that
// will never restart. For those pods, instead of restarting the same pod, a new pod will be created
// to complete the task.
if ignoreRestartPolicyNever &&
builder.Object.Status.Phase == corev1.PodFailed &&
builder.Object.Spec.RestartPolicy == corev1.RestartPolicyNever {
glog.V(100).Infof("Ignore failed pod with restart policy never. Message: %s",
builder.Object.Status.Message)
return nil
}
if includeSucceeded {
statusesChecked = append(statusesChecked, corev1.PodSucceeded)
}
podPhase, err := builder.WaitUntilInOneOfStatuses(statusesChecked, timeout)
if err != nil {
glog.V(100).Infof("pod condition is not in %v. Message: %s", statusesChecked, builder.Object.Status.Message)
return err
}
if skipReadinessCheck || *podPhase == corev1.PodSucceeded {
return nil
}
err = builder.WaitUntilCondition(corev1.PodReady, timeout)
if err != nil {
glog.V(100).Infof("pod condition is not Ready. Message: %s", builder.Object.Status.Message)
return err
}
return nil
}
// WaitUntilInStatus waits for the duration of the defined timeout or until the pod gets to a specific status.
func (builder *Builder) WaitUntilInStatus(status corev1.PodPhase, timeout time.Duration) error {
if valid, err := builder.validate(); !valid {
return err
}
glog.V(100).Infof("Waiting for the defined period until pod %s in namespace %s has status %v",
builder.Definition.Name, builder.Definition.Namespace, status)
_, err := builder.WaitUntilInOneOfStatuses([]corev1.PodPhase{status}, timeout)
return err
}
// WaitUntilInOneOfStatuses waits for the duration of the defined timeout or until the pod gets to any specific status
// in a list of statues.
func (builder *Builder) WaitUntilInOneOfStatuses(statuses []corev1.PodPhase,
timeout time.Duration) (*corev1.PodPhase, error) {
if valid, err := builder.validate(); !valid {
return nil, err
}
glog.V(100).Infof("Waiting for the defined period until pod %s in namespace %s has status %v",
builder.Definition.Name, builder.Definition.Namespace, statuses)
var foundPhase corev1.PodPhase
return &foundPhase, wait.PollUntilContextTimeout(
context.TODO(), time.Second, timeout, true, func(ctx context.Context) (bool, error) {
updatePod, err := builder.apiClient.Pods(builder.Definition.Namespace).Get(
context.TODO(), builder.Definition.Name, metav1.GetOptions{})
if k8serrors.IsNotFound(err) {
glog.V(100).Infof("Pod %s in namespace %s does not exist", builder.Definition.Name, builder.Definition.Namespace)
return false, err
}
if err != nil {
glog.V(100).Infof("Failed to get pod %s in namespace %s: %v",
builder.Definition.Name, builder.Definition.Namespace, err)
return false, nil
}
for _, phase := range statuses {
if updatePod.Status.Phase == phase {
foundPhase = phase
return true, nil
}
}
return false, nil
})
}
// WaitUntilDeleted waits for the duration of the defined timeout or until the pod is deleted.
func (builder *Builder) WaitUntilDeleted(timeout time.Duration) error {
if valid, err := builder.validate(); !valid {
return err
}
glog.V(100).Infof("Waiting for the defined period until pod %s in namespace %s is deleted",
builder.Definition.Name, builder.Definition.Namespace)
err := wait.PollUntilContextTimeout(
context.TODO(), time.Second, timeout, false, func(ctx context.Context) (bool, error) {
_, err := builder.apiClient.Pods(builder.Definition.Namespace).Get(
context.TODO(), builder.Definition.Name, metav1.GetOptions{})
if err == nil {
glog.V(100).Infof("pod %s/%s still present", builder.Definition.Namespace, builder.Definition.Name)
return false, nil
}
if k8serrors.IsNotFound(err) {
glog.V(100).Infof("pod %s/%s is gone", builder.Definition.Namespace, builder.Definition.Name)
return true, nil
}
glog.V(100).Infof("failed to get pod %s/%s: %v", builder.Definition.Namespace, builder.Definition.Name, err)
return false, err
})
return err
}
// WaitUntilReady waits for the duration of the defined timeout or until the pod reaches the Ready condition.
func (builder *Builder) WaitUntilReady(timeout time.Duration) error {
if valid, err := builder.validate(); !valid {
return err
}
glog.V(100).Infof("Waiting for the defined period until pod %s in namespace %s is Ready",
builder.Definition.Name, builder.Definition.Namespace)
return builder.WaitUntilCondition(corev1.PodReady, timeout)
}
// WaitUntilCondition waits for the duration of the defined timeout or until the pod gets to a specific condition.
func (builder *Builder) WaitUntilCondition(condition corev1.PodConditionType, timeout time.Duration) error {
if valid, err := builder.validate(); !valid {
return err
}
glog.V(100).Infof("Waiting for the defined period until pod %s in namespace %s has condition %v",
builder.Definition.Name, builder.Definition.Namespace, condition)
return wait.PollUntilContextTimeout(
context.TODO(), time.Second, timeout, true, func(ctx context.Context) (bool, error) {
updatePod, err := builder.apiClient.Pods(builder.Definition.Namespace).Get(
context.TODO(), builder.Definition.Name, metav1.GetOptions{})
if err != nil {
return false, nil
}
for _, cond := range updatePod.Status.Conditions {
if cond.Type == condition && cond.Status == corev1.ConditionTrue {
return true, nil
}
}
return false, nil
})
}
// ExecCommand runs command in the pod and returns the buffer output.
func (builder *Builder) ExecCommand(command []string, containerName ...string) (bytes.Buffer, error) {
if valid, err := builder.validate(); !valid {
return bytes.Buffer{}, err
}
var (
buffer bytes.Buffer
cName string
)
if len(containerName) > 0 {
cName = containerName[0]
} else {
cName = builder.Definition.Spec.Containers[0].Name
}
glog.V(100).Infof("Execute command %v in the pod %s container %s in namespace %s",
command, builder.Object.Name, cName, builder.Object.Namespace)
req := builder.apiClient.CoreV1Interface.RESTClient().
Post().
Namespace(builder.Object.Namespace).
Resource("pods").
Name(builder.Object.Name).
SubResource("exec").
VersionedParams(&corev1.PodExecOptions{
Container: cName,
Command: command,
Stdin: true,
Stdout: true,
Stderr: true,
TTY: true,
}, scheme.ParameterCodec)
exec, err := remotecommand.NewSPDYExecutor(builder.apiClient.Config, "POST", req.URL())
if err != nil {
return buffer, err
}
err = exec.StreamWithContext(context.TODO(), remotecommand.StreamOptions{
Stdin: os.Stdin,
Stdout: &buffer,
Stderr: os.Stderr,
Tty: true,
})
if err != nil {
return buffer, err
}
return buffer, nil
}
// Copy returns the contents of a file or path from a specified container into a buffer.
// Setting the tar option returns a tar archive of the specified path.
func (builder *Builder) Copy(path, containerName string, tar bool) (bytes.Buffer, error) {
if valid, err := builder.validate(); !valid {
return bytes.Buffer{}, err
}
glog.V(100).Infof("Copying %s from %s in the pod",
path, containerName)
var command []string
if tar {
command = []string{
"tar",
"cf",
"-",
path,
}
} else {
command = []string{
"cat",
path,
}
}
var buffer bytes.Buffer
req := builder.apiClient.CoreV1Interface.RESTClient().
Post().
Namespace(builder.Object.Namespace).
Resource("pods").
Name(builder.Object.Name).
SubResource("exec").
VersionedParams(&corev1.PodExecOptions{
Container: containerName,
Command: command,
Stdin: true,
Stdout: true,
Stderr: true,
TTY: false,
}, scheme.ParameterCodec)
tlsConfig, err := rest.TLSConfigFor(builder.apiClient.Config)
if err != nil {
return bytes.Buffer{}, err
}
proxy := http.ProxyFromEnvironment
if builder.apiClient.Config.Proxy != nil {
proxy = builder.apiClient.Config.Proxy
}
// More verbose setup of remotecommand executor required in order to tweak PingPeriod.
// By default many large files are not copied in their entirety without disabling PingPeriod during the copy.
// https://github.com/kubernetes/kubernetes/issues/60140#issuecomment-1411477275
upgradeRoundTripper, err := spdy.NewRoundTripperWithConfig(spdy.RoundTripperConfig{
TLS: tlsConfig,
Proxier: proxy,
PingPeriod: 0,
})
if err != nil {
return bytes.Buffer{}, err
}
wrapper, err := rest.HTTPWrappersForConfig(builder.apiClient.Config, upgradeRoundTripper)
if err != nil {
return bytes.Buffer{}, err
}
exec, err := remotecommand.NewSPDYExecutorForTransports(wrapper, upgradeRoundTripper, "POST", req.URL())
if err != nil {
return buffer, err
}
err = exec.StreamWithContext(context.TODO(), remotecommand.StreamOptions{
Stdin: os.Stdin,
Stdout: &buffer,
Stderr: os.Stderr,
Tty: false,
})
if err != nil {
return buffer, err
}
return buffer, nil
}
// Exists checks whether the given pod exists.
func (builder *Builder) Exists() bool {
if valid, _ := builder.validate(); !valid {
return false
}
glog.V(100).Infof("Checking if pod %s exists in namespace %s",
builder.Definition.Name, builder.Definition.Namespace)
var err error
builder.Object, err = builder.apiClient.Pods(builder.Definition.Namespace).Get(
context.TODO(), builder.Definition.Name, metav1.GetOptions{})
return err == nil || !k8serrors.IsNotFound(err)
}
// RedefineDefaultCMD redefines default command in pod's definition.
func (builder *Builder) RedefineDefaultCMD(command []string) *Builder {
if valid, _ := builder.validate(); !valid {
return builder
}
glog.V(100).Infof("Redefining default pod's container cmd with the new %v", command)
builder.isMutationAllowed("cmd")
if builder.errorMsg != "" {
return builder
}
builder.Definition.Spec.Containers[0].Command = command
return builder
}
// WithRestartPolicy applies restart policy to pod's definition.
func (builder *Builder) WithRestartPolicy(restartPolicy corev1.RestartPolicy) *Builder {
if valid, _ := builder.validate(); !valid {
return builder
}
glog.V(100).Infof("Redefining pod's RestartPolicy to %v", restartPolicy)
builder.isMutationAllowed("RestartPolicy")
if restartPolicy == "" {
glog.V(100).Infof(
"Failed to set RestartPolicy on pod %s in namespace %s. RestartPolicy can not be empty",
builder.Definition.Name, builder.Definition.Namespace)
builder.errorMsg = "can not define pod with empty restart policy"
return builder
}
builder.Definition.Spec.RestartPolicy = restartPolicy
return builder
}
// WithTolerationToMaster sets toleration policy which allows pod to be running on master node.
func (builder *Builder) WithTolerationToMaster() *Builder {
if valid, _ := builder.validate(); !valid {
return builder
}
glog.V(100).Infof("Appending pod's %s with toleration to master node", builder.Definition.Name)
builder.isMutationAllowed("toleration to master node")
if builder.errorMsg != "" {
return builder
}
builder.Definition.Spec.Tolerations = []corev1.Toleration{
{
Key: "node-role.kubernetes.io/master",
Effect: "NoSchedule",
},
}
return builder
}
// WithTolerationToControlPlane sets toleration policy which allows pod to be running on control plane node.
func (builder *Builder) WithTolerationToControlPlane() *Builder {
if valid, _ := builder.validate(); !valid {
return builder
}
glog.V(100).Infof("Appending pod's %s with toleration to control plane node", builder.Definition.Name)
builder.isMutationAllowed("toleration to control plane node")
if builder.errorMsg != "" {
return builder
}
builder.Definition.Spec.Tolerations = []corev1.Toleration{
{
Key: "node-role.kubernetes.io/control-plane",
Effect: "NoSchedule",
},
}
return builder
}
// WithToleration adds a toleration configuration inside the pod.
func (builder *Builder) WithToleration(toleration corev1.Toleration) *Builder {
if valid, _ := builder.validate(); !valid {
return builder
}
glog.V(100).Infof("Updating pod %s with toleration %v", builder.Definition.Name, toleration)
builder.isMutationAllowed("custom toleration")
if builder.errorMsg != "" {
return builder
}
builder.Definition.Spec.Tolerations = append(builder.Definition.Spec.Tolerations, toleration)
return builder
}
// WithNodeSelector adds a nodeSelector configuration inside the pod.
func (builder *Builder) WithNodeSelector(nodeSelector map[string]string) *Builder {
if valid, _ := builder.validate(); !valid {
return builder
}
glog.V(100).Infof("Redefining pod %s in namespace %s with nodeSelector %v",
builder.Definition.Name, builder.Definition.Namespace, nodeSelector)
builder.isMutationAllowed("nodeSelector")
if len(nodeSelector) == 0 {
glog.V(100).Infof(
"Failed to set nodeSelector on pod %s in namespace %s. nodeSelector can not be empty",
builder.Definition.Name, builder.Definition.Namespace)
builder.errorMsg = "can not define pod with empty nodeSelector"
return builder
}
builder.Definition.Spec.NodeSelector = nodeSelector
return builder
}
// WithPrivilegedFlag sets privileged flag on all containers.
func (builder *Builder) WithPrivilegedFlag() *Builder {
if valid, _ := builder.validate(); !valid {
return builder
}
glog.V(100).Infof("Applying privileged flag to all pod's: %s containers", builder.Definition.Name)
builder.isMutationAllowed("privileged container flag")
if builder.errorMsg != "" {
return builder
}
for idx := range builder.Definition.Spec.Containers {
builder.Definition.Spec.Containers[idx].SecurityContext = &corev1.SecurityContext{}
trueFlag := true
builder.Definition.Spec.Containers[idx].SecurityContext.Privileged = &trueFlag
}
return builder
}
// WithVolume attaches given volume to a pod.
func (builder *Builder) WithVolume(volume corev1.Volume) *Builder {
if valid, _ := builder.validate(); !valid {
return builder
}
if volume.Name == "" {
glog.V(100).Infof("The volume's Name cannot be empty")
builder.errorMsg = "the volume's name cannot be empty"
return builder
}
glog.V(100).Infof("Adding volume %s to pod %s in namespace %s",
volume.Name, builder.Definition.Name, builder.Definition.Namespace)
builder.Definition.Spec.Volumes = append(builder.Definition.Spec.Volumes, volume)
return builder
}
// WithLocalVolume attaches given volume to all pod's containers.
func (builder *Builder) WithLocalVolume(volumeName, mountPath string) *Builder {
if valid, _ := builder.validate(); !valid {
return builder
}
glog.V(100).Infof("Configuring volume %s for all pod's: %s containers. MountPath %s",
volumeName, builder.Definition.Name, mountPath)
builder.isMutationAllowed("LocalVolume")
if volumeName == "" {
glog.V(100).Infof("The 'volumeName' of the pod is empty")
builder.errorMsg = "'volumeName' parameter is empty"
return builder
}
if mountPath == "" {
glog.V(100).Infof("The 'mountPath' of the pod is empty")
builder.errorMsg = "'mountPath' parameter is empty"
return builder
}
mountConfig := corev1.VolumeMount{Name: volumeName, MountPath: mountPath, ReadOnly: false}
builder.isMountAlreadyInUseInPod(mountConfig)
if builder.errorMsg != "" {
return builder
}
for index := range builder.Definition.Spec.Containers {
builder.Definition.Spec.Containers[index].VolumeMounts = append(
builder.Definition.Spec.Containers[index].VolumeMounts, mountConfig)
}
if len(builder.Definition.Spec.InitContainers) > 0 {
for index := range builder.Definition.Spec.InitContainers {
builder.Definition.Spec.InitContainers[index].VolumeMounts = append(
builder.Definition.Spec.InitContainers[index].VolumeMounts, mountConfig)
}
}
builder.Definition.Spec.Volumes = append(builder.Definition.Spec.Volumes,
corev1.Volume{Name: mountConfig.Name, VolumeSource: corev1.VolumeSource{
ConfigMap: &corev1.ConfigMapVolumeSource{
LocalObjectReference: corev1.LocalObjectReference{
Name: mountConfig.Name,
},
},
}})
return builder
}
// WithAdditionalContainer appends additional container to pod.
func (builder *Builder) WithAdditionalContainer(container *corev1.Container) *Builder {
if valid, _ := builder.validate(); !valid {
return builder
}
glog.V(100).Infof("Adding new container %v to pod %s", container, builder.Definition.Name)
builder.isMutationAllowed("additional container")
if container == nil {
builder.errorMsg = "'container' parameter cannot be empty"
return builder
}
builder.Definition.Spec.Containers = append(builder.Definition.Spec.Containers, *container)
return builder
}
// WithAdditionalInitContainer appends additional init container to pod.
func (builder *Builder) WithAdditionalInitContainer(container *corev1.Container) *Builder {
if valid, _ := builder.validate(); !valid {
return builder
}
glog.V(100).Infof("Adding new container %v to pod %s in namespace %s",
container, builder.Definition.Name, builder.Definition.Namespace)
builder.isMutationAllowed("additional container")
if container == nil {
glog.V(100).Infof("The 'container' parameter of the pod is empty")
builder.errorMsg = "'container' parameter cannot be empty"
return builder
}
builder.Definition.Spec.InitContainers = append(builder.Definition.Spec.InitContainers, *container)
return builder
}
// WithSecondaryNetwork applies Multus secondary network on pod definition.
func (builder *Builder) WithSecondaryNetwork(network []*multus.NetworkSelectionElement) *Builder {
if valid, _ := builder.validate(); !valid {
return builder
}
glog.V(100).Infof("Applying secondary network %v to pod %s", network, builder.Definition.Name)
builder.isMutationAllowed("secondary network")
if builder.errorMsg != "" {
return builder
}
netAnnotation, err := json.Marshal(network)
if err != nil {
builder.errorMsg = fmt.Sprintf("error to unmarshal network annotation due to: %s", err.Error())
return builder
}
builder.Definition.Annotations = map[string]string{"k8s.v1.cni.cncf.io/networks": string(netAnnotation)}
return builder
}
// WithHostNetwork applies HostNetwork to pod's definition.
func (builder *Builder) WithHostNetwork() *Builder {
if valid, _ := builder.validate(); !valid {
return builder
}
glog.V(100).Infof("Applying HostNetwork flag to pod's %s configuration", builder.Definition.Name)
builder.isMutationAllowed("HostNetwork")
if builder.errorMsg != "" {
return builder
}
builder.Definition.Spec.HostNetwork = true
return builder
}
// WithHostPid configures a pod's access to the host process ID namespace based on a boolean parameter.
func (builder *Builder) WithHostPid(hostPid bool) *Builder {
if valid, _ := builder.validate(); !valid {
return builder
}
glog.V(100).Infof("Applying HostPID flag to the configuration of pod: %s in namespace: %s",
builder.Definition.Name, builder.Definition.Namespace)
builder.isMutationAllowed("HostPID")
if builder.errorMsg != "" {
return builder
}
builder.Definition.Spec.HostPID = hostPid
return builder
}
// RedefineDefaultContainer redefines default container with the new one.
func (builder *Builder) RedefineDefaultContainer(container corev1.Container) *Builder {
if valid, _ := builder.validate(); !valid {
return builder