-
Notifications
You must be signed in to change notification settings - Fork 38.7k
/
wait.go
388 lines (337 loc) · 13.2 KB
/
wait.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
/*
Copyright 2018 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 apiclient
import (
"context"
"crypto/tls"
"fmt"
"io"
"net/http"
"time"
"github.com/pkg/errors"
v1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
utilerrors "k8s.io/apimachinery/pkg/util/errors"
netutil "k8s.io/apimachinery/pkg/util/net"
"k8s.io/apimachinery/pkg/util/wait"
clientset "k8s.io/client-go/kubernetes"
kubeadmapi "k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm"
"k8s.io/kubernetes/cmd/kubeadm/app/constants"
)
// Waiter is an interface for waiting for criteria in Kubernetes to happen
type Waiter interface {
// WaitForControlPlaneComponents waits for all control plane components to report "ok" on /healthz
WaitForControlPlaneComponents(cfg *kubeadmapi.ClusterConfiguration) error
// WaitForAPI waits for the API Server's /healthz endpoint to become "ok"
// TODO: remove WaitForAPI once WaitForAllControlPlaneComponents goes GA:
// https://github.com/kubernetes/kubeadm/issues/2907
WaitForAPI() error
// WaitForPodsWithLabel waits for Pods in the kube-system namespace to become Ready
WaitForPodsWithLabel(kvLabel string) error
// WaitForPodToDisappear waits for the given Pod in the kube-system namespace to be deleted
WaitForPodToDisappear(staticPodName string) error
// WaitForStaticPodSingleHash fetches sha256 hash for the control plane static pod
WaitForStaticPodSingleHash(nodeName string, component string) (string, error)
// WaitForStaticPodHashChange waits for the given static pod component's static pod hash to get updated.
// By doing that we can be sure that the kubelet has restarted the given Static Pod
WaitForStaticPodHashChange(nodeName, component, previousHash string) error
// WaitForStaticPodControlPlaneHashes fetches sha256 hashes for the control plane static pods
WaitForStaticPodControlPlaneHashes(nodeName string) (map[string]string, error)
// WaitForKubelet blocks until the kubelet /healthz endpoint returns 'ok'
WaitForKubelet() error
// SetTimeout adjusts the timeout to the specified duration
SetTimeout(timeout time.Duration)
}
// KubeWaiter is an implementation of Waiter that is backed by a Kubernetes client
type KubeWaiter struct {
client clientset.Interface
timeout time.Duration
writer io.Writer
}
// NewKubeWaiter returns a new Waiter object that talks to the given Kubernetes cluster
func NewKubeWaiter(client clientset.Interface, timeout time.Duration, writer io.Writer) Waiter {
return &KubeWaiter{
client: client,
timeout: timeout,
writer: writer,
}
}
type controlPlaneComponent struct {
name string
url string
}
// getControlPlaneComponents takes a ClusterConfiguration and returns a slice of
// control plane components and their secure ports.
func getControlPlaneComponents(cfg *kubeadmapi.ClusterConfiguration) []controlPlaneComponent {
portArg := "secure-port"
portAPIServer, idx := kubeadmapi.GetArgValue(cfg.APIServer.ExtraArgs, portArg, -1)
if idx == -1 {
portAPIServer = "6443"
}
portKCM, idx := kubeadmapi.GetArgValue(cfg.ControllerManager.ExtraArgs, portArg, -1)
if idx == -1 {
portKCM = "10257"
}
portScheduler, idx := kubeadmapi.GetArgValue(cfg.Scheduler.ExtraArgs, portArg, -1)
if idx == -1 {
portScheduler = "10259"
}
urlFormat := "https://127.0.0.1:%s/healthz"
return []controlPlaneComponent{
{name: "kube-apiserver", url: fmt.Sprintf(urlFormat, portAPIServer)},
{name: "kube-controller-manager", url: fmt.Sprintf(urlFormat, portKCM)},
{name: "kube-scheduler", url: fmt.Sprintf(urlFormat, portScheduler)},
}
}
// WaitForControlPlaneComponents waits for all control plane components to report "ok" on /healthz
func (w *KubeWaiter) WaitForControlPlaneComponents(cfg *kubeadmapi.ClusterConfiguration) error {
fmt.Printf("[control-plane-check] Waiting for healthy control plane components."+
" This can take up to %v\n", w.timeout)
components := getControlPlaneComponents(cfg)
var errs []error
errChan := make(chan error, len(components))
for _, comp := range components {
fmt.Printf("[control-plane-check] Checking %s at %s\n", comp.name, comp.url)
go func(comp controlPlaneComponent) {
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
client := &http.Client{Transport: tr}
start := time.Now()
var lastError error
err := wait.PollUntilContextTimeout(
context.Background(),
constants.KubernetesAPICallRetryInterval,
w.timeout,
true, func(ctx context.Context) (bool, error) {
resp, err := client.Get(comp.url)
if err != nil {
lastError = errors.WithMessagef(err, "%s /healthz check failed", comp.name)
return false, nil
}
defer func() {
_ = resp.Body.Close()
}()
if resp.StatusCode != http.StatusOK {
lastError = errors.Errorf("%s /healthz check failed with status: %d", comp.name, resp.StatusCode)
return false, nil
}
return true, nil
})
if err != nil {
fmt.Printf("[control-plane-check] %s is not healthy after %v\n", comp.name, time.Since(start))
errChan <- lastError
return
}
fmt.Printf("[control-plane-check] %s is healthy after %v\n", comp.name, time.Since(start))
errChan <- nil
}(comp)
}
for i := 0; i < len(components); i++ {
if err := <-errChan; err != nil {
errs = append(errs, err)
}
}
return utilerrors.NewAggregate(errs)
}
// WaitForAPI waits for the API Server's /healthz endpoint to report "ok"
func (w *KubeWaiter) WaitForAPI() error {
fmt.Printf("[api-check] Waiting for a healthy API server. This can take up to %v\n", w.timeout)
start := time.Now()
err := wait.PollUntilContextTimeout(
context.Background(),
constants.KubernetesAPICallRetryInterval,
w.timeout,
true, func(ctx context.Context) (bool, error) {
healthStatus := 0
w.client.Discovery().RESTClient().Get().AbsPath("/healthz").Do(ctx).StatusCode(&healthStatus)
if healthStatus != http.StatusOK {
return false, nil
}
return true, nil
})
if err != nil {
fmt.Printf("[api-check] The API server is not healthy after %v\n", time.Since(start))
return err
}
fmt.Printf("[api-check] The API server is healthy after %v\n", time.Since(start))
return nil
}
// WaitForPodsWithLabel will lookup pods with the given label and wait until they are all
// reporting status as running.
func (w *KubeWaiter) WaitForPodsWithLabel(kvLabel string) error {
lastKnownPodNumber := -1
return wait.PollUntilContextTimeout(context.Background(),
constants.KubernetesAPICallRetryInterval, w.timeout,
true, func(_ context.Context) (bool, error) {
listOpts := metav1.ListOptions{LabelSelector: kvLabel}
pods, err := w.client.CoreV1().Pods(metav1.NamespaceSystem).List(context.TODO(), listOpts)
if err != nil {
fmt.Fprintf(w.writer, "[apiclient] Error getting Pods with label selector %q [%v]\n", kvLabel, err)
return false, nil
}
if lastKnownPodNumber != len(pods.Items) {
fmt.Fprintf(w.writer, "[apiclient] Found %d Pods for label selector %s\n", len(pods.Items), kvLabel)
lastKnownPodNumber = len(pods.Items)
}
if len(pods.Items) == 0 {
return false, nil
}
for _, pod := range pods.Items {
if pod.Status.Phase != v1.PodRunning {
return false, nil
}
}
return true, nil
})
}
// WaitForPodToDisappear blocks until it timeouts or gets a "NotFound" response from the API Server when getting the Static Pod in question
func (w *KubeWaiter) WaitForPodToDisappear(podName string) error {
return wait.PollUntilContextTimeout(context.Background(),
constants.KubernetesAPICallRetryInterval, w.timeout,
true, func(_ context.Context) (bool, error) {
_, err := w.client.CoreV1().Pods(metav1.NamespaceSystem).Get(context.TODO(), podName, metav1.GetOptions{})
if err != nil && apierrors.IsNotFound(err) {
fmt.Printf("[apiclient] The old Pod %q is now removed (which is desired)\n", podName)
return true, nil
}
return false, nil
})
}
// WaitForKubelet blocks until the kubelet /healthz endpoint returns 'ok'.
func (w *KubeWaiter) WaitForKubelet() error {
var (
lastError error
start = time.Now()
healthzEndpoint = fmt.Sprintf("http://localhost:%d/healthz", constants.KubeletHealthzPort)
)
fmt.Printf("[kubelet-check] Waiting for a healthy kubelet. This can take up to %v\n", w.timeout)
formatError := func(cause string) error {
return errors.Errorf("The HTTP call equal to 'curl -sSL %s' returned %s\n",
healthzEndpoint, cause)
}
err := wait.PollUntilContextTimeout(
context.Background(),
constants.KubernetesAPICallRetryInterval,
w.timeout,
true, func(ctx context.Context) (bool, error) {
client := &http.Client{Transport: netutil.SetOldTransportDefaults(&http.Transport{})}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, healthzEndpoint, nil)
if err != nil {
lastError = formatError(fmt.Sprintf("error: %v", err))
return false, err
}
resp, err := client.Do(req)
if err != nil {
lastError = formatError(fmt.Sprintf("error: %v", err))
return false, nil
}
defer func() {
_ = resp.Body.Close()
}()
if resp.StatusCode != http.StatusOK {
lastError = formatError(fmt.Sprintf("status code: %d", resp.StatusCode))
return false, nil
}
return true, nil
})
if err != nil {
fmt.Printf("[kubelet-check] The kubelet is not healthy after %v\n", time.Since(start))
return lastError
}
fmt.Printf("[kubelet-check] The kubelet is healthy after %v\n", time.Since(start))
return nil
}
// SetTimeout adjusts the timeout to the specified duration
func (w *KubeWaiter) SetTimeout(timeout time.Duration) {
w.timeout = timeout
}
// WaitForStaticPodControlPlaneHashes blocks until it timeouts or gets a hash map for all components and their Static Pods
func (w *KubeWaiter) WaitForStaticPodControlPlaneHashes(nodeName string) (map[string]string, error) {
componentHash := ""
var err, lastErr error
mirrorPodHashes := map[string]string{}
for _, component := range constants.ControlPlaneComponents {
err = wait.PollUntilContextTimeout(context.Background(),
constants.KubernetesAPICallRetryInterval, w.timeout,
true, func(_ context.Context) (bool, error) {
componentHash, err = getStaticPodSingleHash(w.client, nodeName, component)
if err != nil {
lastErr = err
return false, nil
}
return true, nil
})
if err != nil {
return nil, lastErr
}
mirrorPodHashes[component] = componentHash
}
return mirrorPodHashes, nil
}
// WaitForStaticPodSingleHash blocks until it timeouts or gets a hash for a single component and its Static Pod
func (w *KubeWaiter) WaitForStaticPodSingleHash(nodeName string, component string) (string, error) {
componentPodHash := ""
var err, lastErr error
err = wait.PollUntilContextTimeout(context.Background(),
constants.KubernetesAPICallRetryInterval, w.timeout,
true, func(_ context.Context) (bool, error) {
componentPodHash, err = getStaticPodSingleHash(w.client, nodeName, component)
if err != nil {
lastErr = err
return false, nil
}
return true, nil
})
if err != nil {
err = lastErr
}
return componentPodHash, err
}
// WaitForStaticPodHashChange blocks until it timeouts or notices that the Mirror Pod (for the Static Pod, respectively) has changed
// This implicitly means this function blocks until the kubelet has restarted the Static Pod in question
func (w *KubeWaiter) WaitForStaticPodHashChange(nodeName, component, previousHash string) error {
var err, lastErr error
err = wait.PollUntilContextTimeout(context.Background(),
constants.KubernetesAPICallRetryInterval, w.timeout,
true, func(_ context.Context) (bool, error) {
hash, err := getStaticPodSingleHash(w.client, nodeName, component)
if err != nil {
lastErr = err
return false, nil
}
// Set lastErr to nil to be able to later distinguish between getStaticPodSingleHash() and timeout errors
lastErr = nil
// We should continue polling until the UID changes
if hash == previousHash {
return false, nil
}
return true, nil
})
// If lastError is not nil, this must be a getStaticPodSingleHash() error, else if err is not nil there was a poll timeout
if lastErr != nil {
return lastErr
}
return errors.Wrapf(err, "static Pod hash for component %s on Node %s did not change after %v", component, nodeName, w.timeout)
}
// getStaticPodSingleHash computes hashes for a single Static Pod resource
func getStaticPodSingleHash(client clientset.Interface, nodeName string, component string) (string, error) {
staticPodName := fmt.Sprintf("%s-%s", component, nodeName)
staticPod, err := client.CoreV1().Pods(metav1.NamespaceSystem).Get(context.TODO(), staticPodName, metav1.GetOptions{})
if err != nil {
return "", errors.Wrapf(err, "failed to obtain static Pod hash for component %s on Node %s", component, nodeName)
}
staticPodHash := staticPod.Annotations["kubernetes.io/config.hash"]
return staticPodHash, nil
}