diff --git a/pkg/api/errors/errors.go b/pkg/api/errors/errors.go index 8f1fdb965b2..4ad72721f93 100644 --- a/pkg/api/errors/errors.go +++ b/pkg/api/errors/errors.go @@ -25,7 +25,7 @@ import ( "k8s.io/kubernetes/pkg/api/unversioned" "k8s.io/kubernetes/pkg/runtime" utilerrors "k8s.io/kubernetes/pkg/util/errors" - "k8s.io/kubernetes/pkg/util/fielderrors" + "k8s.io/kubernetes/pkg/util/validation" ) // HTTP Status codes not in the golang http package. @@ -159,10 +159,10 @@ func NewConflict(kind, name string, err error) error { } // NewInvalid returns an error indicating the item is invalid and cannot be processed. -func NewInvalid(kind, name string, errs fielderrors.ValidationErrorList) error { +func NewInvalid(kind, name string, errs validation.ValidationErrorList) error { causes := make([]unversioned.StatusCause, 0, len(errs)) for i := range errs { - if err, ok := errs[i].(*fielderrors.ValidationError); ok { + if err, ok := errs[i].(*validation.ValidationError); ok { causes = append(causes, unversioned.StatusCause{ Type: unversioned.CauseType(err.Type), Message: err.ErrorBody(), diff --git a/pkg/api/errors/errors_test.go b/pkg/api/errors/errors_test.go index 35c6d080131..138311cbe44 100644 --- a/pkg/api/errors/errors_test.go +++ b/pkg/api/errors/errors_test.go @@ -24,7 +24,7 @@ import ( "k8s.io/kubernetes/pkg/api/unversioned" "k8s.io/kubernetes/pkg/runtime" - "k8s.io/kubernetes/pkg/util/fielderrors" + "k8s.io/kubernetes/pkg/util/validation" ) func TestErrorNew(t *testing.T) { @@ -88,11 +88,11 @@ func TestErrorNew(t *testing.T) { func TestNewInvalid(t *testing.T) { testCases := []struct { - Err *fielderrors.ValidationError + Err *validation.ValidationError Details *unversioned.StatusDetails }{ { - fielderrors.NewFieldDuplicate("field[0].name", "bar"), + validation.NewFieldDuplicate("field[0].name", "bar"), &unversioned.StatusDetails{ Kind: "kind", Name: "name", @@ -103,7 +103,7 @@ func TestNewInvalid(t *testing.T) { }, }, { - fielderrors.NewFieldInvalid("field[0].name", "bar", "detail"), + validation.NewFieldInvalid("field[0].name", "bar", "detail"), &unversioned.StatusDetails{ Kind: "kind", Name: "name", @@ -114,7 +114,7 @@ func TestNewInvalid(t *testing.T) { }, }, { - fielderrors.NewFieldNotFound("field[0].name", "bar"), + validation.NewFieldNotFound("field[0].name", "bar"), &unversioned.StatusDetails{ Kind: "kind", Name: "name", @@ -125,7 +125,7 @@ func TestNewInvalid(t *testing.T) { }, }, { - fielderrors.NewFieldValueNotSupported("field[0].name", "bar", nil), + validation.NewFieldValueNotSupported("field[0].name", "bar", nil), &unversioned.StatusDetails{ Kind: "kind", Name: "name", @@ -136,7 +136,7 @@ func TestNewInvalid(t *testing.T) { }, }, { - fielderrors.NewFieldRequired("field[0].name"), + validation.NewFieldRequired("field[0].name"), &unversioned.StatusDetails{ Kind: "kind", Name: "name", @@ -150,7 +150,7 @@ func TestNewInvalid(t *testing.T) { for i, testCase := range testCases { vErr, expected := testCase.Err, testCase.Details expected.Causes[0].Message = vErr.ErrorBody() - err := NewInvalid("kind", "name", fielderrors.ValidationErrorList{vErr}) + err := NewInvalid("kind", "name", validation.ValidationErrorList{vErr}) status := err.(*StatusError).ErrStatus if status.Code != 422 || status.Reason != unversioned.StatusReasonInvalid { t.Errorf("%d: unexpected status: %#v", i, status) diff --git a/pkg/api/rest/create.go b/pkg/api/rest/create.go index d896e3954c6..62e409019ca 100644 --- a/pkg/api/rest/create.go +++ b/pkg/api/rest/create.go @@ -21,7 +21,7 @@ import ( "k8s.io/kubernetes/pkg/api/errors" "k8s.io/kubernetes/pkg/api/validation" "k8s.io/kubernetes/pkg/runtime" - "k8s.io/kubernetes/pkg/util/fielderrors" + utilvalidation "k8s.io/kubernetes/pkg/util/validation" ) // RESTCreateStrategy defines the minimum validation, accepted input, and @@ -42,7 +42,7 @@ type RESTCreateStrategy interface { PrepareForCreate(obj runtime.Object) // Validate is invoked after default fields in the object have been filled in before // the object is persisted. This method should not mutate the object. - Validate(ctx api.Context, obj runtime.Object) fielderrors.ValidationErrorList + Validate(ctx api.Context, obj runtime.Object) utilvalidation.ValidationErrorList // Canonicalize is invoked after validation has succeeded but before the // object has been persisted. This method may mutate the object. Canonicalize(obj runtime.Object) diff --git a/pkg/api/rest/update.go b/pkg/api/rest/update.go index 9601f64cdcc..a9e10e3c17c 100644 --- a/pkg/api/rest/update.go +++ b/pkg/api/rest/update.go @@ -21,7 +21,7 @@ import ( "k8s.io/kubernetes/pkg/api/errors" "k8s.io/kubernetes/pkg/api/validation" "k8s.io/kubernetes/pkg/runtime" - "k8s.io/kubernetes/pkg/util/fielderrors" + utilvalidation "k8s.io/kubernetes/pkg/util/validation" ) // RESTUpdateStrategy defines the minimum validation, accepted input, and @@ -42,7 +42,7 @@ type RESTUpdateStrategy interface { // ValidateUpdate is invoked after default fields in the object have been // filled in before the object is persisted. This method should not mutate // the object. - ValidateUpdate(ctx api.Context, obj, old runtime.Object) fielderrors.ValidationErrorList + ValidateUpdate(ctx api.Context, obj, old runtime.Object) utilvalidation.ValidationErrorList // Canonicalize is invoked after validation has succeeded but before the // object has been persisted. This method may mutate the object. Canonicalize(obj runtime.Object) @@ -53,8 +53,8 @@ type RESTUpdateStrategy interface { } // TODO: add other common fields that require global validation. -func validateCommonFields(obj, old runtime.Object) fielderrors.ValidationErrorList { - allErrs := fielderrors.ValidationErrorList{} +func validateCommonFields(obj, old runtime.Object) utilvalidation.ValidationErrorList { + allErrs := utilvalidation.ValidationErrorList{} objectMeta, err := api.ObjectMetaFor(obj) if err != nil { return append(allErrs, errors.NewInternalError(err)) diff --git a/pkg/api/testing/compat/compatibility_tester.go b/pkg/api/testing/compat/compatibility_tester.go index 42314d18621..401aebb0e12 100644 --- a/pkg/api/testing/compat/compatibility_tester.go +++ b/pkg/api/testing/compat/compatibility_tester.go @@ -28,7 +28,7 @@ import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/runtime" - "k8s.io/kubernetes/pkg/util/fielderrors" + "k8s.io/kubernetes/pkg/util/validation" "k8s.io/kubernetes/pkg/kubectl" ) @@ -42,7 +42,7 @@ func TestCompatibility( t *testing.T, version string, input []byte, - validator func(obj runtime.Object) fielderrors.ValidationErrorList, + validator func(obj runtime.Object) validation.ValidationErrorList, expectedKeys map[string]string, absentKeys []string, ) { diff --git a/pkg/api/v1/backward_compatibility_test.go b/pkg/api/v1/backward_compatibility_test.go index c5b6f93607e..17e504ceb6c 100644 --- a/pkg/api/v1/backward_compatibility_test.go +++ b/pkg/api/v1/backward_compatibility_test.go @@ -23,7 +23,7 @@ import ( "k8s.io/kubernetes/pkg/api/testing/compat" "k8s.io/kubernetes/pkg/api/validation" "k8s.io/kubernetes/pkg/runtime" - "k8s.io/kubernetes/pkg/util/fielderrors" + utilvalidation "k8s.io/kubernetes/pkg/util/validation" ) func TestCompatibility_v1_PodSecurityContext(t *testing.T) { @@ -217,7 +217,7 @@ func TestCompatibility_v1_PodSecurityContext(t *testing.T) { }, } - validator := func(obj runtime.Object) fielderrors.ValidationErrorList { + validator := func(obj runtime.Object) utilvalidation.ValidationErrorList { return validation.ValidatePodSpec(&(obj.(*api.Pod).Spec)) } diff --git a/pkg/api/validation/events.go b/pkg/api/validation/events.go index cc44d2b6bb0..5bc11572bb7 100644 --- a/pkg/api/validation/events.go +++ b/pkg/api/validation/events.go @@ -18,20 +18,19 @@ package validation import ( "k8s.io/kubernetes/pkg/api" - errs "k8s.io/kubernetes/pkg/util/fielderrors" "k8s.io/kubernetes/pkg/util/validation" ) // ValidateEvent makes sure that the event makes sense. -func ValidateEvent(event *api.Event) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func ValidateEvent(event *api.Event) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} // TODO: There is no namespace required for node. if event.InvolvedObject.Kind != "Node" && event.Namespace != event.InvolvedObject.Namespace { - allErrs = append(allErrs, errs.NewFieldInvalid("involvedObject.namespace", event.InvolvedObject.Namespace, "namespace does not match involvedObject")) + allErrs = append(allErrs, validation.NewFieldInvalid("involvedObject.namespace", event.InvolvedObject.Namespace, "namespace does not match involvedObject")) } if !validation.IsDNS1123Subdomain(event.Namespace) { - allErrs = append(allErrs, errs.NewFieldInvalid("namespace", event.Namespace, "")) + allErrs = append(allErrs, validation.NewFieldInvalid("namespace", event.Namespace, "")) } return allErrs } diff --git a/pkg/api/validation/schema.go b/pkg/api/validation/schema.go index 86a2c98886a..c96978ffd6d 100644 --- a/pkg/api/validation/schema.go +++ b/pkg/api/validation/schema.go @@ -27,7 +27,7 @@ import ( "github.com/golang/glog" apiutil "k8s.io/kubernetes/pkg/api/util" utilerrors "k8s.io/kubernetes/pkg/util/errors" - errs "k8s.io/kubernetes/pkg/util/fielderrors" + "k8s.io/kubernetes/pkg/util/validation" "k8s.io/kubernetes/pkg/util/yaml" ) @@ -70,8 +70,8 @@ func NewSwaggerSchemaFromBytes(data []byte) (Schema, error) { // validateList unpack a list and validate every item in the list. // It return nil if every item is ok. // Otherwise it return an error list contain errors of every item. -func (s *SwaggerSchema) validateList(obj map[string]interface{}) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func (s *SwaggerSchema) validateList(obj map[string]interface{}) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} items, exists := obj["items"] if !exists { return append(allErrs, fmt.Errorf("no items field in %#v", obj)) @@ -160,8 +160,8 @@ func (s *SwaggerSchema) ValidateBytes(data []byte) error { return utilerrors.NewAggregate(allErrs) } -func (s *SwaggerSchema) ValidateObject(obj interface{}, fieldName, typeName string) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func (s *SwaggerSchema) ValidateObject(obj interface{}, fieldName, typeName string) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} models := s.api.Models model, ok := models.At(typeName) if !ok { @@ -215,7 +215,7 @@ func (s *SwaggerSchema) ValidateObject(obj interface{}, fieldName, typeName stri // This matches type name in the swagger spec, such as "v1.Binding". var versionRegexp = regexp.MustCompile(`^v.+\..*`) -func (s *SwaggerSchema) validateField(value interface{}, fieldName, fieldType string, fieldDetails *swagger.ModelProperty) errs.ValidationErrorList { +func (s *SwaggerSchema) validateField(value interface{}, fieldName, fieldType string, fieldDetails *swagger.ModelProperty) validation.ValidationErrorList { // TODO: caesarxuchao: because we have multiple group/versions and objects // may reference objects in other group, the commented out way of checking // if a filedType is a type defined by us is outdated. We use a hacky way @@ -229,7 +229,7 @@ func (s *SwaggerSchema) validateField(value interface{}, fieldName, fieldType st // if strings.HasPrefix(fieldType, apiVersion) { return s.ValidateObject(value, fieldName, fieldType) } - allErrs := errs.ValidationErrorList{} + allErrs := validation.ValidationErrorList{} switch fieldType { case "string": // Be loose about what we accept for 'string' since we use IntOrString in a couple of places diff --git a/pkg/api/validation/validation.go b/pkg/api/validation/validation.go index fe12ef1cde2..5bd0f61b3b8 100644 --- a/pkg/api/validation/validation.go +++ b/pkg/api/validation/validation.go @@ -30,7 +30,6 @@ import ( "k8s.io/kubernetes/pkg/api/resource" "k8s.io/kubernetes/pkg/capabilities" "k8s.io/kubernetes/pkg/labels" - errs "k8s.io/kubernetes/pkg/util/fielderrors" "k8s.io/kubernetes/pkg/util/intstr" "k8s.io/kubernetes/pkg/util/sets" "k8s.io/kubernetes/pkg/util/validation" @@ -62,38 +61,38 @@ var PortNameErrorMsg string = fmt.Sprintf(`must be an IANA_SVC_NAME (at most 15 const totalAnnotationSizeLimitB int = 256 * (1 << 10) // 256 kB -func ValidateLabelName(labelName, fieldName string) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func ValidateLabelName(labelName, fieldName string) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} if !validation.IsQualifiedName(labelName) { - allErrs = append(allErrs, errs.NewFieldInvalid(fieldName, labelName, qualifiedNameErrorMsg)) + allErrs = append(allErrs, validation.NewFieldInvalid(fieldName, labelName, qualifiedNameErrorMsg)) } return allErrs } // ValidateLabels validates that a set of labels are correctly defined. -func ValidateLabels(labels map[string]string, field string) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func ValidateLabels(labels map[string]string, field string) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} for k, v := range labels { allErrs = append(allErrs, ValidateLabelName(k, field)...) if !validation.IsValidLabelValue(v) { - allErrs = append(allErrs, errs.NewFieldInvalid(field, v, labelValueErrorMsg)) + allErrs = append(allErrs, validation.NewFieldInvalid(field, v, labelValueErrorMsg)) } } return allErrs } // ValidateAnnotations validates that a set of annotations are correctly defined. -func ValidateAnnotations(annotations map[string]string, field string) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func ValidateAnnotations(annotations map[string]string, field string) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} var totalSize int64 for k, v := range annotations { if !validation.IsQualifiedName(strings.ToLower(k)) { - allErrs = append(allErrs, errs.NewFieldInvalid(field, k, qualifiedNameErrorMsg)) + allErrs = append(allErrs, validation.NewFieldInvalid(field, k, qualifiedNameErrorMsg)) } totalSize += (int64)(len(k)) + (int64)(len(v)) } if totalSize > (int64)(totalAnnotationSizeLimitB) { - allErrs = append(allErrs, errs.NewFieldTooLong(field, "", totalAnnotationSizeLimitB)) + allErrs = append(allErrs, validation.NewFieldTooLong(field, "", totalAnnotationSizeLimitB)) } return allErrs } @@ -218,27 +217,27 @@ func NameIsDNS952Label(name string, prefix bool) (bool, string) { } // Validates that given value is not negative. -func ValidatePositiveField(value int64, fieldName string) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func ValidatePositiveField(value int64, fieldName string) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} if value < 0 { - allErrs = append(allErrs, errs.NewFieldInvalid(fieldName, value, isNegativeErrorMsg)) + allErrs = append(allErrs, validation.NewFieldInvalid(fieldName, value, isNegativeErrorMsg)) } return allErrs } // Validates that a Quantity is not negative -func ValidatePositiveQuantity(value resource.Quantity, fieldName string) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func ValidatePositiveQuantity(value resource.Quantity, fieldName string) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} if value.Cmp(resource.Quantity{}) < 0 { - allErrs = append(allErrs, errs.NewFieldInvalid(fieldName, value.String(), isNegativeErrorMsg)) + allErrs = append(allErrs, validation.NewFieldInvalid(fieldName, value.String(), isNegativeErrorMsg)) } return allErrs } -func ValidateImmutableField(new, old interface{}, fieldName string) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func ValidateImmutableField(new, old interface{}, fieldName string) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} if !api.Semantic.DeepEqual(old, new) { - allErrs = append(allErrs, errs.NewFieldInvalid(fieldName, new, fieldImmutableErrorMsg)) + allErrs = append(allErrs, validation.NewFieldInvalid(fieldName, new, fieldImmutableErrorMsg)) } return allErrs } @@ -247,36 +246,36 @@ func ValidateImmutableField(new, old interface{}, fieldName string) errs.Validat // been performed. // It doesn't return an error for rootscoped resources with namespace, because namespace should already be cleared before. // TODO: Remove calls to this method scattered in validations of specific resources, e.g., ValidatePodUpdate. -func ValidateObjectMeta(meta *api.ObjectMeta, requiresNamespace bool, nameFn ValidateNameFunc) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func ValidateObjectMeta(meta *api.ObjectMeta, requiresNamespace bool, nameFn ValidateNameFunc) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} if len(meta.GenerateName) != 0 { if ok, qualifier := nameFn(meta.GenerateName, true); !ok { - allErrs = append(allErrs, errs.NewFieldInvalid("generateName", meta.GenerateName, qualifier)) + allErrs = append(allErrs, validation.NewFieldInvalid("generateName", meta.GenerateName, qualifier)) } } // If the generated name validates, but the calculated value does not, it's a problem with generation, and we // report it here. This may confuse users, but indicates a programming bug and still must be validated. // If there are multiple fields out of which one is required then add a or as a separator if len(meta.Name) == 0 { - requiredErr := errs.NewFieldRequired("name") + requiredErr := validation.NewFieldRequired("name") requiredErr.Detail = "name or generateName is required" allErrs = append(allErrs, requiredErr) } else { if ok, qualifier := nameFn(meta.Name, false); !ok { - allErrs = append(allErrs, errs.NewFieldInvalid("name", meta.Name, qualifier)) + allErrs = append(allErrs, validation.NewFieldInvalid("name", meta.Name, qualifier)) } } allErrs = append(allErrs, ValidatePositiveField(meta.Generation, "generation")...) if requiresNamespace { if len(meta.Namespace) == 0 { - allErrs = append(allErrs, errs.NewFieldRequired("namespace")) + allErrs = append(allErrs, validation.NewFieldRequired("namespace")) } else if ok, _ := ValidateNamespaceName(meta.Namespace, false); !ok { - allErrs = append(allErrs, errs.NewFieldInvalid("namespace", meta.Namespace, DNS1123LabelErrorMsg)) + allErrs = append(allErrs, validation.NewFieldInvalid("namespace", meta.Namespace, DNS1123LabelErrorMsg)) } } else { if len(meta.Namespace) != 0 { - allErrs = append(allErrs, errs.NewFieldInvalid("namespace", meta.Namespace, "namespace is not allowed on this type")) + allErrs = append(allErrs, validation.NewFieldInvalid("namespace", meta.Namespace, "namespace is not allowed on this type")) } } allErrs = append(allErrs, ValidateLabels(meta.Labels, "labels")...) @@ -286,11 +285,11 @@ func ValidateObjectMeta(meta *api.ObjectMeta, requiresNamespace bool, nameFn Val } // ValidateObjectMetaUpdate validates an object's metadata when updated -func ValidateObjectMetaUpdate(new, old *api.ObjectMeta) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func ValidateObjectMetaUpdate(new, old *api.ObjectMeta) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} if !RepairMalformedUpdates && new.UID != old.UID { - allErrs = append(allErrs, errs.NewFieldInvalid("uid", new.UID, "field is immutable")) + allErrs = append(allErrs, validation.NewFieldInvalid("uid", new.UID, "field is immutable")) } // in the event it is left empty, set it, to allow clients more flexibility // TODO: remove the following code that repairs the update request when we retire the clients that modify the immutable fields. @@ -316,12 +315,12 @@ func ValidateObjectMetaUpdate(new, old *api.ObjectMeta) errs.ValidationErrorList // TODO: needs to check if new==nil && old !=nil after the repair logic is removed. if new.DeletionGracePeriodSeconds != nil && old.DeletionGracePeriodSeconds != nil && *new.DeletionGracePeriodSeconds != *old.DeletionGracePeriodSeconds { - allErrs = append(allErrs, errs.NewFieldInvalid("deletionGracePeriodSeconds", new.DeletionGracePeriodSeconds, "field is immutable; may only be changed via deletion")) + allErrs = append(allErrs, validation.NewFieldInvalid("deletionGracePeriodSeconds", new.DeletionGracePeriodSeconds, "field is immutable; may only be changed via deletion")) } // Reject updates that don't specify a resource version if new.ResourceVersion == "" { - allErrs = append(allErrs, errs.NewFieldInvalid("resourceVersion", new.ResourceVersion, "resourceVersion must be specified for an update")) + allErrs = append(allErrs, validation.NewFieldInvalid("resourceVersion", new.ResourceVersion, "resourceVersion must be specified for an update")) } allErrs = append(allErrs, ValidateImmutableField(new.Name, old.Name, "name")...) @@ -335,18 +334,18 @@ func ValidateObjectMetaUpdate(new, old *api.ObjectMeta) errs.ValidationErrorList return allErrs } -func validateVolumes(volumes []api.Volume) (sets.String, errs.ValidationErrorList) { - allErrs := errs.ValidationErrorList{} +func validateVolumes(volumes []api.Volume) (sets.String, validation.ValidationErrorList) { + allErrs := validation.ValidationErrorList{} allNames := sets.String{} for i, vol := range volumes { el := validateSource(&vol.VolumeSource).Prefix("source") if len(vol.Name) == 0 { - el = append(el, errs.NewFieldRequired("name")) + el = append(el, validation.NewFieldRequired("name")) } else if !validation.IsDNS1123Label(vol.Name) { - el = append(el, errs.NewFieldInvalid("name", vol.Name, DNS1123LabelErrorMsg)) + el = append(el, validation.NewFieldInvalid("name", vol.Name, DNS1123LabelErrorMsg)) } else if allNames.Has(vol.Name) { - el = append(el, errs.NewFieldDuplicate("name", vol.Name)) + el = append(el, validation.NewFieldDuplicate("name", vol.Name)) } if len(el) == 0 { allNames.Insert(vol.Name) @@ -357,9 +356,9 @@ func validateVolumes(volumes []api.Volume) (sets.String, errs.ValidationErrorLis return allNames, allErrs } -func validateSource(source *api.VolumeSource) errs.ValidationErrorList { +func validateSource(source *api.VolumeSource) validation.ValidationErrorList { numVolumes := 0 - allErrs := errs.ValidationErrorList{} + allErrs := validation.ValidationErrorList{} if source.HostPath != nil { numVolumes++ allErrs = append(allErrs, validateHostPathVolumeSource(source.HostPath).Prefix("hostPath")...) @@ -425,198 +424,198 @@ func validateSource(source *api.VolumeSource) errs.ValidationErrorList { allErrs = append(allErrs, validateFCVolumeSource(source.FC).Prefix("fc")...) } if numVolumes != 1 { - allErrs = append(allErrs, errs.NewFieldInvalid("", source, "exactly 1 volume type is required")) + allErrs = append(allErrs, validation.NewFieldInvalid("", source, "exactly 1 volume type is required")) } return allErrs } -func validateHostPathVolumeSource(hostPath *api.HostPathVolumeSource) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func validateHostPathVolumeSource(hostPath *api.HostPathVolumeSource) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} if hostPath.Path == "" { - allErrs = append(allErrs, errs.NewFieldRequired("path")) + allErrs = append(allErrs, validation.NewFieldRequired("path")) } return allErrs } -func validateGitRepoVolumeSource(gitRepo *api.GitRepoVolumeSource) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func validateGitRepoVolumeSource(gitRepo *api.GitRepoVolumeSource) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} if gitRepo.Repository == "" { - allErrs = append(allErrs, errs.NewFieldRequired("repository")) + allErrs = append(allErrs, validation.NewFieldRequired("repository")) } return allErrs } -func validateISCSIVolumeSource(iscsi *api.ISCSIVolumeSource) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func validateISCSIVolumeSource(iscsi *api.ISCSIVolumeSource) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} if iscsi.TargetPortal == "" { - allErrs = append(allErrs, errs.NewFieldRequired("targetPortal")) + allErrs = append(allErrs, validation.NewFieldRequired("targetPortal")) } if iscsi.IQN == "" { - allErrs = append(allErrs, errs.NewFieldRequired("iqn")) + allErrs = append(allErrs, validation.NewFieldRequired("iqn")) } if iscsi.FSType == "" { - allErrs = append(allErrs, errs.NewFieldRequired("fsType")) + allErrs = append(allErrs, validation.NewFieldRequired("fsType")) } if iscsi.Lun < 0 || iscsi.Lun > 255 { - allErrs = append(allErrs, errs.NewFieldInvalid("lun", iscsi.Lun, "")) + allErrs = append(allErrs, validation.NewFieldInvalid("lun", iscsi.Lun, "")) } return allErrs } -func validateFCVolumeSource(fc *api.FCVolumeSource) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func validateFCVolumeSource(fc *api.FCVolumeSource) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} if len(fc.TargetWWNs) < 1 { - allErrs = append(allErrs, errs.NewFieldRequired("targetWWNs")) + allErrs = append(allErrs, validation.NewFieldRequired("targetWWNs")) } if fc.FSType == "" { - allErrs = append(allErrs, errs.NewFieldRequired("fsType")) + allErrs = append(allErrs, validation.NewFieldRequired("fsType")) } if fc.Lun == nil { - allErrs = append(allErrs, errs.NewFieldRequired("lun")) + allErrs = append(allErrs, validation.NewFieldRequired("lun")) } else { if *fc.Lun < 0 || *fc.Lun > 255 { - allErrs = append(allErrs, errs.NewFieldInvalid("lun", fc.Lun, "")) + allErrs = append(allErrs, validation.NewFieldInvalid("lun", fc.Lun, "")) } } return allErrs } -func validateGCEPersistentDiskVolumeSource(PD *api.GCEPersistentDiskVolumeSource) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func validateGCEPersistentDiskVolumeSource(PD *api.GCEPersistentDiskVolumeSource) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} if PD.PDName == "" { - allErrs = append(allErrs, errs.NewFieldRequired("pdName")) + allErrs = append(allErrs, validation.NewFieldRequired("pdName")) } if PD.FSType == "" { - allErrs = append(allErrs, errs.NewFieldRequired("fsType")) + allErrs = append(allErrs, validation.NewFieldRequired("fsType")) } if PD.Partition < 0 || PD.Partition > 255 { - allErrs = append(allErrs, errs.NewFieldInvalid("partition", PD.Partition, pdPartitionErrorMsg)) + allErrs = append(allErrs, validation.NewFieldInvalid("partition", PD.Partition, pdPartitionErrorMsg)) } return allErrs } -func validateAWSElasticBlockStoreVolumeSource(PD *api.AWSElasticBlockStoreVolumeSource) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func validateAWSElasticBlockStoreVolumeSource(PD *api.AWSElasticBlockStoreVolumeSource) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} if PD.VolumeID == "" { - allErrs = append(allErrs, errs.NewFieldRequired("volumeID")) + allErrs = append(allErrs, validation.NewFieldRequired("volumeID")) } if PD.FSType == "" { - allErrs = append(allErrs, errs.NewFieldRequired("fsType")) + allErrs = append(allErrs, validation.NewFieldRequired("fsType")) } if PD.Partition < 0 || PD.Partition > 255 { - allErrs = append(allErrs, errs.NewFieldInvalid("partition", PD.Partition, pdPartitionErrorMsg)) + allErrs = append(allErrs, validation.NewFieldInvalid("partition", PD.Partition, pdPartitionErrorMsg)) } return allErrs } -func validateSecretVolumeSource(secretSource *api.SecretVolumeSource) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func validateSecretVolumeSource(secretSource *api.SecretVolumeSource) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} if secretSource.SecretName == "" { - allErrs = append(allErrs, errs.NewFieldRequired("secretName")) + allErrs = append(allErrs, validation.NewFieldRequired("secretName")) } return allErrs } -func validatePersistentClaimVolumeSource(claim *api.PersistentVolumeClaimVolumeSource) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func validatePersistentClaimVolumeSource(claim *api.PersistentVolumeClaimVolumeSource) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} if claim.ClaimName == "" { - allErrs = append(allErrs, errs.NewFieldRequired("claimName")) + allErrs = append(allErrs, validation.NewFieldRequired("claimName")) } return allErrs } -func validateNFS(nfs *api.NFSVolumeSource) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func validateNFS(nfs *api.NFSVolumeSource) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} if nfs.Server == "" { - allErrs = append(allErrs, errs.NewFieldRequired("server")) + allErrs = append(allErrs, validation.NewFieldRequired("server")) } if nfs.Path == "" { - allErrs = append(allErrs, errs.NewFieldRequired("path")) + allErrs = append(allErrs, validation.NewFieldRequired("path")) } if !path.IsAbs(nfs.Path) { - allErrs = append(allErrs, errs.NewFieldInvalid("path", nfs.Path, "must be an absolute path")) + allErrs = append(allErrs, validation.NewFieldInvalid("path", nfs.Path, "must be an absolute path")) } return allErrs } -func validateGlusterfs(glusterfs *api.GlusterfsVolumeSource) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func validateGlusterfs(glusterfs *api.GlusterfsVolumeSource) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} if glusterfs.EndpointsName == "" { - allErrs = append(allErrs, errs.NewFieldRequired("endpoints")) + allErrs = append(allErrs, validation.NewFieldRequired("endpoints")) } if glusterfs.Path == "" { - allErrs = append(allErrs, errs.NewFieldRequired("path")) + allErrs = append(allErrs, validation.NewFieldRequired("path")) } return allErrs } -func validateFlocker(flocker *api.FlockerVolumeSource) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func validateFlocker(flocker *api.FlockerVolumeSource) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} if flocker.DatasetName == "" { - allErrs = append(allErrs, errs.NewFieldRequired("datasetName")) + allErrs = append(allErrs, validation.NewFieldRequired("datasetName")) } if strings.Contains(flocker.DatasetName, "/") { - allErrs = append(allErrs, errs.NewFieldInvalid("datasetName", flocker.DatasetName, "must not contain '/'")) + allErrs = append(allErrs, validation.NewFieldInvalid("datasetName", flocker.DatasetName, "must not contain '/'")) } return allErrs } var validDownwardAPIFieldPathExpressions = sets.NewString("metadata.name", "metadata.namespace", "metadata.labels", "metadata.annotations") -func validateDownwardAPIVolumeSource(downwardAPIVolume *api.DownwardAPIVolumeSource) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func validateDownwardAPIVolumeSource(downwardAPIVolume *api.DownwardAPIVolumeSource) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} for _, downwardAPIVolumeFile := range downwardAPIVolume.Items { if len(downwardAPIVolumeFile.Path) == 0 { - allErrs = append(allErrs, errs.NewFieldRequired("path")) + allErrs = append(allErrs, validation.NewFieldRequired("path")) } if path.IsAbs(downwardAPIVolumeFile.Path) { - allErrs = append(allErrs, errs.NewFieldForbidden("path", "must not be an absolute path")) + allErrs = append(allErrs, validation.NewFieldForbidden("path", "must not be an absolute path")) } items := strings.Split(downwardAPIVolumeFile.Path, string(os.PathSeparator)) for _, item := range items { if item == ".." { - allErrs = append(allErrs, errs.NewFieldInvalid("path", downwardAPIVolumeFile.Path, "must not contain \"..\".")) + allErrs = append(allErrs, validation.NewFieldInvalid("path", downwardAPIVolumeFile.Path, "must not contain \"..\".")) } } if strings.HasPrefix(items[0], "..") && len(items[0]) > 2 { - allErrs = append(allErrs, errs.NewFieldInvalid("path", downwardAPIVolumeFile.Path, "must not start with \"..\".")) + allErrs = append(allErrs, validation.NewFieldInvalid("path", downwardAPIVolumeFile.Path, "must not start with \"..\".")) } allErrs = append(allErrs, validateObjectFieldSelector(&downwardAPIVolumeFile.FieldRef, &validDownwardAPIFieldPathExpressions).Prefix("FieldRef")...) } return allErrs } -func validateRBD(rbd *api.RBDVolumeSource) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func validateRBD(rbd *api.RBDVolumeSource) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} if len(rbd.CephMonitors) == 0 { - allErrs = append(allErrs, errs.NewFieldRequired("monitors")) + allErrs = append(allErrs, validation.NewFieldRequired("monitors")) } if rbd.RBDImage == "" { - allErrs = append(allErrs, errs.NewFieldRequired("image")) + allErrs = append(allErrs, validation.NewFieldRequired("image")) } if rbd.FSType == "" { - allErrs = append(allErrs, errs.NewFieldRequired("fsType")) + allErrs = append(allErrs, validation.NewFieldRequired("fsType")) } return allErrs } -func validateCinderVolumeSource(cd *api.CinderVolumeSource) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func validateCinderVolumeSource(cd *api.CinderVolumeSource) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} if cd.VolumeID == "" { - allErrs = append(allErrs, errs.NewFieldRequired("volumeID")) + allErrs = append(allErrs, validation.NewFieldRequired("volumeID")) } if cd.FSType == "" || (cd.FSType != "ext3" && cd.FSType != "ext4") { - allErrs = append(allErrs, errs.NewFieldRequired("fsType required and should be of type ext3 or ext4")) + allErrs = append(allErrs, validation.NewFieldRequired("fsType required and should be of type ext3 or ext4")) } return allErrs } -func validateCephFS(cephfs *api.CephFSVolumeSource) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func validateCephFS(cephfs *api.CephFSVolumeSource) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} if len(cephfs.Monitors) == 0 { - allErrs = append(allErrs, errs.NewFieldRequired("monitors")) + allErrs = append(allErrs, validation.NewFieldRequired("monitors")) } return allErrs } @@ -625,26 +624,26 @@ func ValidatePersistentVolumeName(name string, prefix bool) (bool, string) { return NameIsDNSSubdomain(name, prefix) } -func ValidatePersistentVolume(pv *api.PersistentVolume) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func ValidatePersistentVolume(pv *api.PersistentVolume) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} allErrs = append(allErrs, ValidateObjectMeta(&pv.ObjectMeta, false, ValidatePersistentVolumeName).Prefix("metadata")...) if len(pv.Spec.AccessModes) == 0 { - allErrs = append(allErrs, errs.NewFieldRequired("persistentVolume.AccessModes")) + allErrs = append(allErrs, validation.NewFieldRequired("persistentVolume.AccessModes")) } for _, mode := range pv.Spec.AccessModes { if mode != api.ReadWriteOnce && mode != api.ReadOnlyMany && mode != api.ReadWriteMany { - allErrs = append(allErrs, errs.NewFieldInvalid("persistentVolume.Spec.AccessModes", mode, fmt.Sprintf("only %s, %s, and %s are valid", api.ReadWriteOnce, api.ReadOnlyMany, api.ReadWriteMany))) + allErrs = append(allErrs, validation.NewFieldInvalid("persistentVolume.Spec.AccessModes", mode, fmt.Sprintf("only %s, %s, and %s are valid", api.ReadWriteOnce, api.ReadOnlyMany, api.ReadWriteMany))) } } if len(pv.Spec.Capacity) == 0 { - allErrs = append(allErrs, errs.NewFieldRequired("persistentVolume.Capacity")) + allErrs = append(allErrs, validation.NewFieldRequired("persistentVolume.Capacity")) } if _, ok := pv.Spec.Capacity[api.ResourceStorage]; !ok || len(pv.Spec.Capacity) > 1 { - allErrs = append(allErrs, errs.NewFieldInvalid("", pv.Spec.Capacity, fmt.Sprintf("only %s is expected", api.ResourceStorage))) + allErrs = append(allErrs, validation.NewFieldInvalid("", pv.Spec.Capacity, fmt.Sprintf("only %s is expected", api.ResourceStorage))) } for _, qty := range pv.Spec.Capacity { @@ -697,15 +696,15 @@ func ValidatePersistentVolume(pv *api.PersistentVolume) errs.ValidationErrorList allErrs = append(allErrs, validateFCVolumeSource(pv.Spec.FC).Prefix("fc")...) } if numVolumes != 1 { - allErrs = append(allErrs, errs.NewFieldInvalid("", pv.Spec.PersistentVolumeSource, "exactly 1 volume type is required")) + allErrs = append(allErrs, validation.NewFieldInvalid("", pv.Spec.PersistentVolumeSource, "exactly 1 volume type is required")) } return allErrs } // ValidatePersistentVolumeUpdate tests to see if the update is legal for an end user to make. // newPv is updated with fields that cannot be changed. -func ValidatePersistentVolumeUpdate(newPv, oldPv *api.PersistentVolume) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func ValidatePersistentVolumeUpdate(newPv, oldPv *api.PersistentVolume) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} allErrs = ValidatePersistentVolume(newPv) newPv.Status = oldPv.Status return allErrs @@ -713,47 +712,47 @@ func ValidatePersistentVolumeUpdate(newPv, oldPv *api.PersistentVolume) errs.Val // ValidatePersistentVolumeStatusUpdate tests to see if the status update is legal for an end user to make. // newPv is updated with fields that cannot be changed. -func ValidatePersistentVolumeStatusUpdate(newPv, oldPv *api.PersistentVolume) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func ValidatePersistentVolumeStatusUpdate(newPv, oldPv *api.PersistentVolume) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} allErrs = append(allErrs, ValidateObjectMetaUpdate(&newPv.ObjectMeta, &oldPv.ObjectMeta).Prefix("metadata")...) if newPv.ResourceVersion == "" { - allErrs = append(allErrs, errs.NewFieldRequired("resourceVersion")) + allErrs = append(allErrs, validation.NewFieldRequired("resourceVersion")) } newPv.Spec = oldPv.Spec return allErrs } -func ValidatePersistentVolumeClaim(pvc *api.PersistentVolumeClaim) errs.ValidationErrorList { +func ValidatePersistentVolumeClaim(pvc *api.PersistentVolumeClaim) validation.ValidationErrorList { allErrs := ValidateObjectMeta(&pvc.ObjectMeta, true, ValidatePersistentVolumeName) if len(pvc.Spec.AccessModes) == 0 { - allErrs = append(allErrs, errs.NewFieldInvalid("persistentVolumeClaim.Spec.AccessModes", pvc.Spec.AccessModes, "at least 1 PersistentVolumeAccessMode is required")) + allErrs = append(allErrs, validation.NewFieldInvalid("persistentVolumeClaim.Spec.AccessModes", pvc.Spec.AccessModes, "at least 1 PersistentVolumeAccessMode is required")) } for _, mode := range pvc.Spec.AccessModes { if mode != api.ReadWriteOnce && mode != api.ReadOnlyMany && mode != api.ReadWriteMany { - allErrs = append(allErrs, errs.NewFieldInvalid("persistentVolumeClaim.Spec.AccessModes", mode, fmt.Sprintf("only %s, %s, and %s are valid", api.ReadWriteOnce, api.ReadOnlyMany, api.ReadWriteMany))) + allErrs = append(allErrs, validation.NewFieldInvalid("persistentVolumeClaim.Spec.AccessModes", mode, fmt.Sprintf("only %s, %s, and %s are valid", api.ReadWriteOnce, api.ReadOnlyMany, api.ReadWriteMany))) } } if _, ok := pvc.Spec.Resources.Requests[api.ResourceStorage]; !ok { - allErrs = append(allErrs, errs.NewFieldInvalid("persistentVolumeClaim.Spec.Resources.Requests", pvc.Spec.Resources.Requests, "No Storage size specified")) + allErrs = append(allErrs, validation.NewFieldInvalid("persistentVolumeClaim.Spec.Resources.Requests", pvc.Spec.Resources.Requests, "No Storage size specified")) } return allErrs } -func ValidatePersistentVolumeClaimUpdate(newPvc, oldPvc *api.PersistentVolumeClaim) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func ValidatePersistentVolumeClaimUpdate(newPvc, oldPvc *api.PersistentVolumeClaim) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} allErrs = ValidatePersistentVolumeClaim(newPvc) newPvc.Status = oldPvc.Status return allErrs } -func ValidatePersistentVolumeClaimStatusUpdate(newPvc, oldPvc *api.PersistentVolumeClaim) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func ValidatePersistentVolumeClaimStatusUpdate(newPvc, oldPvc *api.PersistentVolumeClaim) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} allErrs = append(allErrs, ValidateObjectMetaUpdate(&newPvc.ObjectMeta, &oldPvc.ObjectMeta).Prefix("metadata")...) if newPvc.ResourceVersion == "" { - allErrs = append(allErrs, errs.NewFieldRequired("resourceVersion")) + allErrs = append(allErrs, validation.NewFieldRequired("resourceVersion")) } if len(newPvc.Spec.AccessModes) == 0 { - allErrs = append(allErrs, errs.NewFieldRequired("persistentVolume.AccessModes")) + allErrs = append(allErrs, validation.NewFieldRequired("persistentVolume.AccessModes")) } for _, qty := range newPvc.Status.Capacity { allErrs = append(allErrs, validateBasicResource(qty)...) @@ -764,48 +763,48 @@ func ValidatePersistentVolumeClaimStatusUpdate(newPvc, oldPvc *api.PersistentVol var supportedPortProtocols = sets.NewString(string(api.ProtocolTCP), string(api.ProtocolUDP)) -func validatePorts(ports []api.ContainerPort) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func validatePorts(ports []api.ContainerPort) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} allNames := sets.String{} for i, port := range ports { - pErrs := errs.ValidationErrorList{} + pErrs := validation.ValidationErrorList{} if len(port.Name) > 0 { if !validation.IsValidPortName(port.Name) { - pErrs = append(pErrs, errs.NewFieldInvalid("name", port.Name, PortNameErrorMsg)) + pErrs = append(pErrs, validation.NewFieldInvalid("name", port.Name, PortNameErrorMsg)) } else if allNames.Has(port.Name) { - pErrs = append(pErrs, errs.NewFieldDuplicate("name", port.Name)) + pErrs = append(pErrs, validation.NewFieldDuplicate("name", port.Name)) } else { allNames.Insert(port.Name) } } if port.ContainerPort == 0 { - pErrs = append(pErrs, errs.NewFieldInvalid("containerPort", port.ContainerPort, PortRangeErrorMsg)) + pErrs = append(pErrs, validation.NewFieldInvalid("containerPort", port.ContainerPort, PortRangeErrorMsg)) } else if !validation.IsValidPortNum(port.ContainerPort) { - pErrs = append(pErrs, errs.NewFieldInvalid("containerPort", port.ContainerPort, PortRangeErrorMsg)) + pErrs = append(pErrs, validation.NewFieldInvalid("containerPort", port.ContainerPort, PortRangeErrorMsg)) } if port.HostPort != 0 && !validation.IsValidPortNum(port.HostPort) { - pErrs = append(pErrs, errs.NewFieldInvalid("hostPort", port.HostPort, PortRangeErrorMsg)) + pErrs = append(pErrs, validation.NewFieldInvalid("hostPort", port.HostPort, PortRangeErrorMsg)) } if len(port.Protocol) == 0 { - pErrs = append(pErrs, errs.NewFieldRequired("protocol")) + pErrs = append(pErrs, validation.NewFieldRequired("protocol")) } else if !supportedPortProtocols.Has(string(port.Protocol)) { - pErrs = append(pErrs, errs.NewFieldValueNotSupported("protocol", port.Protocol, supportedPortProtocols.List())) + pErrs = append(pErrs, validation.NewFieldValueNotSupported("protocol", port.Protocol, supportedPortProtocols.List())) } allErrs = append(allErrs, pErrs.PrefixIndex(i)...) } return allErrs } -func validateEnv(vars []api.EnvVar) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func validateEnv(vars []api.EnvVar) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} for i, ev := range vars { - vErrs := errs.ValidationErrorList{} + vErrs := validation.ValidationErrorList{} if len(ev.Name) == 0 { - vErrs = append(vErrs, errs.NewFieldRequired("name")) + vErrs = append(vErrs, validation.NewFieldRequired("name")) } else if !validation.IsCIdentifier(ev.Name) { - vErrs = append(vErrs, errs.NewFieldInvalid("name", ev.Name, cIdentifierErrorMsg)) + vErrs = append(vErrs, validation.NewFieldInvalid("name", ev.Name, cIdentifierErrorMsg)) } vErrs = append(vErrs, validateEnvVarValueFrom(ev).Prefix("valueFrom")...) allErrs = append(allErrs, vErrs.PrefixIndex(i)...) @@ -815,8 +814,8 @@ func validateEnv(vars []api.EnvVar) errs.ValidationErrorList { var validFieldPathExpressionsEnv = sets.NewString("metadata.name", "metadata.namespace", "status.podIP") -func validateEnvVarValueFrom(ev api.EnvVar) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func validateEnvVarValueFrom(ev api.EnvVar) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} if ev.ValueFrom == nil { return allErrs @@ -831,51 +830,51 @@ func validateEnvVarValueFrom(ev api.EnvVar) errs.ValidationErrorList { } if ev.Value != "" && numSources != 0 { - allErrs = append(allErrs, errs.NewFieldInvalid("", "", "sources cannot be specified when value is not empty")) + allErrs = append(allErrs, validation.NewFieldInvalid("", "", "sources cannot be specified when value is not empty")) } return allErrs } -func validateObjectFieldSelector(fs *api.ObjectFieldSelector, expressions *sets.String) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func validateObjectFieldSelector(fs *api.ObjectFieldSelector, expressions *sets.String) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} if fs.APIVersion == "" { - allErrs = append(allErrs, errs.NewFieldRequired("apiVersion")) + allErrs = append(allErrs, validation.NewFieldRequired("apiVersion")) } else if fs.FieldPath == "" { - allErrs = append(allErrs, errs.NewFieldRequired("fieldPath")) + allErrs = append(allErrs, validation.NewFieldRequired("fieldPath")) } else { internalFieldPath, _, err := api.Scheme.ConvertFieldLabel(fs.APIVersion, "Pod", fs.FieldPath, "") if err != nil { - allErrs = append(allErrs, errs.NewFieldInvalid("fieldPath", fs.FieldPath, "error converting fieldPath")) + allErrs = append(allErrs, validation.NewFieldInvalid("fieldPath", fs.FieldPath, "error converting fieldPath")) } else if !expressions.Has(internalFieldPath) { - allErrs = append(allErrs, errs.NewFieldValueNotSupported("fieldPath", internalFieldPath, expressions.List())) + allErrs = append(allErrs, validation.NewFieldValueNotSupported("fieldPath", internalFieldPath, expressions.List())) } } return allErrs } -func validateVolumeMounts(mounts []api.VolumeMount, volumes sets.String) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func validateVolumeMounts(mounts []api.VolumeMount, volumes sets.String) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} for i, mnt := range mounts { - mErrs := errs.ValidationErrorList{} + mErrs := validation.ValidationErrorList{} if len(mnt.Name) == 0 { - mErrs = append(mErrs, errs.NewFieldRequired("name")) + mErrs = append(mErrs, validation.NewFieldRequired("name")) } else if !volumes.Has(mnt.Name) { - mErrs = append(mErrs, errs.NewFieldNotFound("name", mnt.Name)) + mErrs = append(mErrs, validation.NewFieldNotFound("name", mnt.Name)) } if len(mnt.MountPath) == 0 { - mErrs = append(mErrs, errs.NewFieldRequired("mountPath")) + mErrs = append(mErrs, validation.NewFieldRequired("mountPath")) } allErrs = append(allErrs, mErrs.PrefixIndex(i)...) } return allErrs } -func validateProbe(probe *api.Probe) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func validateProbe(probe *api.Probe) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} if probe == nil { return allErrs @@ -891,11 +890,11 @@ func validateProbe(probe *api.Probe) errs.ValidationErrorList { // AccumulateUniqueHostPorts extracts each HostPort of each Container, // accumulating the results and returning an error if any ports conflict. -func AccumulateUniqueHostPorts(containers []api.Container, accumulator *sets.String) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func AccumulateUniqueHostPorts(containers []api.Container, accumulator *sets.String) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} for ci, ctr := range containers { - cErrs := errs.ValidationErrorList{} + cErrs := validation.ValidationErrorList{} for pi := range ctr.Ports { port := ctr.Ports[pi].HostPort if port == 0 { @@ -903,7 +902,7 @@ func AccumulateUniqueHostPorts(containers []api.Container, accumulator *sets.Str } str := fmt.Sprintf("%d/%s", port, ctr.Ports[pi].Protocol) if accumulator.Has(str) { - cErrs = append(cErrs, errs.NewFieldDuplicate("port", str)) + cErrs = append(cErrs, validation.NewFieldDuplicate("port", str)) } else { accumulator.Insert(str) } @@ -915,49 +914,49 @@ func AccumulateUniqueHostPorts(containers []api.Container, accumulator *sets.Str // checkHostPortConflicts checks for colliding Port.HostPort values across // a slice of containers. -func checkHostPortConflicts(containers []api.Container) errs.ValidationErrorList { +func checkHostPortConflicts(containers []api.Container) validation.ValidationErrorList { allPorts := sets.String{} return AccumulateUniqueHostPorts(containers, &allPorts) } -func validateExecAction(exec *api.ExecAction) errs.ValidationErrorList { - allErrors := errs.ValidationErrorList{} +func validateExecAction(exec *api.ExecAction) validation.ValidationErrorList { + allErrors := validation.ValidationErrorList{} if len(exec.Command) == 0 { - allErrors = append(allErrors, errs.NewFieldRequired("command")) + allErrors = append(allErrors, validation.NewFieldRequired("command")) } return allErrors } -func validateHTTPGetAction(http *api.HTTPGetAction) errs.ValidationErrorList { - allErrors := errs.ValidationErrorList{} +func validateHTTPGetAction(http *api.HTTPGetAction) validation.ValidationErrorList { + allErrors := validation.ValidationErrorList{} if len(http.Path) == 0 { - allErrors = append(allErrors, errs.NewFieldRequired("path")) + allErrors = append(allErrors, validation.NewFieldRequired("path")) } if http.Port.Type == intstr.Int && !validation.IsValidPortNum(http.Port.IntVal) { - allErrors = append(allErrors, errs.NewFieldInvalid("port", http.Port, PortRangeErrorMsg)) + allErrors = append(allErrors, validation.NewFieldInvalid("port", http.Port, PortRangeErrorMsg)) } else if http.Port.Type == intstr.String && !validation.IsValidPortName(http.Port.StrVal) { - allErrors = append(allErrors, errs.NewFieldInvalid("port", http.Port.StrVal, PortNameErrorMsg)) + allErrors = append(allErrors, validation.NewFieldInvalid("port", http.Port.StrVal, PortNameErrorMsg)) } supportedSchemes := sets.NewString(string(api.URISchemeHTTP), string(api.URISchemeHTTPS)) if !supportedSchemes.Has(string(http.Scheme)) { - allErrors = append(allErrors, errs.NewFieldInvalid("scheme", http.Scheme, fmt.Sprintf("must be one of %v", supportedSchemes.List()))) + allErrors = append(allErrors, validation.NewFieldInvalid("scheme", http.Scheme, fmt.Sprintf("must be one of %v", supportedSchemes.List()))) } return allErrors } -func validateTCPSocketAction(tcp *api.TCPSocketAction) errs.ValidationErrorList { - allErrors := errs.ValidationErrorList{} +func validateTCPSocketAction(tcp *api.TCPSocketAction) validation.ValidationErrorList { + allErrors := validation.ValidationErrorList{} if tcp.Port.Type == intstr.Int && !validation.IsValidPortNum(tcp.Port.IntVal) { - allErrors = append(allErrors, errs.NewFieldInvalid("port", tcp.Port, PortRangeErrorMsg)) + allErrors = append(allErrors, validation.NewFieldInvalid("port", tcp.Port, PortRangeErrorMsg)) } else if tcp.Port.Type == intstr.String && !validation.IsValidPortName(tcp.Port.StrVal) { - allErrors = append(allErrors, errs.NewFieldInvalid("port", tcp.Port.StrVal, PortNameErrorMsg)) + allErrors = append(allErrors, validation.NewFieldInvalid("port", tcp.Port.StrVal, PortNameErrorMsg)) } return allErrors } -func validateHandler(handler *api.Handler) errs.ValidationErrorList { +func validateHandler(handler *api.Handler) validation.ValidationErrorList { numHandlers := 0 - allErrors := errs.ValidationErrorList{} + allErrors := validation.ValidationErrorList{} if handler.Exec != nil { numHandlers++ allErrors = append(allErrors, validateExecAction(handler.Exec).Prefix("exec")...) @@ -971,13 +970,13 @@ func validateHandler(handler *api.Handler) errs.ValidationErrorList { allErrors = append(allErrors, validateTCPSocketAction(handler.TCPSocket).Prefix("tcpSocket")...) } if numHandlers != 1 { - allErrors = append(allErrors, errs.NewFieldInvalid("", handler, "exactly 1 handler type is required")) + allErrors = append(allErrors, validation.NewFieldInvalid("", handler, "exactly 1 handler type is required")) } return allErrors } -func validateLifecycle(lifecycle *api.Lifecycle) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func validateLifecycle(lifecycle *api.Lifecycle) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} if lifecycle.PostStart != nil { allErrs = append(allErrs, validateHandler(lifecycle.PostStart).Prefix("postStart")...) } @@ -987,43 +986,43 @@ func validateLifecycle(lifecycle *api.Lifecycle) errs.ValidationErrorList { return allErrs } -func validatePullPolicy(ctr *api.Container) errs.ValidationErrorList { - allErrors := errs.ValidationErrorList{} +func validatePullPolicy(ctr *api.Container) validation.ValidationErrorList { + allErrors := validation.ValidationErrorList{} switch ctr.ImagePullPolicy { case api.PullAlways, api.PullIfNotPresent, api.PullNever: break case "": - allErrors = append(allErrors, errs.NewFieldRequired("")) + allErrors = append(allErrors, validation.NewFieldRequired("")) default: validValues := []string{string(api.PullAlways), string(api.PullIfNotPresent), string(api.PullNever)} - allErrors = append(allErrors, errs.NewFieldValueNotSupported("", ctr.ImagePullPolicy, validValues)) + allErrors = append(allErrors, validation.NewFieldValueNotSupported("", ctr.ImagePullPolicy, validValues)) } return allErrors } -func validateContainers(containers []api.Container, volumes sets.String) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func validateContainers(containers []api.Container, volumes sets.String) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} if len(containers) == 0 { - return append(allErrs, errs.NewFieldRequired("")) + return append(allErrs, validation.NewFieldRequired("")) } allNames := sets.String{} for i, ctr := range containers { - cErrs := errs.ValidationErrorList{} + cErrs := validation.ValidationErrorList{} if len(ctr.Name) == 0 { - cErrs = append(cErrs, errs.NewFieldRequired("name")) + cErrs = append(cErrs, validation.NewFieldRequired("name")) } else if !validation.IsDNS1123Label(ctr.Name) { - cErrs = append(cErrs, errs.NewFieldInvalid("name", ctr.Name, DNS1123LabelErrorMsg)) + cErrs = append(cErrs, validation.NewFieldInvalid("name", ctr.Name, DNS1123LabelErrorMsg)) } else if allNames.Has(ctr.Name) { - cErrs = append(cErrs, errs.NewFieldDuplicate("name", ctr.Name)) + cErrs = append(cErrs, validation.NewFieldDuplicate("name", ctr.Name)) } else { allNames.Insert(ctr.Name) } if len(ctr.Image) == 0 { - cErrs = append(cErrs, errs.NewFieldRequired("image")) + cErrs = append(cErrs, validation.NewFieldRequired("image")) } if ctr.Lifecycle != nil { cErrs = append(cErrs, validateLifecycle(ctr.Lifecycle).Prefix("lifecycle")...) @@ -1031,7 +1030,7 @@ func validateContainers(containers []api.Container, volumes sets.String) errs.Va cErrs = append(cErrs, validateProbe(ctr.LivenessProbe).Prefix("livenessProbe")...) // Liveness-specific validation if ctr.LivenessProbe != nil && ctr.LivenessProbe.SuccessThreshold != 1 { - allErrs = append(allErrs, errs.NewFieldForbidden("livenessProbe.successThreshold", "must be 1")) + allErrs = append(allErrs, validation.NewFieldForbidden("livenessProbe.successThreshold", "must be 1")) } cErrs = append(cErrs, validateProbe(ctr.ReadinessProbe).Prefix("readinessProbe")...) @@ -1049,42 +1048,42 @@ func validateContainers(containers []api.Container, volumes sets.String) errs.Va return allErrs } -func validateRestartPolicy(restartPolicy *api.RestartPolicy) errs.ValidationErrorList { - allErrors := errs.ValidationErrorList{} +func validateRestartPolicy(restartPolicy *api.RestartPolicy) validation.ValidationErrorList { + allErrors := validation.ValidationErrorList{} switch *restartPolicy { case api.RestartPolicyAlways, api.RestartPolicyOnFailure, api.RestartPolicyNever: break case "": - allErrors = append(allErrors, errs.NewFieldRequired("")) + allErrors = append(allErrors, validation.NewFieldRequired("")) default: validValues := []string{string(api.RestartPolicyAlways), string(api.RestartPolicyOnFailure), string(api.RestartPolicyNever)} - allErrors = append(allErrors, errs.NewFieldValueNotSupported("", *restartPolicy, validValues)) + allErrors = append(allErrors, validation.NewFieldValueNotSupported("", *restartPolicy, validValues)) } return allErrors } -func validateDNSPolicy(dnsPolicy *api.DNSPolicy) errs.ValidationErrorList { - allErrors := errs.ValidationErrorList{} +func validateDNSPolicy(dnsPolicy *api.DNSPolicy) validation.ValidationErrorList { + allErrors := validation.ValidationErrorList{} switch *dnsPolicy { case api.DNSClusterFirst, api.DNSDefault: break case "": - allErrors = append(allErrors, errs.NewFieldRequired("")) + allErrors = append(allErrors, validation.NewFieldRequired("")) default: validValues := []string{string(api.DNSClusterFirst), string(api.DNSDefault)} - allErrors = append(allErrors, errs.NewFieldValueNotSupported("", dnsPolicy, validValues)) + allErrors = append(allErrors, validation.NewFieldValueNotSupported("", dnsPolicy, validValues)) } return allErrors } -func validateHostNetwork(hostNetwork bool, containers []api.Container) errs.ValidationErrorList { - allErrors := errs.ValidationErrorList{} +func validateHostNetwork(hostNetwork bool, containers []api.Container) validation.ValidationErrorList { + allErrors := validation.ValidationErrorList{} if hostNetwork { for _, container := range containers { for _, port := range container.Ports { if port.HostPort != port.ContainerPort { - allErrors = append(allErrors, errs.NewFieldInvalid("containerPort", port.ContainerPort, "containerPort must match hostPort if hostNetwork is set to true")) + allErrors = append(allErrors, validation.NewFieldInvalid("containerPort", port.ContainerPort, "containerPort must match hostPort if hostNetwork is set to true")) } } } @@ -1094,21 +1093,21 @@ func validateHostNetwork(hostNetwork bool, containers []api.Container) errs.Vali // validateImagePullSecrets checks to make sure the pull secrets are well formed. Right now, we only expect name to be set (it's the only field). If this ever changes // and someone decides to set those fields, we'd like to know. -func validateImagePullSecrets(imagePullSecrets []api.LocalObjectReference) errs.ValidationErrorList { - allErrors := errs.ValidationErrorList{} +func validateImagePullSecrets(imagePullSecrets []api.LocalObjectReference) validation.ValidationErrorList { + allErrors := validation.ValidationErrorList{} for i, currPullSecret := range imagePullSecrets { strippedRef := api.LocalObjectReference{Name: currPullSecret.Name} if !reflect.DeepEqual(strippedRef, currPullSecret) { - allErrors = append(allErrors, errs.NewFieldInvalid(fmt.Sprintf("[%d]", i), currPullSecret, "only name may be set")) + allErrors = append(allErrors, validation.NewFieldInvalid(fmt.Sprintf("[%d]", i), currPullSecret, "only name may be set")) } } return allErrors } // ValidatePod tests if required fields in the pod are set. -func ValidatePod(pod *api.Pod) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func ValidatePod(pod *api.Pod) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} allErrs = append(allErrs, ValidateObjectMeta(&pod.ObjectMeta, true, ValidatePodName).Prefix("metadata")...) allErrs = append(allErrs, ValidatePodSpec(&pod.Spec).Prefix("spec")...) @@ -1119,8 +1118,8 @@ func ValidatePod(pod *api.Pod) errs.ValidationErrorList { // This includes checking formatting and uniqueness. It also canonicalizes the // structure by setting default values and implementing any backwards-compatibility // tricks. -func ValidatePodSpec(spec *api.PodSpec) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func ValidatePodSpec(spec *api.PodSpec) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} allVolumes, vErrs := validateVolumes(spec.Volumes) allErrs = append(allErrs, vErrs.Prefix("volumes")...) @@ -1132,21 +1131,21 @@ func ValidatePodSpec(spec *api.PodSpec) errs.ValidationErrorList { allErrs = append(allErrs, validateImagePullSecrets(spec.ImagePullSecrets).Prefix("imagePullSecrets")...) if len(spec.ServiceAccountName) > 0 { if ok, msg := ValidateServiceAccountName(spec.ServiceAccountName, false); !ok { - allErrs = append(allErrs, errs.NewFieldInvalid("serviceAccountName", spec.ServiceAccountName, msg)) + allErrs = append(allErrs, validation.NewFieldInvalid("serviceAccountName", spec.ServiceAccountName, msg)) } } if spec.ActiveDeadlineSeconds != nil { if *spec.ActiveDeadlineSeconds <= 0 { - allErrs = append(allErrs, errs.NewFieldInvalid("activeDeadlineSeconds", spec.ActiveDeadlineSeconds, "activeDeadlineSeconds must be a positive integer greater than 0")) + allErrs = append(allErrs, validation.NewFieldInvalid("activeDeadlineSeconds", spec.ActiveDeadlineSeconds, "activeDeadlineSeconds must be a positive integer greater than 0")) } } return allErrs } // ValidatePodSecurityContext test that the specified PodSecurityContext has valid data. -func ValidatePodSecurityContext(securityContext *api.PodSecurityContext, spec *api.PodSpec) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func ValidatePodSecurityContext(securityContext *api.PodSecurityContext, spec *api.PodSpec) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} if securityContext != nil { allErrs = append(allErrs, validateHostNetwork(securityContext.HostNetwork, spec.Containers).Prefix("hostNetwork")...) @@ -1157,14 +1156,14 @@ func ValidatePodSecurityContext(securityContext *api.PodSecurityContext, spec *a // ValidatePodUpdate tests to see if the update is legal for an end user to make. newPod is updated with fields // that cannot be changed. -func ValidatePodUpdate(newPod, oldPod *api.Pod) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func ValidatePodUpdate(newPod, oldPod *api.Pod) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} allErrs = append(allErrs, ValidateObjectMetaUpdate(&newPod.ObjectMeta, &oldPod.ObjectMeta).Prefix("metadata")...) if len(newPod.Spec.Containers) != len(oldPod.Spec.Containers) { //TODO: Pinpoint the specific container that causes the invalid error after we have strategic merge diff - allErrs = append(allErrs, errs.NewFieldInvalid("spec.containers", "content of spec.containers is not printed out, please refer to the \"details\"", "may not add or remove containers")) + allErrs = append(allErrs, validation.NewFieldInvalid("spec.containers", "content of spec.containers is not printed out, please refer to the \"details\"", "may not add or remove containers")) return allErrs } pod := *newPod @@ -1177,7 +1176,7 @@ func ValidatePodUpdate(newPod, oldPod *api.Pod) errs.ValidationErrorList { pod.Spec.Containers = newContainers if !api.Semantic.DeepEqual(pod.Spec, oldPod.Spec) { //TODO: Pinpoint the specific field that causes the invalid error after we have strategic merge diff - allErrs = append(allErrs, errs.NewFieldInvalid("spec", "content of spec is not printed out, please refer to the \"details\"", "may not update fields other than container.image")) + allErrs = append(allErrs, validation.NewFieldInvalid("spec", "content of spec is not printed out, please refer to the \"details\"", "may not update fields other than container.image")) } newPod.Status = oldPod.Status @@ -1186,14 +1185,14 @@ func ValidatePodUpdate(newPod, oldPod *api.Pod) errs.ValidationErrorList { // ValidatePodStatusUpdate tests to see if the update is legal for an end user to make. newPod is updated with fields // that cannot be changed. -func ValidatePodStatusUpdate(newPod, oldPod *api.Pod) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func ValidatePodStatusUpdate(newPod, oldPod *api.Pod) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} allErrs = append(allErrs, ValidateObjectMetaUpdate(&newPod.ObjectMeta, &oldPod.ObjectMeta).Prefix("metadata")...) // TODO: allow change when bindings are properly decoupled from pods if newPod.Spec.NodeName != oldPod.Spec.NodeName { - allErrs = append(allErrs, errs.NewFieldInvalid("status.nodeName", newPod.Spec.NodeName, "pod nodename cannot be changed directly")) + allErrs = append(allErrs, validation.NewFieldInvalid("status.nodeName", newPod.Spec.NodeName, "pod nodename cannot be changed directly")) } // For status update we ignore changes to pod spec. @@ -1203,8 +1202,8 @@ func ValidatePodStatusUpdate(newPod, oldPod *api.Pod) errs.ValidationErrorList { } // ValidatePodTemplate tests if required fields in the pod template are set. -func ValidatePodTemplate(pod *api.PodTemplate) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func ValidatePodTemplate(pod *api.PodTemplate) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} allErrs = append(allErrs, ValidateObjectMeta(&pod.ObjectMeta, true, ValidatePodName).Prefix("metadata")...) allErrs = append(allErrs, ValidatePodTemplateSpec(&pod.Template).Prefix("template")...) return allErrs @@ -1212,8 +1211,8 @@ func ValidatePodTemplate(pod *api.PodTemplate) errs.ValidationErrorList { // ValidatePodTemplateUpdate tests to see if the update is legal for an end user to make. newPod is updated with fields // that cannot be changed. -func ValidatePodTemplateUpdate(newPod, oldPod *api.PodTemplate) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func ValidatePodTemplateUpdate(newPod, oldPod *api.PodTemplate) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} allErrs = append(allErrs, ValidateObjectMetaUpdate(&oldPod.ObjectMeta, &newPod.ObjectMeta).Prefix("metadata")...) allErrs = append(allErrs, ValidatePodTemplateSpec(&newPod.Template).Prefix("template")...) return allErrs @@ -1224,18 +1223,18 @@ var supportedServiceType = sets.NewString(string(api.ServiceTypeClusterIP), stri string(api.ServiceTypeLoadBalancer)) // ValidateService tests if required fields in the service are set. -func ValidateService(service *api.Service) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func ValidateService(service *api.Service) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} allErrs = append(allErrs, ValidateObjectMeta(&service.ObjectMeta, true, ValidateServiceName).Prefix("metadata")...) if len(service.Spec.Ports) == 0 && service.Spec.ClusterIP != api.ClusterIPNone { - allErrs = append(allErrs, errs.NewFieldRequired("spec.ports")) + allErrs = append(allErrs, validation.NewFieldRequired("spec.ports")) } if service.Spec.Type == api.ServiceTypeLoadBalancer { for ix := range service.Spec.Ports { port := &service.Spec.Ports[ix] if port.Port == 10250 { - allErrs = append(allErrs, errs.NewFieldInvalid(fmt.Sprintf("spec.ports[%d].port", ix), port.Port, "can not expose port 10250 externally since it is used by kubelet")) + allErrs = append(allErrs, validation.NewFieldInvalid(fmt.Sprintf("spec.ports[%d].port", ix), port.Port, "can not expose port 10250 externally since it is used by kubelet")) } } } @@ -1249,34 +1248,34 @@ func ValidateService(service *api.Service) errs.ValidationErrorList { } if service.Spec.SessionAffinity == "" { - allErrs = append(allErrs, errs.NewFieldRequired("spec.sessionAffinity")) + allErrs = append(allErrs, validation.NewFieldRequired("spec.sessionAffinity")) } else if !supportedSessionAffinityType.Has(string(service.Spec.SessionAffinity)) { - allErrs = append(allErrs, errs.NewFieldValueNotSupported("spec.sessionAffinity", service.Spec.SessionAffinity, supportedSessionAffinityType.List())) + allErrs = append(allErrs, validation.NewFieldValueNotSupported("spec.sessionAffinity", service.Spec.SessionAffinity, supportedSessionAffinityType.List())) } if api.IsServiceIPSet(service) { if ip := net.ParseIP(service.Spec.ClusterIP); ip == nil { - allErrs = append(allErrs, errs.NewFieldInvalid("spec.clusterIP", service.Spec.ClusterIP, "clusterIP should be empty, 'None', or a valid IP address")) + allErrs = append(allErrs, validation.NewFieldInvalid("spec.clusterIP", service.Spec.ClusterIP, "clusterIP should be empty, 'None', or a valid IP address")) } } for _, ip := range service.Spec.ExternalIPs { if ip == "0.0.0.0" { - allErrs = append(allErrs, errs.NewFieldInvalid("spec.externalIPs", ip, "is not an IP address")) + allErrs = append(allErrs, validation.NewFieldInvalid("spec.externalIPs", ip, "is not an IP address")) } allErrs = append(allErrs, validateIpIsNotLinkLocalOrLoopback(ip, "spec.externalIPs")...) } if service.Spec.Type == "" { - allErrs = append(allErrs, errs.NewFieldRequired("spec.type")) + allErrs = append(allErrs, validation.NewFieldRequired("spec.type")) } else if !supportedServiceType.Has(string(service.Spec.Type)) { - allErrs = append(allErrs, errs.NewFieldValueNotSupported("spec.type", service.Spec.Type, supportedServiceType.List())) + allErrs = append(allErrs, validation.NewFieldValueNotSupported("spec.type", service.Spec.Type, supportedServiceType.List())) } if service.Spec.Type == api.ServiceTypeLoadBalancer { for i := range service.Spec.Ports { if service.Spec.Ports[i].Protocol != api.ProtocolTCP { - allErrs = append(allErrs, errs.NewFieldInvalid(fmt.Sprintf("spec.ports[%d].protocol", i), service.Spec.Ports[i].Protocol, "cannot create an external load balancer with non-TCP ports")) + allErrs = append(allErrs, validation.NewFieldInvalid(fmt.Sprintf("spec.ports[%d].protocol", i), service.Spec.Ports[i].Protocol, "cannot create an external load balancer with non-TCP ports")) } } } @@ -1284,7 +1283,7 @@ func ValidateService(service *api.Service) errs.ValidationErrorList { if service.Spec.Type == api.ServiceTypeClusterIP { for i := range service.Spec.Ports { if service.Spec.Ports[i].NodePort != 0 { - allErrs = append(allErrs, errs.NewFieldInvalid(fmt.Sprintf("spec.ports[%d].nodePort", i), service.Spec.Ports[i].NodePort, "cannot specify a node port with services of type ClusterIP")) + allErrs = append(allErrs, validation.NewFieldInvalid(fmt.Sprintf("spec.ports[%d].nodePort", i), service.Spec.Ports[i].NodePort, "cannot specify a node port with services of type ClusterIP")) } } } @@ -1301,7 +1300,7 @@ func ValidateService(service *api.Service) errs.ValidationErrorList { key.NodePort = port.NodePort _, found := nodePorts[key] if found { - allErrs = append(allErrs, errs.NewFieldInvalid(fmt.Sprintf("spec.ports[%d].nodePort", i), port.NodePort, "duplicate nodePort specified")) + allErrs = append(allErrs, validation.NewFieldInvalid(fmt.Sprintf("spec.ports[%d].nodePort", i), port.NodePort, "duplicate nodePort specified")) } nodePorts[key] = true } @@ -1309,44 +1308,44 @@ func ValidateService(service *api.Service) errs.ValidationErrorList { return allErrs } -func validateServicePort(sp *api.ServicePort, requireName bool, allNames *sets.String) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func validateServicePort(sp *api.ServicePort, requireName bool, allNames *sets.String) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} if requireName && sp.Name == "" { - allErrs = append(allErrs, errs.NewFieldRequired("name")) + allErrs = append(allErrs, validation.NewFieldRequired("name")) } else if sp.Name != "" { if !validation.IsDNS1123Label(sp.Name) { - allErrs = append(allErrs, errs.NewFieldInvalid("name", sp.Name, DNS1123LabelErrorMsg)) + allErrs = append(allErrs, validation.NewFieldInvalid("name", sp.Name, DNS1123LabelErrorMsg)) } else if allNames.Has(sp.Name) { - allErrs = append(allErrs, errs.NewFieldDuplicate("name", sp.Name)) + allErrs = append(allErrs, validation.NewFieldDuplicate("name", sp.Name)) } else { allNames.Insert(sp.Name) } } if !validation.IsValidPortNum(sp.Port) { - allErrs = append(allErrs, errs.NewFieldInvalid("port", sp.Port, PortRangeErrorMsg)) + allErrs = append(allErrs, validation.NewFieldInvalid("port", sp.Port, PortRangeErrorMsg)) } if len(sp.Protocol) == 0 { - allErrs = append(allErrs, errs.NewFieldRequired("protocol")) + allErrs = append(allErrs, validation.NewFieldRequired("protocol")) } else if !supportedPortProtocols.Has(string(sp.Protocol)) { - allErrs = append(allErrs, errs.NewFieldValueNotSupported("protocol", sp.Protocol, supportedPortProtocols.List())) + allErrs = append(allErrs, validation.NewFieldValueNotSupported("protocol", sp.Protocol, supportedPortProtocols.List())) } if sp.TargetPort.Type == intstr.Int && !validation.IsValidPortNum(sp.TargetPort.IntVal) { - allErrs = append(allErrs, errs.NewFieldInvalid("targetPort", sp.TargetPort, PortRangeErrorMsg)) + allErrs = append(allErrs, validation.NewFieldInvalid("targetPort", sp.TargetPort, PortRangeErrorMsg)) } if sp.TargetPort.Type == intstr.String && !validation.IsValidPortName(sp.TargetPort.StrVal) { - allErrs = append(allErrs, errs.NewFieldInvalid("targetPort", sp.TargetPort, PortNameErrorMsg)) + allErrs = append(allErrs, validation.NewFieldInvalid("targetPort", sp.TargetPort, PortNameErrorMsg)) } return allErrs } // ValidateServiceUpdate tests if required fields in the service are set during an update -func ValidateServiceUpdate(service, oldService *api.Service) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func ValidateServiceUpdate(service, oldService *api.Service) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} allErrs = append(allErrs, ValidateObjectMetaUpdate(&service.ObjectMeta, &oldService.ObjectMeta).Prefix("metadata")...) if api.IsServiceIPSet(oldService) { @@ -1358,24 +1357,24 @@ func ValidateServiceUpdate(service, oldService *api.Service) errs.ValidationErro } // ValidateReplicationController tests if required fields in the replication controller are set. -func ValidateReplicationController(controller *api.ReplicationController) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func ValidateReplicationController(controller *api.ReplicationController) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} allErrs = append(allErrs, ValidateObjectMeta(&controller.ObjectMeta, true, ValidateReplicationControllerName).Prefix("metadata")...) allErrs = append(allErrs, ValidateReplicationControllerSpec(&controller.Spec).Prefix("spec")...) return allErrs } // ValidateReplicationControllerUpdate tests if required fields in the replication controller are set. -func ValidateReplicationControllerUpdate(controller, oldController *api.ReplicationController) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func ValidateReplicationControllerUpdate(controller, oldController *api.ReplicationController) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} allErrs = append(allErrs, ValidateObjectMetaUpdate(&controller.ObjectMeta, &oldController.ObjectMeta).Prefix("metadata")...) allErrs = append(allErrs, ValidateReplicationControllerSpec(&controller.Spec).Prefix("spec")...) return allErrs } // ValidateReplicationControllerStatusUpdate tests if required fields in the replication controller are set. -func ValidateReplicationControllerStatusUpdate(controller, oldController *api.ReplicationController) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func ValidateReplicationControllerStatusUpdate(controller, oldController *api.ReplicationController) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} allErrs = append(allErrs, ValidateObjectMetaUpdate(&controller.ObjectMeta, &oldController.ObjectMeta).Prefix("metadata")...) allErrs = append(allErrs, ValidatePositiveField(int64(controller.Status.Replicas), "status.replicas")...) allErrs = append(allErrs, ValidatePositiveField(int64(controller.Status.ObservedGeneration), "status.observedGeneration")...) @@ -1383,27 +1382,27 @@ func ValidateReplicationControllerStatusUpdate(controller, oldController *api.Re } // Validates that the given selector is non-empty. -func ValidateNonEmptySelector(selectorMap map[string]string, fieldName string) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func ValidateNonEmptySelector(selectorMap map[string]string, fieldName string) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} selector := labels.Set(selectorMap).AsSelector() if selector.Empty() { - allErrs = append(allErrs, errs.NewFieldRequired(fieldName)) + allErrs = append(allErrs, validation.NewFieldRequired(fieldName)) } return allErrs } // Validates the given template and ensures that it is in accordance with the desrired selector and replicas. -func ValidatePodTemplateSpecForRC(template *api.PodTemplateSpec, selectorMap map[string]string, replicas int, fieldName string) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func ValidatePodTemplateSpecForRC(template *api.PodTemplateSpec, selectorMap map[string]string, replicas int, fieldName string) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} if template == nil { - allErrs = append(allErrs, errs.NewFieldRequired(fieldName)) + allErrs = append(allErrs, validation.NewFieldRequired(fieldName)) } else { selector := labels.Set(selectorMap).AsSelector() if !selector.Empty() { // Verify that the RC selector matches the labels in template. labels := labels.Set(template.Labels) if !selector.Matches(labels) { - allErrs = append(allErrs, errs.NewFieldInvalid(fieldName+".metadata.labels", template.Labels, "selector does not match labels in "+fieldName)) + allErrs = append(allErrs, validation.NewFieldInvalid(fieldName+".metadata.labels", template.Labels, "selector does not match labels in "+fieldName)) } } allErrs = append(allErrs, ValidatePodTemplateSpec(template).Prefix(fieldName)...) @@ -1412,15 +1411,15 @@ func ValidatePodTemplateSpecForRC(template *api.PodTemplateSpec, selectorMap map } // RestartPolicy has already been first-order validated as per ValidatePodTemplateSpec(). if template.Spec.RestartPolicy != api.RestartPolicyAlways { - allErrs = append(allErrs, errs.NewFieldValueNotSupported(fieldName+".spec.restartPolicy", template.Spec.RestartPolicy, []string{string(api.RestartPolicyAlways)})) + allErrs = append(allErrs, validation.NewFieldValueNotSupported(fieldName+".spec.restartPolicy", template.Spec.RestartPolicy, []string{string(api.RestartPolicyAlways)})) } } return allErrs } // ValidateReplicationControllerSpec tests if required fields in the replication controller spec are set. -func ValidateReplicationControllerSpec(spec *api.ReplicationControllerSpec) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func ValidateReplicationControllerSpec(spec *api.ReplicationControllerSpec) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} allErrs = append(allErrs, ValidateNonEmptySelector(spec.Selector, "selector")...) allErrs = append(allErrs, ValidatePositiveField(int64(spec.Replicas), "replicas")...) @@ -1429,20 +1428,20 @@ func ValidateReplicationControllerSpec(spec *api.ReplicationControllerSpec) errs } // ValidatePodTemplateSpec validates the spec of a pod template -func ValidatePodTemplateSpec(spec *api.PodTemplateSpec) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func ValidatePodTemplateSpec(spec *api.PodTemplateSpec) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} allErrs = append(allErrs, ValidateLabels(spec.Labels, "labels")...) allErrs = append(allErrs, ValidateAnnotations(spec.Annotations, "annotations")...) allErrs = append(allErrs, ValidatePodSpec(&spec.Spec).Prefix("spec")...) return allErrs } -func ValidateReadOnlyPersistentDisks(volumes []api.Volume) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func ValidateReadOnlyPersistentDisks(volumes []api.Volume) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} for _, vol := range volumes { if vol.GCEPersistentDisk != nil { if vol.GCEPersistentDisk.ReadOnly == false { - allErrs = append(allErrs, errs.NewFieldInvalid("GCEPersistentDisk.ReadOnly", false, "ReadOnly must be true for replicated pods > 1, as GCE PD can only be mounted on multiple machines if it is read-only.")) + allErrs = append(allErrs, validation.NewFieldInvalid("GCEPersistentDisk.ReadOnly", false, "ReadOnly must be true for replicated pods > 1, as GCE PD can only be mounted on multiple machines if it is read-only.")) } } // TODO: What to do for AWS? It doesn't support replicas @@ -1451,15 +1450,15 @@ func ValidateReadOnlyPersistentDisks(volumes []api.Volume) errs.ValidationErrorL } // ValidateNode tests if required fields in the node are set. -func ValidateNode(node *api.Node) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func ValidateNode(node *api.Node) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} allErrs = append(allErrs, ValidateObjectMeta(&node.ObjectMeta, false, ValidateNodeName).Prefix("metadata")...) // Only validate spec. All status fields are optional and can be updated later. // external ID is required. if len(node.Spec.ExternalID) == 0 { - allErrs = append(allErrs, errs.NewFieldRequired("spec.ExternalID")) + allErrs = append(allErrs, validation.NewFieldRequired("spec.ExternalID")) } // TODO(rjnagal): Ignore PodCIDR till its completely implemented. @@ -1467,14 +1466,14 @@ func ValidateNode(node *api.Node) errs.ValidationErrorList { } // ValidateNodeUpdate tests to make sure a node update can be applied. Modifies oldNode. -func ValidateNodeUpdate(node *api.Node, oldNode *api.Node) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func ValidateNodeUpdate(node, oldNode *api.Node) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} allErrs = append(allErrs, ValidateObjectMetaUpdate(&node.ObjectMeta, &oldNode.ObjectMeta).Prefix("metadata")...) // TODO: Enable the code once we have better api object.status update model. Currently, // anyone can update node status. // if !api.Semantic.DeepEqual(node.Status, api.NodeStatus{}) { - // allErrs = append(allErrs, errs.NewFieldInvalid("status", node.Status, "status must be empty")) + // allErrs = append(allErrs, validation.NewFieldInvalid("status", node.Status, "status must be empty")) // } // Validte no duplicate addresses in node status. @@ -1509,24 +1508,24 @@ func ValidateNodeUpdate(node *api.Node, oldNode *api.Node) errs.ValidationErrorL // Validate compute resource typename. // Refer to docs/design/resources.md for more details. -func validateResourceName(value string, field string) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func validateResourceName(value string, field string) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} if !validation.IsQualifiedName(value) { - return append(allErrs, errs.NewFieldInvalid(field, value, "resource typename: "+qualifiedNameErrorMsg)) + return append(allErrs, validation.NewFieldInvalid(field, value, "resource typename: "+qualifiedNameErrorMsg)) } if len(strings.Split(value, "/")) == 1 { if !api.IsStandardResourceName(value) { - return append(allErrs, errs.NewFieldInvalid(field, value, "is neither a standard resource type nor is fully qualified")) + return append(allErrs, validation.NewFieldInvalid(field, value, "is neither a standard resource type nor is fully qualified")) } } - return errs.ValidationErrorList{} + return validation.ValidationErrorList{} } // ValidateLimitRange tests if required fields in the LimitRange are set. -func ValidateLimitRange(limitRange *api.LimitRange) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func ValidateLimitRange(limitRange *api.LimitRange) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} allErrs = append(allErrs, ValidateObjectMeta(&limitRange.ObjectMeta, true, ValidateLimitRangeName).Prefix("metadata")...) // ensure resource names are properly qualified per docs/design/resources.md @@ -1535,7 +1534,7 @@ func ValidateLimitRange(limitRange *api.LimitRange) errs.ValidationErrorList { limit := limitRange.Spec.Limits[i] _, found := limitTypeSet[limit.Type] if found { - allErrs = append(allErrs, errs.NewFieldDuplicate(fmt.Sprintf("spec.limits[%d].type", i), limit.Type)) + allErrs = append(allErrs, validation.NewFieldDuplicate(fmt.Sprintf("spec.limits[%d].type", i), limit.Type)) } limitTypeSet[limit.Type] = true @@ -1559,10 +1558,10 @@ func ValidateLimitRange(limitRange *api.LimitRange) errs.ValidationErrorList { if limit.Type == api.LimitTypePod { if len(limit.Default) > 0 { - allErrs = append(allErrs, errs.NewFieldInvalid("spec.limits[%d].default", limit.Default, "Default is not supported when limit type is Pod")) + allErrs = append(allErrs, validation.NewFieldInvalid("spec.limits[%d].default", limit.Default, "Default is not supported when limit type is Pod")) } if len(limit.DefaultRequest) > 0 { - allErrs = append(allErrs, errs.NewFieldInvalid("spec.limits[%d].defaultRequest", limit.DefaultRequest, "DefaultRequest is not supported when limit type is Pod")) + allErrs = append(allErrs, validation.NewFieldInvalid("spec.limits[%d].defaultRequest", limit.DefaultRequest, "DefaultRequest is not supported when limit type is Pod")) } } else { for k, q := range limit.Default { @@ -1591,30 +1590,30 @@ func ValidateLimitRange(limitRange *api.LimitRange) errs.ValidationErrorList { maxRatio, maxRatioFound := maxLimitRequestRatios[k] if minQuantityFound && maxQuantityFound && minQuantity.Cmp(maxQuantity) > 0 { - allErrs = append(allErrs, errs.NewFieldInvalid(fmt.Sprintf("spec.limits[%d].min[%s]", i, k), minQuantity, fmt.Sprintf("min value %s is greater than max value %s", minQuantity.String(), maxQuantity.String()))) + allErrs = append(allErrs, validation.NewFieldInvalid(fmt.Sprintf("spec.limits[%d].min[%s]", i, k), minQuantity, fmt.Sprintf("min value %s is greater than max value %s", minQuantity.String(), maxQuantity.String()))) } if defaultRequestQuantityFound && minQuantityFound && minQuantity.Cmp(defaultRequestQuantity) > 0 { - allErrs = append(allErrs, errs.NewFieldInvalid(fmt.Sprintf("spec.limits[%d].defaultRequest[%s]", i, k), defaultRequestQuantity, fmt.Sprintf("min value %s is greater than default request value %s", minQuantity.String(), defaultRequestQuantity.String()))) + allErrs = append(allErrs, validation.NewFieldInvalid(fmt.Sprintf("spec.limits[%d].defaultRequest[%s]", i, k), defaultRequestQuantity, fmt.Sprintf("min value %s is greater than default request value %s", minQuantity.String(), defaultRequestQuantity.String()))) } if defaultRequestQuantityFound && maxQuantityFound && defaultRequestQuantity.Cmp(maxQuantity) > 0 { - allErrs = append(allErrs, errs.NewFieldInvalid(fmt.Sprintf("spec.limits[%d].defaultRequest[%s]", i, k), defaultRequestQuantity, fmt.Sprintf("default request value %s is greater than max value %s", defaultRequestQuantity.String(), maxQuantity.String()))) + allErrs = append(allErrs, validation.NewFieldInvalid(fmt.Sprintf("spec.limits[%d].defaultRequest[%s]", i, k), defaultRequestQuantity, fmt.Sprintf("default request value %s is greater than max value %s", defaultRequestQuantity.String(), maxQuantity.String()))) } if defaultRequestQuantityFound && defaultQuantityFound && defaultRequestQuantity.Cmp(defaultQuantity) > 0 { - allErrs = append(allErrs, errs.NewFieldInvalid(fmt.Sprintf("spec.limits[%d].defaultRequest[%s]", i, k), defaultRequestQuantity, fmt.Sprintf("default request value %s is greater than default limit value %s", defaultRequestQuantity.String(), defaultQuantity.String()))) + allErrs = append(allErrs, validation.NewFieldInvalid(fmt.Sprintf("spec.limits[%d].defaultRequest[%s]", i, k), defaultRequestQuantity, fmt.Sprintf("default request value %s is greater than default limit value %s", defaultRequestQuantity.String(), defaultQuantity.String()))) } if defaultQuantityFound && minQuantityFound && minQuantity.Cmp(defaultQuantity) > 0 { - allErrs = append(allErrs, errs.NewFieldInvalid(fmt.Sprintf("spec.limits[%d].default[%s]", i, k), minQuantity, fmt.Sprintf("min value %s is greater than default value %s", minQuantity.String(), defaultQuantity.String()))) + allErrs = append(allErrs, validation.NewFieldInvalid(fmt.Sprintf("spec.limits[%d].default[%s]", i, k), minQuantity, fmt.Sprintf("min value %s is greater than default value %s", minQuantity.String(), defaultQuantity.String()))) } if defaultQuantityFound && maxQuantityFound && defaultQuantity.Cmp(maxQuantity) > 0 { - allErrs = append(allErrs, errs.NewFieldInvalid(fmt.Sprintf("spec.limits[%d].default[%s]", i, k), maxQuantity, fmt.Sprintf("default value %s is greater than max value %s", defaultQuantity.String(), maxQuantity.String()))) + allErrs = append(allErrs, validation.NewFieldInvalid(fmt.Sprintf("spec.limits[%d].default[%s]", i, k), maxQuantity, fmt.Sprintf("default value %s is greater than max value %s", defaultQuantity.String(), maxQuantity.String()))) } if maxRatioFound && maxRatio.Cmp(*resource.NewQuantity(1, resource.DecimalSI)) < 0 { - allErrs = append(allErrs, errs.NewFieldInvalid(fmt.Sprintf("spec.limits[%d].maxLimitRequestRatio[%s]", i, k), maxRatio, fmt.Sprintf("maxLimitRequestRatio %s is less than 1", maxRatio.String()))) + allErrs = append(allErrs, validation.NewFieldInvalid(fmt.Sprintf("spec.limits[%d].maxLimitRequestRatio[%s]", i, k), maxRatio, fmt.Sprintf("maxLimitRequestRatio %s is less than 1", maxRatio.String()))) } if maxRatioFound && minQuantityFound && maxQuantityFound { maxRatioValue := float64(maxRatio.Value()) @@ -1627,7 +1626,7 @@ func ValidateLimitRange(limitRange *api.LimitRange) errs.ValidationErrorList { } maxRatioLimit := float64(maxQuantityValue) / float64(minQuantityValue) if maxRatioValue > maxRatioLimit { - allErrs = append(allErrs, errs.NewFieldInvalid(fmt.Sprintf("spec.limits[%d].maxLimitRequestRatio[%s]", i, k), maxRatio, fmt.Sprintf("maxLimitRequestRatio %s is greater than max/min = %f", maxRatio.String(), maxRatioLimit))) + allErrs = append(allErrs, validation.NewFieldInvalid(fmt.Sprintf("spec.limits[%d].maxLimitRequestRatio[%s]", i, k), maxRatio, fmt.Sprintf("maxLimitRequestRatio %s is greater than max/min = %f", maxRatio.String(), maxRatioLimit))) } } } @@ -1637,15 +1636,15 @@ func ValidateLimitRange(limitRange *api.LimitRange) errs.ValidationErrorList { } // ValidateServiceAccount tests if required fields in the ServiceAccount are set. -func ValidateServiceAccount(serviceAccount *api.ServiceAccount) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func ValidateServiceAccount(serviceAccount *api.ServiceAccount) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} allErrs = append(allErrs, ValidateObjectMeta(&serviceAccount.ObjectMeta, true, ValidateServiceAccountName).Prefix("metadata")...) return allErrs } // ValidateServiceAccountUpdate tests if required fields in the ServiceAccount are set. -func ValidateServiceAccountUpdate(newServiceAccount, oldServiceAccount *api.ServiceAccount) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func ValidateServiceAccountUpdate(newServiceAccount, oldServiceAccount *api.ServiceAccount) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} allErrs = append(allErrs, ValidateObjectMetaUpdate(&newServiceAccount.ObjectMeta, &oldServiceAccount.ObjectMeta).Prefix("metadata")...) allErrs = append(allErrs, ValidateServiceAccount(newServiceAccount)...) return allErrs @@ -1662,21 +1661,21 @@ func IsSecretKey(value string) bool { } // ValidateSecret tests if required fields in the Secret are set. -func ValidateSecret(secret *api.Secret) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func ValidateSecret(secret *api.Secret) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} allErrs = append(allErrs, ValidateObjectMeta(&secret.ObjectMeta, true, ValidateSecretName).Prefix("metadata")...) totalSize := 0 for key, value := range secret.Data { if !IsSecretKey(key) { - allErrs = append(allErrs, errs.NewFieldInvalid(fmt.Sprintf("data[%s]", key), key, fmt.Sprintf("must have at most %d characters and match regex %s", validation.DNS1123SubdomainMaxLength, SecretKeyFmt))) + allErrs = append(allErrs, validation.NewFieldInvalid(fmt.Sprintf("data[%s]", key), key, fmt.Sprintf("must have at most %d characters and match regex %s", validation.DNS1123SubdomainMaxLength, SecretKeyFmt))) } totalSize += len(value) } if totalSize > api.MaxSecretSize { - allErrs = append(allErrs, errs.NewFieldForbidden("data", "Maximum secret size exceeded")) + allErrs = append(allErrs, validation.NewFieldForbidden("data", "Maximum secret size exceeded")) } switch secret.Type { @@ -1684,20 +1683,20 @@ func ValidateSecret(secret *api.Secret) errs.ValidationErrorList { // Only require Annotations[kubernetes.io/service-account.name] // Additional fields (like Annotations[kubernetes.io/service-account.uid] and Data[token]) might be contributed later by a controller loop if value := secret.Annotations[api.ServiceAccountNameKey]; len(value) == 0 { - allErrs = append(allErrs, errs.NewFieldRequired(fmt.Sprintf("metadata.annotations[%s]", api.ServiceAccountNameKey))) + allErrs = append(allErrs, validation.NewFieldRequired(fmt.Sprintf("metadata.annotations[%s]", api.ServiceAccountNameKey))) } case api.SecretTypeOpaque, "": // no-op case api.SecretTypeDockercfg: dockercfgBytes, exists := secret.Data[api.DockerConfigKey] if !exists { - allErrs = append(allErrs, errs.NewFieldRequired(fmt.Sprintf("data[%s]", api.DockerConfigKey))) + allErrs = append(allErrs, validation.NewFieldRequired(fmt.Sprintf("data[%s]", api.DockerConfigKey))) break } // make sure that the content is well-formed json. if err := json.Unmarshal(dockercfgBytes, &map[string]interface{}{}); err != nil { - allErrs = append(allErrs, errs.NewFieldInvalid(fmt.Sprintf("data[%s]", api.DockerConfigKey), "", err.Error())) + allErrs = append(allErrs, validation.NewFieldInvalid(fmt.Sprintf("data[%s]", api.DockerConfigKey), "", err.Error())) } default: @@ -1708,8 +1707,8 @@ func ValidateSecret(secret *api.Secret) errs.ValidationErrorList { } // ValidateSecretUpdate tests if required fields in the Secret are set. -func ValidateSecretUpdate(newSecret, oldSecret *api.Secret) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func ValidateSecretUpdate(newSecret, oldSecret *api.Secret) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} allErrs = append(allErrs, ValidateObjectMetaUpdate(&newSecret.ObjectMeta, &oldSecret.ObjectMeta).Prefix("metadata")...) if len(newSecret.Type) == 0 { @@ -1722,16 +1721,16 @@ func ValidateSecretUpdate(newSecret, oldSecret *api.Secret) errs.ValidationError return allErrs } -func validateBasicResource(quantity resource.Quantity) errs.ValidationErrorList { +func validateBasicResource(quantity resource.Quantity) validation.ValidationErrorList { if quantity.Value() < 0 { - return errs.ValidationErrorList{errs.NewFieldInvalid("", quantity.Value(), "must be a valid resource quantity")} + return validation.ValidationErrorList{validation.NewFieldInvalid("", quantity.Value(), "must be a valid resource quantity")} } - return errs.ValidationErrorList{} + return validation.ValidationErrorList{} } // Validates resource requirement spec. -func ValidateResourceRequirements(requirements *api.ResourceRequirements) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func ValidateResourceRequirements(requirements *api.ResourceRequirements) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} for resourceName, quantity := range requirements.Limits { // Validate resource name. allErrs = append(allErrs, validateResourceName(resourceName.String(), fmt.Sprintf("resources.limits[%s]", resourceName))...) @@ -1750,7 +1749,7 @@ func ValidateResourceRequirements(requirements *api.ResourceRequirements) errs.V limitValue = quantity.MilliValue() } if limitValue < requestValue { - allErrs = append(allErrs, errs.NewFieldInvalid(fmt.Sprintf("resources.limits[%s]", resourceName), quantity.String(), "limit cannot be smaller than request")) + allErrs = append(allErrs, validation.NewFieldInvalid(fmt.Sprintf("resources.limits[%s]", resourceName), quantity.String(), "limit cannot be smaller than request")) } } } @@ -1765,8 +1764,8 @@ func ValidateResourceRequirements(requirements *api.ResourceRequirements) errs.V } // ValidateResourceQuota tests if required fields in the ResourceQuota are set. -func ValidateResourceQuota(resourceQuota *api.ResourceQuota) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func ValidateResourceQuota(resourceQuota *api.ResourceQuota) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} allErrs = append(allErrs, ValidateObjectMeta(&resourceQuota.ObjectMeta, true, ValidateResourceQuotaName).Prefix("metadata")...) for k, v := range resourceQuota.Spec.Hard { @@ -1785,12 +1784,12 @@ func ValidateResourceQuota(resourceQuota *api.ResourceQuota) errs.ValidationErro } // validateResourceQuantityValue enforces that specified quantity is valid for specified resource -func validateResourceQuantityValue(resource string, value resource.Quantity) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func validateResourceQuantityValue(resource string, value resource.Quantity) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} allErrs = append(allErrs, ValidatePositiveQuantity(value, resource)...) if api.IsIntegerResourceName(resource) { if value.MilliValue()%int64(1000) != int64(0) { - allErrs = append(allErrs, errs.NewFieldInvalid(resource, value, isNotIntegerErrorMsg)) + allErrs = append(allErrs, validation.NewFieldInvalid(resource, value, isNotIntegerErrorMsg)) } } return allErrs @@ -1798,8 +1797,8 @@ func validateResourceQuantityValue(resource string, value resource.Quantity) err // ValidateResourceQuotaUpdate tests to see if the update is legal for an end user to make. // newResourceQuota is updated with fields that cannot be changed. -func ValidateResourceQuotaUpdate(newResourceQuota, oldResourceQuota *api.ResourceQuota) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func ValidateResourceQuotaUpdate(newResourceQuota, oldResourceQuota *api.ResourceQuota) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} allErrs = append(allErrs, ValidateObjectMetaUpdate(&newResourceQuota.ObjectMeta, &oldResourceQuota.ObjectMeta).Prefix("metadata")...) for k, v := range newResourceQuota.Spec.Hard { allErrs = append(allErrs, validateResourceName(string(k), string(newResourceQuota.TypeMeta.Kind))...) @@ -1811,11 +1810,11 @@ func ValidateResourceQuotaUpdate(newResourceQuota, oldResourceQuota *api.Resourc // ValidateResourceQuotaStatusUpdate tests to see if the status update is legal for an end user to make. // newResourceQuota is updated with fields that cannot be changed. -func ValidateResourceQuotaStatusUpdate(newResourceQuota, oldResourceQuota *api.ResourceQuota) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func ValidateResourceQuotaStatusUpdate(newResourceQuota, oldResourceQuota *api.ResourceQuota) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} allErrs = append(allErrs, ValidateObjectMetaUpdate(&newResourceQuota.ObjectMeta, &oldResourceQuota.ObjectMeta).Prefix("metadata")...) if newResourceQuota.ResourceVersion == "" { - allErrs = append(allErrs, errs.NewFieldRequired("resourceVersion")) + allErrs = append(allErrs, validation.NewFieldRequired("resourceVersion")) } for k, v := range newResourceQuota.Status.Hard { allErrs = append(allErrs, validateResourceName(string(k), string(newResourceQuota.TypeMeta.Kind))...) @@ -1830,8 +1829,8 @@ func ValidateResourceQuotaStatusUpdate(newResourceQuota, oldResourceQuota *api.R } // ValidateNamespace tests if required fields are set. -func ValidateNamespace(namespace *api.Namespace) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func ValidateNamespace(namespace *api.Namespace) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} allErrs = append(allErrs, ValidateObjectMeta(&namespace.ObjectMeta, false, ValidateNamespaceName).Prefix("metadata")...) for i := range namespace.Spec.Finalizers { allErrs = append(allErrs, validateFinalizerName(string(namespace.Spec.Finalizers[i]))...) @@ -1840,25 +1839,25 @@ func ValidateNamespace(namespace *api.Namespace) errs.ValidationErrorList { } // Validate finalizer names -func validateFinalizerName(stringValue string) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func validateFinalizerName(stringValue string) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} if !validation.IsQualifiedName(stringValue) { - return append(allErrs, errs.NewFieldInvalid("spec.finalizers", stringValue, qualifiedNameErrorMsg)) + return append(allErrs, validation.NewFieldInvalid("spec.finalizers", stringValue, qualifiedNameErrorMsg)) } if len(strings.Split(stringValue, "/")) == 1 { if !api.IsStandardFinalizerName(stringValue) { - return append(allErrs, errs.NewFieldInvalid("spec.finalizers", stringValue, fmt.Sprintf("finalizer name is neither a standard finalizer name nor is it fully qualified"))) + return append(allErrs, validation.NewFieldInvalid("spec.finalizers", stringValue, fmt.Sprintf("finalizer name is neither a standard finalizer name nor is it fully qualified"))) } } - return errs.ValidationErrorList{} + return validation.ValidationErrorList{} } // ValidateNamespaceUpdate tests to make sure a namespace update can be applied. // newNamespace is updated with fields that cannot be changed -func ValidateNamespaceUpdate(newNamespace *api.Namespace, oldNamespace *api.Namespace) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func ValidateNamespaceUpdate(newNamespace *api.Namespace, oldNamespace *api.Namespace) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} allErrs = append(allErrs, ValidateObjectMetaUpdate(&newNamespace.ObjectMeta, &oldNamespace.ObjectMeta).Prefix("metadata")...) newNamespace.Spec.Finalizers = oldNamespace.Spec.Finalizers newNamespace.Status = oldNamespace.Status @@ -1867,17 +1866,17 @@ func ValidateNamespaceUpdate(newNamespace *api.Namespace, oldNamespace *api.Name // ValidateNamespaceStatusUpdate tests to see if the update is legal for an end user to make. newNamespace is updated with fields // that cannot be changed. -func ValidateNamespaceStatusUpdate(newNamespace, oldNamespace *api.Namespace) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func ValidateNamespaceStatusUpdate(newNamespace, oldNamespace *api.Namespace) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} allErrs = append(allErrs, ValidateObjectMetaUpdate(&newNamespace.ObjectMeta, &oldNamespace.ObjectMeta).Prefix("metadata")...) newNamespace.Spec = oldNamespace.Spec if newNamespace.DeletionTimestamp.IsZero() { if newNamespace.Status.Phase != api.NamespaceActive { - allErrs = append(allErrs, errs.NewFieldInvalid("Status.Phase", newNamespace.Status.Phase, "A namespace may only be in active status if it does not have a deletion timestamp.")) + allErrs = append(allErrs, validation.NewFieldInvalid("Status.Phase", newNamespace.Status.Phase, "A namespace may only be in active status if it does not have a deletion timestamp.")) } } else { if newNamespace.Status.Phase != api.NamespaceTerminating { - allErrs = append(allErrs, errs.NewFieldInvalid("Status.Phase", newNamespace.Status.Phase, "A namespace may only be in terminating status if it has a deletion timestamp.")) + allErrs = append(allErrs, validation.NewFieldInvalid("Status.Phase", newNamespace.Status.Phase, "A namespace may only be in terminating status if it has a deletion timestamp.")) } } return allErrs @@ -1885,8 +1884,8 @@ func ValidateNamespaceStatusUpdate(newNamespace, oldNamespace *api.Namespace) er // ValidateNamespaceFinalizeUpdate tests to see if the update is legal for an end user to make. // newNamespace is updated with fields that cannot be changed. -func ValidateNamespaceFinalizeUpdate(newNamespace, oldNamespace *api.Namespace) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func ValidateNamespaceFinalizeUpdate(newNamespace, oldNamespace *api.Namespace) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} allErrs = append(allErrs, ValidateObjectMetaUpdate(&newNamespace.ObjectMeta, &oldNamespace.ObjectMeta).Prefix("metadata")...) for i := range newNamespace.Spec.Finalizers { allErrs = append(allErrs, validateFinalizerName(string(newNamespace.Spec.Finalizers[i]))...) @@ -1896,26 +1895,26 @@ func ValidateNamespaceFinalizeUpdate(newNamespace, oldNamespace *api.Namespace) } // ValidateEndpoints tests if required fields are set. -func ValidateEndpoints(endpoints *api.Endpoints) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func ValidateEndpoints(endpoints *api.Endpoints) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} allErrs = append(allErrs, ValidateObjectMeta(&endpoints.ObjectMeta, true, ValidateEndpointsName).Prefix("metadata")...) allErrs = append(allErrs, validateEndpointSubsets(endpoints.Subsets).Prefix("subsets")...) return allErrs } -func validateEndpointSubsets(subsets []api.EndpointSubset) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func validateEndpointSubsets(subsets []api.EndpointSubset) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} for i := range subsets { ss := &subsets[i] - ssErrs := errs.ValidationErrorList{} + ssErrs := validation.ValidationErrorList{} if len(ss.Addresses) == 0 && len(ss.NotReadyAddresses) == 0 { - ssErrs = append(ssErrs, errs.NewFieldRequired("addresses or notReadyAddresses")) + ssErrs = append(ssErrs, validation.NewFieldRequired("addresses or notReadyAddresses")) } if len(ss.Ports) == 0 { - ssErrs = append(ssErrs, errs.NewFieldRequired("ports")) + ssErrs = append(ssErrs, validation.NewFieldRequired("ports")) } for addr := range ss.Addresses { ssErrs = append(ssErrs, validateEndpointAddress(&ss.Addresses[addr]).PrefixIndex(addr).Prefix("addresses")...) @@ -1930,67 +1929,67 @@ func validateEndpointSubsets(subsets []api.EndpointSubset) errs.ValidationErrorL return allErrs } -func validateEndpointAddress(address *api.EndpointAddress) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func validateEndpointAddress(address *api.EndpointAddress) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} if !validation.IsValidIPv4(address.IP) { - allErrs = append(allErrs, errs.NewFieldInvalid("ip", address.IP, "invalid IPv4 address")) + allErrs = append(allErrs, validation.NewFieldInvalid("ip", address.IP, "invalid IPv4 address")) return allErrs } return validateIpIsNotLinkLocalOrLoopback(address.IP, "ip") } -func validateIpIsNotLinkLocalOrLoopback(ipAddress, fieldName string) errs.ValidationErrorList { +func validateIpIsNotLinkLocalOrLoopback(ipAddress, fieldName string) validation.ValidationErrorList { // We disallow some IPs as endpoints or external-ips. Specifically, loopback addresses are // nonsensical and link-local addresses tend to be used for node-centric purposes (e.g. metadata service). - allErrs := errs.ValidationErrorList{} + allErrs := validation.ValidationErrorList{} ip := net.ParseIP(ipAddress) if ip == nil { - allErrs = append(allErrs, errs.NewFieldInvalid(fieldName, ipAddress, "not a valid IP address")) + allErrs = append(allErrs, validation.NewFieldInvalid(fieldName, ipAddress, "not a valid IP address")) return allErrs } if ip.IsLoopback() { - allErrs = append(allErrs, errs.NewFieldInvalid(fieldName, ipAddress, "may not be in the loopback range (127.0.0.0/8)")) + allErrs = append(allErrs, validation.NewFieldInvalid(fieldName, ipAddress, "may not be in the loopback range (127.0.0.0/8)")) } if ip.IsLinkLocalUnicast() { - allErrs = append(allErrs, errs.NewFieldInvalid(fieldName, ipAddress, "may not be in the link-local range (169.254.0.0/16)")) + allErrs = append(allErrs, validation.NewFieldInvalid(fieldName, ipAddress, "may not be in the link-local range (169.254.0.0/16)")) } if ip.IsLinkLocalMulticast() { - allErrs = append(allErrs, errs.NewFieldInvalid(fieldName, ipAddress, "may not be in the link-local multicast range (224.0.0.0/24)")) + allErrs = append(allErrs, validation.NewFieldInvalid(fieldName, ipAddress, "may not be in the link-local multicast range (224.0.0.0/24)")) } return allErrs } -func validateEndpointPort(port *api.EndpointPort, requireName bool) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func validateEndpointPort(port *api.EndpointPort, requireName bool) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} if requireName && port.Name == "" { - allErrs = append(allErrs, errs.NewFieldRequired("name")) + allErrs = append(allErrs, validation.NewFieldRequired("name")) } else if port.Name != "" { if !validation.IsDNS1123Label(port.Name) { - allErrs = append(allErrs, errs.NewFieldInvalid("name", port.Name, DNS1123LabelErrorMsg)) + allErrs = append(allErrs, validation.NewFieldInvalid("name", port.Name, DNS1123LabelErrorMsg)) } } if !validation.IsValidPortNum(port.Port) { - allErrs = append(allErrs, errs.NewFieldInvalid("port", port.Port, PortRangeErrorMsg)) + allErrs = append(allErrs, validation.NewFieldInvalid("port", port.Port, PortRangeErrorMsg)) } if len(port.Protocol) == 0 { - allErrs = append(allErrs, errs.NewFieldRequired("protocol")) + allErrs = append(allErrs, validation.NewFieldRequired("protocol")) } else if !supportedPortProtocols.Has(string(port.Protocol)) { - allErrs = append(allErrs, errs.NewFieldValueNotSupported("protocol", port.Protocol, supportedPortProtocols.List())) + allErrs = append(allErrs, validation.NewFieldValueNotSupported("protocol", port.Protocol, supportedPortProtocols.List())) } return allErrs } // ValidateEndpointsUpdate tests to make sure an endpoints update can be applied. -func ValidateEndpointsUpdate(newEndpoints, oldEndpoints *api.Endpoints) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func ValidateEndpointsUpdate(newEndpoints, oldEndpoints *api.Endpoints) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} allErrs = append(allErrs, ValidateObjectMetaUpdate(&newEndpoints.ObjectMeta, &oldEndpoints.ObjectMeta).Prefix("metadata")...) allErrs = append(allErrs, validateEndpointSubsets(newEndpoints.Subsets).Prefix("subsets")...) return allErrs } // ValidateSecurityContext ensure the security context contains valid settings -func ValidateSecurityContext(sc *api.SecurityContext) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func ValidateSecurityContext(sc *api.SecurityContext) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} //this should only be true for testing since SecurityContext is defaulted by the api if sc == nil { return allErrs @@ -1998,53 +1997,53 @@ func ValidateSecurityContext(sc *api.SecurityContext) errs.ValidationErrorList { if sc.Privileged != nil { if *sc.Privileged && !capabilities.Get().AllowPrivileged { - allErrs = append(allErrs, errs.NewFieldForbidden("privileged", sc.Privileged)) + allErrs = append(allErrs, validation.NewFieldForbidden("privileged", sc.Privileged)) } } if sc.RunAsUser != nil { if *sc.RunAsUser < 0 { - allErrs = append(allErrs, errs.NewFieldInvalid("runAsUser", *sc.RunAsUser, "runAsUser cannot be negative")) + allErrs = append(allErrs, validation.NewFieldInvalid("runAsUser", *sc.RunAsUser, "runAsUser cannot be negative")) } } return allErrs } -func ValidatePodLogOptions(opts *api.PodLogOptions) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func ValidatePodLogOptions(opts *api.PodLogOptions) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} if opts.TailLines != nil && *opts.TailLines < 0 { - allErrs = append(allErrs, errs.NewFieldInvalid("tailLines", *opts.TailLines, "tailLines must be a non-negative integer or nil")) + allErrs = append(allErrs, validation.NewFieldInvalid("tailLines", *opts.TailLines, "tailLines must be a non-negative integer or nil")) } if opts.LimitBytes != nil && *opts.LimitBytes < 1 { - allErrs = append(allErrs, errs.NewFieldInvalid("limitBytes", *opts.LimitBytes, "limitBytes must be a positive integer or nil")) + allErrs = append(allErrs, validation.NewFieldInvalid("limitBytes", *opts.LimitBytes, "limitBytes must be a positive integer or nil")) } switch { case opts.SinceSeconds != nil && opts.SinceTime != nil: - allErrs = append(allErrs, errs.NewFieldInvalid("sinceSeconds", *opts.SinceSeconds, "only one of sinceTime or sinceSeconds can be provided")) - allErrs = append(allErrs, errs.NewFieldInvalid("sinceTime", *opts.SinceTime, "only one of sinceTime or sinceSeconds can be provided")) + allErrs = append(allErrs, validation.NewFieldInvalid("sinceSeconds", *opts.SinceSeconds, "only one of sinceTime or sinceSeconds can be provided")) + allErrs = append(allErrs, validation.NewFieldInvalid("sinceTime", *opts.SinceTime, "only one of sinceTime or sinceSeconds can be provided")) case opts.SinceSeconds != nil: if *opts.SinceSeconds < 1 { - allErrs = append(allErrs, errs.NewFieldInvalid("sinceSeconds", *opts.SinceSeconds, "sinceSeconds must be a positive integer")) + allErrs = append(allErrs, validation.NewFieldInvalid("sinceSeconds", *opts.SinceSeconds, "sinceSeconds must be a positive integer")) } } return allErrs } // ValidateLoadBalancerStatus validates required fields on a LoadBalancerStatus -func ValidateLoadBalancerStatus(status *api.LoadBalancerStatus) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func ValidateLoadBalancerStatus(status *api.LoadBalancerStatus) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} for _, ingress := range status.Ingress { if len(ingress.IP) > 0 { if isIP := (net.ParseIP(ingress.IP) != nil); !isIP { - allErrs = append(allErrs, errs.NewFieldInvalid("ingress.ip", ingress.IP, "must be an IP address")) + allErrs = append(allErrs, validation.NewFieldInvalid("ingress.ip", ingress.IP, "must be an IP address")) } } if len(ingress.Hostname) > 0 { if valid, errMsg := NameIsDNSSubdomain(ingress.Hostname, false); !valid { - allErrs = append(allErrs, errs.NewFieldInvalid("ingress.hostname", ingress.Hostname, errMsg)) + allErrs = append(allErrs, validation.NewFieldInvalid("ingress.hostname", ingress.Hostname, errMsg)) } if isIP := (net.ParseIP(ingress.Hostname) != nil); isIP { - allErrs = append(allErrs, errs.NewFieldInvalid("ingress.hostname", ingress.Hostname, "must be a DNS name, not an IP address")) + allErrs = append(allErrs, validation.NewFieldInvalid("ingress.hostname", ingress.Hostname, "must be a DNS name, not an IP address")) } } } diff --git a/pkg/api/validation/validation_test.go b/pkg/api/validation/validation_test.go index 9419d6147da..29f4e5f348d 100644 --- a/pkg/api/validation/validation_test.go +++ b/pkg/api/validation/validation_test.go @@ -29,15 +29,14 @@ import ( "k8s.io/kubernetes/pkg/api/unversioned" "k8s.io/kubernetes/pkg/capabilities" utilerrors "k8s.io/kubernetes/pkg/util/errors" - "k8s.io/kubernetes/pkg/util/fielderrors" - errors "k8s.io/kubernetes/pkg/util/fielderrors" "k8s.io/kubernetes/pkg/util/intstr" "k8s.io/kubernetes/pkg/util/sets" + "k8s.io/kubernetes/pkg/util/validation" ) -func expectPrefix(t *testing.T, prefix string, errs fielderrors.ValidationErrorList) { +func expectPrefix(t *testing.T, prefix string, errs validation.ValidationErrorList) { for i := range errs { - if f, p := errs[i].(*errors.ValidationError).Field, prefix; !strings.HasPrefix(f, p) { + if f, p := errs[i].(*validation.ValidationError).Field, prefix; !strings.HasPrefix(f, p) { t.Errorf("expected prefix '%s' for field '%s' (%v)", p, f, errs[i]) } } @@ -151,7 +150,7 @@ func TestValidateLabels(t *testing.T) { if len(errs) != 1 { t.Errorf("case[%d] expected failure", i) } else { - detail := errs[0].(*errors.ValidationError).Detail + detail := errs[0].(*validation.ValidationError).Detail if detail != qualifiedNameErrorMsg { t.Errorf("error detail %s should be equal %s", detail, qualifiedNameErrorMsg) } @@ -169,7 +168,7 @@ func TestValidateLabels(t *testing.T) { if len(errs) != 1 { t.Errorf("case[%d] expected failure", i) } else { - detail := errs[0].(*errors.ValidationError).Detail + detail := errs[0].(*validation.ValidationError).Detail if detail != labelValueErrorMsg { t.Errorf("error detail %s should be equal %s", detail, labelValueErrorMsg) } @@ -216,7 +215,7 @@ func TestValidateAnnotations(t *testing.T) { if len(errs) != 1 { t.Errorf("case[%d] expected failure", i) } - detail := errs[0].(*errors.ValidationError).Detail + detail := errs[0].(*validation.ValidationError).Detail if detail != qualifiedNameErrorMsg { t.Errorf("error detail %s should be equal %s", detail, qualifiedNameErrorMsg) } @@ -537,30 +536,30 @@ func TestValidateVolumes(t *testing.T) { slashInName := api.VolumeSource{Flocker: &api.FlockerVolumeSource{DatasetName: "foo/bar"}} errorCases := map[string]struct { V []api.Volume - T errors.ValidationErrorType + T validation.ValidationErrorType F string D string }{ - "zero-length name": {[]api.Volume{{Name: "", VolumeSource: emptyVS}}, errors.ValidationErrorTypeRequired, "[0].name", ""}, - "name > 63 characters": {[]api.Volume{{Name: strings.Repeat("a", 64), VolumeSource: emptyVS}}, errors.ValidationErrorTypeInvalid, "[0].name", "must be a DNS label (at most 63 characters, matching regex [a-z0-9]([-a-z0-9]*[a-z0-9])?): e.g. \"my-name\""}, - "name not a DNS label": {[]api.Volume{{Name: "a.b.c", VolumeSource: emptyVS}}, errors.ValidationErrorTypeInvalid, "[0].name", "must be a DNS label (at most 63 characters, matching regex [a-z0-9]([-a-z0-9]*[a-z0-9])?): e.g. \"my-name\""}, - "name not unique": {[]api.Volume{{Name: "abc", VolumeSource: emptyVS}, {Name: "abc", VolumeSource: emptyVS}}, errors.ValidationErrorTypeDuplicate, "[1].name", ""}, - "empty portal": {[]api.Volume{{Name: "badportal", VolumeSource: emptyPortal}}, errors.ValidationErrorTypeRequired, "[0].source.iscsi.targetPortal", ""}, - "empty iqn": {[]api.Volume{{Name: "badiqn", VolumeSource: emptyIQN}}, errors.ValidationErrorTypeRequired, "[0].source.iscsi.iqn", ""}, - "empty hosts": {[]api.Volume{{Name: "badhost", VolumeSource: emptyHosts}}, errors.ValidationErrorTypeRequired, "[0].source.glusterfs.endpoints", ""}, - "empty path": {[]api.Volume{{Name: "badpath", VolumeSource: emptyPath}}, errors.ValidationErrorTypeRequired, "[0].source.glusterfs.path", ""}, - "empty datasetName": {[]api.Volume{{Name: "badname", VolumeSource: emptyName}}, errors.ValidationErrorTypeRequired, "[0].source.flocker.datasetName", ""}, - "empty mon": {[]api.Volume{{Name: "badmon", VolumeSource: emptyMon}}, errors.ValidationErrorTypeRequired, "[0].source.rbd.monitors", ""}, - "empty image": {[]api.Volume{{Name: "badimage", VolumeSource: emptyImage}}, errors.ValidationErrorTypeRequired, "[0].source.rbd.image", ""}, - "empty cephfs mon": {[]api.Volume{{Name: "badmon", VolumeSource: emptyCephFSMon}}, errors.ValidationErrorTypeRequired, "[0].source.cephfs.monitors", ""}, - "empty metatada path": {[]api.Volume{{Name: "emptyname", VolumeSource: emptyPathName}}, errors.ValidationErrorTypeRequired, "[0].source.downwardApi.path", ""}, - "absolute path": {[]api.Volume{{Name: "absolutepath", VolumeSource: absolutePathName}}, errors.ValidationErrorTypeForbidden, "[0].source.downwardApi.path", ""}, - "dot dot path": {[]api.Volume{{Name: "dotdotpath", VolumeSource: dotDotInPath}}, errors.ValidationErrorTypeInvalid, "[0].source.downwardApi.path", "must not contain \"..\"."}, - "dot dot file name": {[]api.Volume{{Name: "dotdotfilename", VolumeSource: dotDotPathName}}, errors.ValidationErrorTypeInvalid, "[0].source.downwardApi.path", "must not start with \"..\"."}, - "dot dot first level dirent": {[]api.Volume{{Name: "dotdotdirfilename", VolumeSource: dotDotFirstLevelDirent}}, errors.ValidationErrorTypeInvalid, "[0].source.downwardApi.path", "must not start with \"..\"."}, - "empty wwn": {[]api.Volume{{Name: "badimage", VolumeSource: zeroWWN}}, errors.ValidationErrorTypeRequired, "[0].source.fc.targetWWNs", ""}, - "empty lun": {[]api.Volume{{Name: "badimage", VolumeSource: emptyLun}}, errors.ValidationErrorTypeRequired, "[0].source.fc.lun", ""}, - "slash in datasetName": {[]api.Volume{{Name: "slashinname", VolumeSource: slashInName}}, errors.ValidationErrorTypeInvalid, "[0].source.flocker.datasetName", "must not contain '/'"}, + "zero-length name": {[]api.Volume{{Name: "", VolumeSource: emptyVS}}, validation.ValidationErrorTypeRequired, "[0].name", ""}, + "name > 63 characters": {[]api.Volume{{Name: strings.Repeat("a", 64), VolumeSource: emptyVS}}, validation.ValidationErrorTypeInvalid, "[0].name", "must be a DNS label (at most 63 characters, matching regex [a-z0-9]([-a-z0-9]*[a-z0-9])?): e.g. \"my-name\""}, + "name not a DNS label": {[]api.Volume{{Name: "a.b.c", VolumeSource: emptyVS}}, validation.ValidationErrorTypeInvalid, "[0].name", "must be a DNS label (at most 63 characters, matching regex [a-z0-9]([-a-z0-9]*[a-z0-9])?): e.g. \"my-name\""}, + "name not unique": {[]api.Volume{{Name: "abc", VolumeSource: emptyVS}, {Name: "abc", VolumeSource: emptyVS}}, validation.ValidationErrorTypeDuplicate, "[1].name", ""}, + "empty portal": {[]api.Volume{{Name: "badportal", VolumeSource: emptyPortal}}, validation.ValidationErrorTypeRequired, "[0].source.iscsi.targetPortal", ""}, + "empty iqn": {[]api.Volume{{Name: "badiqn", VolumeSource: emptyIQN}}, validation.ValidationErrorTypeRequired, "[0].source.iscsi.iqn", ""}, + "empty hosts": {[]api.Volume{{Name: "badhost", VolumeSource: emptyHosts}}, validation.ValidationErrorTypeRequired, "[0].source.glusterfs.endpoints", ""}, + "empty path": {[]api.Volume{{Name: "badpath", VolumeSource: emptyPath}}, validation.ValidationErrorTypeRequired, "[0].source.glusterfs.path", ""}, + "empty datasetName": {[]api.Volume{{Name: "badname", VolumeSource: emptyName}}, validation.ValidationErrorTypeRequired, "[0].source.flocker.datasetName", ""}, + "empty mon": {[]api.Volume{{Name: "badmon", VolumeSource: emptyMon}}, validation.ValidationErrorTypeRequired, "[0].source.rbd.monitors", ""}, + "empty image": {[]api.Volume{{Name: "badimage", VolumeSource: emptyImage}}, validation.ValidationErrorTypeRequired, "[0].source.rbd.image", ""}, + "empty cephfs mon": {[]api.Volume{{Name: "badmon", VolumeSource: emptyCephFSMon}}, validation.ValidationErrorTypeRequired, "[0].source.cephfs.monitors", ""}, + "empty metatada path": {[]api.Volume{{Name: "emptyname", VolumeSource: emptyPathName}}, validation.ValidationErrorTypeRequired, "[0].source.downwardApi.path", ""}, + "absolute path": {[]api.Volume{{Name: "absolutepath", VolumeSource: absolutePathName}}, validation.ValidationErrorTypeForbidden, "[0].source.downwardApi.path", ""}, + "dot dot path": {[]api.Volume{{Name: "dotdotpath", VolumeSource: dotDotInPath}}, validation.ValidationErrorTypeInvalid, "[0].source.downwardApi.path", "must not contain \"..\"."}, + "dot dot file name": {[]api.Volume{{Name: "dotdotfilename", VolumeSource: dotDotPathName}}, validation.ValidationErrorTypeInvalid, "[0].source.downwardApi.path", "must not start with \"..\"."}, + "dot dot first level dirent": {[]api.Volume{{Name: "dotdotdirfilename", VolumeSource: dotDotFirstLevelDirent}}, validation.ValidationErrorTypeInvalid, "[0].source.downwardApi.path", "must not start with \"..\"."}, + "empty wwn": {[]api.Volume{{Name: "badimage", VolumeSource: zeroWWN}}, validation.ValidationErrorTypeRequired, "[0].source.fc.targetWWNs", ""}, + "empty lun": {[]api.Volume{{Name: "badimage", VolumeSource: emptyLun}}, validation.ValidationErrorTypeRequired, "[0].source.fc.lun", ""}, + "slash in datasetName": {[]api.Volume{{Name: "slashinname", VolumeSource: slashInName}}, validation.ValidationErrorTypeInvalid, "[0].source.flocker.datasetName", "must not contain '/'"}, } for k, v := range errorCases { _, errs := validateVolumes(v.V) @@ -569,13 +568,13 @@ func TestValidateVolumes(t *testing.T) { continue } for i := range errs { - if errs[i].(*errors.ValidationError).Type != v.T { + if errs[i].(*validation.ValidationError).Type != v.T { t.Errorf("%s: expected errors to have type %s: %v", k, v.T, errs[i]) } - if errs[i].(*errors.ValidationError).Field != v.F { + if errs[i].(*validation.ValidationError).Field != v.F { t.Errorf("%s: expected errors to have field %s: %v", k, v.F, errs[i]) } - detail := errs[i].(*errors.ValidationError).Detail + detail := errs[i].(*validation.ValidationError).Detail if detail != v.D { t.Errorf("%s: expected error detail \"%s\", got \"%s\"", k, v.D, detail) } @@ -604,23 +603,23 @@ func TestValidatePorts(t *testing.T) { errorCases := map[string]struct { P []api.ContainerPort - T errors.ValidationErrorType + T validation.ValidationErrorType F string D string }{ - "name > 15 characters": {[]api.ContainerPort{{Name: strings.Repeat("a", 16), ContainerPort: 80, Protocol: "TCP"}}, errors.ValidationErrorTypeInvalid, "[0].name", PortNameErrorMsg}, - "name not a IANA svc name ": {[]api.ContainerPort{{Name: "a.b.c", ContainerPort: 80, Protocol: "TCP"}}, errors.ValidationErrorTypeInvalid, "[0].name", PortNameErrorMsg}, - "name not a IANA svc name (i.e. a number)": {[]api.ContainerPort{{Name: "80", ContainerPort: 80, Protocol: "TCP"}}, errors.ValidationErrorTypeInvalid, "[0].name", PortNameErrorMsg}, + "name > 15 characters": {[]api.ContainerPort{{Name: strings.Repeat("a", 16), ContainerPort: 80, Protocol: "TCP"}}, validation.ValidationErrorTypeInvalid, "[0].name", PortNameErrorMsg}, + "name not a IANA svc name ": {[]api.ContainerPort{{Name: "a.b.c", ContainerPort: 80, Protocol: "TCP"}}, validation.ValidationErrorTypeInvalid, "[0].name", PortNameErrorMsg}, + "name not a IANA svc name (i.e. a number)": {[]api.ContainerPort{{Name: "80", ContainerPort: 80, Protocol: "TCP"}}, validation.ValidationErrorTypeInvalid, "[0].name", PortNameErrorMsg}, "name not unique": {[]api.ContainerPort{ {Name: "abc", ContainerPort: 80, Protocol: "TCP"}, {Name: "abc", ContainerPort: 81, Protocol: "TCP"}, - }, errors.ValidationErrorTypeDuplicate, "[1].name", ""}, - "zero container port": {[]api.ContainerPort{{ContainerPort: 0, Protocol: "TCP"}}, errors.ValidationErrorTypeInvalid, "[0].containerPort", PortRangeErrorMsg}, - "invalid container port": {[]api.ContainerPort{{ContainerPort: 65536, Protocol: "TCP"}}, errors.ValidationErrorTypeInvalid, "[0].containerPort", PortRangeErrorMsg}, - "invalid host port": {[]api.ContainerPort{{ContainerPort: 80, HostPort: 65536, Protocol: "TCP"}}, errors.ValidationErrorTypeInvalid, "[0].hostPort", PortRangeErrorMsg}, - "invalid protocol case": {[]api.ContainerPort{{ContainerPort: 80, Protocol: "tcp"}}, errors.ValidationErrorTypeNotSupported, "[0].protocol", "supported values: TCP, UDP"}, - "invalid protocol": {[]api.ContainerPort{{ContainerPort: 80, Protocol: "ICMP"}}, errors.ValidationErrorTypeNotSupported, "[0].protocol", "supported values: TCP, UDP"}, - "protocol required": {[]api.ContainerPort{{Name: "abc", ContainerPort: 80}}, errors.ValidationErrorTypeRequired, "[0].protocol", ""}, + }, validation.ValidationErrorTypeDuplicate, "[1].name", ""}, + "zero container port": {[]api.ContainerPort{{ContainerPort: 0, Protocol: "TCP"}}, validation.ValidationErrorTypeInvalid, "[0].containerPort", PortRangeErrorMsg}, + "invalid container port": {[]api.ContainerPort{{ContainerPort: 65536, Protocol: "TCP"}}, validation.ValidationErrorTypeInvalid, "[0].containerPort", PortRangeErrorMsg}, + "invalid host port": {[]api.ContainerPort{{ContainerPort: 80, HostPort: 65536, Protocol: "TCP"}}, validation.ValidationErrorTypeInvalid, "[0].hostPort", PortRangeErrorMsg}, + "invalid protocol case": {[]api.ContainerPort{{ContainerPort: 80, Protocol: "tcp"}}, validation.ValidationErrorTypeNotSupported, "[0].protocol", "supported values: TCP, UDP"}, + "invalid protocol": {[]api.ContainerPort{{ContainerPort: 80, Protocol: "ICMP"}}, validation.ValidationErrorTypeNotSupported, "[0].protocol", "supported values: TCP, UDP"}, + "protocol required": {[]api.ContainerPort{{Name: "abc", ContainerPort: 80}}, validation.ValidationErrorTypeRequired, "[0].protocol", ""}, } for k, v := range errorCases { errs := validatePorts(v.P) @@ -628,13 +627,13 @@ func TestValidatePorts(t *testing.T) { t.Errorf("expected failure for %s", k) } for i := range errs { - if errs[i].(*errors.ValidationError).Type != v.T { + if errs[i].(*validation.ValidationError).Type != v.T { t.Errorf("%s: expected errors to have type %s: %v", k, v.T, errs[i]) } - if errs[i].(*errors.ValidationError).Field != v.F { + if errs[i].(*validation.ValidationError).Field != v.F { t.Errorf("%s: expected errors to have field %s: %v", k, v.F, errs[i]) } - detail := errs[i].(*errors.ValidationError).Detail + detail := errs[i].(*validation.ValidationError).Detail if detail != v.D { t.Errorf("%s: expected error detail either empty or %s, got %s", k, v.D, detail) } @@ -773,7 +772,7 @@ func TestValidateEnv(t *testing.T) { t.Errorf("expected failure for %s", tc.name) } else { for i := range errs { - str := errs[i].(*errors.ValidationError).Error() + str := errs[i].(*validation.ValidationError).Error() if str != "" && str != tc.expectedError { t.Errorf("%s: expected error detail either empty or %s, got %s", tc.name, tc.expectedError, str) } @@ -2561,7 +2560,7 @@ func TestValidateReplicationController(t *testing.T) { t.Errorf("expected failure for %s", k) } for i := range errs { - field := errs[i].(*errors.ValidationError).Field + field := errs[i].(*validation.ValidationError).Field if !strings.HasPrefix(field, "spec.template.") && field != "metadata.name" && field != "metadata.namespace" && @@ -2677,7 +2676,7 @@ func TestValidateNode(t *testing.T) { t.Errorf("expected failure for %s", k) } for i := range errs { - field := errs[i].(*errors.ValidationError).Field + field := errs[i].(*validation.ValidationError).Field expectedFields := map[string]bool{ "metadata.name": true, "metadata.labels": true, @@ -3009,7 +3008,7 @@ func TestValidateResourceNames(t *testing.T) { } else if len(err) == 0 && !item.success { t.Errorf("expected failure for input %q", item.input) for i := range err { - detail := err[i].(*errors.ValidationError).Detail + detail := err[i].(*validation.ValidationError).Detail if detail != "" && detail != qualifiedNameErrorMsg { t.Errorf("%d: expected error detail either empty or %s, got %s", k, qualifiedNameErrorMsg, detail) } @@ -3225,7 +3224,7 @@ func TestValidateLimitRange(t *testing.T) { t.Errorf("expected failure for %s", k) } for i := range errs { - detail := errs[i].(*errors.ValidationError).Detail + detail := errs[i].(*validation.ValidationError).Detail if detail != v.D { t.Errorf("%s: expected error detail either empty or %s, got %s", k, v.D, detail) } @@ -3330,8 +3329,8 @@ func TestValidateResourceQuota(t *testing.T) { t.Errorf("expected failure for %s", k) } for i := range errs { - field := errs[i].(*errors.ValidationError).Field - detail := errs[i].(*errors.ValidationError).Detail + field := errs[i].(*validation.ValidationError).Field + detail := errs[i].(*validation.ValidationError).Detail if field != "metadata.name" && field != "metadata.namespace" && !api.IsStandardResourceName(field) { t.Errorf("%s: missing prefix for: %v", k, field) } @@ -3765,7 +3764,7 @@ func TestValidateEndpoints(t *testing.T) { errorCases := map[string]struct { endpoints api.Endpoints - errorType fielderrors.ValidationErrorType + errorType validation.ValidationErrorType errorDetail string }{ "missing namespace": { @@ -3938,7 +3937,7 @@ func TestValidateEndpoints(t *testing.T) { } for k, v := range errorCases { - if errs := ValidateEndpoints(&v.endpoints); len(errs) == 0 || errs[0].(*errors.ValidationError).Type != v.errorType || !strings.Contains(errs[0].(*errors.ValidationError).Detail, v.errorDetail) { + if errs := ValidateEndpoints(&v.endpoints); len(errs) == 0 || errs[0].(*validation.ValidationError).Type != v.errorType || !strings.Contains(errs[0].(*validation.ValidationError).Detail, v.errorDetail) { t.Errorf("Expected error type %s with detail %s for %s, got %v", v.errorType, v.errorDetail, k, errs) } } @@ -4003,7 +4002,7 @@ func TestValidateSecurityContext(t *testing.T) { errorCases := map[string]struct { sc *api.SecurityContext - errorType fielderrors.ValidationErrorType + errorType validation.ValidationErrorType errorDetail string }{ "request privileged when capabilities forbids": { @@ -4018,7 +4017,7 @@ func TestValidateSecurityContext(t *testing.T) { }, } for k, v := range errorCases { - if errs := ValidateSecurityContext(v.sc); len(errs) == 0 || errs[0].(*errors.ValidationError).Type != v.errorType || errs[0].(*errors.ValidationError).Detail != v.errorDetail { + if errs := ValidateSecurityContext(v.sc); len(errs) == 0 || errs[0].(*validation.ValidationError).Type != v.errorType || errs[0].(*validation.ValidationError).Detail != v.errorDetail { t.Errorf("Expected error type %s with detail %s for %s, got %v", v.errorType, v.errorDetail, k, errs) } } diff --git a/pkg/apis/extensions/validation/validation.go b/pkg/apis/extensions/validation/validation.go index b1b802793cb..0ade330a52b 100644 --- a/pkg/apis/extensions/validation/validation.go +++ b/pkg/apis/extensions/validation/validation.go @@ -27,11 +27,9 @@ import ( apivalidation "k8s.io/kubernetes/pkg/api/validation" "k8s.io/kubernetes/pkg/apis/extensions" "k8s.io/kubernetes/pkg/labels" - errs "k8s.io/kubernetes/pkg/util/fielderrors" "k8s.io/kubernetes/pkg/util/intstr" "k8s.io/kubernetes/pkg/util/sets" "k8s.io/kubernetes/pkg/util/validation" - utilvalidation "k8s.io/kubernetes/pkg/util/validation" ) // ValidateHorizontalPodAutoscaler can be used to check whether the given autoscaler name is valid. @@ -41,66 +39,66 @@ func ValidateHorizontalPodAutoscalerName(name string, prefix bool) (bool, string return apivalidation.ValidateReplicationControllerName(name, prefix) } -func validateHorizontalPodAutoscalerSpec(autoscaler extensions.HorizontalPodAutoscalerSpec) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func validateHorizontalPodAutoscalerSpec(autoscaler extensions.HorizontalPodAutoscalerSpec) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} if autoscaler.MinReplicas != nil && *autoscaler.MinReplicas < 1 { - allErrs = append(allErrs, errs.NewFieldInvalid("minReplicas", autoscaler.MinReplicas, `must be bigger or equal to 1`)) + allErrs = append(allErrs, validation.NewFieldInvalid("minReplicas", autoscaler.MinReplicas, `must be bigger or equal to 1`)) } if autoscaler.MaxReplicas < 1 { - allErrs = append(allErrs, errs.NewFieldInvalid("maxReplicas", autoscaler.MaxReplicas, `must be bigger or equal to 1`)) + allErrs = append(allErrs, validation.NewFieldInvalid("maxReplicas", autoscaler.MaxReplicas, `must be bigger or equal to 1`)) } if autoscaler.MinReplicas != nil && autoscaler.MaxReplicas < *autoscaler.MinReplicas { - allErrs = append(allErrs, errs.NewFieldInvalid("maxReplicas", autoscaler.MaxReplicas, `must be bigger or equal to minReplicas`)) + allErrs = append(allErrs, validation.NewFieldInvalid("maxReplicas", autoscaler.MaxReplicas, `must be bigger or equal to minReplicas`)) } if autoscaler.CPUUtilization != nil && autoscaler.CPUUtilization.TargetPercentage < 1 { - allErrs = append(allErrs, errs.NewFieldInvalid("cpuUtilization.targetPercentage", autoscaler.CPUUtilization.TargetPercentage, `must be bigger or equal to 1`)) + allErrs = append(allErrs, validation.NewFieldInvalid("cpuUtilization.targetPercentage", autoscaler.CPUUtilization.TargetPercentage, `must be bigger or equal to 1`)) } if refErrs := ValidateSubresourceReference(autoscaler.ScaleRef); len(refErrs) > 0 { allErrs = append(allErrs, refErrs.Prefix("scaleRef")...) } else if autoscaler.ScaleRef.Subresource != "scale" { - allErrs = append(allErrs, errs.NewFieldValueNotSupported("scaleRef.subresource", autoscaler.ScaleRef.Subresource, []string{"scale"})) + allErrs = append(allErrs, validation.NewFieldValueNotSupported("scaleRef.subresource", autoscaler.ScaleRef.Subresource, []string{"scale"})) } return allErrs } -func ValidateSubresourceReference(ref extensions.SubresourceReference) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func ValidateSubresourceReference(ref extensions.SubresourceReference) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} if len(ref.Kind) == 0 { - allErrs = append(allErrs, errs.NewFieldRequired("kind")) + allErrs = append(allErrs, validation.NewFieldRequired("kind")) } else if ok, msg := apivalidation.IsValidPathSegmentName(ref.Kind); !ok { - allErrs = append(allErrs, errs.NewFieldInvalid("kind", ref.Kind, msg)) + allErrs = append(allErrs, validation.NewFieldInvalid("kind", ref.Kind, msg)) } if len(ref.Name) == 0 { - allErrs = append(allErrs, errs.NewFieldRequired("name")) + allErrs = append(allErrs, validation.NewFieldRequired("name")) } else if ok, msg := apivalidation.IsValidPathSegmentName(ref.Name); !ok { - allErrs = append(allErrs, errs.NewFieldInvalid("name", ref.Name, msg)) + allErrs = append(allErrs, validation.NewFieldInvalid("name", ref.Name, msg)) } if len(ref.Subresource) == 0 { - allErrs = append(allErrs, errs.NewFieldRequired("subresource")) + allErrs = append(allErrs, validation.NewFieldRequired("subresource")) } else if ok, msg := apivalidation.IsValidPathSegmentName(ref.Subresource); !ok { - allErrs = append(allErrs, errs.NewFieldInvalid("subresource", ref.Subresource, msg)) + allErrs = append(allErrs, validation.NewFieldInvalid("subresource", ref.Subresource, msg)) } return allErrs } -func ValidateHorizontalPodAutoscaler(autoscaler *extensions.HorizontalPodAutoscaler) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func ValidateHorizontalPodAutoscaler(autoscaler *extensions.HorizontalPodAutoscaler) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} allErrs = append(allErrs, apivalidation.ValidateObjectMeta(&autoscaler.ObjectMeta, true, ValidateHorizontalPodAutoscalerName).Prefix("metadata")...) allErrs = append(allErrs, validateHorizontalPodAutoscalerSpec(autoscaler.Spec)...) return allErrs } -func ValidateHorizontalPodAutoscalerUpdate(newAutoscler, oldAutoscaler *extensions.HorizontalPodAutoscaler) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func ValidateHorizontalPodAutoscalerUpdate(newAutoscler, oldAutoscaler *extensions.HorizontalPodAutoscaler) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} allErrs = append(allErrs, apivalidation.ValidateObjectMetaUpdate(&newAutoscler.ObjectMeta, &oldAutoscaler.ObjectMeta).Prefix("metadata")...) allErrs = append(allErrs, validateHorizontalPodAutoscalerSpec(newAutoscler.Spec)...) return allErrs } -func ValidateHorizontalPodAutoscalerStatusUpdate(controller, oldController *extensions.HorizontalPodAutoscaler) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func ValidateHorizontalPodAutoscalerStatusUpdate(controller, oldController *extensions.HorizontalPodAutoscaler) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} allErrs = append(allErrs, apivalidation.ValidateObjectMetaUpdate(&controller.ObjectMeta, &oldController.ObjectMeta).Prefix("metadata")...) status := controller.Status @@ -109,8 +107,8 @@ func ValidateHorizontalPodAutoscalerStatusUpdate(controller, oldController *exte return allErrs } -func ValidateThirdPartyResourceUpdate(update, old *extensions.ThirdPartyResource) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func ValidateThirdPartyResourceUpdate(update, old *extensions.ThirdPartyResource) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} allErrs = append(allErrs, apivalidation.ValidateObjectMetaUpdate(&update.ObjectMeta, &old.ObjectMeta).Prefix("metadata")...) allErrs = append(allErrs, ValidateThirdPartyResource(update)...) return allErrs @@ -120,18 +118,18 @@ func ValidateThirdPartyResourceName(name string, prefix bool) (bool, string) { return apivalidation.NameIsDNSSubdomain(name, prefix) } -func ValidateThirdPartyResource(obj *extensions.ThirdPartyResource) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func ValidateThirdPartyResource(obj *extensions.ThirdPartyResource) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} allErrs = append(allErrs, apivalidation.ValidateObjectMeta(&obj.ObjectMeta, true, ValidateThirdPartyResourceName).Prefix("metadata")...) versions := sets.String{} for ix := range obj.Versions { version := &obj.Versions[ix] if len(version.Name) == 0 { - allErrs = append(allErrs, errs.NewFieldInvalid("name", version, "name can not be empty")) + allErrs = append(allErrs, validation.NewFieldInvalid("name", version, "name can not be empty")) } if versions.Has(version.Name) { - allErrs = append(allErrs, errs.NewFieldDuplicate("version", version)) + allErrs = append(allErrs, validation.NewFieldDuplicate("version", version)) } versions.Insert(version.Name) } @@ -139,16 +137,16 @@ func ValidateThirdPartyResource(obj *extensions.ThirdPartyResource) errs.Validat } // ValidateDaemonSet tests if required fields in the DaemonSet are set. -func ValidateDaemonSet(controller *extensions.DaemonSet) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func ValidateDaemonSet(controller *extensions.DaemonSet) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} allErrs = append(allErrs, apivalidation.ValidateObjectMeta(&controller.ObjectMeta, true, ValidateDaemonSetName).Prefix("metadata")...) allErrs = append(allErrs, ValidateDaemonSetSpec(&controller.Spec).Prefix("spec")...) return allErrs } // ValidateDaemonSetUpdate tests if required fields in the DaemonSet are set. -func ValidateDaemonSetUpdate(controller, oldController *extensions.DaemonSet) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func ValidateDaemonSetUpdate(controller, oldController *extensions.DaemonSet) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} allErrs = append(allErrs, apivalidation.ValidateObjectMetaUpdate(&controller.ObjectMeta, &oldController.ObjectMeta).Prefix("metadata")...) allErrs = append(allErrs, ValidateDaemonSetSpec(&controller.Spec).Prefix("spec")...) allErrs = append(allErrs, ValidateDaemonSetTemplateUpdate(controller.Spec.Template, oldController.Spec.Template).Prefix("spec.template")...) @@ -156,8 +154,8 @@ func ValidateDaemonSetUpdate(controller, oldController *extensions.DaemonSet) er } // validateDaemonSetStatus validates a DaemonSetStatus -func validateDaemonSetStatus(status *extensions.DaemonSetStatus) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func validateDaemonSetStatus(status *extensions.DaemonSetStatus) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} allErrs = append(allErrs, apivalidation.ValidatePositiveField(int64(status.CurrentNumberScheduled), "currentNumberScheduled")...) allErrs = append(allErrs, apivalidation.ValidatePositiveField(int64(status.NumberMisscheduled), "numberMisscheduled")...) allErrs = append(allErrs, apivalidation.ValidatePositiveField(int64(status.DesiredNumberScheduled), "desiredNumberScheduled")...) @@ -165,16 +163,16 @@ func validateDaemonSetStatus(status *extensions.DaemonSetStatus) errs.Validation } // ValidateDaemonSetStatus validates tests if required fields in the DaemonSet Status section -func ValidateDaemonSetStatusUpdate(controller, oldController *extensions.DaemonSet) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func ValidateDaemonSetStatusUpdate(controller, oldController *extensions.DaemonSet) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} allErrs = append(allErrs, apivalidation.ValidateObjectMetaUpdate(&controller.ObjectMeta, &oldController.ObjectMeta).Prefix("metadata")...) allErrs = append(allErrs, validateDaemonSetStatus(&controller.Status)...) return allErrs } // ValidateDaemonSetTemplateUpdate tests that certain fields in the daemon set's pod template are not updated. -func ValidateDaemonSetTemplateUpdate(podTemplate, oldPodTemplate *api.PodTemplateSpec) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func ValidateDaemonSetTemplateUpdate(podTemplate, oldPodTemplate *api.PodTemplateSpec) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} podSpec := podTemplate.Spec // podTemplate.Spec is not a pointer, so we can modify NodeSelector and NodeName directly. podSpec.NodeSelector = oldPodTemplate.Spec.NodeSelector @@ -182,25 +180,25 @@ func ValidateDaemonSetTemplateUpdate(podTemplate, oldPodTemplate *api.PodTemplat // In particular, we do not allow updates to container images at this point. if !api.Semantic.DeepEqual(oldPodTemplate.Spec, podSpec) { // TODO: Pinpoint the specific field that causes the invalid error after we have strategic merge diff - allErrs = append(allErrs, errs.NewFieldInvalid("spec", "content of spec is not printed out, please refer to the \"details\"", "may not update fields other than spec.nodeSelector")) + allErrs = append(allErrs, validation.NewFieldInvalid("spec", "content of spec is not printed out, please refer to the \"details\"", "may not update fields other than spec.nodeSelector")) } return allErrs } // ValidateDaemonSetSpec tests if required fields in the DaemonSetSpec are set. -func ValidateDaemonSetSpec(spec *extensions.DaemonSetSpec) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func ValidateDaemonSetSpec(spec *extensions.DaemonSetSpec) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} allErrs = append(allErrs, ValidatePodSelector(spec.Selector)...) if spec.Template == nil { - allErrs = append(allErrs, errs.NewFieldRequired("template")) + allErrs = append(allErrs, validation.NewFieldRequired("template")) return allErrs } selector, err := extensions.PodSelectorAsSelector(spec.Selector) if err == nil && !selector.Matches(labels.Set(spec.Template.Labels)) { - allErrs = append(allErrs, errs.NewFieldInvalid("template.metadata.labels", spec.Template.Labels, "selector does not match template")) + allErrs = append(allErrs, validation.NewFieldInvalid("template.metadata.labels", spec.Template.Labels, "selector does not match template")) } allErrs = append(allErrs, apivalidation.ValidatePodTemplateSpec(spec.Template).Prefix("template")...) @@ -208,7 +206,7 @@ func ValidateDaemonSetSpec(spec *extensions.DaemonSetSpec) errs.ValidationErrorL allErrs = append(allErrs, apivalidation.ValidateReadOnlyPersistentDisks(spec.Template.Spec.Volumes).Prefix("template.spec.volumes")...) // RestartPolicy has already been first-order validated as per ValidatePodTemplateSpec(). if spec.Template.Spec.RestartPolicy != api.RestartPolicyAlways { - allErrs = append(allErrs, errs.NewFieldValueNotSupported("template.spec.restartPolicy", spec.Template.Spec.RestartPolicy, []string{string(api.RestartPolicyAlways)})) + allErrs = append(allErrs, validation.NewFieldValueNotSupported("template.spec.restartPolicy", spec.Template.Spec.RestartPolicy, []string{string(api.RestartPolicyAlways)})) } return allErrs @@ -226,11 +224,11 @@ func ValidateDeploymentName(name string, prefix bool) (bool, string) { return apivalidation.NameIsDNSSubdomain(name, prefix) } -func ValidatePositiveIntOrPercent(intOrPercent intstr.IntOrString, fieldName string) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func ValidatePositiveIntOrPercent(intOrPercent intstr.IntOrString, fieldName string) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} if intOrPercent.Type == intstr.String { if !validation.IsValidPercent(intOrPercent.StrVal) { - allErrs = append(allErrs, errs.NewFieldInvalid(fieldName, intOrPercent, "value should be int(5) or percentage(5%)")) + allErrs = append(allErrs, validation.NewFieldInvalid(fieldName, intOrPercent, "value should be int(5) or percentage(5%)")) } } else if intOrPercent.Type == intstr.Int { allErrs = append(allErrs, apivalidation.ValidatePositiveField(int64(intOrPercent.IntVal), fieldName)...) @@ -254,23 +252,23 @@ func getIntOrPercentValue(intOrStringValue intstr.IntOrString) int { return intOrStringValue.IntVal } -func IsNotMoreThan100Percent(intOrStringValue intstr.IntOrString, fieldName string) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func IsNotMoreThan100Percent(intOrStringValue intstr.IntOrString, fieldName string) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} value, isPercent := getPercentValue(intOrStringValue) if !isPercent || value <= 100 { return nil } - allErrs = append(allErrs, errs.NewFieldInvalid(fieldName, intOrStringValue, "should not be more than 100%")) + allErrs = append(allErrs, validation.NewFieldInvalid(fieldName, intOrStringValue, "should not be more than 100%")) return allErrs } -func ValidateRollingUpdateDeployment(rollingUpdate *extensions.RollingUpdateDeployment, fieldName string) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func ValidateRollingUpdateDeployment(rollingUpdate *extensions.RollingUpdateDeployment, fieldName string) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} allErrs = append(allErrs, ValidatePositiveIntOrPercent(rollingUpdate.MaxUnavailable, fieldName+"maxUnavailable")...) allErrs = append(allErrs, ValidatePositiveIntOrPercent(rollingUpdate.MaxSurge, fieldName+".maxSurge")...) if getIntOrPercentValue(rollingUpdate.MaxUnavailable) == 0 && getIntOrPercentValue(rollingUpdate.MaxSurge) == 0 { // Both MaxSurge and MaxUnavailable cannot be zero. - allErrs = append(allErrs, errs.NewFieldInvalid(fieldName+".maxUnavailable", rollingUpdate.MaxUnavailable, "cannot be 0 when maxSurge is 0 as well")) + allErrs = append(allErrs, validation.NewFieldInvalid(fieldName+".maxUnavailable", rollingUpdate.MaxUnavailable, "cannot be 0 when maxSurge is 0 as well")) } // Validate that MaxUnavailable is not more than 100%. allErrs = append(allErrs, IsNotMoreThan100Percent(rollingUpdate.MaxUnavailable, fieldName+".maxUnavailable")...) @@ -278,14 +276,14 @@ func ValidateRollingUpdateDeployment(rollingUpdate *extensions.RollingUpdateDepl return allErrs } -func ValidateDeploymentStrategy(strategy *extensions.DeploymentStrategy, fieldName string) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func ValidateDeploymentStrategy(strategy *extensions.DeploymentStrategy, fieldName string) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} if strategy.RollingUpdate == nil { return allErrs } switch strategy.Type { case extensions.RecreateDeploymentStrategyType: - allErrs = append(allErrs, errs.NewFieldForbidden("rollingUpdate", "rollingUpdate should be nil when strategy type is "+extensions.RecreateDeploymentStrategyType)) + allErrs = append(allErrs, validation.NewFieldForbidden("rollingUpdate", "rollingUpdate should be nil when strategy type is "+extensions.RecreateDeploymentStrategyType)) case extensions.RollingUpdateDeploymentStrategyType: allErrs = append(allErrs, ValidateRollingUpdateDeployment(strategy.RollingUpdate, "rollingUpdate")...) } @@ -293,8 +291,8 @@ func ValidateDeploymentStrategy(strategy *extensions.DeploymentStrategy, fieldNa } // Validates given deployment spec. -func ValidateDeploymentSpec(spec *extensions.DeploymentSpec) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func ValidateDeploymentSpec(spec *extensions.DeploymentSpec) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} allErrs = append(allErrs, apivalidation.ValidateNonEmptySelector(spec.Selector, "selector")...) allErrs = append(allErrs, apivalidation.ValidatePositiveField(int64(spec.Replicas), "replicas")...) allErrs = append(allErrs, apivalidation.ValidatePodTemplateSpecForRC(&spec.Template, spec.Selector, spec.Replicas, "template")...) @@ -303,42 +301,42 @@ func ValidateDeploymentSpec(spec *extensions.DeploymentSpec) errs.ValidationErro return allErrs } -func ValidateDeploymentUpdate(update, old *extensions.Deployment) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func ValidateDeploymentUpdate(update, old *extensions.Deployment) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} allErrs = append(allErrs, apivalidation.ValidateObjectMetaUpdate(&update.ObjectMeta, &old.ObjectMeta).Prefix("metadata")...) allErrs = append(allErrs, ValidateDeploymentSpec(&update.Spec).Prefix("spec")...) return allErrs } -func ValidateDeployment(obj *extensions.Deployment) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func ValidateDeployment(obj *extensions.Deployment) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} allErrs = append(allErrs, apivalidation.ValidateObjectMeta(&obj.ObjectMeta, true, ValidateDeploymentName).Prefix("metadata")...) allErrs = append(allErrs, ValidateDeploymentSpec(&obj.Spec).Prefix("spec")...) return allErrs } -func ValidateThirdPartyResourceDataUpdate(update, old *extensions.ThirdPartyResourceData) errs.ValidationErrorList { +func ValidateThirdPartyResourceDataUpdate(update, old *extensions.ThirdPartyResourceData) validation.ValidationErrorList { return ValidateThirdPartyResourceData(update) } -func ValidateThirdPartyResourceData(obj *extensions.ThirdPartyResourceData) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func ValidateThirdPartyResourceData(obj *extensions.ThirdPartyResourceData) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} if len(obj.Name) == 0 { - allErrs = append(allErrs, errs.NewFieldInvalid("name", obj.Name, "name must be non-empty")) + allErrs = append(allErrs, validation.NewFieldInvalid("name", obj.Name, "name must be non-empty")) } return allErrs } -func ValidateJob(job *extensions.Job) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func ValidateJob(job *extensions.Job) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} // Jobs and rcs have the same name validation allErrs = append(allErrs, apivalidation.ValidateObjectMeta(&job.ObjectMeta, true, apivalidation.ValidateReplicationControllerName).Prefix("metadata")...) allErrs = append(allErrs, ValidateJobSpec(&job.Spec).Prefix("spec")...) return allErrs } -func ValidateJobSpec(spec *extensions.JobSpec) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func ValidateJobSpec(spec *extensions.JobSpec) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} if spec.Parallelism != nil { allErrs = append(allErrs, apivalidation.ValidatePositiveField(int64(*spec.Parallelism), "parallelism")...) @@ -347,7 +345,7 @@ func ValidateJobSpec(spec *extensions.JobSpec) errs.ValidationErrorList { allErrs = append(allErrs, apivalidation.ValidatePositiveField(int64(*spec.Completions), "completions")...) } if spec.Selector == nil { - allErrs = append(allErrs, errs.NewFieldRequired("selector")) + allErrs = append(allErrs, validation.NewFieldRequired("selector")) } else { allErrs = append(allErrs, ValidatePodSelector(spec.Selector).Prefix("selector")...) } @@ -355,43 +353,43 @@ func ValidateJobSpec(spec *extensions.JobSpec) errs.ValidationErrorList { if selector, err := extensions.PodSelectorAsSelector(spec.Selector); err == nil { labels := labels.Set(spec.Template.Labels) if !selector.Matches(labels) { - allErrs = append(allErrs, errs.NewFieldInvalid("template.metadata.labels", spec.Template.Labels, "selector does not match template")) + allErrs = append(allErrs, validation.NewFieldInvalid("template.metadata.labels", spec.Template.Labels, "selector does not match template")) } } allErrs = append(allErrs, apivalidation.ValidatePodTemplateSpec(&spec.Template).Prefix("template")...) if spec.Template.Spec.RestartPolicy != api.RestartPolicyOnFailure && spec.Template.Spec.RestartPolicy != api.RestartPolicyNever { - allErrs = append(allErrs, errs.NewFieldValueNotSupported("template.spec.restartPolicy", + allErrs = append(allErrs, validation.NewFieldValueNotSupported("template.spec.restartPolicy", spec.Template.Spec.RestartPolicy, []string{string(api.RestartPolicyOnFailure), string(api.RestartPolicyNever)})) } return allErrs } -func ValidateJobStatus(status *extensions.JobStatus) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func ValidateJobStatus(status *extensions.JobStatus) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} allErrs = append(allErrs, apivalidation.ValidatePositiveField(int64(status.Active), "active")...) allErrs = append(allErrs, apivalidation.ValidatePositiveField(int64(status.Succeeded), "succeeded")...) allErrs = append(allErrs, apivalidation.ValidatePositiveField(int64(status.Failed), "failed")...) return allErrs } -func ValidateJobUpdate(job, oldJob *extensions.Job) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func ValidateJobUpdate(job, oldJob *extensions.Job) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} allErrs = append(allErrs, apivalidation.ValidateObjectMetaUpdate(&oldJob.ObjectMeta, &job.ObjectMeta).Prefix("metadata")...) allErrs = append(allErrs, ValidateJobSpecUpdate(job.Spec, oldJob.Spec).Prefix("spec")...) return allErrs } -func ValidateJobUpdateStatus(job, oldJob *extensions.Job) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func ValidateJobUpdateStatus(job, oldJob *extensions.Job) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} allErrs = append(allErrs, apivalidation.ValidateObjectMetaUpdate(&oldJob.ObjectMeta, &job.ObjectMeta).Prefix("metadata")...) allErrs = append(allErrs, ValidateJobStatusUpdate(job.Status, oldJob.Status).Prefix("status")...) return allErrs } -func ValidateJobSpecUpdate(spec, oldSpec extensions.JobSpec) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func ValidateJobSpecUpdate(spec, oldSpec extensions.JobSpec) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} allErrs = append(allErrs, ValidateJobSpec(&spec)...) allErrs = append(allErrs, apivalidation.ValidateImmutableField(spec.Completions, oldSpec.Completions, "completions")...) allErrs = append(allErrs, apivalidation.ValidateImmutableField(spec.Selector, oldSpec.Selector, "selector")...) @@ -399,15 +397,15 @@ func ValidateJobSpecUpdate(spec, oldSpec extensions.JobSpec) errs.ValidationErro return allErrs } -func ValidateJobStatusUpdate(status, oldStatus extensions.JobStatus) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func ValidateJobStatusUpdate(status, oldStatus extensions.JobStatus) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} allErrs = append(allErrs, ValidateJobStatus(&status)...) return allErrs } // ValidateIngress tests if required fields in the Ingress are set. -func ValidateIngress(ingress *extensions.Ingress) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func ValidateIngress(ingress *extensions.Ingress) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} allErrs = append(allErrs, apivalidation.ValidateObjectMeta(&ingress.ObjectMeta, true, ValidateIngressName).Prefix("metadata")...) allErrs = append(allErrs, ValidateIngressSpec(&ingress.Spec).Prefix("spec")...) return allErrs @@ -419,13 +417,13 @@ func ValidateIngressName(name string, prefix bool) (bool, string) { } // ValidateIngressSpec tests if required fields in the IngressSpec are set. -func ValidateIngressSpec(spec *extensions.IngressSpec) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func ValidateIngressSpec(spec *extensions.IngressSpec) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} // TODO: Is a default backend mandatory? if spec.Backend != nil { allErrs = append(allErrs, validateIngressBackend(spec.Backend).Prefix("backend")...) } else if len(spec.Rules) == 0 { - allErrs = append(allErrs, errs.NewFieldInvalid("rules", spec.Rules, "Either a default backend or a set of host rules are required for ingress.")) + allErrs = append(allErrs, validation.NewFieldInvalid("rules", spec.Rules, "Either a default backend or a set of host rules are required for ingress.")) } if len(spec.Rules) > 0 { allErrs = append(allErrs, validateIngressRules(spec.Rules).Prefix("rules")...) @@ -434,35 +432,35 @@ func ValidateIngressSpec(spec *extensions.IngressSpec) errs.ValidationErrorList } // ValidateIngressUpdate tests if required fields in the Ingress are set. -func ValidateIngressUpdate(ingress, oldIngress *extensions.Ingress) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func ValidateIngressUpdate(ingress, oldIngress *extensions.Ingress) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} allErrs = append(allErrs, apivalidation.ValidateObjectMetaUpdate(&ingress.ObjectMeta, &oldIngress.ObjectMeta).Prefix("metadata")...) allErrs = append(allErrs, ValidateIngressSpec(&ingress.Spec).Prefix("spec")...) return allErrs } // ValidateIngressStatusUpdate tests if required fields in the Ingress are set when updating status. -func ValidateIngressStatusUpdate(ingress, oldIngress *extensions.Ingress) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func ValidateIngressStatusUpdate(ingress, oldIngress *extensions.Ingress) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} allErrs = append(allErrs, apivalidation.ValidateObjectMetaUpdate(&ingress.ObjectMeta, &oldIngress.ObjectMeta).Prefix("metadata")...) allErrs = append(allErrs, apivalidation.ValidateLoadBalancerStatus(&ingress.Status.LoadBalancer).Prefix("status.loadBalancer")...) return allErrs } -func validateIngressRules(IngressRules []extensions.IngressRule) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func validateIngressRules(IngressRules []extensions.IngressRule) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} if len(IngressRules) == 0 { - return append(allErrs, errs.NewFieldRequired("IngressRules")) + return append(allErrs, validation.NewFieldRequired("IngressRules")) } for _, ih := range IngressRules { if len(ih.Host) > 0 { // TODO: Ports and ips are allowed in the host part of a url // according to RFC 3986, consider allowing them. if valid, errMsg := apivalidation.NameIsDNSSubdomain(ih.Host, false); !valid { - allErrs = append(allErrs, errs.NewFieldInvalid("host", ih.Host, errMsg)) + allErrs = append(allErrs, validation.NewFieldInvalid("host", ih.Host, errMsg)) } if isIP := (net.ParseIP(ih.Host) != nil); isIP { - allErrs = append(allErrs, errs.NewFieldInvalid("host", ih.Host, "Host must be a DNS name, not ip address")) + allErrs = append(allErrs, validation.NewFieldInvalid("host", ih.Host, "Host must be a DNS name, not ip address")) } } allErrs = append(allErrs, validateIngressRuleValue(&ih.IngressRuleValue).Prefix("ingressRule")...) @@ -470,23 +468,23 @@ func validateIngressRules(IngressRules []extensions.IngressRule) errs.Validation return allErrs } -func validateIngressRuleValue(ingressRule *extensions.IngressRuleValue) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func validateIngressRuleValue(ingressRule *extensions.IngressRuleValue) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} if ingressRule.HTTP != nil { allErrs = append(allErrs, validateHTTPIngressRuleValue(ingressRule.HTTP).Prefix("http")...) } return allErrs } -func validateHTTPIngressRuleValue(httpIngressRuleValue *extensions.HTTPIngressRuleValue) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func validateHTTPIngressRuleValue(httpIngressRuleValue *extensions.HTTPIngressRuleValue) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} if len(httpIngressRuleValue.Paths) == 0 { - allErrs = append(allErrs, errs.NewFieldRequired("paths")) + allErrs = append(allErrs, validation.NewFieldRequired("paths")) } for _, rule := range httpIngressRuleValue.Paths { if len(rule.Path) > 0 { if !strings.HasPrefix(rule.Path, "/") { - allErrs = append(allErrs, errs.NewFieldInvalid("path", rule.Path, "path must begin with /")) + allErrs = append(allErrs, validation.NewFieldInvalid("path", rule.Path, "path must begin with /")) } // TODO: More draconian path regex validation. // Path must be a valid regex. This is the basic requirement. @@ -499,7 +497,7 @@ func validateHTTPIngressRuleValue(httpIngressRuleValue *extensions.HTTPIngressRu // the user is confusing url regexes with path regexes. _, err := regexp.CompilePOSIX(rule.Path) if err != nil { - allErrs = append(allErrs, errs.NewFieldInvalid("path", rule.Path, "httpIngressRuleValue.path must be a valid regex.")) + allErrs = append(allErrs, validation.NewFieldInvalid("path", rule.Path, "httpIngressRuleValue.path must be a valid regex.")) } } allErrs = append(allErrs, validateIngressBackend(&rule.Backend).Prefix("backend")...) @@ -508,67 +506,67 @@ func validateHTTPIngressRuleValue(httpIngressRuleValue *extensions.HTTPIngressRu } // validateIngressBackend tests if a given backend is valid. -func validateIngressBackend(backend *extensions.IngressBackend) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func validateIngressBackend(backend *extensions.IngressBackend) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} // All backends must reference a single local service by name, and a single service port by name or number. if len(backend.ServiceName) == 0 { - return append(allErrs, errs.NewFieldRequired("serviceName")) + return append(allErrs, validation.NewFieldRequired("serviceName")) } else if ok, errMsg := apivalidation.ValidateServiceName(backend.ServiceName, false); !ok { - allErrs = append(allErrs, errs.NewFieldInvalid("serviceName", backend.ServiceName, errMsg)) + allErrs = append(allErrs, validation.NewFieldInvalid("serviceName", backend.ServiceName, errMsg)) } if backend.ServicePort.Type == intstr.String { - if !utilvalidation.IsDNS1123Label(backend.ServicePort.StrVal) { - allErrs = append(allErrs, errs.NewFieldInvalid("servicePort", backend.ServicePort.StrVal, apivalidation.DNS1123LabelErrorMsg)) + if !validation.IsDNS1123Label(backend.ServicePort.StrVal) { + allErrs = append(allErrs, validation.NewFieldInvalid("servicePort", backend.ServicePort.StrVal, apivalidation.DNS1123LabelErrorMsg)) } - if !utilvalidation.IsValidPortName(backend.ServicePort.StrVal) { - allErrs = append(allErrs, errs.NewFieldInvalid("servicePort", backend.ServicePort.StrVal, apivalidation.PortNameErrorMsg)) + if !validation.IsValidPortName(backend.ServicePort.StrVal) { + allErrs = append(allErrs, validation.NewFieldInvalid("servicePort", backend.ServicePort.StrVal, apivalidation.PortNameErrorMsg)) } - } else if !utilvalidation.IsValidPortNum(backend.ServicePort.IntVal) { - allErrs = append(allErrs, errs.NewFieldInvalid("servicePort", backend.ServicePort, apivalidation.PortRangeErrorMsg)) + } else if !validation.IsValidPortNum(backend.ServicePort.IntVal) { + allErrs = append(allErrs, validation.NewFieldInvalid("servicePort", backend.ServicePort, apivalidation.PortRangeErrorMsg)) } return allErrs } -func validateClusterAutoscalerSpec(spec extensions.ClusterAutoscalerSpec) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func validateClusterAutoscalerSpec(spec extensions.ClusterAutoscalerSpec) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} if spec.MinNodes < 0 { - allErrs = append(allErrs, errs.NewFieldInvalid("minNodes", spec.MinNodes, `must be non-negative`)) + allErrs = append(allErrs, validation.NewFieldInvalid("minNodes", spec.MinNodes, `must be non-negative`)) } if spec.MaxNodes < spec.MinNodes { - allErrs = append(allErrs, errs.NewFieldInvalid("maxNodes", spec.MaxNodes, `must be bigger or equal to minNodes`)) + allErrs = append(allErrs, validation.NewFieldInvalid("maxNodes", spec.MaxNodes, `must be bigger or equal to minNodes`)) } if len(spec.TargetUtilization) == 0 { - allErrs = append(allErrs, errs.NewFieldRequired("targetUtilization")) + allErrs = append(allErrs, validation.NewFieldRequired("targetUtilization")) } for _, target := range spec.TargetUtilization { if len(target.Resource) == 0 { - allErrs = append(allErrs, errs.NewFieldRequired("targetUtilization.resource")) + allErrs = append(allErrs, validation.NewFieldRequired("targetUtilization.resource")) } if target.Value <= 0 { - allErrs = append(allErrs, errs.NewFieldInvalid("targetUtilization.value", target.Value, "must be greater than 0")) + allErrs = append(allErrs, validation.NewFieldInvalid("targetUtilization.value", target.Value, "must be greater than 0")) } if target.Value > 1 { - allErrs = append(allErrs, errs.NewFieldInvalid("targetUtilization.value", target.Value, "must be less or equal 1")) + allErrs = append(allErrs, validation.NewFieldInvalid("targetUtilization.value", target.Value, "must be less or equal 1")) } } return allErrs } -func ValidateClusterAutoscaler(autoscaler *extensions.ClusterAutoscaler) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func ValidateClusterAutoscaler(autoscaler *extensions.ClusterAutoscaler) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} if autoscaler.Name != "ClusterAutoscaler" { - allErrs = append(allErrs, errs.NewFieldInvalid("name", autoscaler.Name, `name must be ClusterAutoscaler`)) + allErrs = append(allErrs, validation.NewFieldInvalid("name", autoscaler.Name, `name must be ClusterAutoscaler`)) } if autoscaler.Namespace != api.NamespaceDefault { - allErrs = append(allErrs, errs.NewFieldInvalid("namespace", autoscaler.Namespace, `namespace must be default`)) + allErrs = append(allErrs, validation.NewFieldInvalid("namespace", autoscaler.Namespace, `namespace must be default`)) } allErrs = append(allErrs, validateClusterAutoscalerSpec(autoscaler.Spec)...) return allErrs } -func ValidatePodSelector(ps *extensions.PodSelector) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func ValidatePodSelector(ps *extensions.PodSelector) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} if ps == nil { return allErrs } @@ -579,30 +577,30 @@ func ValidatePodSelector(ps *extensions.PodSelector) errs.ValidationErrorList { return allErrs } -func ValidatePodSelectorRequirement(sr extensions.PodSelectorRequirement) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func ValidatePodSelectorRequirement(sr extensions.PodSelectorRequirement) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} switch sr.Operator { case extensions.PodSelectorOpIn, extensions.PodSelectorOpNotIn: if len(sr.Values) == 0 { - allErrs = append(allErrs, errs.NewFieldInvalid("values", sr.Values, "must be non-empty when operator is In or NotIn")) + allErrs = append(allErrs, validation.NewFieldInvalid("values", sr.Values, "must be non-empty when operator is In or NotIn")) } case extensions.PodSelectorOpExists, extensions.PodSelectorOpDoesNotExist: if len(sr.Values) > 0 { - allErrs = append(allErrs, errs.NewFieldInvalid("values", sr.Values, "must be empty when operator is Exists or DoesNotExist")) + allErrs = append(allErrs, validation.NewFieldInvalid("values", sr.Values, "must be empty when operator is Exists or DoesNotExist")) } default: - allErrs = append(allErrs, errs.NewFieldInvalid("operator", sr.Operator, "not a valid pod selector operator")) + allErrs = append(allErrs, validation.NewFieldInvalid("operator", sr.Operator, "not a valid pod selector operator")) } allErrs = append(allErrs, apivalidation.ValidateLabelName(sr.Key, "key")...) return allErrs } -func ValidateScale(scale *extensions.Scale) errs.ValidationErrorList { - allErrs := errs.ValidationErrorList{} +func ValidateScale(scale *extensions.Scale) validation.ValidationErrorList { + allErrs := validation.ValidationErrorList{} allErrs = append(allErrs, apivalidation.ValidateObjectMeta(&scale.ObjectMeta, true, apivalidation.NameIsDNSSubdomain).Prefix("metadata")...) if scale.Spec.Replicas < 0 { - allErrs = append(allErrs, errs.NewFieldInvalid("spec.replicas", scale.Spec.Replicas, "must be non-negative")) + allErrs = append(allErrs, validation.NewFieldInvalid("spec.replicas", scale.Spec.Replicas, "must be non-negative")) } return allErrs diff --git a/pkg/apis/extensions/validation/validation_test.go b/pkg/apis/extensions/validation/validation_test.go index aaad166e2a0..f5e70ebcba6 100644 --- a/pkg/apis/extensions/validation/validation_test.go +++ b/pkg/apis/extensions/validation/validation_test.go @@ -23,8 +23,8 @@ import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/apis/extensions" - errors "k8s.io/kubernetes/pkg/util/fielderrors" "k8s.io/kubernetes/pkg/util/intstr" + "k8s.io/kubernetes/pkg/util/validation" ) func TestValidateHorizontalPodAutoscaler(t *testing.T) { @@ -675,7 +675,7 @@ func TestValidateDaemonSet(t *testing.T) { t.Errorf("expected failure for %s", k) } for i := range errs { - field := errs[i].(*errors.ValidationError).Field + field := errs[i].(*validation.ValidationError).Field if !strings.HasPrefix(field, "spec.template.") && field != "metadata.name" && field != "metadata.namespace" && @@ -918,7 +918,7 @@ func TestValidateJob(t *testing.T) { t.Errorf("expected failure for %s", k) } else { s := strings.Split(k, ":") - err := errs[0].(*errors.ValidationError) + err := errs[0].(*validation.ValidationError) if err.Field != s[0] || !strings.Contains(err.Error(), s[1]) { t.Errorf("unexpected error: %v, expected: %s", errs[0], k) } @@ -1019,7 +1019,7 @@ func TestValidateIngress(t *testing.T) { t.Errorf("expected failure for %s", k) } else { s := strings.Split(k, ":") - err := errs[0].(*errors.ValidationError) + err := errs[0].(*validation.ValidationError) if err.Field != s[0] || !strings.Contains(err.Error(), s[1]) { t.Errorf("unexpected error: %v, expected: %s", errs[0], k) } @@ -1111,7 +1111,7 @@ func TestValidateIngressStatusUpdate(t *testing.T) { t.Errorf("expected failure for %s", k) } else { s := strings.Split(k, ":") - err := errs[0].(*errors.ValidationError) + err := errs[0].(*validation.ValidationError) if err.Field != s[0] || !strings.Contains(err.Error(), s[1]) { t.Errorf("unexpected error: %v, expected: %s", errs[0], k) } diff --git a/pkg/kubectl/cmd/util/helpers_test.go b/pkg/kubectl/cmd/util/helpers_test.go index a0e7d629943..f009098810a 100644 --- a/pkg/kubectl/cmd/util/helpers_test.go +++ b/pkg/kubectl/cmd/util/helpers_test.go @@ -31,7 +31,7 @@ import ( "k8s.io/kubernetes/pkg/api/testapi" apitesting "k8s.io/kubernetes/pkg/api/testing" "k8s.io/kubernetes/pkg/runtime" - "k8s.io/kubernetes/pkg/util/fielderrors" + "k8s.io/kubernetes/pkg/util/validation" ) func TestMerge(t *testing.T) { @@ -274,15 +274,15 @@ func TestCheckInvalidErr(t *testing.T) { expected string }{ { - errors.NewInvalid("Invalid1", "invalidation", fielderrors.ValidationErrorList{fielderrors.NewFieldInvalid("Cause", "single", "details")}), + errors.NewInvalid("Invalid1", "invalidation", validation.ValidationErrorList{validation.NewFieldInvalid("Cause", "single", "details")}), `Error from server: Invalid1 "invalidation" is invalid: Cause: invalid value 'single', Details: details`, }, { - errors.NewInvalid("Invalid2", "invalidation", fielderrors.ValidationErrorList{fielderrors.NewFieldInvalid("Cause", "multi1", "details"), fielderrors.NewFieldInvalid("Cause", "multi2", "details")}), + errors.NewInvalid("Invalid2", "invalidation", validation.ValidationErrorList{validation.NewFieldInvalid("Cause", "multi1", "details"), validation.NewFieldInvalid("Cause", "multi2", "details")}), `Error from server: Invalid2 "invalidation" is invalid: [Cause: invalid value 'multi1', Details: details, Cause: invalid value 'multi2', Details: details]`, }, { - errors.NewInvalid("Invalid3", "invalidation", fielderrors.ValidationErrorList{}), + errors.NewInvalid("Invalid3", "invalidation", validation.ValidationErrorList{}), `Error from server: Invalid3 "invalidation" is invalid: `, }, } diff --git a/pkg/kubelet/config/config.go b/pkg/kubelet/config/config.go index 7eddcfd62bb..ff0bd1a0459 100644 --- a/pkg/kubelet/config/config.go +++ b/pkg/kubelet/config/config.go @@ -30,8 +30,8 @@ import ( kubeletutil "k8s.io/kubernetes/pkg/kubelet/util" "k8s.io/kubernetes/pkg/util/config" utilerrors "k8s.io/kubernetes/pkg/util/errors" - "k8s.io/kubernetes/pkg/util/fielderrors" "k8s.io/kubernetes/pkg/util/sets" + utilvalidation "k8s.io/kubernetes/pkg/util/validation" ) // PodConfigNotificationMode describes how changes are sent to the update channel. @@ -318,7 +318,7 @@ func filterInvalidPods(pods []*api.Pod, source string, recorder record.EventReco } else { name := kubecontainer.GetPodFullName(pod) if names.Has(name) { - errlist = append(errlist, fielderrors.NewFieldDuplicate("name", pod.Name)) + errlist = append(errlist, utilvalidation.NewFieldDuplicate("name", pod.Name)) } else { names.Insert(name) } diff --git a/pkg/labels/selector.go b/pkg/labels/selector.go index 07a9bf90bce..c3e70b56cb4 100644 --- a/pkg/labels/selector.go +++ b/pkg/labels/selector.go @@ -22,7 +22,6 @@ import ( "sort" "strings" - "k8s.io/kubernetes/pkg/util/fielderrors" "k8s.io/kubernetes/pkg/util/sets" "k8s.io/kubernetes/pkg/util/validation" ) @@ -702,14 +701,14 @@ const qualifiedNameErrorMsg string = "must match regex [" + validation.DNS1123Su func validateLabelKey(k string) error { if !validation.IsQualifiedName(k) { - return fielderrors.NewFieldInvalid("label key", k, qualifiedNameErrorMsg) + return validation.NewFieldInvalid("label key", k, qualifiedNameErrorMsg) } return nil } func validateLabelValue(v string) error { if !validation.IsValidLabelValue(v) { - return fielderrors.NewFieldInvalid("label value", v, qualifiedNameErrorMsg) + return validation.NewFieldInvalid("label value", v, qualifiedNameErrorMsg) } return nil } diff --git a/pkg/registry/controller/strategy.go b/pkg/registry/controller/strategy.go index a740778a900..a9c54b6d904 100644 --- a/pkg/registry/controller/strategy.go +++ b/pkg/registry/controller/strategy.go @@ -27,7 +27,7 @@ import ( "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/registry/generic" "k8s.io/kubernetes/pkg/runtime" - "k8s.io/kubernetes/pkg/util/fielderrors" + utilvalidation "k8s.io/kubernetes/pkg/util/validation" ) // rcStrategy implements verification logic for Replication Controllers. @@ -76,7 +76,7 @@ func (rcStrategy) PrepareForUpdate(obj, old runtime.Object) { } // Validate validates a new replication controller. -func (rcStrategy) Validate(ctx api.Context, obj runtime.Object) fielderrors.ValidationErrorList { +func (rcStrategy) Validate(ctx api.Context, obj runtime.Object) utilvalidation.ValidationErrorList { controller := obj.(*api.ReplicationController) return validation.ValidateReplicationController(controller) } @@ -92,7 +92,7 @@ func (rcStrategy) AllowCreateOnUpdate() bool { } // ValidateUpdate is the default update validation for an end user. -func (rcStrategy) ValidateUpdate(ctx api.Context, obj, old runtime.Object) fielderrors.ValidationErrorList { +func (rcStrategy) ValidateUpdate(ctx api.Context, obj, old runtime.Object) utilvalidation.ValidationErrorList { validationErrorList := validation.ValidateReplicationController(obj.(*api.ReplicationController)) updateErrorList := validation.ValidateReplicationControllerUpdate(obj.(*api.ReplicationController), old.(*api.ReplicationController)) return append(validationErrorList, updateErrorList...) @@ -141,6 +141,6 @@ func (rcStatusStrategy) PrepareForUpdate(obj, old runtime.Object) { newRc.Spec = oldRc.Spec } -func (rcStatusStrategy) ValidateUpdate(ctx api.Context, obj, old runtime.Object) fielderrors.ValidationErrorList { +func (rcStatusStrategy) ValidateUpdate(ctx api.Context, obj, old runtime.Object) utilvalidation.ValidationErrorList { return validation.ValidateReplicationControllerStatusUpdate(obj.(*api.ReplicationController), old.(*api.ReplicationController)) } diff --git a/pkg/registry/daemonset/strategy.go b/pkg/registry/daemonset/strategy.go index 79d8f45a92a..8f7ce7a4c44 100644 --- a/pkg/registry/daemonset/strategy.go +++ b/pkg/registry/daemonset/strategy.go @@ -27,7 +27,7 @@ import ( "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/registry/generic" "k8s.io/kubernetes/pkg/runtime" - "k8s.io/kubernetes/pkg/util/fielderrors" + utilvalidation "k8s.io/kubernetes/pkg/util/validation" ) // daemonSetStrategy implements verification logic for daemon sets. @@ -77,7 +77,7 @@ func (daemonSetStrategy) PrepareForUpdate(obj, old runtime.Object) { } // Validate validates a new daemon set. -func (daemonSetStrategy) Validate(ctx api.Context, obj runtime.Object) fielderrors.ValidationErrorList { +func (daemonSetStrategy) Validate(ctx api.Context, obj runtime.Object) utilvalidation.ValidationErrorList { daemonSet := obj.(*extensions.DaemonSet) return validation.ValidateDaemonSet(daemonSet) } @@ -93,7 +93,7 @@ func (daemonSetStrategy) AllowCreateOnUpdate() bool { } // ValidateUpdate is the default update validation for an end user. -func (daemonSetStrategy) ValidateUpdate(ctx api.Context, obj, old runtime.Object) fielderrors.ValidationErrorList { +func (daemonSetStrategy) ValidateUpdate(ctx api.Context, obj, old runtime.Object) utilvalidation.ValidationErrorList { validationErrorList := validation.ValidateDaemonSet(obj.(*extensions.DaemonSet)) updateErrorList := validation.ValidateDaemonSetUpdate(obj.(*extensions.DaemonSet), old.(*extensions.DaemonSet)) return append(validationErrorList, updateErrorList...) @@ -138,6 +138,6 @@ func (daemonSetStatusStrategy) PrepareForUpdate(obj, old runtime.Object) { newDaemonSet.Spec = oldDaemonSet.Spec } -func (daemonSetStatusStrategy) ValidateUpdate(ctx api.Context, obj, old runtime.Object) fielderrors.ValidationErrorList { +func (daemonSetStatusStrategy) ValidateUpdate(ctx api.Context, obj, old runtime.Object) utilvalidation.ValidationErrorList { return validation.ValidateDaemonSetStatusUpdate(obj.(*extensions.DaemonSet), old.(*extensions.DaemonSet)) } diff --git a/pkg/registry/deployment/strategy.go b/pkg/registry/deployment/strategy.go index 8d9e87ba89b..91e51cea8c9 100644 --- a/pkg/registry/deployment/strategy.go +++ b/pkg/registry/deployment/strategy.go @@ -26,7 +26,7 @@ import ( "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/registry/generic" "k8s.io/kubernetes/pkg/runtime" - errs "k8s.io/kubernetes/pkg/util/fielderrors" + utilvalidation "k8s.io/kubernetes/pkg/util/validation" ) // deploymentStrategy implements behavior for Deployments. @@ -51,7 +51,7 @@ func (deploymentStrategy) PrepareForCreate(obj runtime.Object) { } // Validate validates a new deployment. -func (deploymentStrategy) Validate(ctx api.Context, obj runtime.Object) errs.ValidationErrorList { +func (deploymentStrategy) Validate(ctx api.Context, obj runtime.Object) utilvalidation.ValidationErrorList { deployment := obj.(*extensions.Deployment) return validation.ValidateDeployment(deployment) } @@ -73,7 +73,7 @@ func (deploymentStrategy) PrepareForUpdate(obj, old runtime.Object) { } // ValidateUpdate is the default update validation for an end user. -func (deploymentStrategy) ValidateUpdate(ctx api.Context, obj, old runtime.Object) errs.ValidationErrorList { +func (deploymentStrategy) ValidateUpdate(ctx api.Context, obj, old runtime.Object) utilvalidation.ValidationErrorList { return validation.ValidateDeploymentUpdate(obj.(*extensions.Deployment), old.(*extensions.Deployment)) } @@ -95,7 +95,7 @@ func (deploymentStatusStrategy) PrepareForUpdate(obj, old runtime.Object) { } // ValidateUpdate is the default update validation for an end user updating status -func (deploymentStatusStrategy) ValidateUpdate(ctx api.Context, obj, old runtime.Object) errs.ValidationErrorList { +func (deploymentStatusStrategy) ValidateUpdate(ctx api.Context, obj, old runtime.Object) utilvalidation.ValidationErrorList { return validation.ValidateDeploymentUpdate(obj.(*extensions.Deployment), old.(*extensions.Deployment)) } diff --git a/pkg/registry/endpoint/strategy.go b/pkg/registry/endpoint/strategy.go index 9fad2d1e9a3..9c0d8903270 100644 --- a/pkg/registry/endpoint/strategy.go +++ b/pkg/registry/endpoint/strategy.go @@ -26,7 +26,7 @@ import ( "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/registry/generic" "k8s.io/kubernetes/pkg/runtime" - "k8s.io/kubernetes/pkg/util/fielderrors" + utilvalidation "k8s.io/kubernetes/pkg/util/validation" ) // endpointsStrategy implements behavior for Endpoints @@ -53,7 +53,7 @@ func (endpointsStrategy) PrepareForUpdate(obj, old runtime.Object) { } // Validate validates a new endpoints. -func (endpointsStrategy) Validate(ctx api.Context, obj runtime.Object) fielderrors.ValidationErrorList { +func (endpointsStrategy) Validate(ctx api.Context, obj runtime.Object) utilvalidation.ValidationErrorList { return validation.ValidateEndpoints(obj.(*api.Endpoints)) } @@ -69,7 +69,7 @@ func (endpointsStrategy) AllowCreateOnUpdate() bool { } // ValidateUpdate is the default update validation for an end user. -func (endpointsStrategy) ValidateUpdate(ctx api.Context, obj, old runtime.Object) fielderrors.ValidationErrorList { +func (endpointsStrategy) ValidateUpdate(ctx api.Context, obj, old runtime.Object) utilvalidation.ValidationErrorList { errorList := validation.ValidateEndpoints(obj.(*api.Endpoints)) return append(errorList, validation.ValidateEndpointsUpdate(obj.(*api.Endpoints), old.(*api.Endpoints))...) } diff --git a/pkg/registry/event/strategy.go b/pkg/registry/event/strategy.go index a11ddb819b8..775c63871d2 100644 --- a/pkg/registry/event/strategy.go +++ b/pkg/registry/event/strategy.go @@ -26,7 +26,7 @@ import ( "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/registry/generic" "k8s.io/kubernetes/pkg/runtime" - "k8s.io/kubernetes/pkg/util/fielderrors" + utilvalidation "k8s.io/kubernetes/pkg/util/validation" ) type eventStrategy struct { @@ -48,7 +48,7 @@ func (eventStrategy) PrepareForCreate(obj runtime.Object) { func (eventStrategy) PrepareForUpdate(obj, old runtime.Object) { } -func (eventStrategy) Validate(ctx api.Context, obj runtime.Object) fielderrors.ValidationErrorList { +func (eventStrategy) Validate(ctx api.Context, obj runtime.Object) utilvalidation.ValidationErrorList { event := obj.(*api.Event) return validation.ValidateEvent(event) } @@ -61,7 +61,7 @@ func (eventStrategy) AllowCreateOnUpdate() bool { return true } -func (eventStrategy) ValidateUpdate(ctx api.Context, obj, old runtime.Object) fielderrors.ValidationErrorList { +func (eventStrategy) ValidateUpdate(ctx api.Context, obj, old runtime.Object) utilvalidation.ValidationErrorList { event := obj.(*api.Event) return validation.ValidateEvent(event) } diff --git a/pkg/registry/generic/etcd/etcd_test.go b/pkg/registry/generic/etcd/etcd_test.go index 9d7395dbee3..d7881e8df2a 100644 --- a/pkg/registry/generic/etcd/etcd_test.go +++ b/pkg/registry/generic/etcd/etcd_test.go @@ -31,8 +31,8 @@ import ( "k8s.io/kubernetes/pkg/storage/etcd/etcdtest" etcdtesting "k8s.io/kubernetes/pkg/storage/etcd/testing" storagetesting "k8s.io/kubernetes/pkg/storage/testing" - "k8s.io/kubernetes/pkg/util/fielderrors" "k8s.io/kubernetes/pkg/util/sets" + "k8s.io/kubernetes/pkg/util/validation" ) type testRESTStrategy struct { @@ -49,10 +49,10 @@ func (t *testRESTStrategy) AllowUnconditionalUpdate() bool { return t.allowUncon func (t *testRESTStrategy) PrepareForCreate(obj runtime.Object) {} func (t *testRESTStrategy) PrepareForUpdate(obj, old runtime.Object) {} -func (t *testRESTStrategy) Validate(ctx api.Context, obj runtime.Object) fielderrors.ValidationErrorList { +func (t *testRESTStrategy) Validate(ctx api.Context, obj runtime.Object) validation.ValidationErrorList { return nil } -func (t *testRESTStrategy) ValidateUpdate(ctx api.Context, obj, old runtime.Object) fielderrors.ValidationErrorList { +func (t *testRESTStrategy) ValidateUpdate(ctx api.Context, obj, old runtime.Object) validation.ValidationErrorList { return nil } func (t *testRESTStrategy) Canonicalize(obj runtime.Object) {} diff --git a/pkg/registry/horizontalpodautoscaler/strategy.go b/pkg/registry/horizontalpodautoscaler/strategy.go index 725b4ea135c..973e39c4af6 100644 --- a/pkg/registry/horizontalpodautoscaler/strategy.go +++ b/pkg/registry/horizontalpodautoscaler/strategy.go @@ -26,7 +26,7 @@ import ( "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/registry/generic" "k8s.io/kubernetes/pkg/runtime" - errs "k8s.io/kubernetes/pkg/util/fielderrors" + utilvalidation "k8s.io/kubernetes/pkg/util/validation" ) // autoscalerStrategy implements behavior for HorizontalPodAutoscalers @@ -53,7 +53,7 @@ func (autoscalerStrategy) PrepareForCreate(obj runtime.Object) { } // Validate validates a new autoscaler. -func (autoscalerStrategy) Validate(ctx api.Context, obj runtime.Object) errs.ValidationErrorList { +func (autoscalerStrategy) Validate(ctx api.Context, obj runtime.Object) utilvalidation.ValidationErrorList { autoscaler := obj.(*extensions.HorizontalPodAutoscaler) return validation.ValidateHorizontalPodAutoscaler(autoscaler) } @@ -76,7 +76,7 @@ func (autoscalerStrategy) PrepareForUpdate(obj, old runtime.Object) { } // ValidateUpdate is the default update validation for an end user. -func (autoscalerStrategy) ValidateUpdate(ctx api.Context, obj, old runtime.Object) errs.ValidationErrorList { +func (autoscalerStrategy) ValidateUpdate(ctx api.Context, obj, old runtime.Object) utilvalidation.ValidationErrorList { return validation.ValidateHorizontalPodAutoscalerUpdate(obj.(*extensions.HorizontalPodAutoscaler), old.(*extensions.HorizontalPodAutoscaler)) } @@ -115,6 +115,6 @@ func (autoscalerStatusStrategy) PrepareForUpdate(obj, old runtime.Object) { newAutoscaler.Spec = oldAutoscaler.Spec } -func (autoscalerStatusStrategy) ValidateUpdate(ctx api.Context, obj, old runtime.Object) errs.ValidationErrorList { +func (autoscalerStatusStrategy) ValidateUpdate(ctx api.Context, obj, old runtime.Object) utilvalidation.ValidationErrorList { return validation.ValidateHorizontalPodAutoscalerStatusUpdate(obj.(*extensions.HorizontalPodAutoscaler), old.(*extensions.HorizontalPodAutoscaler)) } diff --git a/pkg/registry/ingress/strategy.go b/pkg/registry/ingress/strategy.go index 8ffe645a22e..69e0cb4c82b 100644 --- a/pkg/registry/ingress/strategy.go +++ b/pkg/registry/ingress/strategy.go @@ -27,7 +27,7 @@ import ( "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/registry/generic" "k8s.io/kubernetes/pkg/runtime" - "k8s.io/kubernetes/pkg/util/fielderrors" + utilvalidation "k8s.io/kubernetes/pkg/util/validation" ) // ingressStrategy implements verification logic for Replication Ingresss. @@ -70,7 +70,7 @@ func (ingressStrategy) PrepareForUpdate(obj, old runtime.Object) { } // Validate validates a new Ingress. -func (ingressStrategy) Validate(ctx api.Context, obj runtime.Object) fielderrors.ValidationErrorList { +func (ingressStrategy) Validate(ctx api.Context, obj runtime.Object) utilvalidation.ValidationErrorList { ingress := obj.(*extensions.Ingress) err := validation.ValidateIngress(ingress) return err @@ -86,7 +86,7 @@ func (ingressStrategy) AllowCreateOnUpdate() bool { } // ValidateUpdate is the default update validation for an end user. -func (ingressStrategy) ValidateUpdate(ctx api.Context, obj, old runtime.Object) fielderrors.ValidationErrorList { +func (ingressStrategy) ValidateUpdate(ctx api.Context, obj, old runtime.Object) utilvalidation.ValidationErrorList { validationErrorList := validation.ValidateIngress(obj.(*extensions.Ingress)) updateErrorList := validation.ValidateIngressUpdate(obj.(*extensions.Ingress), old.(*extensions.Ingress)) return append(validationErrorList, updateErrorList...) @@ -134,6 +134,6 @@ func (ingressStatusStrategy) PrepareForUpdate(obj, old runtime.Object) { } // ValidateUpdate is the default update validation for an end user updating status -func (ingressStatusStrategy) ValidateUpdate(ctx api.Context, obj, old runtime.Object) fielderrors.ValidationErrorList { +func (ingressStatusStrategy) ValidateUpdate(ctx api.Context, obj, old runtime.Object) utilvalidation.ValidationErrorList { return validation.ValidateIngressStatusUpdate(obj.(*extensions.Ingress), old.(*extensions.Ingress)) } diff --git a/pkg/registry/job/strategy.go b/pkg/registry/job/strategy.go index 28fabe6a829..27f64c4004a 100644 --- a/pkg/registry/job/strategy.go +++ b/pkg/registry/job/strategy.go @@ -27,7 +27,7 @@ import ( "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/registry/generic" "k8s.io/kubernetes/pkg/runtime" - "k8s.io/kubernetes/pkg/util/fielderrors" + utilvalidation "k8s.io/kubernetes/pkg/util/validation" ) // jobStrategy implements verification logic for Replication Controllers. @@ -58,7 +58,7 @@ func (jobStrategy) PrepareForUpdate(obj, old runtime.Object) { } // Validate validates a new job. -func (jobStrategy) Validate(ctx api.Context, obj runtime.Object) fielderrors.ValidationErrorList { +func (jobStrategy) Validate(ctx api.Context, obj runtime.Object) utilvalidation.ValidationErrorList { job := obj.(*extensions.Job) return validation.ValidateJob(job) } @@ -77,7 +77,7 @@ func (jobStrategy) AllowCreateOnUpdate() bool { } // ValidateUpdate is the default update validation for an end user. -func (jobStrategy) ValidateUpdate(ctx api.Context, obj, old runtime.Object) fielderrors.ValidationErrorList { +func (jobStrategy) ValidateUpdate(ctx api.Context, obj, old runtime.Object) utilvalidation.ValidationErrorList { validationErrorList := validation.ValidateJob(obj.(*extensions.Job)) updateErrorList := validation.ValidateJobUpdate(obj.(*extensions.Job), old.(*extensions.Job)) return append(validationErrorList, updateErrorList...) @@ -95,7 +95,7 @@ func (jobStatusStrategy) PrepareForUpdate(obj, old runtime.Object) { newJob.Spec = oldJob.Spec } -func (jobStatusStrategy) ValidateUpdate(ctx api.Context, obj, old runtime.Object) fielderrors.ValidationErrorList { +func (jobStatusStrategy) ValidateUpdate(ctx api.Context, obj, old runtime.Object) utilvalidation.ValidationErrorList { return validation.ValidateJobUpdateStatus(obj.(*extensions.Job), old.(*extensions.Job)) } diff --git a/pkg/registry/limitrange/strategy.go b/pkg/registry/limitrange/strategy.go index e0de8cdb456..297afad92ab 100644 --- a/pkg/registry/limitrange/strategy.go +++ b/pkg/registry/limitrange/strategy.go @@ -26,7 +26,7 @@ import ( "k8s.io/kubernetes/pkg/registry/generic" "k8s.io/kubernetes/pkg/runtime" "k8s.io/kubernetes/pkg/util" - "k8s.io/kubernetes/pkg/util/fielderrors" + utilvalidation "k8s.io/kubernetes/pkg/util/validation" ) type limitrangeStrategy struct { @@ -52,7 +52,7 @@ func (limitrangeStrategy) PrepareForCreate(obj runtime.Object) { func (limitrangeStrategy) PrepareForUpdate(obj, old runtime.Object) { } -func (limitrangeStrategy) Validate(ctx api.Context, obj runtime.Object) fielderrors.ValidationErrorList { +func (limitrangeStrategy) Validate(ctx api.Context, obj runtime.Object) utilvalidation.ValidationErrorList { limitRange := obj.(*api.LimitRange) return validation.ValidateLimitRange(limitRange) } @@ -65,7 +65,7 @@ func (limitrangeStrategy) AllowCreateOnUpdate() bool { return true } -func (limitrangeStrategy) ValidateUpdate(ctx api.Context, obj, old runtime.Object) fielderrors.ValidationErrorList { +func (limitrangeStrategy) ValidateUpdate(ctx api.Context, obj, old runtime.Object) utilvalidation.ValidationErrorList { limitRange := obj.(*api.LimitRange) return validation.ValidateLimitRange(limitRange) } diff --git a/pkg/registry/namespace/strategy.go b/pkg/registry/namespace/strategy.go index d3f989b5fcc..d6341696ccb 100644 --- a/pkg/registry/namespace/strategy.go +++ b/pkg/registry/namespace/strategy.go @@ -25,7 +25,7 @@ import ( "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/registry/generic" "k8s.io/kubernetes/pkg/runtime" - "k8s.io/kubernetes/pkg/util/fielderrors" + utilvalidation "k8s.io/kubernetes/pkg/util/validation" ) // namespaceStrategy implements behavior for Namespaces @@ -77,7 +77,7 @@ func (namespaceStrategy) PrepareForUpdate(obj, old runtime.Object) { } // Validate validates a new namespace. -func (namespaceStrategy) Validate(ctx api.Context, obj runtime.Object) fielderrors.ValidationErrorList { +func (namespaceStrategy) Validate(ctx api.Context, obj runtime.Object) utilvalidation.ValidationErrorList { namespace := obj.(*api.Namespace) return validation.ValidateNamespace(namespace) } @@ -92,7 +92,7 @@ func (namespaceStrategy) AllowCreateOnUpdate() bool { } // ValidateUpdate is the default update validation for an end user. -func (namespaceStrategy) ValidateUpdate(ctx api.Context, obj, old runtime.Object) fielderrors.ValidationErrorList { +func (namespaceStrategy) ValidateUpdate(ctx api.Context, obj, old runtime.Object) utilvalidation.ValidationErrorList { errorList := validation.ValidateNamespace(obj.(*api.Namespace)) return append(errorList, validation.ValidateNamespaceUpdate(obj.(*api.Namespace), old.(*api.Namespace))...) } @@ -113,7 +113,7 @@ func (namespaceStatusStrategy) PrepareForUpdate(obj, old runtime.Object) { newNamespace.Spec = oldNamespace.Spec } -func (namespaceStatusStrategy) ValidateUpdate(ctx api.Context, obj, old runtime.Object) fielderrors.ValidationErrorList { +func (namespaceStatusStrategy) ValidateUpdate(ctx api.Context, obj, old runtime.Object) utilvalidation.ValidationErrorList { return validation.ValidateNamespaceStatusUpdate(obj.(*api.Namespace), old.(*api.Namespace)) } @@ -123,7 +123,7 @@ type namespaceFinalizeStrategy struct { var FinalizeStrategy = namespaceFinalizeStrategy{Strategy} -func (namespaceFinalizeStrategy) ValidateUpdate(ctx api.Context, obj, old runtime.Object) fielderrors.ValidationErrorList { +func (namespaceFinalizeStrategy) ValidateUpdate(ctx api.Context, obj, old runtime.Object) utilvalidation.ValidationErrorList { return validation.ValidateNamespaceFinalizeUpdate(obj.(*api.Namespace), old.(*api.Namespace)) } diff --git a/pkg/registry/node/strategy.go b/pkg/registry/node/strategy.go index 651622d70a4..3f56602d611 100644 --- a/pkg/registry/node/strategy.go +++ b/pkg/registry/node/strategy.go @@ -33,8 +33,8 @@ import ( "k8s.io/kubernetes/pkg/registry/generic" "k8s.io/kubernetes/pkg/runtime" "k8s.io/kubernetes/pkg/util" - "k8s.io/kubernetes/pkg/util/fielderrors" nodeutil "k8s.io/kubernetes/pkg/util/node" + utilvalidation "k8s.io/kubernetes/pkg/util/validation" ) // nodeStrategy implements behavior for nodes @@ -71,7 +71,7 @@ func (nodeStrategy) PrepareForUpdate(obj, old runtime.Object) { } // Validate validates a new node. -func (nodeStrategy) Validate(ctx api.Context, obj runtime.Object) fielderrors.ValidationErrorList { +func (nodeStrategy) Validate(ctx api.Context, obj runtime.Object) utilvalidation.ValidationErrorList { node := obj.(*api.Node) return validation.ValidateNode(node) } @@ -81,7 +81,7 @@ func (nodeStrategy) Canonicalize(obj runtime.Object) { } // ValidateUpdate is the default update validation for an end user. -func (nodeStrategy) ValidateUpdate(ctx api.Context, obj, old runtime.Object) fielderrors.ValidationErrorList { +func (nodeStrategy) ValidateUpdate(ctx api.Context, obj, old runtime.Object) utilvalidation.ValidationErrorList { errorList := validation.ValidateNode(obj.(*api.Node)) return append(errorList, validation.ValidateNodeUpdate(obj.(*api.Node), old.(*api.Node))...) } @@ -107,7 +107,7 @@ func (nodeStatusStrategy) PrepareForUpdate(obj, old runtime.Object) { newNode.Spec = oldNode.Spec } -func (nodeStatusStrategy) ValidateUpdate(ctx api.Context, obj, old runtime.Object) fielderrors.ValidationErrorList { +func (nodeStatusStrategy) ValidateUpdate(ctx api.Context, obj, old runtime.Object) utilvalidation.ValidationErrorList { return validation.ValidateNodeUpdate(obj.(*api.Node), old.(*api.Node)) } diff --git a/pkg/registry/persistentvolume/strategy.go b/pkg/registry/persistentvolume/strategy.go index e0c0e737fdd..f1be9ad8073 100644 --- a/pkg/registry/persistentvolume/strategy.go +++ b/pkg/registry/persistentvolume/strategy.go @@ -25,7 +25,7 @@ import ( "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/registry/generic" "k8s.io/kubernetes/pkg/runtime" - "k8s.io/kubernetes/pkg/util/fielderrors" + utilvalidation "k8s.io/kubernetes/pkg/util/validation" ) // persistentvolumeStrategy implements behavior for PersistentVolume objects @@ -48,7 +48,7 @@ func (persistentvolumeStrategy) PrepareForCreate(obj runtime.Object) { pv.Status = api.PersistentVolumeStatus{} } -func (persistentvolumeStrategy) Validate(ctx api.Context, obj runtime.Object) fielderrors.ValidationErrorList { +func (persistentvolumeStrategy) Validate(ctx api.Context, obj runtime.Object) utilvalidation.ValidationErrorList { persistentvolume := obj.(*api.PersistentVolume) return validation.ValidatePersistentVolume(persistentvolume) } @@ -68,7 +68,7 @@ func (persistentvolumeStrategy) PrepareForUpdate(obj, old runtime.Object) { newPv.Status = oldPv.Status } -func (persistentvolumeStrategy) ValidateUpdate(ctx api.Context, obj, old runtime.Object) fielderrors.ValidationErrorList { +func (persistentvolumeStrategy) ValidateUpdate(ctx api.Context, obj, old runtime.Object) utilvalidation.ValidationErrorList { errorList := validation.ValidatePersistentVolume(obj.(*api.PersistentVolume)) return append(errorList, validation.ValidatePersistentVolumeUpdate(obj.(*api.PersistentVolume), old.(*api.PersistentVolume))...) } @@ -90,7 +90,7 @@ func (persistentvolumeStatusStrategy) PrepareForUpdate(obj, old runtime.Object) newPv.Spec = oldPv.Spec } -func (persistentvolumeStatusStrategy) ValidateUpdate(ctx api.Context, obj, old runtime.Object) fielderrors.ValidationErrorList { +func (persistentvolumeStatusStrategy) ValidateUpdate(ctx api.Context, obj, old runtime.Object) utilvalidation.ValidationErrorList { return validation.ValidatePersistentVolumeStatusUpdate(obj.(*api.PersistentVolume), old.(*api.PersistentVolume)) } diff --git a/pkg/registry/persistentvolumeclaim/strategy.go b/pkg/registry/persistentvolumeclaim/strategy.go index 8c32223da61..a996278aa35 100644 --- a/pkg/registry/persistentvolumeclaim/strategy.go +++ b/pkg/registry/persistentvolumeclaim/strategy.go @@ -25,7 +25,7 @@ import ( "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/registry/generic" "k8s.io/kubernetes/pkg/runtime" - "k8s.io/kubernetes/pkg/util/fielderrors" + utilvalidation "k8s.io/kubernetes/pkg/util/validation" ) // persistentvolumeclaimStrategy implements behavior for PersistentVolumeClaim objects @@ -48,7 +48,7 @@ func (persistentvolumeclaimStrategy) PrepareForCreate(obj runtime.Object) { pv.Status = api.PersistentVolumeClaimStatus{} } -func (persistentvolumeclaimStrategy) Validate(ctx api.Context, obj runtime.Object) fielderrors.ValidationErrorList { +func (persistentvolumeclaimStrategy) Validate(ctx api.Context, obj runtime.Object) utilvalidation.ValidationErrorList { pvc := obj.(*api.PersistentVolumeClaim) return validation.ValidatePersistentVolumeClaim(pvc) } @@ -68,7 +68,7 @@ func (persistentvolumeclaimStrategy) PrepareForUpdate(obj, old runtime.Object) { newPvc.Status = oldPvc.Status } -func (persistentvolumeclaimStrategy) ValidateUpdate(ctx api.Context, obj, old runtime.Object) fielderrors.ValidationErrorList { +func (persistentvolumeclaimStrategy) ValidateUpdate(ctx api.Context, obj, old runtime.Object) utilvalidation.ValidationErrorList { errorList := validation.ValidatePersistentVolumeClaim(obj.(*api.PersistentVolumeClaim)) return append(errorList, validation.ValidatePersistentVolumeClaimUpdate(obj.(*api.PersistentVolumeClaim), old.(*api.PersistentVolumeClaim))...) } @@ -90,7 +90,7 @@ func (persistentvolumeclaimStatusStrategy) PrepareForUpdate(obj, old runtime.Obj newPv.Spec = oldPv.Spec } -func (persistentvolumeclaimStatusStrategy) ValidateUpdate(ctx api.Context, obj, old runtime.Object) fielderrors.ValidationErrorList { +func (persistentvolumeclaimStatusStrategy) ValidateUpdate(ctx api.Context, obj, old runtime.Object) utilvalidation.ValidationErrorList { return validation.ValidatePersistentVolumeClaimStatusUpdate(obj.(*api.PersistentVolumeClaim), old.(*api.PersistentVolumeClaim)) } diff --git a/pkg/registry/pod/etcd/etcd.go b/pkg/registry/pod/etcd/etcd.go index 4aa968a2500..e96bef04cdd 100644 --- a/pkg/registry/pod/etcd/etcd.go +++ b/pkg/registry/pod/etcd/etcd.go @@ -35,7 +35,7 @@ import ( podrest "k8s.io/kubernetes/pkg/registry/pod/rest" "k8s.io/kubernetes/pkg/runtime" "k8s.io/kubernetes/pkg/storage" - "k8s.io/kubernetes/pkg/util/fielderrors" + "k8s.io/kubernetes/pkg/util/validation" ) // PodStorage includes storage for pods and all sub resources @@ -129,10 +129,10 @@ func (r *BindingREST) Create(ctx api.Context, obj runtime.Object) (out runtime.O binding := obj.(*api.Binding) // TODO: move me to a binding strategy if len(binding.Target.Kind) != 0 && binding.Target.Kind != "Node" { - return nil, errors.NewInvalid("binding", binding.Name, fielderrors.ValidationErrorList{fielderrors.NewFieldInvalid("to.kind", binding.Target.Kind, "must be empty or 'Node'")}) + return nil, errors.NewInvalid("binding", binding.Name, validation.ValidationErrorList{validation.NewFieldInvalid("to.kind", binding.Target.Kind, "must be empty or 'Node'")}) } if len(binding.Target.Name) == 0 { - return nil, errors.NewInvalid("binding", binding.Name, fielderrors.ValidationErrorList{fielderrors.NewFieldRequired("to.name")}) + return nil, errors.NewInvalid("binding", binding.Name, validation.ValidationErrorList{validation.NewFieldRequired("to.name")}) } err = r.assignPod(ctx, binding.Name, binding.Target.Name, binding.Annotations) out = &unversioned.Status{Status: unversioned.StatusSuccess} diff --git a/pkg/registry/pod/strategy.go b/pkg/registry/pod/strategy.go index 69f13f659a9..e587900fd0d 100644 --- a/pkg/registry/pod/strategy.go +++ b/pkg/registry/pod/strategy.go @@ -33,7 +33,7 @@ import ( "k8s.io/kubernetes/pkg/registry/generic" "k8s.io/kubernetes/pkg/runtime" "k8s.io/kubernetes/pkg/util" - "k8s.io/kubernetes/pkg/util/fielderrors" + utilvalidation "k8s.io/kubernetes/pkg/util/validation" ) // podStrategy implements behavior for Pods @@ -67,7 +67,7 @@ func (podStrategy) PrepareForUpdate(obj, old runtime.Object) { } // Validate validates a new pod. -func (podStrategy) Validate(ctx api.Context, obj runtime.Object) fielderrors.ValidationErrorList { +func (podStrategy) Validate(ctx api.Context, obj runtime.Object) utilvalidation.ValidationErrorList { pod := obj.(*api.Pod) return validation.ValidatePod(pod) } @@ -82,7 +82,7 @@ func (podStrategy) AllowCreateOnUpdate() bool { } // ValidateUpdate is the default update validation for an end user. -func (podStrategy) ValidateUpdate(ctx api.Context, obj, old runtime.Object) fielderrors.ValidationErrorList { +func (podStrategy) ValidateUpdate(ctx api.Context, obj, old runtime.Object) utilvalidation.ValidationErrorList { errorList := validation.ValidatePod(obj.(*api.Pod)) return append(errorList, validation.ValidatePodUpdate(obj.(*api.Pod), old.(*api.Pod))...) } @@ -147,7 +147,7 @@ func (podStatusStrategy) PrepareForUpdate(obj, old runtime.Object) { newPod.DeletionTimestamp = nil } -func (podStatusStrategy) ValidateUpdate(ctx api.Context, obj, old runtime.Object) fielderrors.ValidationErrorList { +func (podStatusStrategy) ValidateUpdate(ctx api.Context, obj, old runtime.Object) utilvalidation.ValidationErrorList { // TODO: merge valid fields after update return validation.ValidatePodStatusUpdate(obj.(*api.Pod), old.(*api.Pod)) } diff --git a/pkg/registry/podtemplate/strategy.go b/pkg/registry/podtemplate/strategy.go index 43433521a8a..a4bb8fbc09e 100644 --- a/pkg/registry/podtemplate/strategy.go +++ b/pkg/registry/podtemplate/strategy.go @@ -25,7 +25,7 @@ import ( "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/registry/generic" "k8s.io/kubernetes/pkg/runtime" - errs "k8s.io/kubernetes/pkg/util/fielderrors" + utilvalidation "k8s.io/kubernetes/pkg/util/validation" ) // podTemplateStrategy implements behavior for PodTemplates @@ -49,7 +49,7 @@ func (podTemplateStrategy) PrepareForCreate(obj runtime.Object) { } // Validate validates a new pod template. -func (podTemplateStrategy) Validate(ctx api.Context, obj runtime.Object) errs.ValidationErrorList { +func (podTemplateStrategy) Validate(ctx api.Context, obj runtime.Object) utilvalidation.ValidationErrorList { pod := obj.(*api.PodTemplate) return validation.ValidatePodTemplate(pod) } @@ -69,7 +69,7 @@ func (podTemplateStrategy) PrepareForUpdate(obj, old runtime.Object) { } // ValidateUpdate is the default update validation for an end user. -func (podTemplateStrategy) ValidateUpdate(ctx api.Context, obj, old runtime.Object) errs.ValidationErrorList { +func (podTemplateStrategy) ValidateUpdate(ctx api.Context, obj, old runtime.Object) utilvalidation.ValidationErrorList { return validation.ValidatePodTemplateUpdate(obj.(*api.PodTemplate), old.(*api.PodTemplate)) } diff --git a/pkg/registry/resourcequota/strategy.go b/pkg/registry/resourcequota/strategy.go index 5a82dcc2804..48d31cdc305 100644 --- a/pkg/registry/resourcequota/strategy.go +++ b/pkg/registry/resourcequota/strategy.go @@ -25,7 +25,7 @@ import ( "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/registry/generic" "k8s.io/kubernetes/pkg/runtime" - "k8s.io/kubernetes/pkg/util/fielderrors" + utilvalidation "k8s.io/kubernetes/pkg/util/validation" ) // resourcequotaStrategy implements behavior for ResourceQuota objects @@ -57,7 +57,7 @@ func (resourcequotaStrategy) PrepareForUpdate(obj, old runtime.Object) { } // Validate validates a new resourcequota. -func (resourcequotaStrategy) Validate(ctx api.Context, obj runtime.Object) fielderrors.ValidationErrorList { +func (resourcequotaStrategy) Validate(ctx api.Context, obj runtime.Object) utilvalidation.ValidationErrorList { resourcequota := obj.(*api.ResourceQuota) return validation.ValidateResourceQuota(resourcequota) } @@ -72,7 +72,7 @@ func (resourcequotaStrategy) AllowCreateOnUpdate() bool { } // ValidateUpdate is the default update validation for an end user. -func (resourcequotaStrategy) ValidateUpdate(ctx api.Context, obj, old runtime.Object) fielderrors.ValidationErrorList { +func (resourcequotaStrategy) ValidateUpdate(ctx api.Context, obj, old runtime.Object) utilvalidation.ValidationErrorList { errorList := validation.ValidateResourceQuota(obj.(*api.ResourceQuota)) return append(errorList, validation.ValidateResourceQuotaUpdate(obj.(*api.ResourceQuota), old.(*api.ResourceQuota))...) } @@ -93,7 +93,7 @@ func (resourcequotaStatusStrategy) PrepareForUpdate(obj, old runtime.Object) { newResourcequota.Spec = oldResourcequota.Spec } -func (resourcequotaStatusStrategy) ValidateUpdate(ctx api.Context, obj, old runtime.Object) fielderrors.ValidationErrorList { +func (resourcequotaStatusStrategy) ValidateUpdate(ctx api.Context, obj, old runtime.Object) utilvalidation.ValidationErrorList { return validation.ValidateResourceQuotaStatusUpdate(obj.(*api.ResourceQuota), old.(*api.ResourceQuota)) } diff --git a/pkg/registry/secret/strategy.go b/pkg/registry/secret/strategy.go index fd2d3930f86..375d7c89237 100644 --- a/pkg/registry/secret/strategy.go +++ b/pkg/registry/secret/strategy.go @@ -26,7 +26,7 @@ import ( "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/registry/generic" "k8s.io/kubernetes/pkg/runtime" - "k8s.io/kubernetes/pkg/util/fielderrors" + utilvalidation "k8s.io/kubernetes/pkg/util/validation" ) // strategy implements behavior for Secret objects @@ -50,7 +50,7 @@ func (strategy) NamespaceScoped() bool { func (strategy) PrepareForCreate(obj runtime.Object) { } -func (strategy) Validate(ctx api.Context, obj runtime.Object) fielderrors.ValidationErrorList { +func (strategy) Validate(ctx api.Context, obj runtime.Object) utilvalidation.ValidationErrorList { return validation.ValidateSecret(obj.(*api.Secret)) } @@ -64,7 +64,7 @@ func (strategy) AllowCreateOnUpdate() bool { func (strategy) PrepareForUpdate(obj, old runtime.Object) { } -func (strategy) ValidateUpdate(ctx api.Context, obj, old runtime.Object) fielderrors.ValidationErrorList { +func (strategy) ValidateUpdate(ctx api.Context, obj, old runtime.Object) utilvalidation.ValidationErrorList { return validation.ValidateSecretUpdate(obj.(*api.Secret), old.(*api.Secret)) } diff --git a/pkg/registry/service/rest.go b/pkg/registry/service/rest.go index 6699c00022d..385edd79e97 100644 --- a/pkg/registry/service/rest.go +++ b/pkg/registry/service/rest.go @@ -35,7 +35,7 @@ import ( "k8s.io/kubernetes/pkg/registry/service/portallocator" "k8s.io/kubernetes/pkg/runtime" "k8s.io/kubernetes/pkg/util" - "k8s.io/kubernetes/pkg/util/fielderrors" + utilvalidation "k8s.io/kubernetes/pkg/util/validation" "k8s.io/kubernetes/pkg/watch" ) @@ -84,7 +84,7 @@ func (rs *REST) Create(ctx api.Context, obj runtime.Object) (runtime.Object, err // Allocate next available. ip, err := rs.serviceIPs.AllocateNext() if err != nil { - el := fielderrors.ValidationErrorList{fielderrors.NewFieldInvalid("spec.clusterIP", service.Spec.ClusterIP, err.Error())} + el := utilvalidation.ValidationErrorList{utilvalidation.NewFieldInvalid("spec.clusterIP", service.Spec.ClusterIP, err.Error())} return nil, errors.NewInvalid("Service", service.Name, el) } service.Spec.ClusterIP = ip.String() @@ -92,7 +92,7 @@ func (rs *REST) Create(ctx api.Context, obj runtime.Object) (runtime.Object, err } else if api.IsServiceIPSet(service) { // Try to respect the requested IP. if err := rs.serviceIPs.Allocate(net.ParseIP(service.Spec.ClusterIP)); err != nil { - el := fielderrors.ValidationErrorList{fielderrors.NewFieldInvalid("spec.clusterIP", service.Spec.ClusterIP, err.Error())} + el := utilvalidation.ValidationErrorList{utilvalidation.NewFieldInvalid("spec.clusterIP", service.Spec.ClusterIP, err.Error())} return nil, errors.NewInvalid("Service", service.Name, el) } releaseServiceIP = true @@ -104,13 +104,13 @@ func (rs *REST) Create(ctx api.Context, obj runtime.Object) (runtime.Object, err if servicePort.NodePort != 0 { err := nodePortOp.Allocate(servicePort.NodePort) if err != nil { - el := fielderrors.ValidationErrorList{fielderrors.NewFieldInvalid("nodePort", servicePort.NodePort, err.Error())}.PrefixIndex(i).Prefix("spec.ports") + el := utilvalidation.ValidationErrorList{utilvalidation.NewFieldInvalid("nodePort", servicePort.NodePort, err.Error())}.PrefixIndex(i).Prefix("spec.ports") return nil, errors.NewInvalid("Service", service.Name, el) } } else if assignNodePorts { nodePort, err := nodePortOp.AllocateNext() if err != nil { - el := fielderrors.ValidationErrorList{fielderrors.NewFieldInvalid("nodePort", servicePort.NodePort, err.Error())}.PrefixIndex(i).Prefix("spec.ports") + el := utilvalidation.ValidationErrorList{utilvalidation.NewFieldInvalid("nodePort", servicePort.NodePort, err.Error())}.PrefixIndex(i).Prefix("spec.ports") return nil, errors.NewInvalid("Service", service.Name, el) } servicePort.NodePort = nodePort @@ -223,14 +223,14 @@ func (rs *REST) Update(ctx api.Context, obj runtime.Object) (runtime.Object, boo if !contains(oldNodePorts, nodePort) { err := nodePortOp.Allocate(nodePort) if err != nil { - el := fielderrors.ValidationErrorList{fielderrors.NewFieldInvalid("nodePort", nodePort, err.Error())}.PrefixIndex(i).Prefix("spec.ports") + el := utilvalidation.ValidationErrorList{utilvalidation.NewFieldInvalid("nodePort", nodePort, err.Error())}.PrefixIndex(i).Prefix("spec.ports") return nil, false, errors.NewInvalid("Service", service.Name, el) } } } else { nodePort, err = nodePortOp.AllocateNext() if err != nil { - el := fielderrors.ValidationErrorList{fielderrors.NewFieldInvalid("nodePort", nodePort, err.Error())}.PrefixIndex(i).Prefix("spec.ports") + el := utilvalidation.ValidationErrorList{utilvalidation.NewFieldInvalid("nodePort", nodePort, err.Error())}.PrefixIndex(i).Prefix("spec.ports") return nil, false, errors.NewInvalid("Service", service.Name, el) } servicePort.NodePort = nodePort diff --git a/pkg/registry/service/strategy.go b/pkg/registry/service/strategy.go index 3072053f709..e314c277b82 100644 --- a/pkg/registry/service/strategy.go +++ b/pkg/registry/service/strategy.go @@ -25,7 +25,7 @@ import ( "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/registry/generic" "k8s.io/kubernetes/pkg/runtime" - "k8s.io/kubernetes/pkg/util/fielderrors" + utilvalidation "k8s.io/kubernetes/pkg/util/validation" ) // svcStrategy implements behavior for Services @@ -58,7 +58,7 @@ func (svcStrategy) PrepareForUpdate(obj, old runtime.Object) { } // Validate validates a new service. -func (svcStrategy) Validate(ctx api.Context, obj runtime.Object) fielderrors.ValidationErrorList { +func (svcStrategy) Validate(ctx api.Context, obj runtime.Object) utilvalidation.ValidationErrorList { service := obj.(*api.Service) return validation.ValidateService(service) } @@ -71,7 +71,7 @@ func (svcStrategy) AllowCreateOnUpdate() bool { return true } -func (svcStrategy) ValidateUpdate(ctx api.Context, obj, old runtime.Object) fielderrors.ValidationErrorList { +func (svcStrategy) ValidateUpdate(ctx api.Context, obj, old runtime.Object) utilvalidation.ValidationErrorList { return validation.ValidateServiceUpdate(obj.(*api.Service), old.(*api.Service)) } diff --git a/pkg/registry/serviceaccount/strategy.go b/pkg/registry/serviceaccount/strategy.go index 2e53c922def..57a6d614118 100644 --- a/pkg/registry/serviceaccount/strategy.go +++ b/pkg/registry/serviceaccount/strategy.go @@ -25,7 +25,7 @@ import ( "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/registry/generic" "k8s.io/kubernetes/pkg/runtime" - "k8s.io/kubernetes/pkg/util/fielderrors" + utilvalidation "k8s.io/kubernetes/pkg/util/validation" ) // strategy implements behavior for ServiceAccount objects @@ -46,7 +46,7 @@ func (strategy) PrepareForCreate(obj runtime.Object) { cleanSecretReferences(obj.(*api.ServiceAccount)) } -func (strategy) Validate(ctx api.Context, obj runtime.Object) fielderrors.ValidationErrorList { +func (strategy) Validate(ctx api.Context, obj runtime.Object) utilvalidation.ValidationErrorList { return validation.ValidateServiceAccount(obj.(*api.ServiceAccount)) } @@ -68,7 +68,7 @@ func cleanSecretReferences(serviceAccount *api.ServiceAccount) { } } -func (strategy) ValidateUpdate(ctx api.Context, obj, old runtime.Object) fielderrors.ValidationErrorList { +func (strategy) ValidateUpdate(ctx api.Context, obj, old runtime.Object) utilvalidation.ValidationErrorList { return validation.ValidateServiceAccountUpdate(obj.(*api.ServiceAccount), old.(*api.ServiceAccount)) } diff --git a/pkg/registry/thirdpartyresource/strategy.go b/pkg/registry/thirdpartyresource/strategy.go index 5a2487bfa5d..6da11576364 100644 --- a/pkg/registry/thirdpartyresource/strategy.go +++ b/pkg/registry/thirdpartyresource/strategy.go @@ -27,7 +27,7 @@ import ( "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/registry/generic" "k8s.io/kubernetes/pkg/runtime" - "k8s.io/kubernetes/pkg/util/fielderrors" + utilvalidation "k8s.io/kubernetes/pkg/util/validation" ) // strategy implements behavior for ThirdPartyResource objects @@ -51,7 +51,7 @@ func (strategy) NamespaceScoped() bool { func (strategy) PrepareForCreate(obj runtime.Object) { } -func (strategy) Validate(ctx api.Context, obj runtime.Object) fielderrors.ValidationErrorList { +func (strategy) Validate(ctx api.Context, obj runtime.Object) utilvalidation.ValidationErrorList { return validation.ValidateThirdPartyResource(obj.(*extensions.ThirdPartyResource)) } @@ -66,7 +66,7 @@ func (strategy) AllowCreateOnUpdate() bool { func (strategy) PrepareForUpdate(obj, old runtime.Object) { } -func (strategy) ValidateUpdate(ctx api.Context, obj, old runtime.Object) fielderrors.ValidationErrorList { +func (strategy) ValidateUpdate(ctx api.Context, obj, old runtime.Object) utilvalidation.ValidationErrorList { return validation.ValidateThirdPartyResourceUpdate(obj.(*extensions.ThirdPartyResource), old.(*extensions.ThirdPartyResource)) } diff --git a/pkg/registry/thirdpartyresourcedata/strategy.go b/pkg/registry/thirdpartyresourcedata/strategy.go index 9a3e3856e56..5a26107c46d 100644 --- a/pkg/registry/thirdpartyresourcedata/strategy.go +++ b/pkg/registry/thirdpartyresourcedata/strategy.go @@ -27,7 +27,7 @@ import ( "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/registry/generic" "k8s.io/kubernetes/pkg/runtime" - "k8s.io/kubernetes/pkg/util/fielderrors" + utilvalidation "k8s.io/kubernetes/pkg/util/validation" ) // strategy implements behavior for ThirdPartyResource objects @@ -51,7 +51,7 @@ func (strategy) NamespaceScoped() bool { func (strategy) PrepareForCreate(obj runtime.Object) { } -func (strategy) Validate(ctx api.Context, obj runtime.Object) fielderrors.ValidationErrorList { +func (strategy) Validate(ctx api.Context, obj runtime.Object) utilvalidation.ValidationErrorList { return validation.ValidateThirdPartyResourceData(obj.(*extensions.ThirdPartyResourceData)) } @@ -66,7 +66,7 @@ func (strategy) AllowCreateOnUpdate() bool { func (strategy) PrepareForUpdate(obj, old runtime.Object) { } -func (strategy) ValidateUpdate(ctx api.Context, obj, old runtime.Object) fielderrors.ValidationErrorList { +func (strategy) ValidateUpdate(ctx api.Context, obj, old runtime.Object) utilvalidation.ValidationErrorList { return validation.ValidateThirdPartyResourceDataUpdate(obj.(*extensions.ThirdPartyResourceData), old.(*extensions.ThirdPartyResourceData)) } diff --git a/pkg/storage/util.go b/pkg/storage/util.go index c10a8ee2311..a7e95ac25bf 100644 --- a/pkg/storage/util.go +++ b/pkg/storage/util.go @@ -24,7 +24,7 @@ import ( "k8s.io/kubernetes/pkg/api/meta" "k8s.io/kubernetes/pkg/api/validation" "k8s.io/kubernetes/pkg/runtime" - "k8s.io/kubernetes/pkg/util/fielderrors" + utilvalidation "k8s.io/kubernetes/pkg/util/validation" ) type SimpleUpdateFunc func(runtime.Object) (runtime.Object, error) @@ -48,7 +48,7 @@ func ParseWatchResourceVersion(resourceVersion, kind string) (uint64, error) { version, err := strconv.ParseUint(resourceVersion, 10, 64) if err != nil { // TODO: Does this need to be a ValidationErrorList? I can't convince myself it does. - return 0, errors.NewInvalid(kind, "", fielderrors.ValidationErrorList{fielderrors.NewFieldInvalid("resourceVersion", resourceVersion, err.Error())}) + return 0, errors.NewInvalid(kind, "", utilvalidation.ValidationErrorList{utilvalidation.NewFieldInvalid("resourceVersion", resourceVersion, err.Error())}) } return version + 1, nil } diff --git a/pkg/util/fielderrors/fielderrors.go b/pkg/util/validation/errors.go similarity index 99% rename from pkg/util/fielderrors/fielderrors.go rename to pkg/util/validation/errors.go index aa2e022b358..12dd5767fb7 100644 --- a/pkg/util/fielderrors/fielderrors.go +++ b/pkg/util/validation/errors.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package fielderrors +package validation import ( "fmt" diff --git a/pkg/util/fielderrors/fielderrors_test.go b/pkg/util/validation/errors_test.go similarity index 99% rename from pkg/util/fielderrors/fielderrors_test.go rename to pkg/util/validation/errors_test.go index b77c641c29f..25f0b31d893 100644 --- a/pkg/util/fielderrors/fielderrors_test.go +++ b/pkg/util/validation/errors_test.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package fielderrors +package validation import ( "strings"