1/*
2Copyright 2021 The Kubernetes Authors.
3
4Licensed under the Apache License, Version 2.0 (the "License");
5you may not use this file except in compliance with the License.
6You may obtain a copy of the License at
7
8    http://www.apache.org/licenses/LICENSE-2.0
9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15*/
16
17package test
18
19import (
20	corev1 "k8s.io/api/core/v1"
21)
22
23// tweak makes a copy of in, passes it to f(), and returns the result.
24// the input is not modified.
25func tweak(in *corev1.Pod, f func(copy *corev1.Pod)) *corev1.Pod {
26	out := in.DeepCopy()
27	f(out)
28	return out
29}
30
31// ensureSecurityContext ensures the pod and all initContainers and containers have a non-nil security context.
32func ensureSecurityContext(p *corev1.Pod) *corev1.Pod {
33	p = p.DeepCopy()
34	if p.Spec.SecurityContext == nil {
35		p.Spec.SecurityContext = &corev1.PodSecurityContext{}
36	}
37	for i := range p.Spec.Containers {
38		if p.Spec.Containers[i].SecurityContext == nil {
39			p.Spec.Containers[i].SecurityContext = &corev1.SecurityContext{}
40		}
41	}
42	for i := range p.Spec.InitContainers {
43		if p.Spec.InitContainers[i].SecurityContext == nil {
44			p.Spec.InitContainers[i].SecurityContext = &corev1.SecurityContext{}
45		}
46	}
47	return p
48}
49
50// ensureSELinuxOptions ensures the pod and all initContainers and containers have a non-nil seLinuxOptions.
51func ensureSELinuxOptions(p *corev1.Pod) *corev1.Pod {
52	p = ensureSecurityContext(p)
53	if p.Spec.SecurityContext.SELinuxOptions == nil {
54		p.Spec.SecurityContext.SELinuxOptions = &corev1.SELinuxOptions{}
55	}
56	for i := range p.Spec.Containers {
57		if p.Spec.Containers[i].SecurityContext.SELinuxOptions == nil {
58			p.Spec.Containers[i].SecurityContext.SELinuxOptions = &corev1.SELinuxOptions{}
59		}
60	}
61	for i := range p.Spec.InitContainers {
62		if p.Spec.InitContainers[i].SecurityContext.SELinuxOptions == nil {
63			p.Spec.InitContainers[i].SecurityContext.SELinuxOptions = &corev1.SELinuxOptions{}
64		}
65	}
66	return p
67}
68
69// ensureAnnotation makes sure that pod.Annotations is never nil
70func ensureAnnotation(pod *corev1.Pod) *corev1.Pod {
71	if pod.Annotations == nil {
72		pod.Annotations = map[string]string{}
73	}
74	return pod
75}
76