| 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 handlers |
| 18 |
|
| 19 |
import ( |
| 20 |
"context" |
| 21 |
"fmt" |
| 22 |
"math/rand" |
| 23 |
"net/http" |
| 24 |
"net/url" |
| 25 |
"strings" |
| 26 |
"time" |
| 27 |
|
| 28 |
"go.opentelemetry.io/otel/attribute" |
| 29 |
|
| 30 |
"k8s.io/apimachinery/pkg/api/errors" |
| 31 |
"k8s.io/apimachinery/pkg/api/meta" |
| 32 |
metainternalversion "k8s.io/apimachinery/pkg/apis/meta/internalversion" |
| 33 |
metainternalversionscheme "k8s.io/apimachinery/pkg/apis/meta/internalversion/scheme" |
| 34 |
metainternalversionvalidation "k8s.io/apimachinery/pkg/apis/meta/internalversion/validation" |
| 35 |
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" |
| 36 |
"k8s.io/apimachinery/pkg/fields" |
| 37 |
"k8s.io/apimachinery/pkg/runtime" |
| 38 |
"k8s.io/apimachinery/pkg/runtime/schema" |
| 39 |
"k8s.io/apiserver/pkg/endpoints/handlers/negotiation" |
| 40 |
"k8s.io/apiserver/pkg/endpoints/metrics" |
| 41 |
"k8s.io/apiserver/pkg/endpoints/request" |
| 42 |
"k8s.io/apiserver/pkg/features" |
| 43 |
"k8s.io/apiserver/pkg/registry/rest" |
| 44 |
"k8s.io/apiserver/pkg/server/routine" |
| 45 |
utilfeature "k8s.io/apiserver/pkg/util/feature" |
| 46 |
"k8s.io/component-base/tracing" |
| 47 |
"k8s.io/klog/v2" |
| 48 |
"k8s.io/utils/ptr" |
| 49 |
) |
| 50 |
|
| 51 |
// getterFunc performs a get request with the given context and object name. The request |
| 52 |
// may be used to deserialize an options object to pass to the getter. |
| 53 |
type getterFunc func(ctx context.Context, name string, req *http.Request) (runtime.Object, error) |
| 54 |
|
| 55 |
// getResourceHandler is an HTTP handler function for get requests. It delegates to the |
| 56 |
// passed-in getterFunc to perform the actual get. |
| 57 |
func getResourceHandler(scope *RequestScope, getter getterFunc) http.HandlerFunc { |
| 58 |
return func(w http.ResponseWriter, req *http.Request) { |
| 59 |
ctx := req.Context() |
| 60 |
ctx, span := tracing.Start(ctx, "Get", traceFields(req)...) |
| 61 |
req = req.WithContext(ctx) |
| 62 |
defer span.End(500 * time.Millisecond) |
| 63 |
|
| 64 |
namespace, name, err := scope.Namer.Name(req) |
| 65 |
if err != nil { |
| 66 |
scope.err(err, w, req) |
| 67 |
return |
| 68 |
} |
| 69 |
ctx = request.WithNamespace(ctx, namespace) |
| 70 |
|
| 71 |
outputMediaType, _, err := negotiation.NegotiateOutputMediaType(req, scope.Serializer, scope) |
| 72 |
if err != nil { |
| 73 |
scope.err(err, w, req) |
| 74 |
return |
| 75 |
} |
| 76 |
|
| 77 |
result, err := getter(ctx, name, req) |
| 78 |
if err != nil { |
| 79 |
scope.err(err, w, req) |
| 80 |
return |
| 81 |
} |
| 82 |
|
| 83 |
span.AddEvent("About to write a response") |
| 84 |
defer span.AddEvent("Writing http response done") |
| 85 |
transformResponseObject(ctx, scope, req, w, http.StatusOK, outputMediaType, result) |
| 86 |
} |
| 87 |
} |
| 88 |
|
| 89 |
// GetResource returns a function that handles retrieving a single resource from a rest.Storage object. |
| 90 |
func GetResource(r rest.Getter, scope *RequestScope) http.HandlerFunc { |
| 91 |
return getResourceHandler(scope, |
| 92 |
func(ctx context.Context, name string, req *http.Request) (runtime.Object, error) { |
| 93 |
// check for export |
| 94 |
options := metav1.GetOptions{} |
| 95 |
if values := req.URL.Query(); len(values) > 0 { |
| 96 |
if len(values["export"]) > 0 { |
| 97 |
exportBool := true |
| 98 |
exportStrings := values["export"] |
| 99 |
err := runtime.Convert_Slice_string_To_bool(&exportStrings, &exportBool, nil) |
| 100 |
if err != nil { |
| 101 |
return nil, errors.NewBadRequest(fmt.Sprintf("the export parameter cannot be parsed: %v", err)) |
| 102 |
} |
| 103 |
if exportBool { |
| 104 |
return nil, errors.NewBadRequest("the export parameter, deprecated since v1.14, is no longer supported") |
| 105 |
} |
| 106 |
} |
| 107 |
if err := metainternalversionscheme.ParameterCodec.DecodeParameters(values, scope.MetaGroupVersion, &options); err != nil { |
| 108 |
err = errors.NewBadRequest(err.Error()) |
| 109 |
return nil, err |
| 110 |
} |
| 111 |
} |
| 112 |
tracing.SpanFromContext(ctx).AddEvent("About to Get from storage") |
| 113 |
return r.Get(ctx, name, &options) |
| 114 |
}) |
| 115 |
} |
| 116 |
|
| 117 |
// GetResourceWithOptions returns a function that handles retrieving a single resource from a rest.Storage object. |
| 118 |
func GetResourceWithOptions(r rest.GetterWithOptions, scope *RequestScope, isSubresource bool) http.HandlerFunc { |
| 119 |
return getResourceHandler(scope, |
| 120 |
func(ctx context.Context, name string, req *http.Request) (runtime.Object, error) { |
| 121 |
opts, subpath, subpathKey := r.NewGetOptions() |
| 122 |
span := tracing.SpanFromContext(ctx) |
| 123 |
span.AddEvent("About to process Get options") |
| 124 |
if err := getRequestOptions(req, scope, opts, subpath, subpathKey, isSubresource); err != nil { |
| 125 |
err = errors.NewBadRequest(err.Error()) |
| 126 |
return nil, err |
| 127 |
} |
| 128 |
span.AddEvent("About to Get from storage") |
| 129 |
return r.Get(ctx, name, opts) |
| 130 |
}) |
| 131 |
} |
| 132 |
|
| 133 |
// getRequestOptions parses out options and can include path information. The path information shouldn't include the subresource. |
| 134 |
func getRequestOptions(req *http.Request, scope *RequestScope, into runtime.Object, subpath bool, subpathKey string, isSubresource bool) error { |
| 135 |
if into == nil { |
| 136 |
return nil |
| 137 |
} |
| 138 |
|
| 139 |
query := req.URL.Query() |
| 140 |
if subpath { |
| 141 |
newQuery := make(url.Values) |
| 142 |
for k, v := range query { |
| 143 |
newQuery[k] = v |
| 144 |
} |
| 145 |
|
| 146 |
ctx := req.Context() |
| 147 |
requestInfo, _ := request.RequestInfoFrom(ctx) |
| 148 |
startingIndex := 2 |
| 149 |
if isSubresource { |
| 150 |
startingIndex = 3 |
| 151 |
} |
| 152 |
|
| 153 |
p := strings.Join(requestInfo.Parts[startingIndex:], "/") |
| 154 |
|
| 155 |
// ensure non-empty subpaths correctly reflect a leading slash |
| 156 |
if len(p) > 0 && !strings.HasPrefix(p, "/") { |
| 157 |
p = "/" + p |
| 158 |
} |
| 159 |
|
| 160 |
// ensure subpaths correctly reflect the presence of a trailing slash on the original request |
| 161 |
if strings.HasSuffix(requestInfo.Path, "/") && !strings.HasSuffix(p, "/") { |
| 162 |
p += "/" |
| 163 |
} |
| 164 |
|
| 165 |
newQuery[subpathKey] = []string{p} |
| 166 |
query = newQuery |
| 167 |
} |
| 168 |
return scope.ParameterCodec.DecodeParameters(query, scope.Kind.GroupVersion(), into) |
| 169 |
} |
| 170 |
|
| 171 |
func ListResource(r rest.Lister, rw rest.Watcher, scope *RequestScope, forceWatch bool, minRequestTimeout time.Duration) http.HandlerFunc { |
| 172 |
return func(w http.ResponseWriter, req *http.Request) { |
| 173 |
ctx := req.Context() |
| 174 |
// For performance tracking purposes. |
| 175 |
ctx, span := tracing.Start(ctx, "List", traceFields(req)...) |
| 176 |
req = req.WithContext(ctx) |
| 177 |
|
| 178 |
namespace, err := scope.Namer.Namespace(req) |
| 179 |
if err != nil { |
| 180 |
scope.err(err, w, req) |
| 181 |
return |
| 182 |
} |
| 183 |
|
| 184 |
// Watches for single objects are routed to this function. |
| 185 |
// Treat a name parameter the same as a field selector entry. |
| 186 |
hasName := true |
| 187 |
_, name, err := scope.Namer.Name(req) |
| 188 |
if err != nil { |
| 189 |
hasName = false |
| 190 |
} |
| 191 |
ctx = request.WithNamespace(ctx, namespace) |
| 192 |
|
| 193 |
opts := metainternalversion.ListOptions{} |
| 194 |
if err := metainternalversionscheme.ParameterCodec.DecodeParameters(req.URL.Query(), scope.MetaGroupVersion, &opts); err != nil { |
| 195 |
err = errors.NewBadRequest(err.Error()) |
| 196 |
scope.err(err, w, req) |
| 197 |
return |
| 198 |
} |
| 199 |
|
| 200 |
metainternalversion.SetListOptionsDefaults(&opts, utilfeature.DefaultFeatureGate.Enabled(features.WatchList)) |
| 201 |
if errs := metainternalversionvalidation.ValidateListOptions(&opts, utilfeature.DefaultFeatureGate.Enabled(features.WatchList)); len(errs) > 0 { |
| 202 |
err := errors.NewInvalid(schema.GroupKind{Group: metav1.GroupName, Kind: "ListOptions"}, "", errs) |
| 203 |
scope.err(err, w, req) |
| 204 |
return |
| 205 |
} |
| 206 |
|
| 207 |
var restrictions negotiation.EndpointRestrictions |
| 208 |
restrictions = scope |
| 209 |
if isListWatchRequest(opts) { |
| 210 |
restrictions = &watchListEndpointRestrictions{scope} |
| 211 |
} |
| 212 |
outputMediaType, _, err := negotiation.NegotiateOutputMediaType(req, scope.Serializer, restrictions) |
| 213 |
if err != nil { |
| 214 |
scope.err(err, w, req) |
| 215 |
return |
| 216 |
} |
| 217 |
|
| 218 |
// transform fields |
| 219 |
// TODO: DecodeParametersInto should do this. |
| 220 |
if opts.FieldSelector != nil { |
| 221 |
fn := func(label, value string) (newLabel, newValue string, err error) { |
| 222 |
return scope.Convertor.ConvertFieldLabel(scope.Kind, label, value) |
| 223 |
} |
| 224 |
if opts.FieldSelector, err = opts.FieldSelector.Transform(fn); err != nil { |
| 225 |
// TODO: allow bad request to set field causes based on query parameters |
| 226 |
err = errors.NewBadRequest(err.Error()) |
| 227 |
scope.err(err, w, req) |
| 228 |
return |
| 229 |
} |
| 230 |
} |
| 231 |
|
| 232 |
if hasName { |
| 233 |
// metadata.name is the canonical internal name. |
| 234 |
// SelectionPredicate will notice that this is a request for |
| 235 |
// a single object and optimize the storage query accordingly. |
| 236 |
nameSelector := fields.OneTermEqualSelector("metadata.name", name) |
| 237 |
|
| 238 |
// Note that fieldSelector setting explicitly the "metadata.name" |
| 239 |
// will result in reaching this branch (as the value of that field |
| 240 |
// is propagated to requestInfo as the name parameter. |
| 241 |
// That said, the allowed field selectors in this branch are: |
| 242 |
// nil, fields.Everything and field selector matching metadata.name |
| 243 |
// for our name. |
| 244 |
if opts.FieldSelector != nil && !opts.FieldSelector.Empty() { |
| 245 |
selectedName, ok := opts.FieldSelector.RequiresExactMatch("metadata.name") |
| 246 |
if !ok || name != selectedName { |
| 247 |
scope.err(errors.NewBadRequest("fieldSelector metadata.name doesn't match requested name"), w, req) |
| 248 |
return |
| 249 |
} |
| 250 |
} else { |
| 251 |
opts.FieldSelector = nameSelector |
| 252 |
} |
| 253 |
} |
| 254 |
|
| 255 |
if opts.Watch || forceWatch { |
| 256 |
if rw == nil { |
| 257 |
scope.err(errors.NewMethodNotSupported(scope.Resource.GroupResource(), "watch"), w, req) |
| 258 |
return |
| 259 |
} |
| 260 |
// TODO: Currently we explicitly ignore ?timeout= and use only ?timeoutSeconds=. |
| 261 |
timeout := time.Duration(0) |
| 262 |
if opts.TimeoutSeconds != nil { |
| 263 |
timeout = time.Duration(*opts.TimeoutSeconds) * time.Second |
| 264 |
} |
| 265 |
if timeout == 0 && minRequestTimeout > 0 { |
| 266 |
timeout = time.Duration(float64(minRequestTimeout) * (rand.Float64() + 1.0)) |
| 267 |
} |
| 268 |
|
| 269 |
var emptyVersionedList runtime.Object |
| 270 |
if isListWatchRequest(opts) { |
| 271 |
emptyVersionedList, err = scope.Convertor.ConvertToVersion(r.NewList(), scope.Kind.GroupVersion()) |
| 272 |
if err != nil { |
| 273 |
scope.err(errors.NewInternalError(err), w, req) |
| 274 |
return |
| 275 |
} |
| 276 |
} |
| 277 |
|
| 278 |
klog.V(3).InfoS("Starting watch", "path", req.URL.Path, "resourceVersion", opts.ResourceVersion, "labels", opts.LabelSelector, "fields", opts.FieldSelector, "timeout", timeout) |
| 279 |
ctx, cancel := context.WithTimeout(ctx, timeout) |
| 280 |
defer func() { cancel() }() |
| 281 |
watcher, err := rw.Watch(ctx, &opts) |
| 282 |
if err != nil { |
| 283 |
scope.err(err, w, req) |
| 284 |
return |
| 285 |
} |
| 286 |
handler, err := serveWatchHandler(watcher, scope, outputMediaType, req, w, timeout, metrics.CleanListScope(ctx, &opts), emptyVersionedList) |
| 287 |
if err != nil { |
| 288 |
scope.err(err, w, req) |
| 289 |
return |
| 290 |
} |
| 291 |
// Invalidate cancel() to defer until serve() is complete. |
| 292 |
deferredCancel := cancel |
| 293 |
cancel = func() {} |
| 294 |
|
| 295 |
serve := func() { |
| 296 |
defer deferredCancel() |
| 297 |
requestInfo, _ := request.RequestInfoFrom(ctx) |
| 298 |
metrics.RecordLongRunning(req, requestInfo, metrics.APIServerComponent, func() { |
| 299 |
defer watcher.Stop() |
| 300 |
handler.ServeHTTP(w, req) |
| 301 |
}) |
| 302 |
} |
| 303 |
|
| 304 |
// Run watch serving in a separate goroutine to allow freeing current stack memory |
| 305 |
t := routine.TaskFrom(req.Context()) |
| 306 |
if t != nil { |
| 307 |
t.Func = serve |
| 308 |
} else { |
| 309 |
serve() |
| 310 |
} |
| 311 |
return |
| 312 |
} |
| 313 |
|
| 314 |
// Log only long List requests (ignore Watch). |
| 315 |
defer span.End(500 * time.Millisecond) |
| 316 |
span.AddEvent("About to List from storage") |
| 317 |
result, err := r.List(ctx, &opts) |
| 318 |
if err != nil { |
| 319 |
scope.err(err, w, req) |
| 320 |
return |
| 321 |
} |
| 322 |
span.AddEvent("Listing from storage done") |
| 323 |
defer span.AddEvent("Writing http response done", attribute.Int("count", meta.LenList(result))) |
| 324 |
transformResponseObject(ctx, scope, req, w, http.StatusOK, outputMediaType, result) |
| 325 |
} |
| 326 |
} |
| 327 |
|
| 328 |
type watchListEndpointRestrictions struct { |
| 329 |
negotiation.EndpointRestrictions |
| 330 |
} |
| 331 |
|
| 332 |
func (e *watchListEndpointRestrictions) AllowsMediaTypeTransform(mimeType, mimeSubType string, target *schema.GroupVersionKind) bool { |
| 333 |
if target != nil && target.Kind == "Table" { |
| 334 |
return false |
| 335 |
} |
| 336 |
return e.EndpointRestrictions.AllowsMediaTypeTransform(mimeType, mimeSubType, target) |
| 337 |
} |
| 338 |
|
| 339 |
func isListWatchRequest(opts metainternalversion.ListOptions) bool { |
| 340 |
return utilfeature.DefaultFeatureGate.Enabled(features.WatchList) && ptr.Deref(opts.SendInitialEvents, false) && opts.AllowWatchBookmarks |
| 341 |
} |