| 1 |
/* |
| 2 |
Copyright 2023 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 filters |
| 18 |
|
| 19 |
import ( |
| 20 |
"errors" |
| 21 |
"net/http" |
| 22 |
|
| 23 |
"k8s.io/apiserver/pkg/endpoints/handlers/responsewriters" |
| 24 |
apirequest "k8s.io/apiserver/pkg/endpoints/request" |
| 25 |
"k8s.io/klog/v2" |
| 26 |
) |
| 27 |
|
| 28 |
func WithWatchTerminationDuringShutdown(handler http.Handler, termination apirequest.ServerShutdownSignal, wg RequestWaitGroup) http.Handler { |
| 29 |
if termination == nil || wg == nil { |
| 30 |
klog.Warningf("watch termination during shutdown not attached to the handler chain") |
| 31 |
return handler |
| 32 |
} |
| 33 |
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { |
| 34 |
ctx := req.Context() |
| 35 |
requestInfo, ok := apirequest.RequestInfoFrom(ctx) |
| 36 |
if !ok { |
| 37 |
// if this happens, the handler chain isn't setup correctly because there is no request info |
| 38 |
responsewriters.InternalError(w, req, errors.New("no RequestInfo found in the context")) |
| 39 |
return |
| 40 |
} |
| 41 |
if !watchVerbs.Has(requestInfo.Verb) { |
| 42 |
handler.ServeHTTP(w, req) |
| 43 |
return |
| 44 |
} |
| 45 |
|
| 46 |
if err := wg.Add(1); err != nil { |
| 47 |
// When apiserver is shutting down, signal clients to retry |
| 48 |
// There is a good chance the client hit a different server, so a tight retry is good for client responsiveness. |
| 49 |
waitGroupWriteRetryAfterToResponse(w) |
| 50 |
return |
| 51 |
} |
| 52 |
|
| 53 |
// attach ServerShutdownSignal to the watch request so that the |
| 54 |
// watch handler loop can return as soon as the server signals |
| 55 |
// that it is shutting down. |
| 56 |
ctx = apirequest.WithServerShutdownSignal(req.Context(), termination) |
| 57 |
req = req.WithContext(ctx) |
| 58 |
|
| 59 |
defer wg.Done() |
| 60 |
handler.ServeHTTP(w, req) |
| 61 |
}) |
| 62 |
} |