k8s.io/apiserver@v0.31.1/pkg/server/storage_readiness_hook.go (about) 1 /* 2 Copyright 2024 The Kubernetes Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package server 18 19 import ( 20 "context" 21 "errors" 22 "sync" 23 "time" 24 25 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" 26 "k8s.io/apimachinery/pkg/util/wait" 27 "k8s.io/apiserver/pkg/registry/rest" 28 "k8s.io/klog/v2" 29 ) 30 31 // StorageReadinessHook implements PostStartHook functionality for checking readiness 32 // of underlying storage for registered resources. 33 type StorageReadinessHook struct { 34 timeout time.Duration 35 36 lock sync.Mutex 37 checks map[string]func() error 38 } 39 40 // NewStorageReadinessHook created new StorageReadinessHook. 41 func NewStorageReadinessHook(timeout time.Duration) *StorageReadinessHook { 42 return &StorageReadinessHook{ 43 checks: make(map[string]func() error), 44 timeout: timeout, 45 } 46 } 47 48 func (h *StorageReadinessHook) RegisterStorage(gvr metav1.GroupVersionResource, storage rest.StorageWithReadiness) { 49 h.lock.Lock() 50 defer h.lock.Unlock() 51 52 if _, ok := h.checks[gvr.String()]; !ok { 53 h.checks[gvr.String()] = storage.ReadinessCheck 54 } else { 55 klog.Errorf("Registering storage readiness hook for %s again: ", gvr.String()) 56 } 57 } 58 59 func (h *StorageReadinessHook) check() bool { 60 h.lock.Lock() 61 defer h.lock.Unlock() 62 63 failedChecks := []string{} 64 for gvr, check := range h.checks { 65 if err := check(); err != nil { 66 failedChecks = append(failedChecks, gvr) 67 } 68 } 69 if len(failedChecks) == 0 { 70 klog.Infof("Storage is ready for all registered resources") 71 return true 72 } 73 klog.V(4).Infof("Storage is not ready for: %v", failedChecks) 74 return false 75 } 76 77 func (h *StorageReadinessHook) Hook(ctx PostStartHookContext) error { 78 deadlineCtx, cancel := context.WithTimeout(ctx, h.timeout) 79 defer cancel() 80 err := wait.PollUntilContextCancel(deadlineCtx, 100*time.Millisecond, true, 81 func(_ context.Context) (bool, error) { 82 if ok := h.check(); ok { 83 return true, nil 84 } 85 return false, nil 86 }) 87 if errors.Is(err, context.DeadlineExceeded) { 88 klog.Warningf("Deadline exceeded while waiting for storage readiness... ignoring") 89 } 90 return nil 91 }