Matthias Andreas Benkard | 832a54e | 2019-01-29 09:27:38 +0100 | [diff] [blame] | 1 | /* |
| 2 | Copyright 2017 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 | 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. |
| 29 | func 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 | } |