| 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 |
"net/http" |
| 23 |
"sync" |
| 24 |
"time" |
| 25 |
|
| 26 |
"go.opentelemetry.io/otel/attribute" |
| 27 |
|
| 28 |
"k8s.io/apimachinery/pkg/api/errors" |
| 29 |
"k8s.io/apimachinery/pkg/api/meta" |
| 30 |
metainternalversionscheme "k8s.io/apimachinery/pkg/apis/meta/internalversion/scheme" |
| 31 |
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" |
| 32 |
"k8s.io/apimachinery/pkg/apis/meta/v1/validation" |
| 33 |
"k8s.io/apimachinery/pkg/runtime" |
| 34 |
"k8s.io/apimachinery/pkg/runtime/schema" |
| 35 |
"k8s.io/apiserver/pkg/admission" |
| 36 |
"k8s.io/apiserver/pkg/audit" |
| 37 |
"k8s.io/apiserver/pkg/authorization/authorizer" |
| 38 |
"k8s.io/apiserver/pkg/endpoints/handlers/fieldmanager" |
| 39 |
"k8s.io/apiserver/pkg/endpoints/handlers/finisher" |
| 40 |
requestmetrics "k8s.io/apiserver/pkg/endpoints/handlers/metrics" |
| 41 |
"k8s.io/apiserver/pkg/endpoints/handlers/negotiation" |
| 42 |
"k8s.io/apiserver/pkg/endpoints/handlers/responsewriters" |
| 43 |
"k8s.io/apiserver/pkg/endpoints/request" |
| 44 |
"k8s.io/apiserver/pkg/registry/rest" |
| 45 |
"k8s.io/apiserver/pkg/util/dryrun" |
| 46 |
"k8s.io/component-base/tracing" |
| 47 |
"k8s.io/klog/v2" |
| 48 |
) |
| 49 |
|
| 50 |
// UpdateResource returns a function that will handle a resource update |
| 51 |
func UpdateResource(r rest.Updater, scope *RequestScope, admit admission.Interface) http.HandlerFunc { |
| 52 |
return func(w http.ResponseWriter, req *http.Request) { |
| 53 |
ctx := req.Context() |
| 54 |
// For performance tracking purposes. |
| 55 |
ctx, span := tracing.Start(ctx, "Update", traceFields(req)...) |
| 56 |
req = req.WithContext(ctx) |
| 57 |
defer span.End(500 * time.Millisecond) |
| 58 |
|
| 59 |
namespace, name, err := scope.Namer.Name(req) |
| 60 |
if err != nil { |
| 61 |
scope.err(err, w, req) |
| 62 |
return |
| 63 |
} |
| 64 |
|
| 65 |
// enforce a timeout of at most requestTimeoutUpperBound (34s) or less if the user-provided |
| 66 |
// timeout inside the parent context is lower than requestTimeoutUpperBound. |
| 67 |
ctx, cancel := context.WithTimeout(ctx, requestTimeoutUpperBound) |
| 68 |
defer cancel() |
| 69 |
|
| 70 |
ctx = request.WithNamespace(ctx, namespace) |
| 71 |
|
| 72 |
outputMediaType, _, err := negotiation.NegotiateOutputMediaType(req, scope.Serializer, scope) |
| 73 |
if err != nil { |
| 74 |
scope.err(err, w, req) |
| 75 |
return |
| 76 |
} |
| 77 |
|
| 78 |
body, err := limitedReadBodyWithRecordMetric(ctx, req, scope.MaxRequestBodyBytes, scope.Resource.GroupResource().String(), requestmetrics.Update) |
| 79 |
if err != nil { |
| 80 |
span.AddEvent("limitedReadBody failed", attribute.Int("len", len(body)), attribute.String("err", err.Error())) |
| 81 |
scope.err(err, w, req) |
| 82 |
return |
| 83 |
} |
| 84 |
span.AddEvent("limitedReadBody succeeded", attribute.Int("len", len(body))) |
| 85 |
|
| 86 |
options := &metav1.UpdateOptions{} |
| 87 |
if err := metainternalversionscheme.ParameterCodec.DecodeParameters(req.URL.Query(), scope.MetaGroupVersion, options); err != nil { |
| 88 |
err = errors.NewBadRequest(err.Error()) |
| 89 |
scope.err(err, w, req) |
| 90 |
return |
| 91 |
} |
| 92 |
if errs := validation.ValidateUpdateOptions(options); len(errs) > 0 { |
| 93 |
err := errors.NewInvalid(schema.GroupKind{Group: metav1.GroupName, Kind: "UpdateOptions"}, "", errs) |
| 94 |
scope.err(err, w, req) |
| 95 |
return |
| 96 |
} |
| 97 |
options.TypeMeta.SetGroupVersionKind(metav1.SchemeGroupVersion.WithKind("UpdateOptions")) |
| 98 |
|
| 99 |
s, err := negotiation.NegotiateInputSerializer(req, false, scope.Serializer) |
| 100 |
if err != nil { |
| 101 |
scope.err(err, w, req) |
| 102 |
return |
| 103 |
} |
| 104 |
defaultGVK := scope.Kind |
| 105 |
original := r.New() |
| 106 |
|
| 107 |
validationDirective := fieldValidation(options.FieldValidation) |
| 108 |
decodeSerializer := s.Serializer |
| 109 |
if validationDirective == metav1.FieldValidationWarn || validationDirective == metav1.FieldValidationStrict { |
| 110 |
decodeSerializer = s.StrictSerializer |
| 111 |
} |
| 112 |
|
| 113 |
decoder := scope.Serializer.DecoderToVersion(decodeSerializer, scope.HubGroupVersion) |
| 114 |
span.AddEvent("About to convert to expected version") |
| 115 |
obj, gvk, err := decoder.Decode(body, &defaultGVK, original) |
| 116 |
if err != nil { |
| 117 |
strictError, isStrictError := runtime.AsStrictDecodingError(err) |
| 118 |
switch { |
| 119 |
case isStrictError && obj != nil && validationDirective == metav1.FieldValidationWarn: |
| 120 |
addStrictDecodingWarnings(req.Context(), strictError.Errors()) |
| 121 |
case isStrictError && validationDirective == metav1.FieldValidationIgnore: |
| 122 |
klog.Warningf("unexpected strict error when field validation is set to ignore") |
| 123 |
fallthrough |
| 124 |
default: |
| 125 |
err = transformDecodeError(scope.Typer, err, original, gvk, body) |
| 126 |
scope.err(err, w, req) |
| 127 |
return |
| 128 |
} |
| 129 |
} |
| 130 |
|
| 131 |
objGV := gvk.GroupVersion() |
| 132 |
if !scope.AcceptsGroupVersion(objGV) { |
| 133 |
err = errors.NewBadRequest(fmt.Sprintf("the API version in the data (%s) does not match the expected API version (%s)", objGV, defaultGVK.GroupVersion())) |
| 134 |
scope.err(err, w, req) |
| 135 |
return |
| 136 |
} |
| 137 |
span.AddEvent("Conversion done") |
| 138 |
|
| 139 |
audit.LogRequestObject(req.Context(), obj, objGV, scope.Resource, scope.Subresource, scope.Serializer) |
| 140 |
admit = admission.WithAudit(admit) |
| 141 |
|
| 142 |
// if this object supports namespace info |
| 143 |
if objectMeta, err := meta.Accessor(obj); err == nil { |
| 144 |
// ensure namespace on the object is correct, or error if a conflicting namespace was set in the object |
| 145 |
if err := rest.EnsureObjectNamespaceMatchesRequestNamespace(rest.ExpectedNamespaceForResource(namespace, scope.Resource), objectMeta); err != nil { |
| 146 |
scope.err(err, w, req) |
| 147 |
return |
| 148 |
} |
| 149 |
} |
| 150 |
|
| 151 |
if err := checkName(obj, name, namespace, scope.Namer); err != nil { |
| 152 |
scope.err(err, w, req) |
| 153 |
return |
| 154 |
} |
| 155 |
|
| 156 |
userInfo, _ := request.UserFrom(ctx) |
| 157 |
transformers := []rest.TransformFunc{} |
| 158 |
|
| 159 |
// allows skipping managedFields update if the resulting object is too big |
| 160 |
shouldUpdateManagedFields := true |
| 161 |
admit = fieldmanager.NewManagedFieldsValidatingAdmissionController(admit) |
| 162 |
transformers = append(transformers, func(_ context.Context, newObj, liveObj runtime.Object) (runtime.Object, error) { |
| 163 |
if shouldUpdateManagedFields { |
| 164 |
return scope.FieldManager.UpdateNoErrors(liveObj, newObj, managerOrUserAgent(options.FieldManager, req.UserAgent())), nil |
| 165 |
} |
| 166 |
return newObj, nil |
| 167 |
}) |
| 168 |
|
| 169 |
if mutatingAdmission, ok := admit.(admission.MutationInterface); ok { |
| 170 |
transformers = append(transformers, func(ctx context.Context, newObj, oldObj runtime.Object) (runtime.Object, error) { |
| 171 |
isNotZeroObject, err := hasUID(oldObj) |
| 172 |
if err != nil { |
| 173 |
return nil, fmt.Errorf("unexpected error when extracting UID from oldObj: %v", err.Error()) |
| 174 |
} else if !isNotZeroObject { |
| 175 |
if mutatingAdmission.Handles(admission.Create) { |
| 176 |
return newObj, mutatingAdmission.Admit(ctx, admission.NewAttributesRecord(newObj, nil, scope.Kind, namespace, name, scope.Resource, scope.Subresource, admission.Create, updateToCreateOptions(options), dryrun.IsDryRun(options.DryRun), userInfo), scope) |
| 177 |
} |
| 178 |
} else { |
| 179 |
if mutatingAdmission.Handles(admission.Update) { |
| 180 |
return newObj, mutatingAdmission.Admit(ctx, admission.NewAttributesRecord(newObj, oldObj, scope.Kind, namespace, name, scope.Resource, scope.Subresource, admission.Update, options, dryrun.IsDryRun(options.DryRun), userInfo), scope) |
| 181 |
} |
| 182 |
} |
| 183 |
return newObj, nil |
| 184 |
}) |
| 185 |
transformers = append(transformers, func(ctx context.Context, newObj, oldObj runtime.Object) (runtime.Object, error) { |
| 186 |
// Dedup owner references again after mutating admission happens |
| 187 |
dedupOwnerReferencesAndAddWarning(newObj, req.Context(), true) |
| 188 |
return newObj, nil |
| 189 |
}) |
| 190 |
} |
| 191 |
|
| 192 |
createAuthorizerAttributes := authorizer.AttributesRecord{ |
| 193 |
User: userInfo, |
| 194 |
ResourceRequest: true, |
| 195 |
Path: req.URL.Path, |
| 196 |
Verb: "create", |
| 197 |
APIGroup: scope.Resource.Group, |
| 198 |
APIVersion: scope.Resource.Version, |
| 199 |
Resource: scope.Resource.Resource, |
| 200 |
Subresource: scope.Subresource, |
| 201 |
Namespace: namespace, |
| 202 |
Name: name, |
| 203 |
} |
| 204 |
|
| 205 |
span.AddEvent("About to store object in database") |
| 206 |
wasCreated := false |
| 207 |
requestFunc := func() (runtime.Object, error) { |
| 208 |
obj, created, err := r.Update( |
| 209 |
ctx, |
| 210 |
name, |
| 211 |
rest.DefaultUpdatedObjectInfo(obj, transformers...), |
| 212 |
withAuthorization(rest.AdmissionToValidateObjectFunc( |
| 213 |
admit, |
| 214 |
admission.NewAttributesRecord(nil, nil, scope.Kind, namespace, name, scope.Resource, scope.Subresource, admission.Create, updateToCreateOptions(options), dryrun.IsDryRun(options.DryRun), userInfo), scope), |
| 215 |
scope.Authorizer, createAuthorizerAttributes), |
| 216 |
rest.AdmissionToValidateObjectUpdateFunc( |
| 217 |
admit, |
| 218 |
admission.NewAttributesRecord(nil, nil, scope.Kind, namespace, name, scope.Resource, scope.Subresource, admission.Update, options, dryrun.IsDryRun(options.DryRun), userInfo), scope), |
| 219 |
false, |
| 220 |
options, |
| 221 |
) |
| 222 |
wasCreated = created |
| 223 |
return obj, err |
| 224 |
} |
| 225 |
// Dedup owner references before updating managed fields |
| 226 |
dedupOwnerReferencesAndAddWarning(obj, req.Context(), false) |
| 227 |
result, err := finisher.FinishRequest(ctx, func() (runtime.Object, error) { |
| 228 |
result, err := requestFunc() |
| 229 |
// If the object wasn't committed to storage because it's serialized size was too large, |
| 230 |
// it is safe to remove managedFields (which can be large) and try again. |
| 231 |
if isTooLargeError(err) { |
| 232 |
if accessor, accessorErr := meta.Accessor(obj); accessorErr == nil { |
| 233 |
accessor.SetManagedFields(nil) |
| 234 |
shouldUpdateManagedFields = false |
| 235 |
result, err = requestFunc() |
| 236 |
} |
| 237 |
} |
| 238 |
return result, err |
| 239 |
}) |
| 240 |
if err != nil { |
| 241 |
span.AddEvent("Write to database call failed", attribute.Int("len", len(body)), attribute.String("err", err.Error())) |
| 242 |
scope.err(err, w, req) |
| 243 |
return |
| 244 |
} |
| 245 |
span.AddEvent("Write to database call succeeded", attribute.Int("len", len(body))) |
| 246 |
|
| 247 |
status := http.StatusOK |
| 248 |
if wasCreated { |
| 249 |
status = http.StatusCreated |
| 250 |
} |
| 251 |
|
| 252 |
span.AddEvent("About to write a response") |
| 253 |
defer span.AddEvent("Writing http response done") |
| 254 |
transformResponseObject(ctx, scope, req, w, status, outputMediaType, result) |
| 255 |
} |
| 256 |
} |
| 257 |
|
| 258 |
func withAuthorization(validate rest.ValidateObjectFunc, a authorizer.Authorizer, attributes authorizer.Attributes) rest.ValidateObjectFunc { |
| 259 |
var once sync.Once |
| 260 |
var authorizerDecision authorizer.Decision |
| 261 |
var authorizerReason string |
| 262 |
var authorizerErr error |
| 263 |
return func(ctx context.Context, obj runtime.Object) error { |
| 264 |
if a == nil { |
| 265 |
return errors.NewInternalError(fmt.Errorf("no authorizer provided, unable to authorize a create on update")) |
| 266 |
} |
| 267 |
once.Do(func() { |
| 268 |
authorizerDecision, authorizerReason, authorizerErr = a.Authorize(ctx, attributes) |
| 269 |
}) |
| 270 |
// an authorizer like RBAC could encounter evaluation errors and still allow the request, so authorizer decision is checked before error here. |
| 271 |
if authorizerDecision == authorizer.DecisionAllow { |
| 272 |
// Continue to validating admission |
| 273 |
return validate(ctx, obj) |
| 274 |
} |
| 275 |
if authorizerErr != nil { |
| 276 |
return errors.NewInternalError(authorizerErr) |
| 277 |
} |
| 278 |
|
| 279 |
// The user is not authorized to perform this action, so we need to build the error response |
| 280 |
return responsewriters.ForbiddenStatusError(attributes, authorizerReason) |
| 281 |
} |
| 282 |
} |
| 283 |
|
| 284 |
// updateToCreateOptions creates a CreateOptions with the same field values as the provided UpdateOptions. |
| 285 |
func updateToCreateOptions(uo *metav1.UpdateOptions) *metav1.CreateOptions { |
| 286 |
if uo == nil { |
| 287 |
return nil |
| 288 |
} |
| 289 |
co := &metav1.CreateOptions{ |
| 290 |
DryRun: uo.DryRun, |
| 291 |
FieldManager: uo.FieldManager, |
| 292 |
FieldValidation: uo.FieldValidation, |
| 293 |
} |
| 294 |
co.TypeMeta.SetGroupVersionKind(metav1.SchemeGroupVersion.WithKind("CreateOptions")) |
| 295 |
return co |
| 296 |
} |