blob: d2a9e7d4cf7c5069b88fd567dd16b7f678fc684f [file] [log] [blame]
Matthias Andreas Benkard832a54e2019-01-29 09:27:38 +01001/*
2Copyright 2015 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 admission
18
19import (
20 "time"
21
22 "k8s.io/apimachinery/pkg/util/sets"
23)
24
25const (
26 // timeToWaitForReady is the amount of time to wait to let an admission controller to be ready to satisfy a request.
27 // this is useful when admission controllers need to warm their caches before letting requests through.
28 timeToWaitForReady = 10 * time.Second
29)
30
31// ReadyFunc is a function that returns true if the admission controller is ready to handle requests.
32type ReadyFunc func() bool
33
34// Handler is a base for admission control handlers that
35// support a predefined set of operations
36type Handler struct {
37 operations sets.String
38 readyFunc ReadyFunc
39}
40
41// Handles returns true for methods that this handler supports
42func (h *Handler) Handles(operation Operation) bool {
43 return h.operations.Has(string(operation))
44}
45
46// NewHandler creates a new base handler that handles the passed
47// in operations
48func NewHandler(ops ...Operation) *Handler {
49 operations := sets.NewString()
50 for _, op := range ops {
51 operations.Insert(string(op))
52 }
53 return &Handler{
54 operations: operations,
55 }
56}
57
58// SetReadyFunc allows late registration of a ReadyFunc to know if the handler is ready to process requests.
59func (h *Handler) SetReadyFunc(readyFunc ReadyFunc) {
60 h.readyFunc = readyFunc
61}
62
63// WaitForReady will wait for the readyFunc (if registered) to return ready, and in case of timeout, will return false.
64func (h *Handler) WaitForReady() bool {
65 // there is no ready func configured, so we return immediately
66 if h.readyFunc == nil {
67 return true
68 }
69
70 timeout := time.After(timeToWaitForReady)
71 for !h.readyFunc() {
72 select {
73 case <-time.After(100 * time.Millisecond):
74 case <-timeout:
75 return h.readyFunc()
76 }
77 }
78 return true
79}