generated from kubernetes/kubernetes-template-project
-
Notifications
You must be signed in to change notification settings - Fork 105
/
Copy pathconditions.go
319 lines (289 loc) · 13.9 KB
/
conditions.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
/*
Copyright 2021 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package conditions
import (
"context"
"fmt"
log "k8s.io/klog/v2"
appsv1 "k8s.io/api/apps/v1"
batchv1 "k8s.io/api/batch/v1"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
apimachinerywait "k8s.io/apimachinery/pkg/util/wait"
"sigs.k8s.io/e2e-framework/klient/k8s"
"sigs.k8s.io/e2e-framework/klient/k8s/resources"
)
type Condition struct {
resources *resources.Resources
}
// New is used to create a new Condition that can be used to perform a series of pre-defined wait checks
// against a resource in question
func New(r *resources.Resources) *Condition {
return &Condition{resources: r}
}
func (c *Condition) namespacedName(obj k8s.Object) string {
return fmt.Sprintf("%s [%s/%s]", obj.GetObjectKind().GroupVersionKind().String(), obj.GetNamespace(), obj.GetName())
}
// ResourceScaled is a helper function used to check if the resource under question has a pre-defined number of
// replicas. This can be leveraged for checking cases such as scaling up and down a deployment or STS and any
// other scalable resources.
func (c *Condition) ResourceScaled(obj k8s.Object, scaleFetcher func(object k8s.Object) int32, replica int32) apimachinerywait.ConditionWithContextFunc {
return func(ctx context.Context) (done bool, err error) {
log.V(4).InfoS("Checking for resource to be scaled", "resource", c.namespacedName(obj), "replica", replica)
if err := c.resources.Get(ctx, obj.GetName(), obj.GetNamespace(), obj); err != nil {
return false, nil
}
return scaleFetcher(obj) == replica, nil
}
}
// ResourceMatch is a helper function used to check if the resource under question has met a pre-defined state. This can
// be leveraged for checking fields on a resource that may not be immediately present upon creation.
func (c *Condition) ResourceMatch(obj k8s.Object, matchFetcher func(object k8s.Object) bool) apimachinerywait.ConditionWithContextFunc {
return func(ctx context.Context) (done bool, err error) {
if err := c.resources.Get(ctx, obj.GetName(), obj.GetNamespace(), obj); err != nil {
return false, nil
}
return matchFetcher(obj), nil
}
}
// ResourceListN is a helper function that can be used to check for a minimum number of returned objects in a list. This function
// accepts list options that can be used to adjust the set of objects queried for in the List resource operation.
func (c *Condition) ResourceListN(list k8s.ObjectList, n int, listOptions ...resources.ListOption) apimachinerywait.ConditionWithContextFunc {
return c.ResourceListMatchN(list, n, func(object k8s.Object) bool { return true }, listOptions...)
}
// ResourceListMatchN is a helper function that can be used to check for a minimum number of returned objects in a list. This function
// accepts list options and a match function that can be used to adjust the set of objects queried for in the List resource operation.
func (c *Condition) ResourceListMatchN(list k8s.ObjectList, n int, matchFetcher func(object k8s.Object) bool, listOptions ...resources.ListOption) apimachinerywait.ConditionWithContextFunc {
return func(ctx context.Context) (done bool, err error) {
if err = c.resources.List(ctx, list, listOptions...); err != nil {
return false, nil
}
var found int
metaList, err := meta.ExtractList(list)
if err != nil {
return false, err
}
for _, obj := range metaList {
if o, ok := obj.(k8s.Object); ok && matchFetcher(o) {
found++
} else if !ok {
return false, fmt.Errorf("condition: unexpected type %T in list, does not satisfy k8s.Object", obj)
}
}
return found >= n, nil
}
}
// ResourcesFound is a helper function that can be used to check for a set of objects. This function accepts a list
// of named objects and will wait until it is able to retrieve each.
func (c *Condition) ResourcesFound(list k8s.ObjectList) apimachinerywait.ConditionWithContextFunc {
return c.ResourcesMatch(list, func(object k8s.Object) bool { return true })
}
// ResourcesMatch is a helper function that can be used to check for a set of objects. This function accepts a list
// of named objects and a match function, and will wait until it is able to retrieve each while passing the match validation.
func (c *Condition) ResourcesMatch(list k8s.ObjectList, matchFetcher func(object k8s.Object) bool) apimachinerywait.ConditionWithContextFunc {
metaList, err := meta.ExtractList(list)
if err != nil {
return func(ctx context.Context) (done bool, err error) { return false, err }
}
objects := make(map[k8s.Object]bool)
for _, o := range metaList {
obj, ok := o.(k8s.Object)
if !ok {
return func(ctx context.Context) (done bool, err error) {
return false, fmt.Errorf("condition: unexpected type %T in list, does not satisfy k8s.Object", obj)
}
}
if obj.GetName() != "" {
objects[obj] = false
}
}
return func(ctx context.Context) (done bool, err error) {
found := 0
for obj, created := range objects {
if !created {
if err := c.resources.Get(ctx, obj.GetName(), obj.GetNamespace(), obj); errors.IsNotFound(err) {
continue
} else if err != nil {
return false, err
}
if !matchFetcher(obj) {
continue
}
}
objects[obj] = true
found++
}
return len(objects) == found, nil
}
}
// ResourcesDeleted is a helper function that can be used to check for if a set of objects has been deleted. This function
// accepts a list of named objects and will wait until it is not able to find each.
func (c *Condition) ResourcesDeleted(list k8s.ObjectList) apimachinerywait.ConditionWithContextFunc {
metaList, err := meta.ExtractList(list)
if err != nil {
return func(ctx context.Context) (done bool, err error) { return false, err }
}
objects := make(map[k8s.Object]bool)
for _, o := range metaList {
obj, ok := o.(k8s.Object)
if !ok {
return func(ctx context.Context) (done bool, err error) {
return false, fmt.Errorf("condition: unexpected type %T in list, does not satisfy k8s.Object", obj)
}
}
if obj.GetName() != "" {
objects[obj] = true
}
}
return func(ctx context.Context) (done bool, err error) {
for obj, created := range objects {
if created {
log.V(4).InfoS("Checking for resource to be garbage collected", "resource", c.namespacedName(obj))
if err := c.resources.Get(ctx, obj.GetName(), obj.GetNamespace(), obj); errors.IsNotFound(err) {
delete(objects, obj)
} else if err != nil {
return false, err
}
}
}
return len(objects) == 0, nil
}
}
// ResourceDeleted is a helper function used to check if a resource under question has been deleted. This will enable
// testing cases where the resource have a finalizer and the DELETE operation of such resource have been triggered and
// you want to wait until the resource has been deleted.
//
// This method can be leveraged against any Kubernetes resource to check the deletion workflow and it does so by
// checking the resource and waiting until it obtains a v1.StatusReasonNotFound error from the API
func (c *Condition) ResourceDeleted(obj k8s.Object) apimachinerywait.ConditionWithContextFunc {
return func(ctx context.Context) (done bool, err error) {
log.V(4).InfoS("Checking for resource to be garbage collected", "resource", c.namespacedName(obj))
if err := c.resources.Get(context.Background(), obj.GetName(), obj.GetNamespace(), obj); err != nil {
if errors.IsNotFound(err) {
return true, nil
}
return false, err
}
return false, nil
}
}
// JobConditionMatch is a helper function that can be used to check the Job Completion or runtime status against a
// specific condition. This function accepts both conditionType and conditionState as argument and hence you can use this
// to match both positive or negative cases with suitable values passed to the arguments.
func (c *Condition) JobConditionMatch(job k8s.Object, conditionType batchv1.JobConditionType, conditionState v1.ConditionStatus) apimachinerywait.ConditionWithContextFunc {
return func(ctx context.Context) (done bool, err error) {
log.V(4).InfoS("Checking for condition match", "resource", c.namespacedName(job), "state", conditionState, "conditionType", conditionType)
if err := c.resources.Get(ctx, job.GetName(), job.GetNamespace(), job); err != nil {
return false, err
}
status := job.(*batchv1.Job).Status // nolint: errcheck
log.V(4).InfoS("Current Status of the job resource", "status", status)
for _, cond := range status.Conditions {
if cond.Type == conditionType && cond.Status == conditionState {
done = true
}
}
return
}
}
// DeploymentConditionMatch is a helper function that can be used to check a specific condition match for the Deployment in question.
func (c *Condition) DeploymentConditionMatch(deployment k8s.Object, conditionType appsv1.DeploymentConditionType, conditionState v1.ConditionStatus) apimachinerywait.ConditionWithContextFunc {
return func(ctx context.Context) (done bool, err error) {
if err := c.resources.Get(ctx, deployment.GetName(), deployment.GetNamespace(), deployment); err != nil {
return false, err
}
for _, cond := range deployment.(*appsv1.Deployment).Status.Conditions { // nolint: errcheck
if cond.Type == conditionType && cond.Status == conditionState {
done = true
}
}
return
}
}
// PodConditionMatch is a helper function that can be used to check a specific condition match for the Pod in question.
// This is extended into a few simplified match helpers such as PodReady and ContainersReady as well.
func (c *Condition) PodConditionMatch(pod k8s.Object, conditionType v1.PodConditionType, conditionState v1.ConditionStatus) apimachinerywait.ConditionWithContextFunc {
return func(ctx context.Context) (done bool, err error) {
log.V(4).InfoS("Checking for condition match", "resource", c.namespacedName(pod), "state", conditionState, "conditionType", conditionType)
if err := c.resources.Get(ctx, pod.GetName(), pod.GetNamespace(), pod); err != nil {
return false, err
}
status := pod.(*v1.Pod).Status // nolint: errcheck
log.V(4).InfoS("Current Status of the pod resource", "status", status)
for _, cond := range status.Conditions {
if cond.Type == conditionType && cond.Status == conditionState {
done = true
}
}
return
}
}
// PodPhaseMatch is a helper function that is used to check and see if the Pod Has reached a specific Phase of the
// runtime. This can be combined with PodConditionMatch to check if a specific condition and phase has been met.
// This will enable validation such as checking against CLB of a POD.
func (c *Condition) PodPhaseMatch(pod k8s.Object, phase v1.PodPhase) apimachinerywait.ConditionWithContextFunc {
return func(ctx context.Context) (done bool, err error) {
log.V(4).InfoS("Checking for phase match", "resource", c.namespacedName(pod), "phase", phase)
if err := c.resources.Get(context.Background(), pod.GetName(), pod.GetNamespace(), pod); err != nil {
return false, err
}
log.V(4).InfoS("Current phase", "phase", pod.(*v1.Pod).Status.Phase) // nolint: errcheck
return pod.(*v1.Pod).Status.Phase == phase, nil // nolint: errcheck
}
}
// PodReady is a helper function used to check if the pod condition v1.PodReady has reached v1.ConditionTrue state
func (c *Condition) PodReady(pod k8s.Object) apimachinerywait.ConditionWithContextFunc {
return c.PodConditionMatch(pod, v1.PodReady, v1.ConditionTrue)
}
// ContainersReady is a helper function used to check if the pod condition v1.ContainersReady has reached v1.ConditionTrue
func (c *Condition) ContainersReady(pod k8s.Object) apimachinerywait.ConditionWithContextFunc {
return c.PodConditionMatch(pod, v1.ContainersReady, v1.ConditionTrue)
}
// PodRunning is a helper function used to check if the pod.Status.Phase attribute of the Pod has reached v1.PodRunning
func (c *Condition) PodRunning(pod k8s.Object) apimachinerywait.ConditionWithContextFunc {
return c.PodPhaseMatch(pod, v1.PodRunning)
}
// JobCompleted is a helper function used to check if the Job has been completed successfully by checking if the
// batchv1.JobCompleted has reached the v1.ConditionTrue state
func (c *Condition) JobCompleted(job k8s.Object) apimachinerywait.ConditionWithContextFunc {
return c.JobConditionMatch(job, batchv1.JobComplete, v1.ConditionTrue)
}
// JobFailed is a helper function used to check if the Job has failed by checking if the batchv1.JobFailed has reached
// v1.ConditionTrue state
func (c *Condition) JobFailed(job k8s.Object) apimachinerywait.ConditionWithContextFunc {
return c.JobConditionMatch(job, batchv1.JobFailed, v1.ConditionTrue)
}
// DeploymentAvailable is a helper function used to check if the deployment condition appsv1.DeploymentAvailable
// has reached v1.ConditionTrue state
func (c *Condition) DeploymentAvailable(name, namespace string) apimachinerywait.ConditionWithContextFunc {
return c.DeploymentConditionMatch(
&appsv1.Deployment{ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: namespace}},
appsv1.DeploymentAvailable,
v1.ConditionTrue,
)
}
// DaemonSetReady is a helper function used to check if a daemonset's pods are scheduled and ready
func (c *Condition) DaemonSetReady(daemonset k8s.Object) apimachinerywait.ConditionWithContextFunc {
return func(ctx context.Context) (done bool, err error) {
if err := c.resources.Get(ctx, daemonset.GetName(), daemonset.GetNamespace(), daemonset); err != nil {
return false, err
}
status := daemonset.(*appsv1.DaemonSet).Status // nolint: errcheck
if status.NumberReady == status.DesiredNumberScheduled && status.NumberUnavailable == 0 {
done = true
}
return
}
}