blob: b40a4227296b052cbe2ecdf950489255032b4001 [file] [log] [blame]
Matthias Andreas Benkard832a54e2019-01-29 09:27:38 +01001/*
2Copyright 2017 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 filters
18
19import (
20 "errors"
21 "net/http"
22
23 utilwaitgroup "k8s.io/apimachinery/pkg/util/waitgroup"
24 "k8s.io/apiserver/pkg/endpoints/handlers/responsewriters"
25 apirequest "k8s.io/apiserver/pkg/endpoints/request"
26)
27
28// WithWaitGroup adds all non long-running requests to wait group, which is used for graceful shutdown.
29func WithWaitGroup(handler http.Handler, longRunning apirequest.LongRunningRequestCheck, wg *utilwaitgroup.SafeWaitGroup) http.Handler {
30 return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
31 ctx := req.Context()
32 requestInfo, ok := apirequest.RequestInfoFrom(ctx)
33 if !ok {
34 // if this happens, the handler chain isn't setup correctly because there is no request info
35 responsewriters.InternalError(w, req, errors.New("no RequestInfo found in the context"))
36 return
37 }
38
39 if !longRunning(req, requestInfo) {
40 if err := wg.Add(1); err != nil {
41 http.Error(w, "apiserver is shutting down.", http.StatusInternalServerError)
42 return
43 }
44 defer wg.Done()
45 }
46
47 handler.ServeHTTP(w, req)
48 })
49}