knative.dev/pkg@v0.0.0-20260602142205-ac97e43f6622/apis/duck/v1/podspec_validation.go (about)

     1  /*
     2  Copyright 2021 The Knative 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 v1
    18  
    19  import (
    20  	"context"
    21  
    22  	"knative.dev/pkg/apis"
    23  )
    24  
    25  // PodSpecValidator is a callback to validate a PodSpecable.
    26  type PodSpecValidator func(context.Context, *WithPod) *apis.FieldError
    27  
    28  // Validate implements apis.Validatable
    29  func (wp *WithPod) Validate(ctx context.Context) *apis.FieldError {
    30  	if psv := GetPodSpecValidator(ctx); psv != nil {
    31  		return psv(ctx, wp)
    32  	}
    33  	return nil
    34  }
    35  
    36  // psvKey is used for associating a PodSpecValidator with a context.Context
    37  type psvKey struct{}
    38  
    39  func WithPodSpecValidator(ctx context.Context, psv PodSpecValidator) context.Context {
    40  	return context.WithValue(ctx, psvKey{}, psv)
    41  }
    42  
    43  // GetPodSpecValidator extracts the PodSpecValidator from the context.
    44  func GetPodSpecValidator(ctx context.Context) PodSpecValidator {
    45  	untyped := ctx.Value(psvKey{})
    46  	if untyped == nil {
    47  		return nil
    48  	}
    49  	return untyped.(PodSpecValidator)
    50  }
    51  
    52  // PodValidator is a callback to validate Pods.
    53  type PodValidator func(context.Context, *Pod) *apis.FieldError
    54  
    55  // Validate implements apis.Validatable
    56  func (p *Pod) Validate(ctx context.Context) *apis.FieldError {
    57  	if pv := GetPodValidator(ctx); pv != nil {
    58  		return pv(ctx, p)
    59  	}
    60  	return nil
    61  }
    62  
    63  // pvKey is used for associating a PodValidator with a context.Context
    64  type pvKey struct{}
    65  
    66  func WithPodValidator(ctx context.Context, pv PodValidator) context.Context {
    67  	return context.WithValue(ctx, pvKey{}, pv)
    68  }
    69  
    70  // GetPodValidator extracts the PodValidator from the context.
    71  func GetPodValidator(ctx context.Context) PodValidator {
    72  	untyped := ctx.Value(pvKey{})
    73  	if untyped == nil {
    74  		return nil
    75  	}
    76  	return untyped.(PodValidator)
    77  }