This repository has been archived by the owner on Dec 3, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
k8s.go
287 lines (235 loc) · 8.17 KB
/
k8s.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
package utils
import (
"context"
"fmt"
"time"
corev1 "k8s.io/api/core/v1"
v1beta1 "k8s.io/api/networking/v1beta1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
apierrs "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
utilnet "k8s.io/apimachinery/pkg/util/net"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/client-go/kubernetes"
clientset "k8s.io/client-go/kubernetes"
restclient "k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/klog"
// ensure auth plugins are loaded
_ "k8s.io/client-go/plugin/pkg/client/auth"
)
const (
// NamespaceCleanupTimeout failures caused by leaked resources from a previous test run.
NamespaceCleanupTimeout = 5 * time.Minute
// WaitForIngressAddressTimeout wait time for valid ingress status
WaitForIngressAddressTimeout = 5 * time.Minute
// IngressWaitInterval time to wait between checks for a condition
IngressWaitInterval = 5 * time.Second
)
// KubeClient Kubernetes API client
var KubeClient *kubernetes.Clientset
// WaitForService waits until the service appears (exist == true), or disappears (exist == false)
func WaitForService(c clientset.Interface, namespace, name string, exist bool, interval, timeout time.Duration) error {
err := wait.PollImmediate(interval, timeout, func() (bool, error) {
_, err := c.CoreV1().Services(namespace).Get(context.TODO(), name, metav1.GetOptions{})
switch {
case err == nil:
klog.Infof("Service %s in namespace %s found.", name, namespace)
return exist, nil
case apierrors.IsNotFound(err):
klog.Infof("Service %s in namespace %s disappeared.", name, namespace)
return !exist, nil
case !IsRetryableAPIError(err):
klog.Infof("Non-retryable failure while getting service.")
return false, err
default:
klog.Infof("Get service %s in namespace %s failed: %v", name, namespace, err)
return false, nil
}
})
if err != nil {
stateMsg := map[bool]string{true: "to appear", false: "to disappear"}
return fmt.Errorf("error waiting for service %s/%s %s: %v", namespace, name, stateMsg[exist], err)
}
return nil
}
//WaitForServiceEndpointsNum waits until the amount of endpoints that implement service to expectNum.
func WaitForServiceEndpointsNum(c clientset.Interface, namespace, serviceName string,
expectNum int, interval, timeout time.Duration) error {
return wait.Poll(interval, timeout, func() (bool, error) {
list, err := c.CoreV1().Endpoints(namespace).List(context.TODO(), metav1.ListOptions{})
if err != nil {
return false, err
}
for _, e := range list.Items {
if e.Name == serviceName && countEndpointsNum(&e) == expectNum {
return true, nil
}
}
return false, nil
})
}
func countEndpointsNum(e *corev1.Endpoints) int {
num := 0
for _, sub := range e.Subsets {
num += len(sub.Addresses)
}
return num
}
// LoadClientset returns clientset for connecting to kubernetes clusters.
func LoadClientset() (*clientset.Clientset, error) {
config, err := restclient.InClusterConfig()
if err != nil {
// Attempt to use local KUBECONFIG
loadingRules := clientcmd.NewDefaultClientConfigLoadingRules()
kubeconfig := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(loadingRules, &clientcmd.ConfigOverrides{})
// use the current context in kubeconfig
var err error
config, err = kubeconfig.ClientConfig()
if err != nil {
return nil, err
}
}
client, err := clientset.NewForConfig(config)
if err != nil {
return nil, err
}
return client, nil
}
// CreateTestNamespace creates a new namespace using
// ingress-conformance- as prefix.
func CreateTestNamespace(c kubernetes.Interface) (string, error) {
ns := &corev1.Namespace{
ObjectMeta: metav1.ObjectMeta{
GenerateName: "ingress-conformance-",
Labels: map[string]string{
"app.kubernetes.io/name": "ingress-conformance",
},
},
}
var err error
ns, err = c.CoreV1().Namespaces().Create(context.TODO(), ns, metav1.CreateOptions{})
if err != nil {
return "", fmt.Errorf("unable to create namespace: %v", err)
}
return ns.Name, nil
}
// DeleteKubeNamespace deletes a namespace and all the objects inside
func DeleteKubeNamespace(c kubernetes.Interface, namespace string) error {
grace := int64(0)
pb := metav1.DeletePropagationBackground
return c.CoreV1().Namespaces().Delete(context.TODO(), namespace, metav1.DeleteOptions{
GracePeriodSeconds: &grace,
PropagationPolicy: &pb,
})
}
// CleanupNamespaces removes namespaces created by conformance tests
func CleanupNamespaces(c kubernetes.Interface) error {
namespaces, err := c.CoreV1().Namespaces().List(context.TODO(), metav1.ListOptions{
LabelSelector: "app.kubernetes.io/name=ingress-conformance",
})
if err != nil {
return err
}
for _, namespace := range namespaces.Items {
err := DeleteKubeNamespace(c, namespace.Name)
if err != nil {
return err
}
}
return nil
}
// IsRetryableAPIError checks if an API error allows retries or not
func IsRetryableAPIError(err error) bool {
// These errors may indicate a transient error that we can retry in tests.
if apierrs.IsInternalError(err) || apierrs.IsTimeout(err) || apierrs.IsServerTimeout(err) ||
apierrs.IsTooManyRequests(err) || utilnet.IsProbableEOF(err) || utilnet.IsConnectionReset(err) {
return true
}
// If the error sends the Retry-After header, we respect it as an explicit confirmation we should retry.
if _, shouldRetry := apierrs.SuggestsClientDelay(err); shouldRetry {
return true
}
return false
}
// CreateIngress creates an Ingress object and retunrs it, throws error if it already exists.
func CreateIngress(c kubernetes.Interface, ingress *v1beta1.Ingress) (*v1beta1.Ingress, error) {
err := createIngressWithRetries(c, ingress.Namespace, ingress)
if err != nil {
return nil, err
}
return c.NetworkingV1beta1().Ingresses(ingress.Namespace).Get(context.TODO(), ingress.Name, metav1.GetOptions{})
}
func createIngressWithRetries(c kubernetes.Interface, namespace string, obj *v1beta1.Ingress) error {
if obj == nil {
return fmt.Errorf("object provided to create is empty")
}
createFunc := func() (bool, error) {
_, err := c.NetworkingV1beta1().Ingresses(namespace).Create(context.TODO(), obj, metav1.CreateOptions{})
if err == nil {
return true, nil
}
if apierrs.IsAlreadyExists(err) {
return false, err
}
if IsRetryableAPIError(err) {
return false, nil
}
return false, fmt.Errorf("failed to create object with non-retriable error: %v", err)
}
return retryWithExponentialBackOff(createFunc)
}
// WaitForIngressAddress waits for the Ingress to acquire an address.
func WaitForIngressAddress(c clientset.Interface, ns, ingName string, timeout time.Duration) (string, error) {
var address string
err := wait.PollImmediate(IngressWaitInterval, timeout, func() (bool, error) {
ipOrNameList, err := getIngressAddress(c, ns, ingName)
if err != nil || len(ipOrNameList) == 0 {
if IsRetryableAPIError(err) {
return false, nil
}
return false, err
}
address = ipOrNameList[0]
return true, nil
})
return address, err
}
// getIngressAddress returns the ips/hostnames associated with the Ingress.
func getIngressAddress(c clientset.Interface, ns, name string) ([]string, error) {
ing, err := c.NetworkingV1beta1().Ingresses(ns).Get(context.TODO(), name, metav1.GetOptions{})
if err != nil {
return nil, err
}
class := ing.Annotations[IngressClassKey]
if class != IngressClassValue {
return nil, fmt.Errorf("Ingress with name %v has an invalid annotation (%v)", IngressClassValue, class)
}
var addresses []string
for _, a := range ing.Status.LoadBalancer.Ingress {
if a.IP != "" {
addresses = append(addresses, a.IP)
}
if a.Hostname != "" {
addresses = append(addresses, a.Hostname)
}
}
return addresses, nil
}
const (
// Parameters for retrying with exponential backoff.
retryBackoffInitialDuration = 100 * time.Millisecond
retryBackoffFactor = 3
retryBackoffJitter = 0
retryBackoffSteps = 6
)
// Utility for retrying the given function with exponential backoff.
func retryWithExponentialBackOff(fn wait.ConditionFunc) error {
backoff := wait.Backoff{
Duration: retryBackoffInitialDuration,
Factor: retryBackoffFactor,
Jitter: retryBackoffJitter,
Steps: retryBackoffSteps,
}
return wait.ExponentialBackoff(backoff, fn)
}