objectmeta.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /*
  2. Copyright 2014 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. // Adapted from k8s.io/apimachinery/pkg/api/validation:
  14. // https://github.com/kubernetes/apimachinery/blob/7687996c715ee7d5c8cf1e3215e607eb065a4221/pkg/api/validation/objectmeta.go
  15. package k8s
  16. import (
  17. "fmt"
  18. "strings"
  19. "github.com/container-orchestrated-devices/container-device-interface/internal/multierror"
  20. )
  21. // TotalAnnotationSizeLimitB defines the maximum size of all annotations in characters.
  22. const TotalAnnotationSizeLimitB int = 256 * (1 << 10) // 256 kB
  23. // ValidateAnnotations validates that a set of annotations are correctly defined.
  24. func ValidateAnnotations(annotations map[string]string, path string) error {
  25. errors := multierror.New()
  26. for k := range annotations {
  27. // The rule is QualifiedName except that case doesn't matter, so convert to lowercase before checking.
  28. for _, msg := range IsQualifiedName(strings.ToLower(k)) {
  29. errors = multierror.Append(errors, fmt.Errorf("%v.%v is invalid: %v", path, k, msg))
  30. }
  31. }
  32. if err := ValidateAnnotationsSize(annotations); err != nil {
  33. errors = multierror.Append(errors, fmt.Errorf("%v is too long: %v", path, err))
  34. }
  35. return errors
  36. }
  37. // ValidateAnnotationsSize validates that a set of annotations is not too large.
  38. func ValidateAnnotationsSize(annotations map[string]string) error {
  39. var totalSize int64
  40. for k, v := range annotations {
  41. totalSize += (int64)(len(k)) + (int64)(len(v))
  42. }
  43. if totalSize > (int64)(TotalAnnotationSizeLimitB) {
  44. return fmt.Errorf("annotations size %d is larger than limit %d", totalSize, TotalAnnotationSizeLimitB)
  45. }
  46. return nil
  47. }