| 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 |
"strings" |
| 24 |
"time" |
| 25 |
|
| 26 |
"go.opentelemetry.io/otel/attribute" |
| 27 |
jsonpatch "gopkg.in/evanphx/json-patch.v4" |
| 28 |
kjson "sigs.k8s.io/json" |
| 29 |
|
| 30 |
"k8s.io/apimachinery/pkg/api/errors" |
| 31 |
"k8s.io/apimachinery/pkg/api/meta" |
| 32 |
metainternalversionscheme "k8s.io/apimachinery/pkg/apis/meta/internalversion/scheme" |
| 33 |
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" |
| 34 |
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" |
| 35 |
"k8s.io/apimachinery/pkg/apis/meta/v1/validation" |
| 36 |
"k8s.io/apimachinery/pkg/runtime" |
| 37 |
"k8s.io/apimachinery/pkg/runtime/schema" |
| 38 |
cbor "k8s.io/apimachinery/pkg/runtime/serializer/cbor/direct" |
| 39 |
"k8s.io/apimachinery/pkg/types" |
| 40 |
"k8s.io/apimachinery/pkg/util/managedfields" |
| 41 |
"k8s.io/apimachinery/pkg/util/mergepatch" |
| 42 |
utilruntime "k8s.io/apimachinery/pkg/util/runtime" |
| 43 |
"k8s.io/apimachinery/pkg/util/sets" |
| 44 |
"k8s.io/apimachinery/pkg/util/strategicpatch" |
| 45 |
"k8s.io/apimachinery/pkg/util/validation/field" |
| 46 |
"k8s.io/apimachinery/pkg/util/yaml" |
| 47 |
"k8s.io/apiserver/pkg/admission" |
| 48 |
"k8s.io/apiserver/pkg/audit" |
| 49 |
"k8s.io/apiserver/pkg/authorization/authorizer" |
| 50 |
"k8s.io/apiserver/pkg/endpoints/handlers/fieldmanager" |
| 51 |
"k8s.io/apiserver/pkg/endpoints/handlers/finisher" |
| 52 |
requestmetrics "k8s.io/apiserver/pkg/endpoints/handlers/metrics" |
| 53 |
"k8s.io/apiserver/pkg/endpoints/handlers/negotiation" |
| 54 |
"k8s.io/apiserver/pkg/endpoints/request" |
| 55 |
"k8s.io/apiserver/pkg/features" |
| 56 |
"k8s.io/apiserver/pkg/registry/rest" |
| 57 |
"k8s.io/apiserver/pkg/util/dryrun" |
| 58 |
utilfeature "k8s.io/apiserver/pkg/util/feature" |
| 59 |
"k8s.io/component-base/tracing" |
| 60 |
) |
| 61 |
|
| 62 |
const ( |
| 63 |
// maximum number of operations a single json patch may contain. |
| 64 |
maxJSONPatchOperations = 10000 |
| 65 |
) |
| 66 |
|
| 67 |
// PatchResource returns a function that will handle a resource patch. |
| 68 |
func PatchResource(r rest.Patcher, scope *RequestScope, admit admission.Interface, patchTypes []string) http.HandlerFunc { |
| 69 |
return func(w http.ResponseWriter, req *http.Request) { |
| 70 |
ctx := req.Context() |
| 71 |
// For performance tracking purposes. |
| 72 |
ctx, span := tracing.Start(ctx, "Patch", traceFields(req)...) |
| 73 |
req = req.WithContext(ctx) |
| 74 |
defer span.End(500 * time.Millisecond) |
| 75 |
|
| 76 |
// Do this first, otherwise name extraction can fail for unrecognized content types |
| 77 |
// TODO: handle this in negotiation |
| 78 |
contentType := req.Header.Get("Content-Type") |
| 79 |
// Remove "; charset=" if included in header. |
| 80 |
if idx := strings.Index(contentType, ";"); idx > 0 { |
| 81 |
contentType = contentType[:idx] |
| 82 |
} |
| 83 |
patchType := types.PatchType(contentType) |
| 84 |
|
| 85 |
// Ensure the patchType is one we support |
| 86 |
if !sets.NewString(patchTypes...).Has(contentType) { |
| 87 |
scope.err(negotiation.NewUnsupportedMediaTypeError(patchTypes), w, req) |
| 88 |
return |
| 89 |
} |
| 90 |
|
| 91 |
namespace, name, err := scope.Namer.Name(req) |
| 92 |
if err != nil { |
| 93 |
scope.err(err, w, req) |
| 94 |
return |
| 95 |
} |
| 96 |
|
| 97 |
// enforce a timeout of at most requestTimeoutUpperBound (34s) or less if the user-provided |
| 98 |
// timeout inside the parent context is lower than requestTimeoutUpperBound. |
| 99 |
ctx, cancel := context.WithTimeout(ctx, requestTimeoutUpperBound) |
| 100 |
defer cancel() |
| 101 |
|
| 102 |
ctx = request.WithNamespace(ctx, namespace) |
| 103 |
|
| 104 |
outputMediaType, _, err := negotiation.NegotiateOutputMediaType(req, scope.Serializer, scope) |
| 105 |
if err != nil { |
| 106 |
scope.err(err, w, req) |
| 107 |
return |
| 108 |
} |
| 109 |
|
| 110 |
patchBytes, err := limitedReadBodyWithRecordMetric(ctx, req, scope.MaxRequestBodyBytes, scope.Resource.GroupResource().String(), requestmetrics.Patch) |
| 111 |
if err != nil { |
| 112 |
span.AddEvent("limitedReadBody failed", attribute.Int("len", len(patchBytes)), attribute.String("err", err.Error())) |
| 113 |
scope.err(err, w, req) |
| 114 |
return |
| 115 |
} |
| 116 |
span.AddEvent("limitedReadBody succeeded", attribute.Int("len", len(patchBytes))) |
| 117 |
|
| 118 |
options := &metav1.PatchOptions{} |
| 119 |
if err := metainternalversionscheme.ParameterCodec.DecodeParameters(req.URL.Query(), scope.MetaGroupVersion, options); err != nil { |
| 120 |
err = errors.NewBadRequest(err.Error()) |
| 121 |
scope.err(err, w, req) |
| 122 |
return |
| 123 |
} |
| 124 |
if errs := validation.ValidatePatchOptions(options, patchType); len(errs) > 0 { |
| 125 |
err := errors.NewInvalid(schema.GroupKind{Group: metav1.GroupName, Kind: "PatchOptions"}, "", errs) |
| 126 |
scope.err(err, w, req) |
| 127 |
return |
| 128 |
} |
| 129 |
options.TypeMeta.SetGroupVersionKind(metav1.SchemeGroupVersion.WithKind("PatchOptions")) |
| 130 |
|
| 131 |
admit = admission.WithAudit(admit) |
| 132 |
|
| 133 |
audit.LogRequestPatch(req.Context(), patchBytes) |
| 134 |
span.AddEvent("Recorded the audit event") |
| 135 |
|
| 136 |
var baseContentType string |
| 137 |
switch patchType { |
| 138 |
case types.ApplyYAMLPatchType: |
| 139 |
baseContentType = runtime.ContentTypeYAML |
| 140 |
case types.ApplyCBORPatchType: |
| 141 |
if !utilfeature.DefaultFeatureGate.Enabled(features.CBORServingAndStorage) { |
| 142 |
// This request should have already been rejected by the |
| 143 |
// Content-Type allowlist check. Return 500 because assumptions are |
| 144 |
// already broken and the feature is not GA. |
| 145 |
utilruntime.HandleErrorWithContext(req.Context(), nil, "The patch content-type allowlist check should have made this unreachable.") |
| 146 |
scope.err(errors.NewInternalError(errors.NewInternalError(fmt.Errorf("unexpected patch type: %v", patchType))), w, req) |
| 147 |
return |
| 148 |
} |
| 149 |
|
| 150 |
baseContentType = runtime.ContentTypeCBOR |
| 151 |
default: |
| 152 |
baseContentType = runtime.ContentTypeJSON |
| 153 |
} |
| 154 |
|
| 155 |
s, ok := runtime.SerializerInfoForMediaType(scope.Serializer.SupportedMediaTypes(), baseContentType) |
| 156 |
if !ok { |
| 157 |
scope.err(fmt.Errorf("no serializer defined for %v", baseContentType), w, req) |
| 158 |
return |
| 159 |
} |
| 160 |
gv := scope.Kind.GroupVersion() |
| 161 |
|
| 162 |
validationDirective := fieldValidation(options.FieldValidation) |
| 163 |
decodeSerializer := s.Serializer |
| 164 |
if validationDirective == metav1.FieldValidationWarn || validationDirective == metav1.FieldValidationStrict { |
| 165 |
decodeSerializer = s.StrictSerializer |
| 166 |
} |
| 167 |
|
| 168 |
codec := runtime.NewCodec( |
| 169 |
scope.Serializer.EncoderForVersion(s.Serializer, gv), |
| 170 |
scope.Serializer.DecoderToVersion(decodeSerializer, scope.HubGroupVersion), |
| 171 |
) |
| 172 |
|
| 173 |
userInfo, _ := request.UserFrom(ctx) |
| 174 |
staticCreateAttributes := admission.NewAttributesRecord( |
| 175 |
nil, |
| 176 |
nil, |
| 177 |
scope.Kind, |
| 178 |
namespace, |
| 179 |
name, |
| 180 |
scope.Resource, |
| 181 |
scope.Subresource, |
| 182 |
admission.Create, |
| 183 |
patchToCreateOptions(options), |
| 184 |
dryrun.IsDryRun(options.DryRun), |
| 185 |
userInfo) |
| 186 |
staticUpdateAttributes := admission.NewAttributesRecord( |
| 187 |
nil, |
| 188 |
nil, |
| 189 |
scope.Kind, |
| 190 |
namespace, |
| 191 |
name, |
| 192 |
scope.Resource, |
| 193 |
scope.Subresource, |
| 194 |
admission.Update, |
| 195 |
patchToUpdateOptions(options), |
| 196 |
dryrun.IsDryRun(options.DryRun), |
| 197 |
userInfo, |
| 198 |
) |
| 199 |
|
| 200 |
admit = fieldmanager.NewManagedFieldsValidatingAdmissionController(admit) |
| 201 |
|
| 202 |
mutatingAdmission, _ := admit.(admission.MutationInterface) |
| 203 |
createAuthorizerAttributes := authorizer.AttributesRecord{ |
| 204 |
User: userInfo, |
| 205 |
ResourceRequest: true, |
| 206 |
Path: req.URL.Path, |
| 207 |
Verb: "create", |
| 208 |
APIGroup: scope.Resource.Group, |
| 209 |
APIVersion: scope.Resource.Version, |
| 210 |
Resource: scope.Resource.Resource, |
| 211 |
Subresource: scope.Subresource, |
| 212 |
Namespace: namespace, |
| 213 |
Name: name, |
| 214 |
} |
| 215 |
|
| 216 |
p := patcher{ |
| 217 |
namer: scope.Namer, |
| 218 |
creater: scope.Creater, |
| 219 |
defaulter: scope.Defaulter, |
| 220 |
typer: scope.Typer, |
| 221 |
unsafeConvertor: scope.UnsafeConvertor, |
| 222 |
kind: scope.Kind, |
| 223 |
resource: scope.Resource, |
| 224 |
subresource: scope.Subresource, |
| 225 |
dryRun: dryrun.IsDryRun(options.DryRun), |
| 226 |
validationDirective: validationDirective, |
| 227 |
|
| 228 |
objectInterfaces: scope, |
| 229 |
|
| 230 |
hubGroupVersion: scope.HubGroupVersion, |
| 231 |
|
| 232 |
createValidation: withAuthorization(rest.AdmissionToValidateObjectFunc(admit, staticCreateAttributes, scope), scope.Authorizer, createAuthorizerAttributes), |
| 233 |
updateValidation: rest.AdmissionToValidateObjectUpdateFunc(admit, staticUpdateAttributes, scope), |
| 234 |
admissionCheck: mutatingAdmission, |
| 235 |
|
| 236 |
codec: codec, |
| 237 |
|
| 238 |
options: options, |
| 239 |
|
| 240 |
restPatcher: r, |
| 241 |
name: name, |
| 242 |
patchType: patchType, |
| 243 |
patchBytes: patchBytes, |
| 244 |
userAgent: req.UserAgent(), |
| 245 |
} |
| 246 |
|
| 247 |
result, wasCreated, err := p.patchResource(ctx, scope) |
| 248 |
if err != nil { |
| 249 |
scope.err(err, w, req) |
| 250 |
return |
| 251 |
} |
| 252 |
span.AddEvent("Object stored in database") |
| 253 |
|
| 254 |
status := http.StatusOK |
| 255 |
if wasCreated { |
| 256 |
status = http.StatusCreated |
| 257 |
} |
| 258 |
|
| 259 |
span.AddEvent("About to write a response") |
| 260 |
defer span.AddEvent("Writing http response done") |
| 261 |
transformResponseObject(ctx, scope, req, w, status, outputMediaType, result) |
| 262 |
} |
| 263 |
} |
| 264 |
|
| 265 |
type mutateObjectUpdateFunc func(ctx context.Context, obj, old runtime.Object) error |
| 266 |
|
| 267 |
// patcher breaks the process of patch application and retries into smaller |
| 268 |
// pieces of functionality. |
| 269 |
// TODO: Use builder pattern to construct this object? |
| 270 |
// TODO: As part of that effort, some aspects of PatchResource above could be |
| 271 |
// moved into this type. |
| 272 |
type patcher struct { |
| 273 |
// Pieces of RequestScope |
| 274 |
namer ScopeNamer |
| 275 |
creater runtime.ObjectCreater |
| 276 |
defaulter runtime.ObjectDefaulter |
| 277 |
typer runtime.ObjectTyper |
| 278 |
unsafeConvertor runtime.ObjectConvertor |
| 279 |
resource schema.GroupVersionResource |
| 280 |
kind schema.GroupVersionKind |
| 281 |
subresource string |
| 282 |
dryRun bool |
| 283 |
validationDirective string |
| 284 |
|
| 285 |
objectInterfaces admission.ObjectInterfaces |
| 286 |
|
| 287 |
hubGroupVersion schema.GroupVersion |
| 288 |
|
| 289 |
// Validation functions |
| 290 |
createValidation rest.ValidateObjectFunc |
| 291 |
updateValidation rest.ValidateObjectUpdateFunc |
| 292 |
admissionCheck admission.MutationInterface |
| 293 |
|
| 294 |
codec runtime.Codec |
| 295 |
|
| 296 |
options *metav1.PatchOptions |
| 297 |
|
| 298 |
// Operation information |
| 299 |
restPatcher rest.Patcher |
| 300 |
name string |
| 301 |
patchType types.PatchType |
| 302 |
patchBytes []byte |
| 303 |
userAgent string |
| 304 |
|
| 305 |
// Set at invocation-time (by applyPatch) and immutable thereafter |
| 306 |
namespace string |
| 307 |
updatedObjectInfo rest.UpdatedObjectInfo |
| 308 |
mechanism patchMechanism |
| 309 |
forceAllowCreate bool |
| 310 |
} |
| 311 |
|
| 312 |
type patchMechanism interface { |
| 313 |
applyPatchToCurrentObject(requextContext context.Context, currentObject runtime.Object) (runtime.Object, error) |
| 314 |
createNewObject(requestContext context.Context) (runtime.Object, error) |
| 315 |
} |
| 316 |
|
| 317 |
type jsonPatcher struct { |
| 318 |
*patcher |
| 319 |
|
| 320 |
fieldManager *managedfields.FieldManager |
| 321 |
} |
| 322 |
|
| 323 |
func (p *jsonPatcher) applyPatchToCurrentObject(requestContext context.Context, currentObject runtime.Object) (runtime.Object, error) { |
| 324 |
// Encode will convert & return a versioned object in JSON. |
| 325 |
currentObjJS, err := runtime.Encode(p.codec, currentObject) |
| 326 |
if err != nil { |
| 327 |
return nil, err |
| 328 |
} |
| 329 |
|
| 330 |
// Apply the patch. |
| 331 |
patchedObjJS, appliedStrictErrs, err := p.applyJSPatch(currentObjJS) |
| 332 |
if err != nil { |
| 333 |
return nil, err |
| 334 |
} |
| 335 |
|
| 336 |
// Construct the resulting typed, unversioned object. |
| 337 |
objToUpdate := p.restPatcher.New() |
| 338 |
if err := runtime.DecodeInto(p.codec, patchedObjJS, objToUpdate); err != nil { |
| 339 |
strictError, isStrictError := runtime.AsStrictDecodingError(err) |
| 340 |
switch { |
| 341 |
case !isStrictError: |
| 342 |
// disregard any appliedStrictErrs, because it's an incomplete |
| 343 |
// list of strict errors given that we don't know what fields were |
| 344 |
// unknown because DecodeInto failed. Non-strict errors trump in this case. |
| 345 |
return nil, errors.NewInvalid(schema.GroupKind{}, "", field.ErrorList{ |
| 346 |
field.Invalid(field.NewPath("patch"), string(patchedObjJS), err.Error()), |
| 347 |
}) |
| 348 |
case p.validationDirective == metav1.FieldValidationWarn: |
| 349 |
addStrictDecodingWarnings(requestContext, append(appliedStrictErrs, strictError.Errors()...)) |
| 350 |
default: |
| 351 |
strictDecodingError := runtime.NewStrictDecodingError(append(appliedStrictErrs, strictError.Errors()...)) |
| 352 |
return nil, errors.NewInvalid(schema.GroupKind{}, "", field.ErrorList{ |
| 353 |
field.Invalid(field.NewPath("patch"), string(patchedObjJS), strictDecodingError.Error()), |
| 354 |
}) |
| 355 |
} |
| 356 |
} else if len(appliedStrictErrs) > 0 { |
| 357 |
switch { |
| 358 |
case p.validationDirective == metav1.FieldValidationWarn: |
| 359 |
addStrictDecodingWarnings(requestContext, appliedStrictErrs) |
| 360 |
default: |
| 361 |
return nil, errors.NewInvalid(schema.GroupKind{}, "", field.ErrorList{ |
| 362 |
field.Invalid(field.NewPath("patch"), string(patchedObjJS), runtime.NewStrictDecodingError(appliedStrictErrs).Error()), |
| 363 |
}) |
| 364 |
} |
| 365 |
} |
| 366 |
|
| 367 |
if p.options == nil { |
| 368 |
// Provide a more informative error for the crash that would |
| 369 |
// happen on the next line |
| 370 |
panic("PatchOptions required but not provided") |
| 371 |
} |
| 372 |
objToUpdate = p.fieldManager.UpdateNoErrors(currentObject, objToUpdate, managerOrUserAgent(p.options.FieldManager, p.userAgent)) |
| 373 |
return objToUpdate, nil |
| 374 |
} |
| 375 |
|
| 376 |
func (p *jsonPatcher) createNewObject(_ context.Context) (runtime.Object, error) { |
| 377 |
return nil, errors.NewNotFound(p.resource.GroupResource(), p.name) |
| 378 |
} |
| 379 |
|
| 380 |
type jsonPatchOp struct { |
| 381 |
Op string `json:"op"` |
| 382 |
Path string `json:"path"` |
| 383 |
From string `json:"from"` |
| 384 |
Value interface{} `json:"value"` |
| 385 |
} |
| 386 |
|
| 387 |
// applyJSPatch applies the patch. Input and output objects must both have |
| 388 |
// the external version, since that is what the patch must have been constructed against. |
| 389 |
func (p *jsonPatcher) applyJSPatch(versionedJS []byte) (patchedJS []byte, strictErrors []error, retErr error) { |
| 390 |
switch p.patchType { |
| 391 |
case types.JSONPatchType: |
| 392 |
if p.validationDirective == metav1.FieldValidationStrict || p.validationDirective == metav1.FieldValidationWarn { |
| 393 |
var v []jsonPatchOp |
| 394 |
var err error |
| 395 |
if strictErrors, err = kjson.UnmarshalStrict(p.patchBytes, &v); err != nil { |
| 396 |
return nil, nil, errors.NewBadRequest(fmt.Sprintf("error decoding patch: %v", err)) |
| 397 |
} |
| 398 |
for i, e := range strictErrors { |
| 399 |
strictErrors[i] = fmt.Errorf("json patch %v", e) |
| 400 |
} |
| 401 |
} |
| 402 |
|
| 403 |
patchObj, err := jsonpatch.DecodePatch(p.patchBytes) |
| 404 |
if err != nil { |
| 405 |
return nil, nil, errors.NewBadRequest(err.Error()) |
| 406 |
} |
| 407 |
if len(patchObj) > maxJSONPatchOperations { |
| 408 |
return nil, nil, errors.NewRequestEntityTooLargeError( |
| 409 |
fmt.Sprintf("The allowed maximum operations in a JSON patch is %d, got %d", |
| 410 |
maxJSONPatchOperations, len(patchObj))) |
| 411 |
} |
| 412 |
patchedJS, err := patchObj.Apply(versionedJS) |
| 413 |
if err != nil { |
| 414 |
return nil, nil, errors.NewGenericServerResponse(http.StatusUnprocessableEntity, "", schema.GroupResource{}, "", err.Error(), 0, false) |
| 415 |
} |
| 416 |
return patchedJS, strictErrors, nil |
| 417 |
case types.MergePatchType: |
| 418 |
if p.validationDirective == metav1.FieldValidationStrict || p.validationDirective == metav1.FieldValidationWarn { |
| 419 |
v := map[string]interface{}{} |
| 420 |
var err error |
| 421 |
strictErrors, err = kjson.UnmarshalStrict(p.patchBytes, &v) |
| 422 |
if err != nil { |
| 423 |
return nil, nil, errors.NewBadRequest(fmt.Sprintf("error decoding patch: %v", err)) |
| 424 |
} |
| 425 |
} |
| 426 |
|
| 427 |
patchedJS, retErr = jsonpatch.MergePatch(versionedJS, p.patchBytes) |
| 428 |
if retErr == jsonpatch.ErrBadJSONPatch { |
| 429 |
return nil, nil, errors.NewBadRequest(retErr.Error()) |
| 430 |
} |
| 431 |
return patchedJS, strictErrors, retErr |
| 432 |
default: |
| 433 |
// only here as a safety net - go-restful filters content-type |
| 434 |
return nil, nil, fmt.Errorf("unknown Content-Type header for patch: %v", p.patchType) |
| 435 |
} |
| 436 |
} |
| 437 |
|
| 438 |
type smpPatcher struct { |
| 439 |
*patcher |
| 440 |
|
| 441 |
// Schema |
| 442 |
schemaReferenceObj runtime.Object |
| 443 |
fieldManager *managedfields.FieldManager |
| 444 |
} |
| 445 |
|
| 446 |
func (p *smpPatcher) applyPatchToCurrentObject(requestContext context.Context, currentObject runtime.Object) (runtime.Object, error) { |
| 447 |
// Since the patch is applied on versioned objects, we need to convert the |
| 448 |
// current object to versioned representation first. |
| 449 |
currentVersionedObject, err := p.unsafeConvertor.ConvertToVersion(currentObject, p.kind.GroupVersion()) |
| 450 |
if err != nil { |
| 451 |
return nil, err |
| 452 |
} |
| 453 |
versionedObjToUpdate, err := p.creater.New(p.kind) |
| 454 |
if err != nil { |
| 455 |
return nil, err |
| 456 |
} |
| 457 |
if err := strategicPatchObject(requestContext, p.defaulter, currentVersionedObject, p.patchBytes, versionedObjToUpdate, p.schemaReferenceObj, p.validationDirective); err != nil { |
| 458 |
return nil, err |
| 459 |
} |
| 460 |
// Convert the object back to the hub version |
| 461 |
newObj, err := p.unsafeConvertor.ConvertToVersion(versionedObjToUpdate, p.hubGroupVersion) |
| 462 |
if err != nil { |
| 463 |
return nil, err |
| 464 |
} |
| 465 |
|
| 466 |
newObj = p.fieldManager.UpdateNoErrors(currentObject, newObj, managerOrUserAgent(p.options.FieldManager, p.userAgent)) |
| 467 |
return newObj, nil |
| 468 |
} |
| 469 |
|
| 470 |
func (p *smpPatcher) createNewObject(_ context.Context) (runtime.Object, error) { |
| 471 |
return nil, errors.NewNotFound(p.resource.GroupResource(), p.name) |
| 472 |
} |
| 473 |
|
| 474 |
func newApplyPatcher(p *patcher, fieldManager *managedfields.FieldManager, unmarshalFn, unmarshalStrictFn func([]byte, interface{}) error) *applyPatcher { |
| 475 |
return &applyPatcher{ |
| 476 |
fieldManager: fieldManager, |
| 477 |
patch: p.patchBytes, |
| 478 |
options: p.options, |
| 479 |
creater: p.creater, |
| 480 |
kind: p.kind, |
| 481 |
userAgent: p.userAgent, |
| 482 |
validationDirective: p.validationDirective, |
| 483 |
unmarshalFn: unmarshalFn, |
| 484 |
unmarshalStrictFn: unmarshalStrictFn, |
| 485 |
} |
| 486 |
} |
| 487 |
|
| 488 |
type applyPatcher struct { |
| 489 |
patch []byte |
| 490 |
options *metav1.PatchOptions |
| 491 |
creater runtime.ObjectCreater |
| 492 |
kind schema.GroupVersionKind |
| 493 |
fieldManager *managedfields.FieldManager |
| 494 |
userAgent string |
| 495 |
validationDirective string |
| 496 |
unmarshalFn func(data []byte, v interface{}) error |
| 497 |
unmarshalStrictFn func(data []byte, v interface{}) error |
| 498 |
} |
| 499 |
|
| 500 |
func (p *applyPatcher) applyPatchToCurrentObject(requestContext context.Context, obj runtime.Object) (runtime.Object, error) { |
| 501 |
force := false |
| 502 |
if p.options.Force != nil { |
| 503 |
force = *p.options.Force |
| 504 |
} |
| 505 |
if p.fieldManager == nil { |
| 506 |
panic("FieldManager must be installed to run apply") |
| 507 |
} |
| 508 |
|
| 509 |
patchObj := &unstructured.Unstructured{Object: map[string]interface{}{}} |
| 510 |
if err := p.unmarshalFn(p.patch, &patchObj.Object); err != nil { |
| 511 |
return nil, errors.NewBadRequest(fmt.Sprintf("error decoding YAML: %v", err)) |
| 512 |
} |
| 513 |
|
| 514 |
obj, err := p.fieldManager.Apply(obj, patchObj, p.options.FieldManager, force) |
| 515 |
if err != nil { |
| 516 |
return obj, err |
| 517 |
} |
| 518 |
|
| 519 |
// TODO: spawn something to track deciding whether a fieldValidation=Strict |
| 520 |
// fatal error should return before an error from the apply operation |
| 521 |
if p.validationDirective == metav1.FieldValidationStrict || p.validationDirective == metav1.FieldValidationWarn { |
| 522 |
if err := p.unmarshalStrictFn(p.patch, &map[string]interface{}{}); err != nil { |
| 523 |
if p.validationDirective == metav1.FieldValidationStrict { |
| 524 |
return nil, errors.NewBadRequest(fmt.Sprintf("error strict decoding YAML: %v", err)) |
| 525 |
} |
| 526 |
addStrictDecodingWarnings(requestContext, []error{err}) |
| 527 |
} |
| 528 |
} |
| 529 |
return obj, nil |
| 530 |
} |
| 531 |
|
| 532 |
func (p *applyPatcher) createNewObject(requestContext context.Context) (runtime.Object, error) { |
| 533 |
obj, err := p.creater.New(p.kind) |
| 534 |
if err != nil { |
| 535 |
return nil, fmt.Errorf("failed to create new object: %v", err) |
| 536 |
} |
| 537 |
return p.applyPatchToCurrentObject(requestContext, obj) |
| 538 |
} |
| 539 |
|
| 540 |
// strategicPatchObject applies a strategic merge patch of `patchBytes` to |
| 541 |
// `originalObject` and stores the result in `objToUpdate`. |
| 542 |
// It additionally returns the map[string]interface{} representation of the |
| 543 |
// `originalObject` and `patchBytes`. |
| 544 |
// NOTE: Both `originalObject` and `objToUpdate` are supposed to be versioned. |
| 545 |
func strategicPatchObject( |
| 546 |
requestContext context.Context, |
| 547 |
defaulter runtime.ObjectDefaulter, |
| 548 |
originalObject runtime.Object, |
| 549 |
patchBytes []byte, |
| 550 |
objToUpdate runtime.Object, |
| 551 |
schemaReferenceObj runtime.Object, |
| 552 |
validationDirective string, |
| 553 |
) error { |
| 554 |
originalObjMap, err := runtime.DefaultUnstructuredConverter.ToUnstructured(originalObject) |
| 555 |
if err != nil { |
| 556 |
return err |
| 557 |
} |
| 558 |
|
| 559 |
patchMap := make(map[string]interface{}) |
| 560 |
var strictErrs []error |
| 561 |
if validationDirective == metav1.FieldValidationWarn || validationDirective == metav1.FieldValidationStrict { |
| 562 |
strictErrs, err = kjson.UnmarshalStrict(patchBytes, &patchMap) |
| 563 |
if err != nil { |
| 564 |
return errors.NewBadRequest(err.Error()) |
| 565 |
} |
| 566 |
} else { |
| 567 |
if err = kjson.UnmarshalCaseSensitivePreserveInts(patchBytes, &patchMap); err != nil { |
| 568 |
return errors.NewBadRequest(err.Error()) |
| 569 |
} |
| 570 |
} |
| 571 |
|
| 572 |
if err := applyPatchToObject(requestContext, defaulter, originalObjMap, patchMap, objToUpdate, schemaReferenceObj, strictErrs, validationDirective); err != nil { |
| 573 |
return err |
| 574 |
} |
| 575 |
return nil |
| 576 |
} |
| 577 |
|
| 578 |
// applyPatch is called every time GuaranteedUpdate asks for the updated object, |
| 579 |
// and is given the currently persisted object as input. |
| 580 |
// TODO: rename this function because the name implies it is related to applyPatcher |
| 581 |
func (p *patcher) applyPatch(ctx context.Context, _, currentObject runtime.Object) (objToUpdate runtime.Object, patchErr error) { |
| 582 |
// Make sure we actually have a persisted currentObject |
| 583 |
tracing.SpanFromContext(ctx).AddEvent("About to apply patch") |
| 584 |
currentObjectHasUID, err := hasUID(currentObject) |
| 585 |
if err != nil { |
| 586 |
return nil, err |
| 587 |
} else if !currentObjectHasUID { |
| 588 |
objToUpdate, patchErr = p.mechanism.createNewObject(ctx) |
| 589 |
} else { |
| 590 |
objToUpdate, patchErr = p.mechanism.applyPatchToCurrentObject(ctx, currentObject) |
| 591 |
} |
| 592 |
|
| 593 |
if patchErr != nil { |
| 594 |
return nil, patchErr |
| 595 |
} |
| 596 |
|
| 597 |
objToUpdateHasUID, err := hasUID(objToUpdate) |
| 598 |
if err != nil { |
| 599 |
return nil, err |
| 600 |
} |
| 601 |
if objToUpdateHasUID && !currentObjectHasUID { |
| 602 |
accessor, err := meta.Accessor(objToUpdate) |
| 603 |
if err != nil { |
| 604 |
return nil, err |
| 605 |
} |
| 606 |
return nil, errors.NewConflict(p.resource.GroupResource(), p.name, fmt.Errorf("uid mismatch: the provided object specified uid %s, and no existing object was found", accessor.GetUID())) |
| 607 |
} |
| 608 |
|
| 609 |
// if this object supports namespace info |
| 610 |
if objectMeta, err := meta.Accessor(objToUpdate); err == nil { |
| 611 |
// ensure namespace on the object is correct, or error if a conflicting namespace was set in the object |
| 612 |
if err := rest.EnsureObjectNamespaceMatchesRequestNamespace(rest.ExpectedNamespaceForResource(p.namespace, p.resource), objectMeta); err != nil { |
| 613 |
return nil, err |
| 614 |
} |
| 615 |
} |
| 616 |
|
| 617 |
if err := checkName(objToUpdate, p.name, p.namespace, p.namer); err != nil { |
| 618 |
return nil, err |
| 619 |
} |
| 620 |
return objToUpdate, nil |
| 621 |
} |
| 622 |
|
| 623 |
func (p *patcher) admissionAttributes(ctx context.Context, updatedObject runtime.Object, currentObject runtime.Object, operation admission.Operation, operationOptions runtime.Object) admission.Attributes { |
| 624 |
userInfo, _ := request.UserFrom(ctx) |
| 625 |
return admission.NewAttributesRecord(updatedObject, currentObject, p.kind, p.namespace, p.name, p.resource, p.subresource, operation, operationOptions, p.dryRun, userInfo) |
| 626 |
} |
| 627 |
|
| 628 |
// applyAdmission is called every time GuaranteedUpdate asks for the updated object, |
| 629 |
// and is given the currently persisted object and the patched object as input. |
| 630 |
// TODO: rename this function because the name implies it is related to applyPatcher |
| 631 |
func (p *patcher) applyAdmission(ctx context.Context, patchedObject runtime.Object, currentObject runtime.Object) (runtime.Object, error) { |
| 632 |
tracing.SpanFromContext(ctx).AddEvent("About to check admission control") |
| 633 |
var operation admission.Operation |
| 634 |
var options runtime.Object |
| 635 |
if hasUID, err := hasUID(currentObject); err != nil { |
| 636 |
return nil, err |
| 637 |
} else if !hasUID { |
| 638 |
operation = admission.Create |
| 639 |
currentObject = nil |
| 640 |
options = patchToCreateOptions(p.options) |
| 641 |
} else { |
| 642 |
operation = admission.Update |
| 643 |
options = patchToUpdateOptions(p.options) |
| 644 |
} |
| 645 |
if p.admissionCheck != nil && p.admissionCheck.Handles(operation) { |
| 646 |
attributes := p.admissionAttributes(ctx, patchedObject, currentObject, operation, options) |
| 647 |
return patchedObject, p.admissionCheck.Admit(ctx, attributes, p.objectInterfaces) |
| 648 |
} |
| 649 |
return patchedObject, nil |
| 650 |
} |
| 651 |
|
| 652 |
// patchResource divides PatchResource for easier unit testing |
| 653 |
func (p *patcher) patchResource(ctx context.Context, scope *RequestScope) (runtime.Object, bool, error) { |
| 654 |
p.namespace = request.NamespaceValue(ctx) |
| 655 |
switch p.patchType { |
| 656 |
case types.JSONPatchType, types.MergePatchType: |
| 657 |
p.mechanism = &jsonPatcher{ |
| 658 |
patcher: p, |
| 659 |
fieldManager: scope.FieldManager, |
| 660 |
} |
| 661 |
case types.StrategicMergePatchType: |
| 662 |
schemaReferenceObj, err := p.unsafeConvertor.ConvertToVersion(p.restPatcher.New(), p.kind.GroupVersion()) |
| 663 |
if err != nil { |
| 664 |
return nil, false, err |
| 665 |
} |
| 666 |
p.mechanism = &smpPatcher{ |
| 667 |
patcher: p, |
| 668 |
schemaReferenceObj: schemaReferenceObj, |
| 669 |
fieldManager: scope.FieldManager, |
| 670 |
} |
| 671 |
// this case is unreachable if ServerSideApply is not enabled because we will have already rejected the content type |
| 672 |
case types.ApplyYAMLPatchType: |
| 673 |
p.mechanism = newApplyPatcher(p, scope.FieldManager, yaml.Unmarshal, yaml.UnmarshalStrict) |
| 674 |
p.forceAllowCreate = true |
| 675 |
case types.ApplyCBORPatchType: |
| 676 |
if !utilfeature.DefaultFeatureGate.Enabled(features.CBORServingAndStorage) { |
| 677 |
utilruntime.HandleErrorWithContext(context.TODO(), nil, "CBOR apply requests should be rejected before reaching this point unless the feature gate is enabled.") |
| 678 |
return nil, false, fmt.Errorf("%v: unimplemented patch type", p.patchType) |
| 679 |
} |
| 680 |
|
| 681 |
// The strict and non-strict funcs are the same here because any CBOR map with |
| 682 |
// duplicate keys is invalid and always rejected outright regardless of strictness |
| 683 |
// mode, and unknown field errors can't occur in practice because the type of the |
| 684 |
// destination value for unmarshaling an apply configuration is always |
| 685 |
// "unstructured". |
| 686 |
p.mechanism = newApplyPatcher(p, scope.FieldManager, cbor.Unmarshal, cbor.Unmarshal) |
| 687 |
p.forceAllowCreate = true |
| 688 |
default: |
| 689 |
return nil, false, fmt.Errorf("%v: unimplemented patch type", p.patchType) |
| 690 |
} |
| 691 |
dedupOwnerReferencesTransformer := func(_ context.Context, obj, _ runtime.Object) (runtime.Object, error) { |
| 692 |
// Dedup owner references after mutating admission happens |
| 693 |
dedupOwnerReferencesAndAddWarning(obj, ctx, true) |
| 694 |
return obj, nil |
| 695 |
} |
| 696 |
|
| 697 |
transformers := []rest.TransformFunc{p.applyPatch, p.applyAdmission, dedupOwnerReferencesTransformer} |
| 698 |
|
| 699 |
wasCreated := false |
| 700 |
p.updatedObjectInfo = rest.DefaultUpdatedObjectInfo(nil, transformers...) |
| 701 |
requestFunc := func() (runtime.Object, error) { |
| 702 |
// Pass in UpdateOptions to override UpdateStrategy.AllowUpdateOnCreate |
| 703 |
options := patchToUpdateOptions(p.options) |
| 704 |
updateObject, created, updateErr := p.restPatcher.Update(ctx, p.name, p.updatedObjectInfo, p.createValidation, p.updateValidation, p.forceAllowCreate, options) |
| 705 |
wasCreated = created |
| 706 |
return updateObject, updateErr |
| 707 |
} |
| 708 |
result, err := finisher.FinishRequest(ctx, func() (runtime.Object, error) { |
| 709 |
|
| 710 |
result, err := requestFunc() |
| 711 |
// If the object wasn't committed to storage because it's serialized size was too large, |
| 712 |
// it is safe to remove managedFields (which can be large) and try again. |
| 713 |
if isTooLargeError(err) && p.patchType != types.ApplyYAMLPatchType && p.patchType != types.ApplyCBORPatchType { |
| 714 |
if _, accessorErr := meta.Accessor(p.restPatcher.New()); accessorErr == nil { |
| 715 |
p.updatedObjectInfo = rest.DefaultUpdatedObjectInfo(nil, |
| 716 |
p.applyPatch, |
| 717 |
p.applyAdmission, |
| 718 |
dedupOwnerReferencesTransformer, |
| 719 |
func(_ context.Context, obj, _ runtime.Object) (runtime.Object, error) { |
| 720 |
accessor, _ := meta.Accessor(obj) |
| 721 |
accessor.SetManagedFields(nil) |
| 722 |
return obj, nil |
| 723 |
}) |
| 724 |
result, err = requestFunc() |
| 725 |
} |
| 726 |
} |
| 727 |
return result, err |
| 728 |
}) |
| 729 |
return result, wasCreated, err |
| 730 |
} |
| 731 |
|
| 732 |
// applyPatchToObject applies a strategic merge patch of <patchMap> to |
| 733 |
// <originalMap> and stores the result in <objToUpdate>. |
| 734 |
// NOTE: <objToUpdate> must be a versioned object. |
| 735 |
func applyPatchToObject( |
| 736 |
requestContext context.Context, |
| 737 |
defaulter runtime.ObjectDefaulter, |
| 738 |
originalMap map[string]interface{}, |
| 739 |
patchMap map[string]interface{}, |
| 740 |
objToUpdate runtime.Object, |
| 741 |
schemaReferenceObj runtime.Object, |
| 742 |
strictErrs []error, |
| 743 |
validationDirective string, |
| 744 |
) error { |
| 745 |
patchedObjMap, err := strategicpatch.StrategicMergeMapPatch(originalMap, patchMap, schemaReferenceObj) |
| 746 |
if err != nil { |
| 747 |
return interpretStrategicMergePatchError(err) |
| 748 |
} |
| 749 |
|
| 750 |
// Rather than serialize the patched map to JSON, then decode it to an object, we go directly from a map to an object |
| 751 |
converter := runtime.DefaultUnstructuredConverter |
| 752 |
returnUnknownFields := validationDirective == metav1.FieldValidationWarn || validationDirective == metav1.FieldValidationStrict |
| 753 |
if err := converter.FromUnstructuredWithValidation(patchedObjMap, objToUpdate, returnUnknownFields); err != nil { |
| 754 |
strictError, isStrictError := runtime.AsStrictDecodingError(err) |
| 755 |
switch { |
| 756 |
case !isStrictError: |
| 757 |
// disregard any sttrictErrs, because it's an incomplete |
| 758 |
// list of strict errors given that we don't know what fields were |
| 759 |
// unknown because StrategicMergeMapPatch failed. |
| 760 |
// Non-strict errors trump in this case. |
| 761 |
return errors.NewInvalid(schema.GroupKind{}, "", field.ErrorList{ |
| 762 |
field.Invalid(field.NewPath("patch"), fmt.Sprintf("%+v", patchMap), err.Error()), |
| 763 |
}) |
| 764 |
case validationDirective == metav1.FieldValidationWarn: |
| 765 |
addStrictDecodingWarnings(requestContext, append(strictErrs, strictError.Errors()...)) |
| 766 |
default: |
| 767 |
strictDecodingError := runtime.NewStrictDecodingError(append(strictErrs, strictError.Errors()...)) |
| 768 |
return errors.NewInvalid(schema.GroupKind{}, "", field.ErrorList{ |
| 769 |
field.Invalid(field.NewPath("patch"), fmt.Sprintf("%+v", patchMap), strictDecodingError.Error()), |
| 770 |
}) |
| 771 |
} |
| 772 |
} else if len(strictErrs) > 0 { |
| 773 |
switch { |
| 774 |
case validationDirective == metav1.FieldValidationWarn: |
| 775 |
addStrictDecodingWarnings(requestContext, strictErrs) |
| 776 |
default: |
| 777 |
return errors.NewInvalid(schema.GroupKind{}, "", field.ErrorList{ |
| 778 |
field.Invalid(field.NewPath("patch"), fmt.Sprintf("%+v", patchMap), runtime.NewStrictDecodingError(strictErrs).Error()), |
| 779 |
}) |
| 780 |
} |
| 781 |
} |
| 782 |
|
| 783 |
// Decoding from JSON to a versioned object would apply defaults, so we do the same here |
| 784 |
defaulter.Default(objToUpdate) |
| 785 |
|
| 786 |
return nil |
| 787 |
} |
| 788 |
|
| 789 |
// interpretStrategicMergePatchError interprets the error type and returns an error with appropriate HTTP code. |
| 790 |
func interpretStrategicMergePatchError(err error) error { |
| 791 |
switch err { |
| 792 |
case mergepatch.ErrBadJSONDoc, mergepatch.ErrBadPatchFormatForPrimitiveList, mergepatch.ErrBadPatchFormatForRetainKeys, mergepatch.ErrBadPatchFormatForSetElementOrderList, mergepatch.ErrUnsupportedStrategicMergePatchFormat: |
| 793 |
return errors.NewBadRequest(err.Error()) |
| 794 |
case mergepatch.ErrNoListOfLists, mergepatch.ErrPatchContentNotMatchRetainKeys: |
| 795 |
return errors.NewGenericServerResponse(http.StatusUnprocessableEntity, "", schema.GroupResource{}, "", err.Error(), 0, false) |
| 796 |
default: |
| 797 |
return err |
| 798 |
} |
| 799 |
} |
| 800 |
|
| 801 |
// patchToUpdateOptions creates an UpdateOptions with the same field values as the provided PatchOptions. |
| 802 |
func patchToUpdateOptions(po *metav1.PatchOptions) *metav1.UpdateOptions { |
| 803 |
if po == nil { |
| 804 |
return nil |
| 805 |
} |
| 806 |
uo := &metav1.UpdateOptions{ |
| 807 |
DryRun: po.DryRun, |
| 808 |
FieldManager: po.FieldManager, |
| 809 |
FieldValidation: po.FieldValidation, |
| 810 |
} |
| 811 |
uo.TypeMeta.SetGroupVersionKind(metav1.SchemeGroupVersion.WithKind("UpdateOptions")) |
| 812 |
return uo |
| 813 |
} |
| 814 |
|
| 815 |
// patchToCreateOptions creates an CreateOptions with the same field values as the provided PatchOptions. |
| 816 |
func patchToCreateOptions(po *metav1.PatchOptions) *metav1.CreateOptions { |
| 817 |
if po == nil { |
| 818 |
return nil |
| 819 |
} |
| 820 |
co := &metav1.CreateOptions{ |
| 821 |
DryRun: po.DryRun, |
| 822 |
FieldManager: po.FieldManager, |
| 823 |
FieldValidation: po.FieldValidation, |
| 824 |
} |
| 825 |
co.TypeMeta.SetGroupVersionKind(metav1.SchemeGroupVersion.WithKind("CreateOptions")) |
| 826 |
return co |
| 827 |
} |