Commit 7fb8f607 authored by Tim Hockin's avatar Tim Hockin

Shorten names for better reading

parent 87a35047
...@@ -123,7 +123,7 @@ func validateObject(obj runtime.Object) (errors field.ErrorList) { ...@@ -123,7 +123,7 @@ func validateObject(obj runtime.Object) (errors field.ErrorList) {
} }
errors = expvalidation.ValidateDaemonSet(t) errors = expvalidation.ValidateDaemonSet(t)
default: default:
return field.ErrorList{field.NewInternalError(field.NewPath(""), fmt.Errorf("no validation defined for %#v", obj))} return field.ErrorList{field.InternalError(field.NewPath(""), fmt.Errorf("no validation defined for %#v", obj))}
} }
return errors return errors
} }
......
...@@ -92,7 +92,7 @@ func TestNewInvalid(t *testing.T) { ...@@ -92,7 +92,7 @@ func TestNewInvalid(t *testing.T) {
Details *unversioned.StatusDetails Details *unversioned.StatusDetails
}{ }{
{ {
field.NewDuplicateError(field.NewPath("field[0].name"), "bar"), field.Duplicate(field.NewPath("field[0].name"), "bar"),
&unversioned.StatusDetails{ &unversioned.StatusDetails{
Kind: "kind", Kind: "kind",
Name: "name", Name: "name",
...@@ -103,7 +103,7 @@ func TestNewInvalid(t *testing.T) { ...@@ -103,7 +103,7 @@ func TestNewInvalid(t *testing.T) {
}, },
}, },
{ {
field.NewInvalidError(field.NewPath("field[0].name"), "bar", "detail"), field.Invalid(field.NewPath("field[0].name"), "bar", "detail"),
&unversioned.StatusDetails{ &unversioned.StatusDetails{
Kind: "kind", Kind: "kind",
Name: "name", Name: "name",
...@@ -114,7 +114,7 @@ func TestNewInvalid(t *testing.T) { ...@@ -114,7 +114,7 @@ func TestNewInvalid(t *testing.T) {
}, },
}, },
{ {
field.NewNotFoundError(field.NewPath("field[0].name"), "bar"), field.NotFound(field.NewPath("field[0].name"), "bar"),
&unversioned.StatusDetails{ &unversioned.StatusDetails{
Kind: "kind", Kind: "kind",
Name: "name", Name: "name",
...@@ -125,7 +125,7 @@ func TestNewInvalid(t *testing.T) { ...@@ -125,7 +125,7 @@ func TestNewInvalid(t *testing.T) {
}, },
}, },
{ {
field.NewNotSupportedError(field.NewPath("field[0].name"), "bar", nil), field.NotSupported(field.NewPath("field[0].name"), "bar", nil),
&unversioned.StatusDetails{ &unversioned.StatusDetails{
Kind: "kind", Kind: "kind",
Name: "name", Name: "name",
...@@ -136,7 +136,7 @@ func TestNewInvalid(t *testing.T) { ...@@ -136,7 +136,7 @@ func TestNewInvalid(t *testing.T) {
}, },
}, },
{ {
field.NewRequiredError(field.NewPath("field[0].name")), field.Required(field.NewPath("field[0].name")),
&unversioned.StatusDetails{ &unversioned.StatusDetails{
Kind: "kind", Kind: "kind",
Name: "name", Name: "name",
......
...@@ -57,11 +57,11 @@ func validateCommonFields(obj, old runtime.Object) field.ErrorList { ...@@ -57,11 +57,11 @@ func validateCommonFields(obj, old runtime.Object) field.ErrorList {
allErrs := field.ErrorList{} allErrs := field.ErrorList{}
objectMeta, err := api.ObjectMetaFor(obj) objectMeta, err := api.ObjectMetaFor(obj)
if err != nil { if err != nil {
return append(allErrs, field.NewInternalError(field.NewPath("metadata"), err)) return append(allErrs, field.InternalError(field.NewPath("metadata"), err))
} }
oldObjectMeta, err := api.ObjectMetaFor(old) oldObjectMeta, err := api.ObjectMetaFor(old)
if err != nil { if err != nil {
return append(allErrs, field.NewInternalError(field.NewPath("metadata"), err)) return append(allErrs, field.InternalError(field.NewPath("metadata"), err))
} }
allErrs = append(allErrs, validation.ValidateObjectMetaUpdate(objectMeta, oldObjectMeta, field.NewPath("metadata"))...) allErrs = append(allErrs, validation.ValidateObjectMetaUpdate(objectMeta, oldObjectMeta, field.NewPath("metadata"))...)
......
...@@ -28,14 +28,14 @@ func ValidateEvent(event *api.Event) field.ErrorList { ...@@ -28,14 +28,14 @@ func ValidateEvent(event *api.Event) field.ErrorList {
// There is no namespace required for node. // There is no namespace required for node.
if event.InvolvedObject.Kind == "Node" && if event.InvolvedObject.Kind == "Node" &&
event.Namespace != "" { event.Namespace != "" {
allErrs = append(allErrs, field.NewInvalidError(field.NewPath("involvedObject", "namespace"), event.InvolvedObject.Namespace, "not required for node")) allErrs = append(allErrs, field.Invalid(field.NewPath("involvedObject", "namespace"), event.InvolvedObject.Namespace, "not required for node"))
} }
if event.InvolvedObject.Kind != "Node" && if event.InvolvedObject.Kind != "Node" &&
event.Namespace != event.InvolvedObject.Namespace { event.Namespace != event.InvolvedObject.Namespace {
allErrs = append(allErrs, field.NewInvalidError(field.NewPath("involvedObject", "namespace"), event.InvolvedObject.Namespace, "does not match involvedObject")) allErrs = append(allErrs, field.Invalid(field.NewPath("involvedObject", "namespace"), event.InvolvedObject.Namespace, "does not match involvedObject"))
} }
if !validation.IsDNS1123Subdomain(event.Namespace) { if !validation.IsDNS1123Subdomain(event.Namespace) {
allErrs = append(allErrs, field.NewInvalidError(field.NewPath("namespace"), event.Namespace, "")) allErrs = append(allErrs, field.Invalid(field.NewPath("namespace"), event.Namespace, ""))
} }
return allErrs return allErrs
} }
...@@ -65,7 +65,7 @@ const totalAnnotationSizeLimitB int = 256 * (1 << 10) // 256 kB ...@@ -65,7 +65,7 @@ const totalAnnotationSizeLimitB int = 256 * (1 << 10) // 256 kB
func ValidateLabelName(labelName string, fldPath *field.Path) field.ErrorList { func ValidateLabelName(labelName string, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{} allErrs := field.ErrorList{}
if !validation.IsQualifiedName(labelName) { if !validation.IsQualifiedName(labelName) {
allErrs = append(allErrs, field.NewInvalidError(fldPath, labelName, qualifiedNameErrorMsg)) allErrs = append(allErrs, field.Invalid(fldPath, labelName, qualifiedNameErrorMsg))
} }
return allErrs return allErrs
} }
...@@ -76,7 +76,7 @@ func ValidateLabels(labels map[string]string, fldPath *field.Path) field.ErrorLi ...@@ -76,7 +76,7 @@ func ValidateLabels(labels map[string]string, fldPath *field.Path) field.ErrorLi
for k, v := range labels { for k, v := range labels {
allErrs = append(allErrs, ValidateLabelName(k, fldPath)...) allErrs = append(allErrs, ValidateLabelName(k, fldPath)...)
if !validation.IsValidLabelValue(v) { if !validation.IsValidLabelValue(v) {
allErrs = append(allErrs, field.NewInvalidError(fldPath, v, labelValueErrorMsg)) allErrs = append(allErrs, field.Invalid(fldPath, v, labelValueErrorMsg))
} }
} }
return allErrs return allErrs
...@@ -88,12 +88,12 @@ func ValidateAnnotations(annotations map[string]string, fldPath *field.Path) fie ...@@ -88,12 +88,12 @@ func ValidateAnnotations(annotations map[string]string, fldPath *field.Path) fie
var totalSize int64 var totalSize int64
for k, v := range annotations { for k, v := range annotations {
if !validation.IsQualifiedName(strings.ToLower(k)) { if !validation.IsQualifiedName(strings.ToLower(k)) {
allErrs = append(allErrs, field.NewInvalidError(fldPath, k, qualifiedNameErrorMsg)) allErrs = append(allErrs, field.Invalid(fldPath, k, qualifiedNameErrorMsg))
} }
totalSize += (int64)(len(k)) + (int64)(len(v)) totalSize += (int64)(len(k)) + (int64)(len(v))
} }
if totalSize > (int64)(totalAnnotationSizeLimitB) { if totalSize > (int64)(totalAnnotationSizeLimitB) {
allErrs = append(allErrs, field.NewTooLongError(fldPath, "", totalAnnotationSizeLimitB)) allErrs = append(allErrs, field.TooLong(fldPath, "", totalAnnotationSizeLimitB))
} }
return allErrs return allErrs
} }
...@@ -221,7 +221,7 @@ func NameIsDNS952Label(name string, prefix bool) (bool, string) { ...@@ -221,7 +221,7 @@ func NameIsDNS952Label(name string, prefix bool) (bool, string) {
func ValidatePositiveField(value int64, fldPath *field.Path) field.ErrorList { func ValidatePositiveField(value int64, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{} allErrs := field.ErrorList{}
if value < 0 { if value < 0 {
allErrs = append(allErrs, field.NewInvalidError(fldPath, value, isNegativeErrorMsg)) allErrs = append(allErrs, field.Invalid(fldPath, value, isNegativeErrorMsg))
} }
return allErrs return allErrs
} }
...@@ -230,7 +230,7 @@ func ValidatePositiveField(value int64, fldPath *field.Path) field.ErrorList { ...@@ -230,7 +230,7 @@ func ValidatePositiveField(value int64, fldPath *field.Path) field.ErrorList {
func ValidatePositiveQuantity(value resource.Quantity, fldPath *field.Path) field.ErrorList { func ValidatePositiveQuantity(value resource.Quantity, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{} allErrs := field.ErrorList{}
if value.Cmp(resource.Quantity{}) < 0 { if value.Cmp(resource.Quantity{}) < 0 {
allErrs = append(allErrs, field.NewInvalidError(fldPath, value.String(), isNegativeErrorMsg)) allErrs = append(allErrs, field.Invalid(fldPath, value.String(), isNegativeErrorMsg))
} }
return allErrs return allErrs
} }
...@@ -238,7 +238,7 @@ func ValidatePositiveQuantity(value resource.Quantity, fldPath *field.Path) fiel ...@@ -238,7 +238,7 @@ func ValidatePositiveQuantity(value resource.Quantity, fldPath *field.Path) fiel
func ValidateImmutableField(newVal, oldVal interface{}, fldPath *field.Path) field.ErrorList { func ValidateImmutableField(newVal, oldVal interface{}, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{} allErrs := field.ErrorList{}
if !api.Semantic.DeepEqual(oldVal, newVal) { if !api.Semantic.DeepEqual(oldVal, newVal) {
allErrs = append(allErrs, field.NewInvalidError(fldPath, newVal, fieldImmutableErrorMsg)) allErrs = append(allErrs, field.Invalid(fldPath, newVal, fieldImmutableErrorMsg))
} }
return allErrs return allErrs
} }
...@@ -252,31 +252,31 @@ func ValidateObjectMeta(meta *api.ObjectMeta, requiresNamespace bool, nameFn Val ...@@ -252,31 +252,31 @@ func ValidateObjectMeta(meta *api.ObjectMeta, requiresNamespace bool, nameFn Val
if len(meta.GenerateName) != 0 { if len(meta.GenerateName) != 0 {
if ok, qualifier := nameFn(meta.GenerateName, true); !ok { if ok, qualifier := nameFn(meta.GenerateName, true); !ok {
allErrs = append(allErrs, field.NewInvalidError(fldPath.Child("generateName"), meta.GenerateName, qualifier)) allErrs = append(allErrs, field.Invalid(fldPath.Child("generateName"), meta.GenerateName, qualifier))
} }
} }
// If the generated name validates, but the calculated value does not, it's a problem with generation, and we // 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. // 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 there are multiple fields out of which one is required then add a or as a separator
if len(meta.Name) == 0 { if len(meta.Name) == 0 {
requiredErr := field.NewRequiredError(fldPath.Child("name")) requiredErr := field.Required(fldPath.Child("name"))
requiredErr.Detail = "name or generateName is required" requiredErr.Detail = "name or generateName is required"
allErrs = append(allErrs, requiredErr) allErrs = append(allErrs, requiredErr)
} else { } else {
if ok, qualifier := nameFn(meta.Name, false); !ok { if ok, qualifier := nameFn(meta.Name, false); !ok {
allErrs = append(allErrs, field.NewInvalidError(fldPath.Child("name"), meta.Name, qualifier)) allErrs = append(allErrs, field.Invalid(fldPath.Child("name"), meta.Name, qualifier))
} }
} }
allErrs = append(allErrs, ValidatePositiveField(meta.Generation, fldPath.Child("generation"))...) allErrs = append(allErrs, ValidatePositiveField(meta.Generation, fldPath.Child("generation"))...)
if requiresNamespace { if requiresNamespace {
if len(meta.Namespace) == 0 { if len(meta.Namespace) == 0 {
allErrs = append(allErrs, field.NewRequiredError(fldPath.Child("namespace"))) allErrs = append(allErrs, field.Required(fldPath.Child("namespace")))
} else if ok, _ := ValidateNamespaceName(meta.Namespace, false); !ok { } else if ok, _ := ValidateNamespaceName(meta.Namespace, false); !ok {
allErrs = append(allErrs, field.NewInvalidError(fldPath.Child("namespace"), meta.Namespace, DNS1123LabelErrorMsg)) allErrs = append(allErrs, field.Invalid(fldPath.Child("namespace"), meta.Namespace, DNS1123LabelErrorMsg))
} }
} else { } else {
if len(meta.Namespace) != 0 { if len(meta.Namespace) != 0 {
allErrs = append(allErrs, field.NewInvalidError(fldPath.Child("namespace"), meta.Namespace, "namespace is not allowed on this type")) allErrs = append(allErrs, field.Invalid(fldPath.Child("namespace"), meta.Namespace, "namespace is not allowed on this type"))
} }
} }
allErrs = append(allErrs, ValidateLabels(meta.Labels, fldPath.Child("labels"))...) allErrs = append(allErrs, ValidateLabels(meta.Labels, fldPath.Child("labels"))...)
...@@ -290,7 +290,7 @@ func ValidateObjectMetaUpdate(newMeta, oldMeta *api.ObjectMeta, fldPath *field.P ...@@ -290,7 +290,7 @@ func ValidateObjectMetaUpdate(newMeta, oldMeta *api.ObjectMeta, fldPath *field.P
allErrs := field.ErrorList{} allErrs := field.ErrorList{}
if !RepairMalformedUpdates && newMeta.UID != oldMeta.UID { if !RepairMalformedUpdates && newMeta.UID != oldMeta.UID {
allErrs = append(allErrs, field.NewInvalidError(fldPath.Child("uid"), newMeta.UID, "field is immutable")) allErrs = append(allErrs, field.Invalid(fldPath.Child("uid"), newMeta.UID, "field is immutable"))
} }
// in the event it is left empty, set it, to allow clients more flexibility // 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. // TODO: remove the following code that repairs the update request when we retire the clients that modify the immutable fields.
...@@ -316,12 +316,12 @@ func ValidateObjectMetaUpdate(newMeta, oldMeta *api.ObjectMeta, fldPath *field.P ...@@ -316,12 +316,12 @@ func ValidateObjectMetaUpdate(newMeta, oldMeta *api.ObjectMeta, fldPath *field.P
// TODO: needs to check if newMeta==nil && oldMeta !=nil after the repair logic is removed. // TODO: needs to check if newMeta==nil && oldMeta !=nil after the repair logic is removed.
if newMeta.DeletionGracePeriodSeconds != nil && oldMeta.DeletionGracePeriodSeconds != nil && *newMeta.DeletionGracePeriodSeconds != *oldMeta.DeletionGracePeriodSeconds { if newMeta.DeletionGracePeriodSeconds != nil && oldMeta.DeletionGracePeriodSeconds != nil && *newMeta.DeletionGracePeriodSeconds != *oldMeta.DeletionGracePeriodSeconds {
allErrs = append(allErrs, field.NewInvalidError(fldPath.Child("deletionGracePeriodSeconds"), newMeta.DeletionGracePeriodSeconds, "field is immutable; may only be changed via deletion")) allErrs = append(allErrs, field.Invalid(fldPath.Child("deletionGracePeriodSeconds"), newMeta.DeletionGracePeriodSeconds, "field is immutable; may only be changed via deletion"))
} }
// Reject updates that don't specify a resource version // Reject updates that don't specify a resource version
if newMeta.ResourceVersion == "" { if newMeta.ResourceVersion == "" {
allErrs = append(allErrs, field.NewInvalidError(fldPath.Child("resourceVersion"), newMeta.ResourceVersion, "resourceVersion must be specified for an update")) allErrs = append(allErrs, field.Invalid(fldPath.Child("resourceVersion"), newMeta.ResourceVersion, "resourceVersion must be specified for an update"))
} }
allErrs = append(allErrs, ValidateImmutableField(newMeta.Name, oldMeta.Name, fldPath.Child("name"))...) allErrs = append(allErrs, ValidateImmutableField(newMeta.Name, oldMeta.Name, fldPath.Child("name"))...)
...@@ -343,11 +343,11 @@ func validateVolumes(volumes []api.Volume, fldPath *field.Path) (sets.String, fi ...@@ -343,11 +343,11 @@ func validateVolumes(volumes []api.Volume, fldPath *field.Path) (sets.String, fi
idxPath := fldPath.Index(i) idxPath := fldPath.Index(i)
el := validateVolumeSource(&vol.VolumeSource, idxPath) el := validateVolumeSource(&vol.VolumeSource, idxPath)
if len(vol.Name) == 0 { if len(vol.Name) == 0 {
el = append(el, field.NewRequiredError(idxPath.Child("name"))) el = append(el, field.Required(idxPath.Child("name")))
} else if !validation.IsDNS1123Label(vol.Name) { } else if !validation.IsDNS1123Label(vol.Name) {
el = append(el, field.NewInvalidError(idxPath.Child("name"), vol.Name, DNS1123LabelErrorMsg)) el = append(el, field.Invalid(idxPath.Child("name"), vol.Name, DNS1123LabelErrorMsg))
} else if allNames.Has(vol.Name) { } else if allNames.Has(vol.Name) {
el = append(el, field.NewDuplicateError(idxPath.Child("name"), vol.Name)) el = append(el, field.Duplicate(idxPath.Child("name"), vol.Name))
} }
if len(el) == 0 { if len(el) == 0 {
allNames.Insert(vol.Name) allNames.Insert(vol.Name)
...@@ -427,7 +427,7 @@ func validateVolumeSource(source *api.VolumeSource, fldPath *field.Path) field.E ...@@ -427,7 +427,7 @@ func validateVolumeSource(source *api.VolumeSource, fldPath *field.Path) field.E
allErrs = append(allErrs, validateFCVolumeSource(source.FC, fldPath.Child("fc"))...) allErrs = append(allErrs, validateFCVolumeSource(source.FC, fldPath.Child("fc"))...)
} }
if numVolumes != 1 { if numVolumes != 1 {
allErrs = append(allErrs, field.NewInvalidError(fldPath, source, "exactly 1 volume type is required")) allErrs = append(allErrs, field.Invalid(fldPath, source, "exactly 1 volume type is required"))
} }
return allErrs return allErrs
...@@ -436,7 +436,7 @@ func validateVolumeSource(source *api.VolumeSource, fldPath *field.Path) field.E ...@@ -436,7 +436,7 @@ func validateVolumeSource(source *api.VolumeSource, fldPath *field.Path) field.E
func validateHostPathVolumeSource(hostPath *api.HostPathVolumeSource, fldPath *field.Path) field.ErrorList { func validateHostPathVolumeSource(hostPath *api.HostPathVolumeSource, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{} allErrs := field.ErrorList{}
if hostPath.Path == "" { if hostPath.Path == "" {
allErrs = append(allErrs, field.NewRequiredError(fldPath.Child("path"))) allErrs = append(allErrs, field.Required(fldPath.Child("path")))
} }
return allErrs return allErrs
} }
...@@ -444,7 +444,7 @@ func validateHostPathVolumeSource(hostPath *api.HostPathVolumeSource, fldPath *f ...@@ -444,7 +444,7 @@ func validateHostPathVolumeSource(hostPath *api.HostPathVolumeSource, fldPath *f
func validateGitRepoVolumeSource(gitRepo *api.GitRepoVolumeSource, fldPath *field.Path) field.ErrorList { func validateGitRepoVolumeSource(gitRepo *api.GitRepoVolumeSource, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{} allErrs := field.ErrorList{}
if len(gitRepo.Repository) == 0 { if len(gitRepo.Repository) == 0 {
allErrs = append(allErrs, field.NewRequiredError(fldPath.Child("repository"))) allErrs = append(allErrs, field.Required(fldPath.Child("repository")))
} }
pathErrs := validateVolumeSourcePath(gitRepo.Directory, fldPath.Child("directory")) pathErrs := validateVolumeSourcePath(gitRepo.Directory, fldPath.Child("directory"))
...@@ -455,16 +455,16 @@ func validateGitRepoVolumeSource(gitRepo *api.GitRepoVolumeSource, fldPath *fiel ...@@ -455,16 +455,16 @@ func validateGitRepoVolumeSource(gitRepo *api.GitRepoVolumeSource, fldPath *fiel
func validateISCSIVolumeSource(iscsi *api.ISCSIVolumeSource, fldPath *field.Path) field.ErrorList { func validateISCSIVolumeSource(iscsi *api.ISCSIVolumeSource, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{} allErrs := field.ErrorList{}
if iscsi.TargetPortal == "" { if iscsi.TargetPortal == "" {
allErrs = append(allErrs, field.NewRequiredError(fldPath.Child("targetPortal"))) allErrs = append(allErrs, field.Required(fldPath.Child("targetPortal")))
} }
if iscsi.IQN == "" { if iscsi.IQN == "" {
allErrs = append(allErrs, field.NewRequiredError(fldPath.Child("iqn"))) allErrs = append(allErrs, field.Required(fldPath.Child("iqn")))
} }
if iscsi.FSType == "" { if iscsi.FSType == "" {
allErrs = append(allErrs, field.NewRequiredError(fldPath.Child("fsType"))) allErrs = append(allErrs, field.Required(fldPath.Child("fsType")))
} }
if iscsi.Lun < 0 || iscsi.Lun > 255 { if iscsi.Lun < 0 || iscsi.Lun > 255 {
allErrs = append(allErrs, field.NewInvalidError(fldPath.Child("lun"), iscsi.Lun, "")) allErrs = append(allErrs, field.Invalid(fldPath.Child("lun"), iscsi.Lun, ""))
} }
return allErrs return allErrs
} }
...@@ -472,17 +472,17 @@ func validateISCSIVolumeSource(iscsi *api.ISCSIVolumeSource, fldPath *field.Path ...@@ -472,17 +472,17 @@ func validateISCSIVolumeSource(iscsi *api.ISCSIVolumeSource, fldPath *field.Path
func validateFCVolumeSource(fc *api.FCVolumeSource, fldPath *field.Path) field.ErrorList { func validateFCVolumeSource(fc *api.FCVolumeSource, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{} allErrs := field.ErrorList{}
if len(fc.TargetWWNs) < 1 { if len(fc.TargetWWNs) < 1 {
allErrs = append(allErrs, field.NewRequiredError(fldPath.Child("targetWWNs"))) allErrs = append(allErrs, field.Required(fldPath.Child("targetWWNs")))
} }
if fc.FSType == "" { if fc.FSType == "" {
allErrs = append(allErrs, field.NewRequiredError(fldPath.Child("fsType"))) allErrs = append(allErrs, field.Required(fldPath.Child("fsType")))
} }
if fc.Lun == nil { if fc.Lun == nil {
allErrs = append(allErrs, field.NewRequiredError(fldPath.Child("lun"))) allErrs = append(allErrs, field.Required(fldPath.Child("lun")))
} else { } else {
if *fc.Lun < 0 || *fc.Lun > 255 { if *fc.Lun < 0 || *fc.Lun > 255 {
allErrs = append(allErrs, field.NewInvalidError(fldPath.Child("lun"), fc.Lun, "")) allErrs = append(allErrs, field.Invalid(fldPath.Child("lun"), fc.Lun, ""))
} }
} }
return allErrs return allErrs
...@@ -491,13 +491,13 @@ func validateFCVolumeSource(fc *api.FCVolumeSource, fldPath *field.Path) field.E ...@@ -491,13 +491,13 @@ func validateFCVolumeSource(fc *api.FCVolumeSource, fldPath *field.Path) field.E
func validateGCEPersistentDiskVolumeSource(pd *api.GCEPersistentDiskVolumeSource, fldPath *field.Path) field.ErrorList { func validateGCEPersistentDiskVolumeSource(pd *api.GCEPersistentDiskVolumeSource, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{} allErrs := field.ErrorList{}
if pd.PDName == "" { if pd.PDName == "" {
allErrs = append(allErrs, field.NewRequiredError(fldPath.Child("pdName"))) allErrs = append(allErrs, field.Required(fldPath.Child("pdName")))
} }
if pd.FSType == "" { if pd.FSType == "" {
allErrs = append(allErrs, field.NewRequiredError(fldPath.Child("fsType"))) allErrs = append(allErrs, field.Required(fldPath.Child("fsType")))
} }
if pd.Partition < 0 || pd.Partition > 255 { if pd.Partition < 0 || pd.Partition > 255 {
allErrs = append(allErrs, field.NewInvalidError(fldPath.Child("partition"), pd.Partition, pdPartitionErrorMsg)) allErrs = append(allErrs, field.Invalid(fldPath.Child("partition"), pd.Partition, pdPartitionErrorMsg))
} }
return allErrs return allErrs
} }
...@@ -505,13 +505,13 @@ func validateGCEPersistentDiskVolumeSource(pd *api.GCEPersistentDiskVolumeSource ...@@ -505,13 +505,13 @@ func validateGCEPersistentDiskVolumeSource(pd *api.GCEPersistentDiskVolumeSource
func validateAWSElasticBlockStoreVolumeSource(PD *api.AWSElasticBlockStoreVolumeSource, fldPath *field.Path) field.ErrorList { func validateAWSElasticBlockStoreVolumeSource(PD *api.AWSElasticBlockStoreVolumeSource, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{} allErrs := field.ErrorList{}
if PD.VolumeID == "" { if PD.VolumeID == "" {
allErrs = append(allErrs, field.NewRequiredError(fldPath.Child("volumeID"))) allErrs = append(allErrs, field.Required(fldPath.Child("volumeID")))
} }
if PD.FSType == "" { if PD.FSType == "" {
allErrs = append(allErrs, field.NewRequiredError(fldPath.Child("fsType"))) allErrs = append(allErrs, field.Required(fldPath.Child("fsType")))
} }
if PD.Partition < 0 || PD.Partition > 255 { if PD.Partition < 0 || PD.Partition > 255 {
allErrs = append(allErrs, field.NewInvalidError(fldPath.Child("partition"), PD.Partition, pdPartitionErrorMsg)) allErrs = append(allErrs, field.Invalid(fldPath.Child("partition"), PD.Partition, pdPartitionErrorMsg))
} }
return allErrs return allErrs
} }
...@@ -519,7 +519,7 @@ func validateAWSElasticBlockStoreVolumeSource(PD *api.AWSElasticBlockStoreVolume ...@@ -519,7 +519,7 @@ func validateAWSElasticBlockStoreVolumeSource(PD *api.AWSElasticBlockStoreVolume
func validateSecretVolumeSource(secretSource *api.SecretVolumeSource, fldPath *field.Path) field.ErrorList { func validateSecretVolumeSource(secretSource *api.SecretVolumeSource, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{} allErrs := field.ErrorList{}
if secretSource.SecretName == "" { if secretSource.SecretName == "" {
allErrs = append(allErrs, field.NewRequiredError(fldPath.Child("secretName"))) allErrs = append(allErrs, field.Required(fldPath.Child("secretName")))
} }
return allErrs return allErrs
} }
...@@ -527,7 +527,7 @@ func validateSecretVolumeSource(secretSource *api.SecretVolumeSource, fldPath *f ...@@ -527,7 +527,7 @@ func validateSecretVolumeSource(secretSource *api.SecretVolumeSource, fldPath *f
func validatePersistentClaimVolumeSource(claim *api.PersistentVolumeClaimVolumeSource, fldPath *field.Path) field.ErrorList { func validatePersistentClaimVolumeSource(claim *api.PersistentVolumeClaimVolumeSource, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{} allErrs := field.ErrorList{}
if claim.ClaimName == "" { if claim.ClaimName == "" {
allErrs = append(allErrs, field.NewRequiredError(fldPath.Child("claimName"))) allErrs = append(allErrs, field.Required(fldPath.Child("claimName")))
} }
return allErrs return allErrs
} }
...@@ -535,13 +535,13 @@ func validatePersistentClaimVolumeSource(claim *api.PersistentVolumeClaimVolumeS ...@@ -535,13 +535,13 @@ func validatePersistentClaimVolumeSource(claim *api.PersistentVolumeClaimVolumeS
func validateNFSVolumeSource(nfs *api.NFSVolumeSource, fldPath *field.Path) field.ErrorList { func validateNFSVolumeSource(nfs *api.NFSVolumeSource, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{} allErrs := field.ErrorList{}
if nfs.Server == "" { if nfs.Server == "" {
allErrs = append(allErrs, field.NewRequiredError(fldPath.Child("server"))) allErrs = append(allErrs, field.Required(fldPath.Child("server")))
} }
if nfs.Path == "" { if nfs.Path == "" {
allErrs = append(allErrs, field.NewRequiredError(fldPath.Child("path"))) allErrs = append(allErrs, field.Required(fldPath.Child("path")))
} }
if !path.IsAbs(nfs.Path) { if !path.IsAbs(nfs.Path) {
allErrs = append(allErrs, field.NewInvalidError(fldPath.Child("path"), nfs.Path, "must be an absolute path")) allErrs = append(allErrs, field.Invalid(fldPath.Child("path"), nfs.Path, "must be an absolute path"))
} }
return allErrs return allErrs
} }
...@@ -549,10 +549,10 @@ func validateNFSVolumeSource(nfs *api.NFSVolumeSource, fldPath *field.Path) fiel ...@@ -549,10 +549,10 @@ func validateNFSVolumeSource(nfs *api.NFSVolumeSource, fldPath *field.Path) fiel
func validateGlusterfs(glusterfs *api.GlusterfsVolumeSource, fldPath *field.Path) field.ErrorList { func validateGlusterfs(glusterfs *api.GlusterfsVolumeSource, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{} allErrs := field.ErrorList{}
if glusterfs.EndpointsName == "" { if glusterfs.EndpointsName == "" {
allErrs = append(allErrs, field.NewRequiredError(fldPath.Child("endpoints"))) allErrs = append(allErrs, field.Required(fldPath.Child("endpoints")))
} }
if glusterfs.Path == "" { if glusterfs.Path == "" {
allErrs = append(allErrs, field.NewRequiredError(fldPath.Child("path"))) allErrs = append(allErrs, field.Required(fldPath.Child("path")))
} }
return allErrs return allErrs
} }
...@@ -560,10 +560,10 @@ func validateGlusterfs(glusterfs *api.GlusterfsVolumeSource, fldPath *field.Path ...@@ -560,10 +560,10 @@ func validateGlusterfs(glusterfs *api.GlusterfsVolumeSource, fldPath *field.Path
func validateFlockerVolumeSource(flocker *api.FlockerVolumeSource, fldPath *field.Path) field.ErrorList { func validateFlockerVolumeSource(flocker *api.FlockerVolumeSource, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{} allErrs := field.ErrorList{}
if flocker.DatasetName == "" { if flocker.DatasetName == "" {
allErrs = append(allErrs, field.NewRequiredError(fldPath.Child("datasetName"))) allErrs = append(allErrs, field.Required(fldPath.Child("datasetName")))
} }
if strings.Contains(flocker.DatasetName, "/") { if strings.Contains(flocker.DatasetName, "/") {
allErrs = append(allErrs, field.NewInvalidError(fldPath.Child("datasetName"), flocker.DatasetName, "must not contain '/'")) allErrs = append(allErrs, field.Invalid(fldPath.Child("datasetName"), flocker.DatasetName, "must not contain '/'"))
} }
return allErrs return allErrs
} }
...@@ -574,7 +574,7 @@ func validateDownwardAPIVolumeSource(downwardAPIVolume *api.DownwardAPIVolumeSou ...@@ -574,7 +574,7 @@ func validateDownwardAPIVolumeSource(downwardAPIVolume *api.DownwardAPIVolumeSou
allErrs := field.ErrorList{} allErrs := field.ErrorList{}
for _, downwardAPIVolumeFile := range downwardAPIVolume.Items { for _, downwardAPIVolumeFile := range downwardAPIVolume.Items {
if len(downwardAPIVolumeFile.Path) == 0 { if len(downwardAPIVolumeFile.Path) == 0 {
allErrs = append(allErrs, field.NewRequiredError(fldPath.Child("path"))) allErrs = append(allErrs, field.Required(fldPath.Child("path")))
} }
allErrs = append(allErrs, validateVolumeSourcePath(downwardAPIVolumeFile.Path, fldPath.Child("path"))...) allErrs = append(allErrs, validateVolumeSourcePath(downwardAPIVolumeFile.Path, fldPath.Child("path"))...)
allErrs = append(allErrs, validateObjectFieldSelector(&downwardAPIVolumeFile.FieldRef, &validDownwardAPIFieldPathExpressions, fldPath.Child("fieldRef"))...) allErrs = append(allErrs, validateObjectFieldSelector(&downwardAPIVolumeFile.FieldRef, &validDownwardAPIFieldPathExpressions, fldPath.Child("fieldRef"))...)
...@@ -589,18 +589,18 @@ func validateDownwardAPIVolumeSource(downwardAPIVolume *api.DownwardAPIVolumeSou ...@@ -589,18 +589,18 @@ func validateDownwardAPIVolumeSource(downwardAPIVolume *api.DownwardAPIVolumeSou
func validateVolumeSourcePath(targetPath string, fldPath *field.Path) field.ErrorList { func validateVolumeSourcePath(targetPath string, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{} allErrs := field.ErrorList{}
if path.IsAbs(targetPath) { if path.IsAbs(targetPath) {
allErrs = append(allErrs, field.NewForbiddenError(fldPath, "must not be an absolute path")) allErrs = append(allErrs, field.Forbidden(fldPath, "must not be an absolute path"))
} }
// TODO assume OS of api server & nodes are the same for now // TODO assume OS of api server & nodes are the same for now
items := strings.Split(targetPath, string(os.PathSeparator)) items := strings.Split(targetPath, string(os.PathSeparator))
for _, item := range items { for _, item := range items {
if item == ".." { if item == ".." {
allErrs = append(allErrs, field.NewInvalidError(fldPath, targetPath, "must not contain \"..\"")) allErrs = append(allErrs, field.Invalid(fldPath, targetPath, "must not contain \"..\""))
} }
} }
if strings.HasPrefix(items[0], "..") && len(items[0]) > 2 { if strings.HasPrefix(items[0], "..") && len(items[0]) > 2 {
allErrs = append(allErrs, field.NewInvalidError(fldPath, targetPath, "must not start with \"..\"")) allErrs = append(allErrs, field.Invalid(fldPath, targetPath, "must not start with \"..\""))
} }
return allErrs return allErrs
} }
...@@ -608,13 +608,13 @@ func validateVolumeSourcePath(targetPath string, fldPath *field.Path) field.Erro ...@@ -608,13 +608,13 @@ func validateVolumeSourcePath(targetPath string, fldPath *field.Path) field.Erro
func validateRBDVolumeSource(rbd *api.RBDVolumeSource, fldPath *field.Path) field.ErrorList { func validateRBDVolumeSource(rbd *api.RBDVolumeSource, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{} allErrs := field.ErrorList{}
if len(rbd.CephMonitors) == 0 { if len(rbd.CephMonitors) == 0 {
allErrs = append(allErrs, field.NewRequiredError(fldPath.Child("monitors"))) allErrs = append(allErrs, field.Required(fldPath.Child("monitors")))
} }
if rbd.RBDImage == "" { if rbd.RBDImage == "" {
allErrs = append(allErrs, field.NewRequiredError(fldPath.Child("image"))) allErrs = append(allErrs, field.Required(fldPath.Child("image")))
} }
if rbd.FSType == "" { if rbd.FSType == "" {
allErrs = append(allErrs, field.NewRequiredError(fldPath.Child("fsType"))) allErrs = append(allErrs, field.Required(fldPath.Child("fsType")))
} }
return allErrs return allErrs
} }
...@@ -622,10 +622,10 @@ func validateRBDVolumeSource(rbd *api.RBDVolumeSource, fldPath *field.Path) fiel ...@@ -622,10 +622,10 @@ func validateRBDVolumeSource(rbd *api.RBDVolumeSource, fldPath *field.Path) fiel
func validateCinderVolumeSource(cd *api.CinderVolumeSource, fldPath *field.Path) field.ErrorList { func validateCinderVolumeSource(cd *api.CinderVolumeSource, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{} allErrs := field.ErrorList{}
if cd.VolumeID == "" { if cd.VolumeID == "" {
allErrs = append(allErrs, field.NewRequiredError(fldPath.Child("volumeID"))) allErrs = append(allErrs, field.Required(fldPath.Child("volumeID")))
} }
if cd.FSType == "" || (cd.FSType != "ext3" && cd.FSType != "ext4") { if cd.FSType == "" || (cd.FSType != "ext3" && cd.FSType != "ext4") {
allErrs = append(allErrs, field.NewRequiredError(fldPath.Child("fsType"))) allErrs = append(allErrs, field.Required(fldPath.Child("fsType")))
} }
return allErrs return allErrs
} }
...@@ -633,7 +633,7 @@ func validateCinderVolumeSource(cd *api.CinderVolumeSource, fldPath *field.Path) ...@@ -633,7 +633,7 @@ func validateCinderVolumeSource(cd *api.CinderVolumeSource, fldPath *field.Path)
func validateCephFSVolumeSource(cephfs *api.CephFSVolumeSource, fldPath *field.Path) field.ErrorList { func validateCephFSVolumeSource(cephfs *api.CephFSVolumeSource, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{} allErrs := field.ErrorList{}
if len(cephfs.Monitors) == 0 { if len(cephfs.Monitors) == 0 {
allErrs = append(allErrs, field.NewRequiredError(fldPath.Child("monitors"))) allErrs = append(allErrs, field.Required(fldPath.Child("monitors")))
} }
return allErrs return allErrs
} }
...@@ -649,20 +649,20 @@ func ValidatePersistentVolume(pv *api.PersistentVolume) field.ErrorList { ...@@ -649,20 +649,20 @@ func ValidatePersistentVolume(pv *api.PersistentVolume) field.ErrorList {
specPath := field.NewPath("spec") specPath := field.NewPath("spec")
if len(pv.Spec.AccessModes) == 0 { if len(pv.Spec.AccessModes) == 0 {
allErrs = append(allErrs, field.NewRequiredError(specPath.Child("accessModes"))) allErrs = append(allErrs, field.Required(specPath.Child("accessModes")))
} }
for _, mode := range pv.Spec.AccessModes { for _, mode := range pv.Spec.AccessModes {
if !supportedAccessModes.Has(string(mode)) { if !supportedAccessModes.Has(string(mode)) {
allErrs = append(allErrs, field.NewNotSupportedError(specPath.Child("accessModes"), mode, supportedAccessModes.List())) allErrs = append(allErrs, field.NotSupported(specPath.Child("accessModes"), mode, supportedAccessModes.List()))
} }
} }
if len(pv.Spec.Capacity) == 0 { if len(pv.Spec.Capacity) == 0 {
allErrs = append(allErrs, field.NewRequiredError(specPath.Child("capacity"))) allErrs = append(allErrs, field.Required(specPath.Child("capacity")))
} }
if _, ok := pv.Spec.Capacity[api.ResourceStorage]; !ok || len(pv.Spec.Capacity) > 1 { if _, ok := pv.Spec.Capacity[api.ResourceStorage]; !ok || len(pv.Spec.Capacity) > 1 {
allErrs = append(allErrs, field.NewNotSupportedError(specPath.Child("capacity"), pv.Spec.Capacity, []string{string(api.ResourceStorage)})) allErrs = append(allErrs, field.NotSupported(specPath.Child("capacity"), pv.Spec.Capacity, []string{string(api.ResourceStorage)}))
} }
capPath := specPath.Child("capacity") capPath := specPath.Child("capacity")
for r, qty := range pv.Spec.Capacity { for r, qty := range pv.Spec.Capacity {
...@@ -715,7 +715,7 @@ func ValidatePersistentVolume(pv *api.PersistentVolume) field.ErrorList { ...@@ -715,7 +715,7 @@ func ValidatePersistentVolume(pv *api.PersistentVolume) field.ErrorList {
allErrs = append(allErrs, validateFCVolumeSource(pv.Spec.FC, specPath.Child("fc"))...) allErrs = append(allErrs, validateFCVolumeSource(pv.Spec.FC, specPath.Child("fc"))...)
} }
if numVolumes != 1 { if numVolumes != 1 {
allErrs = append(allErrs, field.NewInvalidError(specPath, pv.Spec.PersistentVolumeSource, "exactly 1 volume type is required")) allErrs = append(allErrs, field.Invalid(specPath, pv.Spec.PersistentVolumeSource, "exactly 1 volume type is required"))
} }
return allErrs return allErrs
} }
...@@ -734,7 +734,7 @@ func ValidatePersistentVolumeUpdate(newPv, oldPv *api.PersistentVolume) field.Er ...@@ -734,7 +734,7 @@ func ValidatePersistentVolumeUpdate(newPv, oldPv *api.PersistentVolume) field.Er
func ValidatePersistentVolumeStatusUpdate(newPv, oldPv *api.PersistentVolume) field.ErrorList { func ValidatePersistentVolumeStatusUpdate(newPv, oldPv *api.PersistentVolume) field.ErrorList {
allErrs := ValidateObjectMetaUpdate(&newPv.ObjectMeta, &oldPv.ObjectMeta, field.NewPath("metadata")) allErrs := ValidateObjectMetaUpdate(&newPv.ObjectMeta, &oldPv.ObjectMeta, field.NewPath("metadata"))
if newPv.ResourceVersion == "" { if newPv.ResourceVersion == "" {
allErrs = append(allErrs, field.NewRequiredError(field.NewPath("resourceVersion"))) allErrs = append(allErrs, field.Required(field.NewPath("resourceVersion")))
} }
newPv.Spec = oldPv.Spec newPv.Spec = oldPv.Spec
return allErrs return allErrs
...@@ -744,15 +744,15 @@ func ValidatePersistentVolumeClaim(pvc *api.PersistentVolumeClaim) field.ErrorLi ...@@ -744,15 +744,15 @@ func ValidatePersistentVolumeClaim(pvc *api.PersistentVolumeClaim) field.ErrorLi
allErrs := ValidateObjectMeta(&pvc.ObjectMeta, true, ValidatePersistentVolumeName, field.NewPath("metadata")) allErrs := ValidateObjectMeta(&pvc.ObjectMeta, true, ValidatePersistentVolumeName, field.NewPath("metadata"))
specPath := field.NewPath("spec") specPath := field.NewPath("spec")
if len(pvc.Spec.AccessModes) == 0 { if len(pvc.Spec.AccessModes) == 0 {
allErrs = append(allErrs, field.NewInvalidError(specPath.Child("accessModes"), pvc.Spec.AccessModes, "at least 1 accessMode is required")) allErrs = append(allErrs, field.Invalid(specPath.Child("accessModes"), pvc.Spec.AccessModes, "at least 1 accessMode is required"))
} }
for _, mode := range pvc.Spec.AccessModes { for _, mode := range pvc.Spec.AccessModes {
if mode != api.ReadWriteOnce && mode != api.ReadOnlyMany && mode != api.ReadWriteMany { if mode != api.ReadWriteOnce && mode != api.ReadOnlyMany && mode != api.ReadWriteMany {
allErrs = append(allErrs, field.NewNotSupportedError(specPath.Child("accessModes"), mode, supportedAccessModes.List())) allErrs = append(allErrs, field.NotSupported(specPath.Child("accessModes"), mode, supportedAccessModes.List()))
} }
} }
if _, ok := pvc.Spec.Resources.Requests[api.ResourceStorage]; !ok { if _, ok := pvc.Spec.Resources.Requests[api.ResourceStorage]; !ok {
allErrs = append(allErrs, field.NewRequiredError(specPath.Child("resources").Key(string(api.ResourceStorage)))) allErrs = append(allErrs, field.Required(specPath.Child("resources").Key(string(api.ResourceStorage))))
} }
return allErrs return allErrs
} }
...@@ -767,10 +767,10 @@ func ValidatePersistentVolumeClaimUpdate(newPvc, oldPvc *api.PersistentVolumeCla ...@@ -767,10 +767,10 @@ func ValidatePersistentVolumeClaimUpdate(newPvc, oldPvc *api.PersistentVolumeCla
func ValidatePersistentVolumeClaimStatusUpdate(newPvc, oldPvc *api.PersistentVolumeClaim) field.ErrorList { func ValidatePersistentVolumeClaimStatusUpdate(newPvc, oldPvc *api.PersistentVolumeClaim) field.ErrorList {
allErrs := ValidateObjectMetaUpdate(&newPvc.ObjectMeta, &oldPvc.ObjectMeta, field.NewPath("metadata")) allErrs := ValidateObjectMetaUpdate(&newPvc.ObjectMeta, &oldPvc.ObjectMeta, field.NewPath("metadata"))
if newPvc.ResourceVersion == "" { if newPvc.ResourceVersion == "" {
allErrs = append(allErrs, field.NewRequiredError(field.NewPath("resourceVersion"))) allErrs = append(allErrs, field.Required(field.NewPath("resourceVersion")))
} }
if len(newPvc.Spec.AccessModes) == 0 { if len(newPvc.Spec.AccessModes) == 0 {
allErrs = append(allErrs, field.NewRequiredError(field.NewPath("Spec", "accessModes"))) allErrs = append(allErrs, field.Required(field.NewPath("Spec", "accessModes")))
} }
capPath := field.NewPath("status", "capacity") capPath := field.NewPath("status", "capacity")
for r, qty := range newPvc.Status.Capacity { for r, qty := range newPvc.Status.Capacity {
...@@ -790,25 +790,25 @@ func validateContainerPorts(ports []api.ContainerPort, fldPath *field.Path) fiel ...@@ -790,25 +790,25 @@ func validateContainerPorts(ports []api.ContainerPort, fldPath *field.Path) fiel
idxPath := fldPath.Index(i) idxPath := fldPath.Index(i)
if len(port.Name) > 0 { if len(port.Name) > 0 {
if !validation.IsValidPortName(port.Name) { if !validation.IsValidPortName(port.Name) {
allErrs = append(allErrs, field.NewInvalidError(idxPath.Child("name"), port.Name, PortNameErrorMsg)) allErrs = append(allErrs, field.Invalid(idxPath.Child("name"), port.Name, PortNameErrorMsg))
} else if allNames.Has(port.Name) { } else if allNames.Has(port.Name) {
allErrs = append(allErrs, field.NewDuplicateError(idxPath.Child("name"), port.Name)) allErrs = append(allErrs, field.Duplicate(idxPath.Child("name"), port.Name))
} else { } else {
allNames.Insert(port.Name) allNames.Insert(port.Name)
} }
} }
if port.ContainerPort == 0 { if port.ContainerPort == 0 {
allErrs = append(allErrs, field.NewInvalidError(idxPath.Child("containerPort"), port.ContainerPort, PortRangeErrorMsg)) allErrs = append(allErrs, field.Invalid(idxPath.Child("containerPort"), port.ContainerPort, PortRangeErrorMsg))
} else if !validation.IsValidPortNum(port.ContainerPort) { } else if !validation.IsValidPortNum(port.ContainerPort) {
allErrs = append(allErrs, field.NewInvalidError(idxPath.Child("containerPort"), port.ContainerPort, PortRangeErrorMsg)) allErrs = append(allErrs, field.Invalid(idxPath.Child("containerPort"), port.ContainerPort, PortRangeErrorMsg))
} }
if port.HostPort != 0 && !validation.IsValidPortNum(port.HostPort) { if port.HostPort != 0 && !validation.IsValidPortNum(port.HostPort) {
allErrs = append(allErrs, field.NewInvalidError(idxPath.Child("hostPort"), port.HostPort, PortRangeErrorMsg)) allErrs = append(allErrs, field.Invalid(idxPath.Child("hostPort"), port.HostPort, PortRangeErrorMsg))
} }
if len(port.Protocol) == 0 { if len(port.Protocol) == 0 {
allErrs = append(allErrs, field.NewRequiredError(idxPath.Child("protocol"))) allErrs = append(allErrs, field.Required(idxPath.Child("protocol")))
} else if !supportedPortProtocols.Has(string(port.Protocol)) { } else if !supportedPortProtocols.Has(string(port.Protocol)) {
allErrs = append(allErrs, field.NewNotSupportedError(idxPath.Child("protocol"), port.Protocol, supportedPortProtocols.List())) allErrs = append(allErrs, field.NotSupported(idxPath.Child("protocol"), port.Protocol, supportedPortProtocols.List()))
} }
} }
return allErrs return allErrs
...@@ -820,9 +820,9 @@ func validateEnv(vars []api.EnvVar, fldPath *field.Path) field.ErrorList { ...@@ -820,9 +820,9 @@ func validateEnv(vars []api.EnvVar, fldPath *field.Path) field.ErrorList {
for i, ev := range vars { for i, ev := range vars {
idxPath := fldPath.Index(i) idxPath := fldPath.Index(i)
if len(ev.Name) == 0 { if len(ev.Name) == 0 {
allErrs = append(allErrs, field.NewRequiredError(idxPath.Child("name"))) allErrs = append(allErrs, field.Required(idxPath.Child("name")))
} else if !validation.IsCIdentifier(ev.Name) { } else if !validation.IsCIdentifier(ev.Name) {
allErrs = append(allErrs, field.NewInvalidError(idxPath.Child("name"), ev.Name, cIdentifierErrorMsg)) allErrs = append(allErrs, field.Invalid(idxPath.Child("name"), ev.Name, cIdentifierErrorMsg))
} }
allErrs = append(allErrs, validateEnvVarValueFrom(ev, idxPath.Child("valueFrom"))...) allErrs = append(allErrs, validateEnvVarValueFrom(ev, idxPath.Child("valueFrom"))...)
} }
...@@ -847,7 +847,7 @@ func validateEnvVarValueFrom(ev api.EnvVar, fldPath *field.Path) field.ErrorList ...@@ -847,7 +847,7 @@ func validateEnvVarValueFrom(ev api.EnvVar, fldPath *field.Path) field.ErrorList
} }
if ev.Value != "" && numSources != 0 { if ev.Value != "" && numSources != 0 {
allErrs = append(allErrs, field.NewInvalidError(fldPath, "", "sources cannot be specified when value is not empty")) allErrs = append(allErrs, field.Invalid(fldPath, "", "sources cannot be specified when value is not empty"))
} }
return allErrs return allErrs
...@@ -857,15 +857,15 @@ func validateObjectFieldSelector(fs *api.ObjectFieldSelector, expressions *sets. ...@@ -857,15 +857,15 @@ func validateObjectFieldSelector(fs *api.ObjectFieldSelector, expressions *sets.
allErrs := field.ErrorList{} allErrs := field.ErrorList{}
if fs.APIVersion == "" { if fs.APIVersion == "" {
allErrs = append(allErrs, field.NewRequiredError(fldPath.Child("apiVersion"))) allErrs = append(allErrs, field.Required(fldPath.Child("apiVersion")))
} else if fs.FieldPath == "" { } else if fs.FieldPath == "" {
allErrs = append(allErrs, field.NewRequiredError(fldPath.Child("fieldPath"))) allErrs = append(allErrs, field.Required(fldPath.Child("fieldPath")))
} else { } else {
internalFieldPath, _, err := api.Scheme.ConvertFieldLabel(fs.APIVersion, "Pod", fs.FieldPath, "") internalFieldPath, _, err := api.Scheme.ConvertFieldLabel(fs.APIVersion, "Pod", fs.FieldPath, "")
if err != nil { if err != nil {
allErrs = append(allErrs, field.NewInvalidError(fldPath.Child("fieldPath"), fs.FieldPath, "error converting fieldPath")) allErrs = append(allErrs, field.Invalid(fldPath.Child("fieldPath"), fs.FieldPath, "error converting fieldPath"))
} else if !expressions.Has(internalFieldPath) { } else if !expressions.Has(internalFieldPath) {
allErrs = append(allErrs, field.NewNotSupportedError(fldPath.Child("fieldPath"), internalFieldPath, expressions.List())) allErrs = append(allErrs, field.NotSupported(fldPath.Child("fieldPath"), internalFieldPath, expressions.List()))
} }
} }
...@@ -878,12 +878,12 @@ func validateVolumeMounts(mounts []api.VolumeMount, volumes sets.String, fldPath ...@@ -878,12 +878,12 @@ func validateVolumeMounts(mounts []api.VolumeMount, volumes sets.String, fldPath
for i, mnt := range mounts { for i, mnt := range mounts {
idxPath := fldPath.Index(i) idxPath := fldPath.Index(i)
if len(mnt.Name) == 0 { if len(mnt.Name) == 0 {
allErrs = append(allErrs, field.NewRequiredError(idxPath.Child("name"))) allErrs = append(allErrs, field.Required(idxPath.Child("name")))
} else if !volumes.Has(mnt.Name) { } else if !volumes.Has(mnt.Name) {
allErrs = append(allErrs, field.NewNotFoundError(idxPath.Child("name"), mnt.Name)) allErrs = append(allErrs, field.NotFound(idxPath.Child("name"), mnt.Name))
} }
if len(mnt.MountPath) == 0 { if len(mnt.MountPath) == 0 {
allErrs = append(allErrs, field.NewRequiredError(idxPath.Child("mountPath"))) allErrs = append(allErrs, field.Required(idxPath.Child("mountPath")))
} }
} }
return allErrs return allErrs
...@@ -921,7 +921,7 @@ func AccumulateUniqueHostPorts(containers []api.Container, accumulator *sets.Str ...@@ -921,7 +921,7 @@ func AccumulateUniqueHostPorts(containers []api.Container, accumulator *sets.Str
} }
str := fmt.Sprintf("%d/%s", port, ctr.Ports[pi].Protocol) str := fmt.Sprintf("%d/%s", port, ctr.Ports[pi].Protocol)
if accumulator.Has(str) { if accumulator.Has(str) {
allErrs = append(allErrs, field.NewDuplicateError(idxPath.Child("hostPort"), str)) allErrs = append(allErrs, field.Duplicate(idxPath.Child("hostPort"), str))
} else { } else {
accumulator.Insert(str) accumulator.Insert(str)
} }
...@@ -940,7 +940,7 @@ func checkHostPortConflicts(containers []api.Container, fldPath *field.Path) fie ...@@ -940,7 +940,7 @@ func checkHostPortConflicts(containers []api.Container, fldPath *field.Path) fie
func validateExecAction(exec *api.ExecAction, fldPath *field.Path) field.ErrorList { func validateExecAction(exec *api.ExecAction, fldPath *field.Path) field.ErrorList {
allErrors := field.ErrorList{} allErrors := field.ErrorList{}
if len(exec.Command) == 0 { if len(exec.Command) == 0 {
allErrors = append(allErrors, field.NewRequiredError(fldPath.Child("command"))) allErrors = append(allErrors, field.Required(fldPath.Child("command")))
} }
return allErrors return allErrors
} }
...@@ -948,16 +948,16 @@ func validateExecAction(exec *api.ExecAction, fldPath *field.Path) field.ErrorLi ...@@ -948,16 +948,16 @@ func validateExecAction(exec *api.ExecAction, fldPath *field.Path) field.ErrorLi
func validateHTTPGetAction(http *api.HTTPGetAction, fldPath *field.Path) field.ErrorList { func validateHTTPGetAction(http *api.HTTPGetAction, fldPath *field.Path) field.ErrorList {
allErrors := field.ErrorList{} allErrors := field.ErrorList{}
if len(http.Path) == 0 { if len(http.Path) == 0 {
allErrors = append(allErrors, field.NewRequiredError(fldPath.Child("path"))) allErrors = append(allErrors, field.Required(fldPath.Child("path")))
} }
if http.Port.Type == intstr.Int && !validation.IsValidPortNum(http.Port.IntValue()) { if http.Port.Type == intstr.Int && !validation.IsValidPortNum(http.Port.IntValue()) {
allErrors = append(allErrors, field.NewInvalidError(fldPath.Child("port"), http.Port, PortRangeErrorMsg)) allErrors = append(allErrors, field.Invalid(fldPath.Child("port"), http.Port, PortRangeErrorMsg))
} else if http.Port.Type == intstr.String && !validation.IsValidPortName(http.Port.StrVal) { } else if http.Port.Type == intstr.String && !validation.IsValidPortName(http.Port.StrVal) {
allErrors = append(allErrors, field.NewInvalidError(fldPath.Child("port"), http.Port.StrVal, PortNameErrorMsg)) allErrors = append(allErrors, field.Invalid(fldPath.Child("port"), http.Port.StrVal, PortNameErrorMsg))
} }
supportedSchemes := sets.NewString(string(api.URISchemeHTTP), string(api.URISchemeHTTPS)) supportedSchemes := sets.NewString(string(api.URISchemeHTTP), string(api.URISchemeHTTPS))
if !supportedSchemes.Has(string(http.Scheme)) { if !supportedSchemes.Has(string(http.Scheme)) {
allErrors = append(allErrors, field.NewInvalidError(fldPath.Child("scheme"), http.Scheme, fmt.Sprintf("must be one of %v", supportedSchemes.List()))) allErrors = append(allErrors, field.Invalid(fldPath.Child("scheme"), http.Scheme, fmt.Sprintf("must be one of %v", supportedSchemes.List())))
} }
return allErrors return allErrors
} }
...@@ -965,9 +965,9 @@ func validateHTTPGetAction(http *api.HTTPGetAction, fldPath *field.Path) field.E ...@@ -965,9 +965,9 @@ func validateHTTPGetAction(http *api.HTTPGetAction, fldPath *field.Path) field.E
func validateTCPSocketAction(tcp *api.TCPSocketAction, fldPath *field.Path) field.ErrorList { func validateTCPSocketAction(tcp *api.TCPSocketAction, fldPath *field.Path) field.ErrorList {
allErrors := field.ErrorList{} allErrors := field.ErrorList{}
if tcp.Port.Type == intstr.Int && !validation.IsValidPortNum(tcp.Port.IntValue()) { if tcp.Port.Type == intstr.Int && !validation.IsValidPortNum(tcp.Port.IntValue()) {
allErrors = append(allErrors, field.NewInvalidError(fldPath.Child("port"), tcp.Port, PortRangeErrorMsg)) allErrors = append(allErrors, field.Invalid(fldPath.Child("port"), tcp.Port, PortRangeErrorMsg))
} else if tcp.Port.Type == intstr.String && !validation.IsValidPortName(tcp.Port.StrVal) { } else if tcp.Port.Type == intstr.String && !validation.IsValidPortName(tcp.Port.StrVal) {
allErrors = append(allErrors, field.NewInvalidError(fldPath.Child("port"), tcp.Port.StrVal, PortNameErrorMsg)) allErrors = append(allErrors, field.Invalid(fldPath.Child("port"), tcp.Port.StrVal, PortNameErrorMsg))
} }
return allErrors return allErrors
} }
...@@ -988,7 +988,7 @@ func validateHandler(handler *api.Handler, fldPath *field.Path) field.ErrorList ...@@ -988,7 +988,7 @@ func validateHandler(handler *api.Handler, fldPath *field.Path) field.ErrorList
allErrors = append(allErrors, validateTCPSocketAction(handler.TCPSocket, fldPath.Child("tcpSocket"))...) allErrors = append(allErrors, validateTCPSocketAction(handler.TCPSocket, fldPath.Child("tcpSocket"))...)
} }
if numHandlers != 1 { if numHandlers != 1 {
allErrors = append(allErrors, field.NewInvalidError(fldPath, handler, "exactly 1 handler type is required")) allErrors = append(allErrors, field.Invalid(fldPath, handler, "exactly 1 handler type is required"))
} }
return allErrors return allErrors
} }
...@@ -1013,9 +1013,9 @@ func validatePullPolicy(policy api.PullPolicy, fldPath *field.Path) field.ErrorL ...@@ -1013,9 +1013,9 @@ func validatePullPolicy(policy api.PullPolicy, fldPath *field.Path) field.ErrorL
case api.PullAlways, api.PullIfNotPresent, api.PullNever: case api.PullAlways, api.PullIfNotPresent, api.PullNever:
break break
case "": case "":
allErrors = append(allErrors, field.NewRequiredError(fldPath)) allErrors = append(allErrors, field.Required(fldPath))
default: default:
allErrors = append(allErrors, field.NewNotSupportedError(fldPath, policy, supportedPullPolicies.List())) allErrors = append(allErrors, field.NotSupported(fldPath, policy, supportedPullPolicies.List()))
} }
return allErrors return allErrors
...@@ -1025,23 +1025,23 @@ func validateContainers(containers []api.Container, volumes sets.String, fldPath ...@@ -1025,23 +1025,23 @@ func validateContainers(containers []api.Container, volumes sets.String, fldPath
allErrs := field.ErrorList{} allErrs := field.ErrorList{}
if len(containers) == 0 { if len(containers) == 0 {
return append(allErrs, field.NewRequiredError(fldPath)) return append(allErrs, field.Required(fldPath))
} }
allNames := sets.String{} allNames := sets.String{}
for i, ctr := range containers { for i, ctr := range containers {
idxPath := fldPath.Index(i) idxPath := fldPath.Index(i)
if len(ctr.Name) == 0 { if len(ctr.Name) == 0 {
allErrs = append(allErrs, field.NewRequiredError(idxPath.Child("name"))) allErrs = append(allErrs, field.Required(idxPath.Child("name")))
} else if !validation.IsDNS1123Label(ctr.Name) { } else if !validation.IsDNS1123Label(ctr.Name) {
allErrs = append(allErrs, field.NewInvalidError(idxPath.Child("name"), ctr.Name, DNS1123LabelErrorMsg)) allErrs = append(allErrs, field.Invalid(idxPath.Child("name"), ctr.Name, DNS1123LabelErrorMsg))
} else if allNames.Has(ctr.Name) { } else if allNames.Has(ctr.Name) {
allErrs = append(allErrs, field.NewDuplicateError(idxPath.Child("name"), ctr.Name)) allErrs = append(allErrs, field.Duplicate(idxPath.Child("name"), ctr.Name))
} else { } else {
allNames.Insert(ctr.Name) allNames.Insert(ctr.Name)
} }
if len(ctr.Image) == 0 { if len(ctr.Image) == 0 {
allErrs = append(allErrs, field.NewRequiredError(idxPath.Child("image"))) allErrs = append(allErrs, field.Required(idxPath.Child("image")))
} }
if ctr.Lifecycle != nil { if ctr.Lifecycle != nil {
allErrs = append(allErrs, validateLifecycle(ctr.Lifecycle, idxPath.Child("lifecycle"))...) allErrs = append(allErrs, validateLifecycle(ctr.Lifecycle, idxPath.Child("lifecycle"))...)
...@@ -1049,7 +1049,7 @@ func validateContainers(containers []api.Container, volumes sets.String, fldPath ...@@ -1049,7 +1049,7 @@ func validateContainers(containers []api.Container, volumes sets.String, fldPath
allErrs = append(allErrs, validateProbe(ctr.LivenessProbe, idxPath.Child("livenessProbe"))...) allErrs = append(allErrs, validateProbe(ctr.LivenessProbe, idxPath.Child("livenessProbe"))...)
// Liveness-specific validation // Liveness-specific validation
if ctr.LivenessProbe != nil && ctr.LivenessProbe.SuccessThreshold != 1 { if ctr.LivenessProbe != nil && ctr.LivenessProbe.SuccessThreshold != 1 {
allErrs = append(allErrs, field.NewForbiddenError(idxPath.Child("livenessProbe", "successThreshold"), "must be 1")) allErrs = append(allErrs, field.Forbidden(idxPath.Child("livenessProbe", "successThreshold"), "must be 1"))
} }
allErrs = append(allErrs, validateProbe(ctr.ReadinessProbe, idxPath.Child("readinessProbe"))...) allErrs = append(allErrs, validateProbe(ctr.ReadinessProbe, idxPath.Child("readinessProbe"))...)
...@@ -1072,10 +1072,10 @@ func validateRestartPolicy(restartPolicy *api.RestartPolicy, fldPath *field.Path ...@@ -1072,10 +1072,10 @@ func validateRestartPolicy(restartPolicy *api.RestartPolicy, fldPath *field.Path
case api.RestartPolicyAlways, api.RestartPolicyOnFailure, api.RestartPolicyNever: case api.RestartPolicyAlways, api.RestartPolicyOnFailure, api.RestartPolicyNever:
break break
case "": case "":
allErrors = append(allErrors, field.NewRequiredError(fldPath)) allErrors = append(allErrors, field.Required(fldPath))
default: default:
validValues := []string{string(api.RestartPolicyAlways), string(api.RestartPolicyOnFailure), string(api.RestartPolicyNever)} validValues := []string{string(api.RestartPolicyAlways), string(api.RestartPolicyOnFailure), string(api.RestartPolicyNever)}
allErrors = append(allErrors, field.NewNotSupportedError(fldPath, *restartPolicy, validValues)) allErrors = append(allErrors, field.NotSupported(fldPath, *restartPolicy, validValues))
} }
return allErrors return allErrors
...@@ -1087,10 +1087,10 @@ func validateDNSPolicy(dnsPolicy *api.DNSPolicy, fldPath *field.Path) field.Erro ...@@ -1087,10 +1087,10 @@ func validateDNSPolicy(dnsPolicy *api.DNSPolicy, fldPath *field.Path) field.Erro
case api.DNSClusterFirst, api.DNSDefault: case api.DNSClusterFirst, api.DNSDefault:
break break
case "": case "":
allErrors = append(allErrors, field.NewRequiredError(fldPath)) allErrors = append(allErrors, field.Required(fldPath))
default: default:
validValues := []string{string(api.DNSClusterFirst), string(api.DNSDefault)} validValues := []string{string(api.DNSClusterFirst), string(api.DNSDefault)}
allErrors = append(allErrors, field.NewNotSupportedError(fldPath, dnsPolicy, validValues)) allErrors = append(allErrors, field.NotSupported(fldPath, dnsPolicy, validValues))
} }
return allErrors return allErrors
} }
...@@ -1103,7 +1103,7 @@ func validateHostNetwork(hostNetwork bool, containers []api.Container, fldPath * ...@@ -1103,7 +1103,7 @@ func validateHostNetwork(hostNetwork bool, containers []api.Container, fldPath *
for i, port := range container.Ports { for i, port := range container.Ports {
idxPath := portsPath.Index(i) idxPath := portsPath.Index(i)
if port.HostPort != port.ContainerPort { if port.HostPort != port.ContainerPort {
allErrors = append(allErrors, field.NewInvalidError(idxPath.Child("containerPort"), port.ContainerPort, "must match hostPort when hostNetwork is set to true")) allErrors = append(allErrors, field.Invalid(idxPath.Child("containerPort"), port.ContainerPort, "must match hostPort when hostNetwork is set to true"))
} }
} }
} }
...@@ -1121,7 +1121,7 @@ func validateImagePullSecrets(imagePullSecrets []api.LocalObjectReference, fldPa ...@@ -1121,7 +1121,7 @@ func validateImagePullSecrets(imagePullSecrets []api.LocalObjectReference, fldPa
idxPath := fldPath.Index(i) idxPath := fldPath.Index(i)
strippedRef := api.LocalObjectReference{Name: currPullSecret.Name} strippedRef := api.LocalObjectReference{Name: currPullSecret.Name}
if !reflect.DeepEqual(strippedRef, currPullSecret) { if !reflect.DeepEqual(strippedRef, currPullSecret) {
allErrors = append(allErrors, field.NewInvalidError(idxPath, currPullSecret, "only name may be set")) allErrors = append(allErrors, field.Invalid(idxPath, currPullSecret, "only name may be set"))
} }
} }
return allErrors return allErrors
...@@ -1151,19 +1151,19 @@ func ValidatePodSpec(spec *api.PodSpec, fldPath *field.Path) field.ErrorList { ...@@ -1151,19 +1151,19 @@ func ValidatePodSpec(spec *api.PodSpec, fldPath *field.Path) field.ErrorList {
allErrs = append(allErrs, validateImagePullSecrets(spec.ImagePullSecrets, fldPath.Child("imagePullSecrets"))...) allErrs = append(allErrs, validateImagePullSecrets(spec.ImagePullSecrets, fldPath.Child("imagePullSecrets"))...)
if len(spec.ServiceAccountName) > 0 { if len(spec.ServiceAccountName) > 0 {
if ok, msg := ValidateServiceAccountName(spec.ServiceAccountName, false); !ok { if ok, msg := ValidateServiceAccountName(spec.ServiceAccountName, false); !ok {
allErrs = append(allErrs, field.NewInvalidError(fldPath.Child("serviceAccountName"), spec.ServiceAccountName, msg)) allErrs = append(allErrs, field.Invalid(fldPath.Child("serviceAccountName"), spec.ServiceAccountName, msg))
} }
} }
if len(spec.NodeName) > 0 { if len(spec.NodeName) > 0 {
if ok, msg := ValidateNodeName(spec.NodeName, false); !ok { if ok, msg := ValidateNodeName(spec.NodeName, false); !ok {
allErrs = append(allErrs, field.NewInvalidError(fldPath.Child("nodeName"), spec.NodeName, msg)) allErrs = append(allErrs, field.Invalid(fldPath.Child("nodeName"), spec.NodeName, msg))
} }
} }
if spec.ActiveDeadlineSeconds != nil { if spec.ActiveDeadlineSeconds != nil {
if *spec.ActiveDeadlineSeconds <= 0 { if *spec.ActiveDeadlineSeconds <= 0 {
allErrs = append(allErrs, field.NewInvalidError(fldPath.Child("activeDeadlineSeconds"), spec.ActiveDeadlineSeconds, "must be greater than 0")) allErrs = append(allErrs, field.Invalid(fldPath.Child("activeDeadlineSeconds"), spec.ActiveDeadlineSeconds, "must be greater than 0"))
} }
} }
return allErrs return allErrs
...@@ -1188,7 +1188,7 @@ func ValidatePodUpdate(newPod, oldPod *api.Pod) field.ErrorList { ...@@ -1188,7 +1188,7 @@ func ValidatePodUpdate(newPod, oldPod *api.Pod) field.ErrorList {
specPath := field.NewPath("spec") specPath := field.NewPath("spec")
if len(newPod.Spec.Containers) != len(oldPod.Spec.Containers) { 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 //TODO: Pinpoint the specific container that causes the invalid error after we have strategic merge diff
allErrs = append(allErrs, field.NewInvalidError(specPath.Child("containers"), "contents not printed here, please refer to the \"details\"", "may not add or remove containers")) allErrs = append(allErrs, field.Invalid(specPath.Child("containers"), "contents not printed here, please refer to the \"details\"", "may not add or remove containers"))
return allErrs return allErrs
} }
pod := *newPod pod := *newPod
...@@ -1201,7 +1201,7 @@ func ValidatePodUpdate(newPod, oldPod *api.Pod) field.ErrorList { ...@@ -1201,7 +1201,7 @@ func ValidatePodUpdate(newPod, oldPod *api.Pod) field.ErrorList {
pod.Spec.Containers = newContainers pod.Spec.Containers = newContainers
if !api.Semantic.DeepEqual(pod.Spec, oldPod.Spec) { if !api.Semantic.DeepEqual(pod.Spec, oldPod.Spec) {
//TODO: Pinpoint the specific field that causes the invalid error after we have strategic merge diff //TODO: Pinpoint the specific field that causes the invalid error after we have strategic merge diff
allErrs = append(allErrs, field.NewInvalidError(specPath, "contents not printed here, please refer to the \"details\"", "may not update fields other than container.image")) allErrs = append(allErrs, field.Invalid(specPath, "contents not printed here, please refer to the \"details\"", "may not update fields other than container.image"))
} }
newPod.Status = oldPod.Status newPod.Status = oldPod.Status
...@@ -1215,7 +1215,7 @@ func ValidatePodStatusUpdate(newPod, oldPod *api.Pod) field.ErrorList { ...@@ -1215,7 +1215,7 @@ func ValidatePodStatusUpdate(newPod, oldPod *api.Pod) field.ErrorList {
// TODO: allow change when bindings are properly decoupled from pods // TODO: allow change when bindings are properly decoupled from pods
if newPod.Spec.NodeName != oldPod.Spec.NodeName { if newPod.Spec.NodeName != oldPod.Spec.NodeName {
allErrs = append(allErrs, field.NewInvalidError(field.NewPath("status", "nodeName"), newPod.Spec.NodeName, "cannot be changed directly")) allErrs = append(allErrs, field.Invalid(field.NewPath("status", "nodeName"), newPod.Spec.NodeName, "cannot be changed directly"))
} }
// For status update we ignore changes to pod spec. // For status update we ignore changes to pod spec.
...@@ -1249,14 +1249,14 @@ func ValidateService(service *api.Service) field.ErrorList { ...@@ -1249,14 +1249,14 @@ func ValidateService(service *api.Service) field.ErrorList {
specPath := field.NewPath("spec") specPath := field.NewPath("spec")
if len(service.Spec.Ports) == 0 && service.Spec.ClusterIP != api.ClusterIPNone { if len(service.Spec.Ports) == 0 && service.Spec.ClusterIP != api.ClusterIPNone {
allErrs = append(allErrs, field.NewRequiredError(specPath.Child("ports"))) allErrs = append(allErrs, field.Required(specPath.Child("ports")))
} }
if service.Spec.Type == api.ServiceTypeLoadBalancer { if service.Spec.Type == api.ServiceTypeLoadBalancer {
for ix := range service.Spec.Ports { for ix := range service.Spec.Ports {
port := &service.Spec.Ports[ix] port := &service.Spec.Ports[ix]
if port.Port == 10250 { if port.Port == 10250 {
portPath := specPath.Child("ports").Index(ix) portPath := specPath.Child("ports").Index(ix)
allErrs = append(allErrs, field.NewInvalidError(portPath, port.Port, "can not expose port 10250 externally since it is used by kubelet")) allErrs = append(allErrs, field.Invalid(portPath, port.Port, "can not expose port 10250 externally since it is used by kubelet"))
} }
} }
} }
...@@ -1274,14 +1274,14 @@ func ValidateService(service *api.Service) field.ErrorList { ...@@ -1274,14 +1274,14 @@ func ValidateService(service *api.Service) field.ErrorList {
} }
if service.Spec.SessionAffinity == "" { if service.Spec.SessionAffinity == "" {
allErrs = append(allErrs, field.NewRequiredError(specPath.Child("sessionAffinity"))) allErrs = append(allErrs, field.Required(specPath.Child("sessionAffinity")))
} else if !supportedSessionAffinityType.Has(string(service.Spec.SessionAffinity)) { } else if !supportedSessionAffinityType.Has(string(service.Spec.SessionAffinity)) {
allErrs = append(allErrs, field.NewNotSupportedError(specPath.Child("sessionAffinity"), service.Spec.SessionAffinity, supportedSessionAffinityType.List())) allErrs = append(allErrs, field.NotSupported(specPath.Child("sessionAffinity"), service.Spec.SessionAffinity, supportedSessionAffinityType.List()))
} }
if api.IsServiceIPSet(service) { if api.IsServiceIPSet(service) {
if ip := net.ParseIP(service.Spec.ClusterIP); ip == nil { if ip := net.ParseIP(service.Spec.ClusterIP); ip == nil {
allErrs = append(allErrs, field.NewInvalidError(specPath.Child("clusterIP"), service.Spec.ClusterIP, "must be empty, 'None', or a valid IP address")) allErrs = append(allErrs, field.Invalid(specPath.Child("clusterIP"), service.Spec.ClusterIP, "must be empty, 'None', or a valid IP address"))
} }
} }
...@@ -1289,15 +1289,15 @@ func ValidateService(service *api.Service) field.ErrorList { ...@@ -1289,15 +1289,15 @@ func ValidateService(service *api.Service) field.ErrorList {
for i, ip := range service.Spec.ExternalIPs { for i, ip := range service.Spec.ExternalIPs {
idxPath := ipPath.Index(i) idxPath := ipPath.Index(i)
if ip == "0.0.0.0" { if ip == "0.0.0.0" {
allErrs = append(allErrs, field.NewInvalidError(idxPath, ip, "is not an IP address")) allErrs = append(allErrs, field.Invalid(idxPath, ip, "is not an IP address"))
} }
allErrs = append(allErrs, validateIpIsNotLinkLocalOrLoopback(ip, idxPath)...) allErrs = append(allErrs, validateIpIsNotLinkLocalOrLoopback(ip, idxPath)...)
} }
if service.Spec.Type == "" { if service.Spec.Type == "" {
allErrs = append(allErrs, field.NewRequiredError(specPath.Child("type"))) allErrs = append(allErrs, field.Required(specPath.Child("type")))
} else if !supportedServiceType.Has(string(service.Spec.Type)) { } else if !supportedServiceType.Has(string(service.Spec.Type)) {
allErrs = append(allErrs, field.NewNotSupportedError(specPath.Child("type"), service.Spec.Type, supportedServiceType.List())) allErrs = append(allErrs, field.NotSupported(specPath.Child("type"), service.Spec.Type, supportedServiceType.List()))
} }
if service.Spec.Type == api.ServiceTypeLoadBalancer { if service.Spec.Type == api.ServiceTypeLoadBalancer {
...@@ -1305,7 +1305,7 @@ func ValidateService(service *api.Service) field.ErrorList { ...@@ -1305,7 +1305,7 @@ func ValidateService(service *api.Service) field.ErrorList {
for i := range service.Spec.Ports { for i := range service.Spec.Ports {
portPath := portsPath.Index(i) portPath := portsPath.Index(i)
if service.Spec.Ports[i].Protocol != api.ProtocolTCP { if service.Spec.Ports[i].Protocol != api.ProtocolTCP {
allErrs = append(allErrs, field.NewInvalidError(portPath.Child("protocol"), service.Spec.Ports[i].Protocol, "cannot create an external load balancer with non-TCP ports")) allErrs = append(allErrs, field.Invalid(portPath.Child("protocol"), service.Spec.Ports[i].Protocol, "cannot create an external load balancer with non-TCP ports"))
} }
} }
} }
...@@ -1315,7 +1315,7 @@ func ValidateService(service *api.Service) field.ErrorList { ...@@ -1315,7 +1315,7 @@ func ValidateService(service *api.Service) field.ErrorList {
for i := range service.Spec.Ports { for i := range service.Spec.Ports {
portPath := portsPath.Index(i) portPath := portsPath.Index(i)
if service.Spec.Ports[i].NodePort != 0 { if service.Spec.Ports[i].NodePort != 0 {
allErrs = append(allErrs, field.NewInvalidError(portPath.Child("nodePort"), service.Spec.Ports[i].NodePort, "cannot specify a node port with services of type ClusterIP")) allErrs = append(allErrs, field.Invalid(portPath.Child("nodePort"), service.Spec.Ports[i].NodePort, "cannot specify a node port with services of type ClusterIP"))
} }
} }
} }
...@@ -1334,7 +1334,7 @@ func ValidateService(service *api.Service) field.ErrorList { ...@@ -1334,7 +1334,7 @@ func ValidateService(service *api.Service) field.ErrorList {
key.NodePort = port.NodePort key.NodePort = port.NodePort
_, found := nodePorts[key] _, found := nodePorts[key]
if found { if found {
allErrs = append(allErrs, field.NewInvalidError(portPath.Child("nodePort"), port.NodePort, "duplicate nodePort specified")) allErrs = append(allErrs, field.Invalid(portPath.Child("nodePort"), port.NodePort, "duplicate nodePort specified"))
} }
nodePorts[key] = true nodePorts[key] = true
} }
...@@ -1346,37 +1346,37 @@ func validateServicePort(sp *api.ServicePort, requireName, isHeadlessService boo ...@@ -1346,37 +1346,37 @@ func validateServicePort(sp *api.ServicePort, requireName, isHeadlessService boo
allErrs := field.ErrorList{} allErrs := field.ErrorList{}
if requireName && sp.Name == "" { if requireName && sp.Name == "" {
allErrs = append(allErrs, field.NewRequiredError(fldPath.Child("name"))) allErrs = append(allErrs, field.Required(fldPath.Child("name")))
} else if sp.Name != "" { } else if sp.Name != "" {
if !validation.IsDNS1123Label(sp.Name) { if !validation.IsDNS1123Label(sp.Name) {
allErrs = append(allErrs, field.NewInvalidError(fldPath.Child("name"), sp.Name, DNS1123LabelErrorMsg)) allErrs = append(allErrs, field.Invalid(fldPath.Child("name"), sp.Name, DNS1123LabelErrorMsg))
} else if allNames.Has(sp.Name) { } else if allNames.Has(sp.Name) {
allErrs = append(allErrs, field.NewDuplicateError(fldPath.Child("name"), sp.Name)) allErrs = append(allErrs, field.Duplicate(fldPath.Child("name"), sp.Name))
} else { } else {
allNames.Insert(sp.Name) allNames.Insert(sp.Name)
} }
} }
if !validation.IsValidPortNum(sp.Port) { if !validation.IsValidPortNum(sp.Port) {
allErrs = append(allErrs, field.NewInvalidError(fldPath.Child("port"), sp.Port, PortRangeErrorMsg)) allErrs = append(allErrs, field.Invalid(fldPath.Child("port"), sp.Port, PortRangeErrorMsg))
} }
if len(sp.Protocol) == 0 { if len(sp.Protocol) == 0 {
allErrs = append(allErrs, field.NewRequiredError(fldPath.Child("protocol"))) allErrs = append(allErrs, field.Required(fldPath.Child("protocol")))
} else if !supportedPortProtocols.Has(string(sp.Protocol)) { } else if !supportedPortProtocols.Has(string(sp.Protocol)) {
allErrs = append(allErrs, field.NewNotSupportedError(fldPath.Child("protocol"), sp.Protocol, supportedPortProtocols.List())) allErrs = append(allErrs, field.NotSupported(fldPath.Child("protocol"), sp.Protocol, supportedPortProtocols.List()))
} }
if sp.TargetPort.Type == intstr.Int && !validation.IsValidPortNum(sp.TargetPort.IntValue()) { if sp.TargetPort.Type == intstr.Int && !validation.IsValidPortNum(sp.TargetPort.IntValue()) {
allErrs = append(allErrs, field.NewInvalidError(fldPath.Child("targetPort"), sp.TargetPort, PortRangeErrorMsg)) allErrs = append(allErrs, field.Invalid(fldPath.Child("targetPort"), sp.TargetPort, PortRangeErrorMsg))
} }
if sp.TargetPort.Type == intstr.String && !validation.IsValidPortName(sp.TargetPort.StrVal) { if sp.TargetPort.Type == intstr.String && !validation.IsValidPortName(sp.TargetPort.StrVal) {
allErrs = append(allErrs, field.NewInvalidError(fldPath.Child("targetPort"), sp.TargetPort, PortNameErrorMsg)) allErrs = append(allErrs, field.Invalid(fldPath.Child("targetPort"), sp.TargetPort, PortNameErrorMsg))
} }
if isHeadlessService { if isHeadlessService {
if sp.TargetPort.Type == intstr.String || (sp.TargetPort.Type == intstr.Int && sp.Port != sp.TargetPort.IntValue()) { if sp.TargetPort.Type == intstr.String || (sp.TargetPort.Type == intstr.Int && sp.Port != sp.TargetPort.IntValue()) {
allErrs = append(allErrs, field.NewInvalidError(fldPath.Child("port"), sp.Port, "must be equal to targetPort when clusterIP = None")) allErrs = append(allErrs, field.Invalid(fldPath.Child("port"), sp.Port, "must be equal to targetPort when clusterIP = None"))
} }
} }
...@@ -1423,7 +1423,7 @@ func ValidateNonEmptySelector(selectorMap map[string]string, fldPath *field.Path ...@@ -1423,7 +1423,7 @@ func ValidateNonEmptySelector(selectorMap map[string]string, fldPath *field.Path
allErrs := field.ErrorList{} allErrs := field.ErrorList{}
selector := labels.Set(selectorMap).AsSelector() selector := labels.Set(selectorMap).AsSelector()
if selector.Empty() { if selector.Empty() {
allErrs = append(allErrs, field.NewRequiredError(fldPath)) allErrs = append(allErrs, field.Required(fldPath))
} }
return allErrs return allErrs
} }
...@@ -1432,14 +1432,14 @@ func ValidateNonEmptySelector(selectorMap map[string]string, fldPath *field.Path ...@@ -1432,14 +1432,14 @@ func ValidateNonEmptySelector(selectorMap map[string]string, fldPath *field.Path
func ValidatePodTemplateSpecForRC(template *api.PodTemplateSpec, selectorMap map[string]string, replicas int, fldPath *field.Path) field.ErrorList { func ValidatePodTemplateSpecForRC(template *api.PodTemplateSpec, selectorMap map[string]string, replicas int, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{} allErrs := field.ErrorList{}
if template == nil { if template == nil {
allErrs = append(allErrs, field.NewRequiredError(fldPath)) allErrs = append(allErrs, field.Required(fldPath))
} else { } else {
selector := labels.Set(selectorMap).AsSelector() selector := labels.Set(selectorMap).AsSelector()
if !selector.Empty() { if !selector.Empty() {
// Verify that the RC selector matches the labels in template. // Verify that the RC selector matches the labels in template.
labels := labels.Set(template.Labels) labels := labels.Set(template.Labels)
if !selector.Matches(labels) { if !selector.Matches(labels) {
allErrs = append(allErrs, field.NewInvalidError(fldPath.Child("metadata", "labels"), template.Labels, "selector does not match labels in "+fldPath.String())) allErrs = append(allErrs, field.Invalid(fldPath.Child("metadata", "labels"), template.Labels, "selector does not match labels in "+fldPath.String()))
} }
} }
allErrs = append(allErrs, ValidatePodTemplateSpec(template, fldPath)...) allErrs = append(allErrs, ValidatePodTemplateSpec(template, fldPath)...)
...@@ -1448,7 +1448,7 @@ func ValidatePodTemplateSpecForRC(template *api.PodTemplateSpec, selectorMap map ...@@ -1448,7 +1448,7 @@ func ValidatePodTemplateSpecForRC(template *api.PodTemplateSpec, selectorMap map
} }
// RestartPolicy has already been first-order validated as per ValidatePodTemplateSpec(). // RestartPolicy has already been first-order validated as per ValidatePodTemplateSpec().
if template.Spec.RestartPolicy != api.RestartPolicyAlways { if template.Spec.RestartPolicy != api.RestartPolicyAlways {
allErrs = append(allErrs, field.NewNotSupportedError(fldPath.Child("spec", "restartPolicy"), template.Spec.RestartPolicy, []string{string(api.RestartPolicyAlways)})) allErrs = append(allErrs, field.NotSupported(fldPath.Child("spec", "restartPolicy"), template.Spec.RestartPolicy, []string{string(api.RestartPolicyAlways)}))
} }
} }
return allErrs return allErrs
...@@ -1479,7 +1479,7 @@ func ValidateReadOnlyPersistentDisks(volumes []api.Volume, fldPath *field.Path) ...@@ -1479,7 +1479,7 @@ func ValidateReadOnlyPersistentDisks(volumes []api.Volume, fldPath *field.Path)
idxPath := fldPath.Index(i) idxPath := fldPath.Index(i)
if vol.GCEPersistentDisk != nil { if vol.GCEPersistentDisk != nil {
if vol.GCEPersistentDisk.ReadOnly == false { if vol.GCEPersistentDisk.ReadOnly == false {
allErrs = append(allErrs, field.NewInvalidError(idxPath.Child("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, field.Invalid(idxPath.Child("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 // TODO: What to do for AWS? It doesn't support replicas
...@@ -1495,7 +1495,7 @@ func ValidateNode(node *api.Node) field.ErrorList { ...@@ -1495,7 +1495,7 @@ func ValidateNode(node *api.Node) field.ErrorList {
// external ID is required. // external ID is required.
if len(node.Spec.ExternalID) == 0 { if len(node.Spec.ExternalID) == 0 {
allErrs = append(allErrs, field.NewRequiredError(field.NewPath("spec", "externalID"))) allErrs = append(allErrs, field.Required(field.NewPath("spec", "externalID")))
} }
// TODO(rjnagal): Ignore PodCIDR till its completely implemented. // TODO(rjnagal): Ignore PodCIDR till its completely implemented.
...@@ -1509,14 +1509,14 @@ func ValidateNodeUpdate(node, oldNode *api.Node) field.ErrorList { ...@@ -1509,14 +1509,14 @@ func ValidateNodeUpdate(node, oldNode *api.Node) field.ErrorList {
// TODO: Enable the code once we have better api object.status update model. Currently, // TODO: Enable the code once we have better api object.status update model. Currently,
// anyone can update node status. // anyone can update node status.
// if !api.Semantic.DeepEqual(node.Status, api.NodeStatus{}) { // if !api.Semantic.DeepEqual(node.Status, api.NodeStatus{}) {
// allErrs = append(allErrs, field.NewInvalidError("status", node.Status, "status must be empty")) // allErrs = append(allErrs, field.Invalid("status", node.Status, "status must be empty"))
// } // }
// Validte no duplicate addresses in node status. // Validte no duplicate addresses in node status.
addresses := make(map[api.NodeAddress]bool) addresses := make(map[api.NodeAddress]bool)
for i, address := range node.Status.Addresses { for i, address := range node.Status.Addresses {
if _, ok := addresses[address]; ok { if _, ok := addresses[address]; ok {
allErrs = append(allErrs, field.NewDuplicateError(field.NewPath("status", "addresses").Index(i), address)) allErrs = append(allErrs, field.Duplicate(field.NewPath("status", "addresses").Index(i), address))
} }
addresses[address] = true addresses[address] = true
} }
...@@ -1536,7 +1536,7 @@ func ValidateNodeUpdate(node, oldNode *api.Node) field.ErrorList { ...@@ -1536,7 +1536,7 @@ func ValidateNodeUpdate(node, oldNode *api.Node) field.ErrorList {
// TODO: Add a 'real' error type for this error and provide print actual diffs. // TODO: Add a 'real' error type for this error and provide print actual diffs.
if !api.Semantic.DeepEqual(oldNode, node) { if !api.Semantic.DeepEqual(oldNode, node) {
glog.V(4).Infof("Update failed validation %#v vs %#v", oldNode, node) glog.V(4).Infof("Update failed validation %#v vs %#v", oldNode, node)
allErrs = append(allErrs, field.NewForbiddenError(field.NewPath(""), "update contains more than labels or capacity changes")) allErrs = append(allErrs, field.Forbidden(field.NewPath(""), "update contains more than labels or capacity changes"))
} }
return allErrs return allErrs
...@@ -1547,12 +1547,12 @@ func ValidateNodeUpdate(node, oldNode *api.Node) field.ErrorList { ...@@ -1547,12 +1547,12 @@ func ValidateNodeUpdate(node, oldNode *api.Node) field.ErrorList {
func validateResourceName(value string, fldPath *field.Path) field.ErrorList { func validateResourceName(value string, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{} allErrs := field.ErrorList{}
if !validation.IsQualifiedName(value) { if !validation.IsQualifiedName(value) {
return append(allErrs, field.NewInvalidError(fldPath, value, "resource typename: "+qualifiedNameErrorMsg)) return append(allErrs, field.Invalid(fldPath, value, "resource typename: "+qualifiedNameErrorMsg))
} }
if len(strings.Split(value, "/")) == 1 { if len(strings.Split(value, "/")) == 1 {
if !api.IsStandardResourceName(value) { if !api.IsStandardResourceName(value) {
return append(allErrs, field.NewInvalidError(fldPath, value, "is neither a standard resource type nor is fully qualified")) return append(allErrs, field.Invalid(fldPath, value, "is neither a standard resource type nor is fully qualified"))
} }
} }
...@@ -1571,7 +1571,7 @@ func ValidateLimitRange(limitRange *api.LimitRange) field.ErrorList { ...@@ -1571,7 +1571,7 @@ func ValidateLimitRange(limitRange *api.LimitRange) field.ErrorList {
limit := &limitRange.Spec.Limits[i] limit := &limitRange.Spec.Limits[i]
_, found := limitTypeSet[limit.Type] _, found := limitTypeSet[limit.Type]
if found { if found {
allErrs = append(allErrs, field.NewDuplicateError(idxPath.Child("type"), limit.Type)) allErrs = append(allErrs, field.Duplicate(idxPath.Child("type"), limit.Type))
} }
limitTypeSet[limit.Type] = true limitTypeSet[limit.Type] = true
...@@ -1595,10 +1595,10 @@ func ValidateLimitRange(limitRange *api.LimitRange) field.ErrorList { ...@@ -1595,10 +1595,10 @@ func ValidateLimitRange(limitRange *api.LimitRange) field.ErrorList {
if limit.Type == api.LimitTypePod { if limit.Type == api.LimitTypePod {
if len(limit.Default) > 0 { if len(limit.Default) > 0 {
allErrs = append(allErrs, field.NewInvalidError(idxPath.Child("default"), limit.Default, "not supported when limit type is Pod")) allErrs = append(allErrs, field.Invalid(idxPath.Child("default"), limit.Default, "not supported when limit type is Pod"))
} }
if len(limit.DefaultRequest) > 0 { if len(limit.DefaultRequest) > 0 {
allErrs = append(allErrs, field.NewInvalidError(idxPath.Child("defaultRequest"), limit.DefaultRequest, "not supported when limit type is Pod")) allErrs = append(allErrs, field.Invalid(idxPath.Child("defaultRequest"), limit.DefaultRequest, "not supported when limit type is Pod"))
} }
} else { } else {
for k, q := range limit.Default { for k, q := range limit.Default {
...@@ -1627,30 +1627,30 @@ func ValidateLimitRange(limitRange *api.LimitRange) field.ErrorList { ...@@ -1627,30 +1627,30 @@ func ValidateLimitRange(limitRange *api.LimitRange) field.ErrorList {
maxRatio, maxRatioFound := maxLimitRequestRatios[k] maxRatio, maxRatioFound := maxLimitRequestRatios[k]
if minQuantityFound && maxQuantityFound && minQuantity.Cmp(maxQuantity) > 0 { if minQuantityFound && maxQuantityFound && minQuantity.Cmp(maxQuantity) > 0 {
allErrs = append(allErrs, field.NewInvalidError(idxPath.Child("min").Key(string(k)), minQuantity, fmt.Sprintf("min value %s is greater than max value %s", minQuantity.String(), maxQuantity.String()))) allErrs = append(allErrs, field.Invalid(idxPath.Child("min").Key(string(k)), minQuantity, fmt.Sprintf("min value %s is greater than max value %s", minQuantity.String(), maxQuantity.String())))
} }
if defaultRequestQuantityFound && minQuantityFound && minQuantity.Cmp(defaultRequestQuantity) > 0 { if defaultRequestQuantityFound && minQuantityFound && minQuantity.Cmp(defaultRequestQuantity) > 0 {
allErrs = append(allErrs, field.NewInvalidError(idxPath.Child("defaultRequest").Key(string(k)), defaultRequestQuantity, fmt.Sprintf("min value %s is greater than default request value %s", minQuantity.String(), defaultRequestQuantity.String()))) allErrs = append(allErrs, field.Invalid(idxPath.Child("defaultRequest").Key(string(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 { if defaultRequestQuantityFound && maxQuantityFound && defaultRequestQuantity.Cmp(maxQuantity) > 0 {
allErrs = append(allErrs, field.NewInvalidError(idxPath.Child("defaultRequest").Key(string(k)), defaultRequestQuantity, fmt.Sprintf("default request value %s is greater than max value %s", defaultRequestQuantity.String(), maxQuantity.String()))) allErrs = append(allErrs, field.Invalid(idxPath.Child("defaultRequest").Key(string(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 { if defaultRequestQuantityFound && defaultQuantityFound && defaultRequestQuantity.Cmp(defaultQuantity) > 0 {
allErrs = append(allErrs, field.NewInvalidError(idxPath.Child("defaultRequest").Key(string(k)), defaultRequestQuantity, fmt.Sprintf("default request value %s is greater than default limit value %s", defaultRequestQuantity.String(), defaultQuantity.String()))) allErrs = append(allErrs, field.Invalid(idxPath.Child("defaultRequest").Key(string(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 { if defaultQuantityFound && minQuantityFound && minQuantity.Cmp(defaultQuantity) > 0 {
allErrs = append(allErrs, field.NewInvalidError(idxPath.Child("default").Key(string(k)), minQuantity, fmt.Sprintf("min value %s is greater than default value %s", minQuantity.String(), defaultQuantity.String()))) allErrs = append(allErrs, field.Invalid(idxPath.Child("default").Key(string(k)), minQuantity, fmt.Sprintf("min value %s is greater than default value %s", minQuantity.String(), defaultQuantity.String())))
} }
if defaultQuantityFound && maxQuantityFound && defaultQuantity.Cmp(maxQuantity) > 0 { if defaultQuantityFound && maxQuantityFound && defaultQuantity.Cmp(maxQuantity) > 0 {
allErrs = append(allErrs, field.NewInvalidError(idxPath.Child("default").Key(string(k)), maxQuantity, fmt.Sprintf("default value %s is greater than max value %s", defaultQuantity.String(), maxQuantity.String()))) allErrs = append(allErrs, field.Invalid(idxPath.Child("default").Key(string(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 { if maxRatioFound && maxRatio.Cmp(*resource.NewQuantity(1, resource.DecimalSI)) < 0 {
allErrs = append(allErrs, field.NewInvalidError(idxPath.Child("maxLimitRequestRatio").Key(string(k)), maxRatio, fmt.Sprintf("ratio %s is less than 1", maxRatio.String()))) allErrs = append(allErrs, field.Invalid(idxPath.Child("maxLimitRequestRatio").Key(string(k)), maxRatio, fmt.Sprintf("ratio %s is less than 1", maxRatio.String())))
} }
if maxRatioFound && minQuantityFound && maxQuantityFound { if maxRatioFound && minQuantityFound && maxQuantityFound {
maxRatioValue := float64(maxRatio.Value()) maxRatioValue := float64(maxRatio.Value())
...@@ -1663,7 +1663,7 @@ func ValidateLimitRange(limitRange *api.LimitRange) field.ErrorList { ...@@ -1663,7 +1663,7 @@ func ValidateLimitRange(limitRange *api.LimitRange) field.ErrorList {
} }
maxRatioLimit := float64(maxQuantityValue) / float64(minQuantityValue) maxRatioLimit := float64(maxQuantityValue) / float64(minQuantityValue)
if maxRatioValue > maxRatioLimit { if maxRatioValue > maxRatioLimit {
allErrs = append(allErrs, field.NewInvalidError(idxPath.Child("maxLimitRequestRatio").Key(string(k)), maxRatio, fmt.Sprintf("ratio %s is greater than max/min = %f", maxRatio.String(), maxRatioLimit))) allErrs = append(allErrs, field.Invalid(idxPath.Child("maxLimitRequestRatio").Key(string(k)), maxRatio, fmt.Sprintf("ratio %s is greater than max/min = %f", maxRatio.String(), maxRatioLimit)))
} }
} }
} }
...@@ -1703,12 +1703,12 @@ func ValidateSecret(secret *api.Secret) field.ErrorList { ...@@ -1703,12 +1703,12 @@ func ValidateSecret(secret *api.Secret) field.ErrorList {
totalSize := 0 totalSize := 0
for key, value := range secret.Data { for key, value := range secret.Data {
if !IsSecretKey(key) { if !IsSecretKey(key) {
allErrs = append(allErrs, field.NewInvalidError(dataPath.Key(key), key, fmt.Sprintf("must have at most %d characters and match regex %s", validation.DNS1123SubdomainMaxLength, SecretKeyFmt))) allErrs = append(allErrs, field.Invalid(dataPath.Key(key), key, fmt.Sprintf("must have at most %d characters and match regex %s", validation.DNS1123SubdomainMaxLength, SecretKeyFmt)))
} }
totalSize += len(value) totalSize += len(value)
} }
if totalSize > api.MaxSecretSize { if totalSize > api.MaxSecretSize {
allErrs = append(allErrs, field.NewTooLongError(dataPath, "", api.MaxSecretSize)) allErrs = append(allErrs, field.TooLong(dataPath, "", api.MaxSecretSize))
} }
switch secret.Type { switch secret.Type {
...@@ -1716,20 +1716,20 @@ func ValidateSecret(secret *api.Secret) field.ErrorList { ...@@ -1716,20 +1716,20 @@ func ValidateSecret(secret *api.Secret) field.ErrorList {
// Only require Annotations[kubernetes.io/service-account.name] // 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 // 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 { if value := secret.Annotations[api.ServiceAccountNameKey]; len(value) == 0 {
allErrs = append(allErrs, field.NewRequiredError(field.NewPath("metadata", "annotations").Key(api.ServiceAccountNameKey))) allErrs = append(allErrs, field.Required(field.NewPath("metadata", "annotations").Key(api.ServiceAccountNameKey)))
} }
case api.SecretTypeOpaque, "": case api.SecretTypeOpaque, "":
// no-op // no-op
case api.SecretTypeDockercfg: case api.SecretTypeDockercfg:
dockercfgBytes, exists := secret.Data[api.DockerConfigKey] dockercfgBytes, exists := secret.Data[api.DockerConfigKey]
if !exists { if !exists {
allErrs = append(allErrs, field.NewRequiredError(dataPath.Key(api.DockerConfigKey))) allErrs = append(allErrs, field.Required(dataPath.Key(api.DockerConfigKey)))
break break
} }
// make sure that the content is well-formed json. // make sure that the content is well-formed json.
if err := json.Unmarshal(dockercfgBytes, &map[string]interface{}{}); err != nil { if err := json.Unmarshal(dockercfgBytes, &map[string]interface{}{}); err != nil {
allErrs = append(allErrs, field.NewInvalidError(dataPath.Key(api.DockerConfigKey), "<secret contents redacted>", err.Error())) allErrs = append(allErrs, field.Invalid(dataPath.Key(api.DockerConfigKey), "<secret contents redacted>", err.Error()))
} }
default: default:
...@@ -1755,7 +1755,7 @@ func ValidateSecretUpdate(newSecret, oldSecret *api.Secret) field.ErrorList { ...@@ -1755,7 +1755,7 @@ func ValidateSecretUpdate(newSecret, oldSecret *api.Secret) field.ErrorList {
func validateBasicResource(quantity resource.Quantity, fldPath *field.Path) field.ErrorList { func validateBasicResource(quantity resource.Quantity, fldPath *field.Path) field.ErrorList {
if quantity.Value() < 0 { if quantity.Value() < 0 {
return field.ErrorList{field.NewInvalidError(fldPath, quantity.Value(), "must be a valid resource quantity")} return field.ErrorList{field.Invalid(fldPath, quantity.Value(), "must be a valid resource quantity")}
} }
return field.ErrorList{} return field.ErrorList{}
} }
...@@ -1783,7 +1783,7 @@ func ValidateResourceRequirements(requirements *api.ResourceRequirements, fldPat ...@@ -1783,7 +1783,7 @@ func ValidateResourceRequirements(requirements *api.ResourceRequirements, fldPat
limitValue = quantity.MilliValue() limitValue = quantity.MilliValue()
} }
if limitValue < requestValue { if limitValue < requestValue {
allErrs = append(allErrs, field.NewInvalidError(fldPath, quantity.String(), "limit cannot be smaller than request")) allErrs = append(allErrs, field.Invalid(fldPath, quantity.String(), "limit cannot be smaller than request"))
} }
} }
} }
...@@ -1830,7 +1830,7 @@ func validateResourceQuantityValue(resource string, value resource.Quantity, fld ...@@ -1830,7 +1830,7 @@ func validateResourceQuantityValue(resource string, value resource.Quantity, fld
allErrs = append(allErrs, ValidatePositiveQuantity(value, fldPath)...) allErrs = append(allErrs, ValidatePositiveQuantity(value, fldPath)...)
if api.IsIntegerResourceName(resource) { if api.IsIntegerResourceName(resource) {
if value.MilliValue()%int64(1000) != int64(0) { if value.MilliValue()%int64(1000) != int64(0) {
allErrs = append(allErrs, field.NewInvalidError(fldPath, value, isNotIntegerErrorMsg)) allErrs = append(allErrs, field.Invalid(fldPath, value, isNotIntegerErrorMsg))
} }
} }
return allErrs return allErrs
...@@ -1855,7 +1855,7 @@ func ValidateResourceQuotaUpdate(newResourceQuota, oldResourceQuota *api.Resourc ...@@ -1855,7 +1855,7 @@ func ValidateResourceQuotaUpdate(newResourceQuota, oldResourceQuota *api.Resourc
func ValidateResourceQuotaStatusUpdate(newResourceQuota, oldResourceQuota *api.ResourceQuota) field.ErrorList { func ValidateResourceQuotaStatusUpdate(newResourceQuota, oldResourceQuota *api.ResourceQuota) field.ErrorList {
allErrs := ValidateObjectMetaUpdate(&newResourceQuota.ObjectMeta, &oldResourceQuota.ObjectMeta, field.NewPath("metadata")) allErrs := ValidateObjectMetaUpdate(&newResourceQuota.ObjectMeta, &oldResourceQuota.ObjectMeta, field.NewPath("metadata"))
if newResourceQuota.ResourceVersion == "" { if newResourceQuota.ResourceVersion == "" {
allErrs = append(allErrs, field.NewRequiredError(field.NewPath("resourceVersion"))) allErrs = append(allErrs, field.Required(field.NewPath("resourceVersion")))
} }
fldPath := field.NewPath("status", "hard") fldPath := field.NewPath("status", "hard")
for k, v := range newResourceQuota.Status.Hard { for k, v := range newResourceQuota.Status.Hard {
...@@ -1886,12 +1886,12 @@ func ValidateNamespace(namespace *api.Namespace) field.ErrorList { ...@@ -1886,12 +1886,12 @@ func ValidateNamespace(namespace *api.Namespace) field.ErrorList {
func validateFinalizerName(stringValue string, fldPath *field.Path) field.ErrorList { func validateFinalizerName(stringValue string, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{} allErrs := field.ErrorList{}
if !validation.IsQualifiedName(stringValue) { if !validation.IsQualifiedName(stringValue) {
return append(allErrs, field.NewInvalidError(fldPath, stringValue, qualifiedNameErrorMsg)) return append(allErrs, field.Invalid(fldPath, stringValue, qualifiedNameErrorMsg))
} }
if len(strings.Split(stringValue, "/")) == 1 { if len(strings.Split(stringValue, "/")) == 1 {
if !api.IsStandardFinalizerName(stringValue) { if !api.IsStandardFinalizerName(stringValue) {
return append(allErrs, field.NewInvalidError(fldPath, stringValue, fmt.Sprintf("name is neither a standard finalizer name nor is it fully qualified"))) return append(allErrs, field.Invalid(fldPath, stringValue, fmt.Sprintf("name is neither a standard finalizer name nor is it fully qualified")))
} }
} }
...@@ -1914,11 +1914,11 @@ func ValidateNamespaceStatusUpdate(newNamespace, oldNamespace *api.Namespace) fi ...@@ -1914,11 +1914,11 @@ func ValidateNamespaceStatusUpdate(newNamespace, oldNamespace *api.Namespace) fi
newNamespace.Spec = oldNamespace.Spec newNamespace.Spec = oldNamespace.Spec
if newNamespace.DeletionTimestamp.IsZero() { if newNamespace.DeletionTimestamp.IsZero() {
if newNamespace.Status.Phase != api.NamespaceActive { if newNamespace.Status.Phase != api.NamespaceActive {
allErrs = append(allErrs, field.NewInvalidError(field.NewPath("status", "Phase"), newNamespace.Status.Phase, "may only be in active status if it does not have a deletion timestamp.")) allErrs = append(allErrs, field.Invalid(field.NewPath("status", "Phase"), newNamespace.Status.Phase, "may only be in active status if it does not have a deletion timestamp."))
} }
} else { } else {
if newNamespace.Status.Phase != api.NamespaceTerminating { if newNamespace.Status.Phase != api.NamespaceTerminating {
allErrs = append(allErrs, field.NewInvalidError(field.NewPath("status", "Phase"), newNamespace.Status.Phase, "may only be in terminating status if it has a deletion timestamp.")) allErrs = append(allErrs, field.Invalid(field.NewPath("status", "Phase"), newNamespace.Status.Phase, "may only be in terminating status if it has a deletion timestamp."))
} }
} }
return allErrs return allErrs
...@@ -1954,10 +1954,10 @@ func validateEndpointSubsets(subsets []api.EndpointSubset, fldPath *field.Path) ...@@ -1954,10 +1954,10 @@ func validateEndpointSubsets(subsets []api.EndpointSubset, fldPath *field.Path)
if len(ss.Addresses) == 0 && len(ss.NotReadyAddresses) == 0 { if len(ss.Addresses) == 0 && len(ss.NotReadyAddresses) == 0 {
//TODO: consider adding a RequiredOneOf() error for this and similar cases //TODO: consider adding a RequiredOneOf() error for this and similar cases
allErrs = append(allErrs, field.NewRequiredError(idxPath.Child("addresses or notReadyAddresses"))) allErrs = append(allErrs, field.Required(idxPath.Child("addresses or notReadyAddresses")))
} }
if len(ss.Ports) == 0 { if len(ss.Ports) == 0 {
allErrs = append(allErrs, field.NewRequiredError(idxPath.Child("ports"))) allErrs = append(allErrs, field.Required(idxPath.Child("ports")))
} }
for addr := range ss.Addresses { for addr := range ss.Addresses {
allErrs = append(allErrs, validateEndpointAddress(&ss.Addresses[addr], idxPath.Child("addresses").Index(addr))...) allErrs = append(allErrs, validateEndpointAddress(&ss.Addresses[addr], idxPath.Child("addresses").Index(addr))...)
...@@ -1973,7 +1973,7 @@ func validateEndpointSubsets(subsets []api.EndpointSubset, fldPath *field.Path) ...@@ -1973,7 +1973,7 @@ func validateEndpointSubsets(subsets []api.EndpointSubset, fldPath *field.Path)
func validateEndpointAddress(address *api.EndpointAddress, fldPath *field.Path) field.ErrorList { func validateEndpointAddress(address *api.EndpointAddress, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{} allErrs := field.ErrorList{}
if !validation.IsValidIPv4(address.IP) { if !validation.IsValidIPv4(address.IP) {
allErrs = append(allErrs, field.NewInvalidError(fldPath.Child("ip"), address.IP, "invalid IPv4 address")) allErrs = append(allErrs, field.Invalid(fldPath.Child("ip"), address.IP, "invalid IPv4 address"))
return allErrs return allErrs
} }
return validateIpIsNotLinkLocalOrLoopback(address.IP, fldPath.Child("ip")) return validateIpIsNotLinkLocalOrLoopback(address.IP, fldPath.Child("ip"))
...@@ -1985,17 +1985,17 @@ func validateIpIsNotLinkLocalOrLoopback(ipAddress string, fldPath *field.Path) f ...@@ -1985,17 +1985,17 @@ func validateIpIsNotLinkLocalOrLoopback(ipAddress string, fldPath *field.Path) f
allErrs := field.ErrorList{} allErrs := field.ErrorList{}
ip := net.ParseIP(ipAddress) ip := net.ParseIP(ipAddress)
if ip == nil { if ip == nil {
allErrs = append(allErrs, field.NewInvalidError(fldPath, ipAddress, "not a valid IP address")) allErrs = append(allErrs, field.Invalid(fldPath, ipAddress, "not a valid IP address"))
return allErrs return allErrs
} }
if ip.IsLoopback() { if ip.IsLoopback() {
allErrs = append(allErrs, field.NewInvalidError(fldPath, ipAddress, "may not be in the loopback range (127.0.0.0/8)")) allErrs = append(allErrs, field.Invalid(fldPath, ipAddress, "may not be in the loopback range (127.0.0.0/8)"))
} }
if ip.IsLinkLocalUnicast() { if ip.IsLinkLocalUnicast() {
allErrs = append(allErrs, field.NewInvalidError(fldPath, ipAddress, "may not be in the link-local range (169.254.0.0/16)")) allErrs = append(allErrs, field.Invalid(fldPath, ipAddress, "may not be in the link-local range (169.254.0.0/16)"))
} }
if ip.IsLinkLocalMulticast() { if ip.IsLinkLocalMulticast() {
allErrs = append(allErrs, field.NewInvalidError(fldPath, ipAddress, "may not be in the link-local multicast range (224.0.0.0/24)")) allErrs = append(allErrs, field.Invalid(fldPath, ipAddress, "may not be in the link-local multicast range (224.0.0.0/24)"))
} }
return allErrs return allErrs
} }
...@@ -2003,19 +2003,19 @@ func validateIpIsNotLinkLocalOrLoopback(ipAddress string, fldPath *field.Path) f ...@@ -2003,19 +2003,19 @@ func validateIpIsNotLinkLocalOrLoopback(ipAddress string, fldPath *field.Path) f
func validateEndpointPort(port *api.EndpointPort, requireName bool, fldPath *field.Path) field.ErrorList { func validateEndpointPort(port *api.EndpointPort, requireName bool, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{} allErrs := field.ErrorList{}
if requireName && port.Name == "" { if requireName && port.Name == "" {
allErrs = append(allErrs, field.NewRequiredError(fldPath.Child("name"))) allErrs = append(allErrs, field.Required(fldPath.Child("name")))
} else if port.Name != "" { } else if port.Name != "" {
if !validation.IsDNS1123Label(port.Name) { if !validation.IsDNS1123Label(port.Name) {
allErrs = append(allErrs, field.NewInvalidError(fldPath.Child("name"), port.Name, DNS1123LabelErrorMsg)) allErrs = append(allErrs, field.Invalid(fldPath.Child("name"), port.Name, DNS1123LabelErrorMsg))
} }
} }
if !validation.IsValidPortNum(port.Port) { if !validation.IsValidPortNum(port.Port) {
allErrs = append(allErrs, field.NewInvalidError(fldPath.Child("port"), port.Port, PortRangeErrorMsg)) allErrs = append(allErrs, field.Invalid(fldPath.Child("port"), port.Port, PortRangeErrorMsg))
} }
if len(port.Protocol) == 0 { if len(port.Protocol) == 0 {
allErrs = append(allErrs, field.NewRequiredError(fldPath.Child("protocol"))) allErrs = append(allErrs, field.Required(fldPath.Child("protocol")))
} else if !supportedPortProtocols.Has(string(port.Protocol)) { } else if !supportedPortProtocols.Has(string(port.Protocol)) {
allErrs = append(allErrs, field.NewNotSupportedError(fldPath.Child("protocol"), port.Protocol, supportedPortProtocols.List())) allErrs = append(allErrs, field.NotSupported(fldPath.Child("protocol"), port.Protocol, supportedPortProtocols.List()))
} }
return allErrs return allErrs
} }
...@@ -2037,13 +2037,13 @@ func ValidateSecurityContext(sc *api.SecurityContext, fldPath *field.Path) field ...@@ -2037,13 +2037,13 @@ func ValidateSecurityContext(sc *api.SecurityContext, fldPath *field.Path) field
if sc.Privileged != nil { if sc.Privileged != nil {
if *sc.Privileged && !capabilities.Get().AllowPrivileged { if *sc.Privileged && !capabilities.Get().AllowPrivileged {
allErrs = append(allErrs, field.NewForbiddenError(fldPath.Child("privileged"), sc.Privileged)) allErrs = append(allErrs, field.Forbidden(fldPath.Child("privileged"), sc.Privileged))
} }
} }
if sc.RunAsUser != nil { if sc.RunAsUser != nil {
if *sc.RunAsUser < 0 { if *sc.RunAsUser < 0 {
allErrs = append(allErrs, field.NewInvalidError(fldPath.Child("runAsUser"), *sc.RunAsUser, "runAsUser cannot be negative")) allErrs = append(allErrs, field.Invalid(fldPath.Child("runAsUser"), *sc.RunAsUser, "runAsUser cannot be negative"))
} }
} }
return allErrs return allErrs
...@@ -2052,18 +2052,18 @@ func ValidateSecurityContext(sc *api.SecurityContext, fldPath *field.Path) field ...@@ -2052,18 +2052,18 @@ func ValidateSecurityContext(sc *api.SecurityContext, fldPath *field.Path) field
func ValidatePodLogOptions(opts *api.PodLogOptions) field.ErrorList { func ValidatePodLogOptions(opts *api.PodLogOptions) field.ErrorList {
allErrs := field.ErrorList{} allErrs := field.ErrorList{}
if opts.TailLines != nil && *opts.TailLines < 0 { if opts.TailLines != nil && *opts.TailLines < 0 {
allErrs = append(allErrs, field.NewInvalidError(field.NewPath("tailLines"), *opts.TailLines, "tailLines must be a non-negative integer or nil")) allErrs = append(allErrs, field.Invalid(field.NewPath("tailLines"), *opts.TailLines, "tailLines must be a non-negative integer or nil"))
} }
if opts.LimitBytes != nil && *opts.LimitBytes < 1 { if opts.LimitBytes != nil && *opts.LimitBytes < 1 {
allErrs = append(allErrs, field.NewInvalidError(field.NewPath("limitBytes"), *opts.LimitBytes, "limitBytes must be a positive integer or nil")) allErrs = append(allErrs, field.Invalid(field.NewPath("limitBytes"), *opts.LimitBytes, "limitBytes must be a positive integer or nil"))
} }
switch { switch {
case opts.SinceSeconds != nil && opts.SinceTime != nil: case opts.SinceSeconds != nil && opts.SinceTime != nil:
allErrs = append(allErrs, field.NewInvalidError(field.NewPath("sinceSeconds"), *opts.SinceSeconds, "only one of sinceTime or sinceSeconds can be provided")) allErrs = append(allErrs, field.Invalid(field.NewPath("sinceSeconds"), *opts.SinceSeconds, "only one of sinceTime or sinceSeconds can be provided"))
allErrs = append(allErrs, field.NewInvalidError(field.NewPath("sinceTime"), *opts.SinceTime, "only one of sinceTime or sinceSeconds can be provided")) allErrs = append(allErrs, field.Invalid(field.NewPath("sinceTime"), *opts.SinceTime, "only one of sinceTime or sinceSeconds can be provided"))
case opts.SinceSeconds != nil: case opts.SinceSeconds != nil:
if *opts.SinceSeconds < 1 { if *opts.SinceSeconds < 1 {
allErrs = append(allErrs, field.NewInvalidError(field.NewPath("sinceSeconds"), *opts.SinceSeconds, "sinceSeconds must be a positive integer")) allErrs = append(allErrs, field.Invalid(field.NewPath("sinceSeconds"), *opts.SinceSeconds, "sinceSeconds must be a positive integer"))
} }
} }
return allErrs return allErrs
...@@ -2076,15 +2076,15 @@ func ValidateLoadBalancerStatus(status *api.LoadBalancerStatus, fldPath *field.P ...@@ -2076,15 +2076,15 @@ func ValidateLoadBalancerStatus(status *api.LoadBalancerStatus, fldPath *field.P
idxPath := fldPath.Child("ingress").Index(i) idxPath := fldPath.Child("ingress").Index(i)
if len(ingress.IP) > 0 { if len(ingress.IP) > 0 {
if isIP := (net.ParseIP(ingress.IP) != nil); !isIP { if isIP := (net.ParseIP(ingress.IP) != nil); !isIP {
allErrs = append(allErrs, field.NewInvalidError(idxPath.Child("ip"), ingress.IP, "must be an IP address")) allErrs = append(allErrs, field.Invalid(idxPath.Child("ip"), ingress.IP, "must be an IP address"))
} }
} }
if len(ingress.Hostname) > 0 { if len(ingress.Hostname) > 0 {
if valid, errMsg := NameIsDNSSubdomain(ingress.Hostname, false); !valid { if valid, errMsg := NameIsDNSSubdomain(ingress.Hostname, false); !valid {
allErrs = append(allErrs, field.NewInvalidError(idxPath.Child("hostname"), ingress.Hostname, errMsg)) allErrs = append(allErrs, field.Invalid(idxPath.Child("hostname"), ingress.Hostname, errMsg))
} }
if isIP := (net.ParseIP(ingress.Hostname) != nil); isIP { if isIP := (net.ParseIP(ingress.Hostname) != nil); isIP {
allErrs = append(allErrs, field.NewInvalidError(idxPath.Child("hostname"), ingress.Hostname, "must be a DNS name, not an IP address")) allErrs = append(allErrs, field.Invalid(idxPath.Child("hostname"), ingress.Hostname, "must be a DNS name, not an IP address"))
} }
} }
} }
......
...@@ -42,21 +42,21 @@ func ValidateHorizontalPodAutoscalerName(name string, prefix bool) (bool, string ...@@ -42,21 +42,21 @@ func ValidateHorizontalPodAutoscalerName(name string, prefix bool) (bool, string
func validateHorizontalPodAutoscalerSpec(autoscaler extensions.HorizontalPodAutoscalerSpec, fldPath *field.Path) field.ErrorList { func validateHorizontalPodAutoscalerSpec(autoscaler extensions.HorizontalPodAutoscalerSpec, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{} allErrs := field.ErrorList{}
if autoscaler.MinReplicas != nil && *autoscaler.MinReplicas < 1 { if autoscaler.MinReplicas != nil && *autoscaler.MinReplicas < 1 {
allErrs = append(allErrs, field.NewInvalidError(fldPath.Child("minReplicas"), autoscaler.MinReplicas, `must be greater than or equal to 1`)) allErrs = append(allErrs, field.Invalid(fldPath.Child("minReplicas"), autoscaler.MinReplicas, `must be greater than or equal to 1`))
} }
if autoscaler.MaxReplicas < 1 { if autoscaler.MaxReplicas < 1 {
allErrs = append(allErrs, field.NewInvalidError(fldPath.Child("maxReplicas"), autoscaler.MaxReplicas, `must be greater than or equal to 1`)) allErrs = append(allErrs, field.Invalid(fldPath.Child("maxReplicas"), autoscaler.MaxReplicas, `must be greater than or equal to 1`))
} }
if autoscaler.MinReplicas != nil && autoscaler.MaxReplicas < *autoscaler.MinReplicas { if autoscaler.MinReplicas != nil && autoscaler.MaxReplicas < *autoscaler.MinReplicas {
allErrs = append(allErrs, field.NewInvalidError(fldPath.Child("maxReplicas"), autoscaler.MaxReplicas, `must be greater than or equal to minReplicas`)) allErrs = append(allErrs, field.Invalid(fldPath.Child("maxReplicas"), autoscaler.MaxReplicas, `must be greater than or equal to minReplicas`))
} }
if autoscaler.CPUUtilization != nil && autoscaler.CPUUtilization.TargetPercentage < 1 { if autoscaler.CPUUtilization != nil && autoscaler.CPUUtilization.TargetPercentage < 1 {
allErrs = append(allErrs, field.NewInvalidError(fldPath.Child("cpuUtilization", "targetPercentage"), autoscaler.CPUUtilization.TargetPercentage, `must be greater than or equal to 1`)) allErrs = append(allErrs, field.Invalid(fldPath.Child("cpuUtilization", "targetPercentage"), autoscaler.CPUUtilization.TargetPercentage, `must be greater than or equal to 1`))
} }
if refErrs := ValidateSubresourceReference(autoscaler.ScaleRef, fldPath.Child("scaleRef")); len(refErrs) > 0 { if refErrs := ValidateSubresourceReference(autoscaler.ScaleRef, fldPath.Child("scaleRef")); len(refErrs) > 0 {
allErrs = append(allErrs, refErrs...) allErrs = append(allErrs, refErrs...)
} else if autoscaler.ScaleRef.Subresource != "scale" { } else if autoscaler.ScaleRef.Subresource != "scale" {
allErrs = append(allErrs, field.NewNotSupportedError(fldPath.Child("scaleRef", "subresource"), autoscaler.ScaleRef.Subresource, []string{"scale"})) allErrs = append(allErrs, field.NotSupported(fldPath.Child("scaleRef", "subresource"), autoscaler.ScaleRef.Subresource, []string{"scale"}))
} }
return allErrs return allErrs
} }
...@@ -64,21 +64,21 @@ func validateHorizontalPodAutoscalerSpec(autoscaler extensions.HorizontalPodAuto ...@@ -64,21 +64,21 @@ func validateHorizontalPodAutoscalerSpec(autoscaler extensions.HorizontalPodAuto
func ValidateSubresourceReference(ref extensions.SubresourceReference, fldPath *field.Path) field.ErrorList { func ValidateSubresourceReference(ref extensions.SubresourceReference, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{} allErrs := field.ErrorList{}
if len(ref.Kind) == 0 { if len(ref.Kind) == 0 {
allErrs = append(allErrs, field.NewRequiredError(fldPath.Child("kind"))) allErrs = append(allErrs, field.Required(fldPath.Child("kind")))
} else if ok, msg := apivalidation.IsValidPathSegmentName(ref.Kind); !ok { } else if ok, msg := apivalidation.IsValidPathSegmentName(ref.Kind); !ok {
allErrs = append(allErrs, field.NewInvalidError(fldPath.Child("kind"), ref.Kind, msg)) allErrs = append(allErrs, field.Invalid(fldPath.Child("kind"), ref.Kind, msg))
} }
if len(ref.Name) == 0 { if len(ref.Name) == 0 {
allErrs = append(allErrs, field.NewRequiredError(fldPath.Child("name"))) allErrs = append(allErrs, field.Required(fldPath.Child("name")))
} else if ok, msg := apivalidation.IsValidPathSegmentName(ref.Name); !ok { } else if ok, msg := apivalidation.IsValidPathSegmentName(ref.Name); !ok {
allErrs = append(allErrs, field.NewInvalidError(fldPath.Child("name"), ref.Name, msg)) allErrs = append(allErrs, field.Invalid(fldPath.Child("name"), ref.Name, msg))
} }
if len(ref.Subresource) == 0 { if len(ref.Subresource) == 0 {
allErrs = append(allErrs, field.NewRequiredError(fldPath.Child("subresource"))) allErrs = append(allErrs, field.Required(fldPath.Child("subresource")))
} else if ok, msg := apivalidation.IsValidPathSegmentName(ref.Subresource); !ok { } else if ok, msg := apivalidation.IsValidPathSegmentName(ref.Subresource); !ok {
allErrs = append(allErrs, field.NewInvalidError(fldPath.Child("subresource"), ref.Subresource, msg)) allErrs = append(allErrs, field.Invalid(fldPath.Child("subresource"), ref.Subresource, msg))
} }
return allErrs return allErrs
} }
...@@ -122,10 +122,10 @@ func ValidateThirdPartyResource(obj *extensions.ThirdPartyResource) field.ErrorL ...@@ -122,10 +122,10 @@ func ValidateThirdPartyResource(obj *extensions.ThirdPartyResource) field.ErrorL
for ix := range obj.Versions { for ix := range obj.Versions {
version := &obj.Versions[ix] version := &obj.Versions[ix]
if len(version.Name) == 0 { if len(version.Name) == 0 {
allErrs = append(allErrs, field.NewInvalidError(field.NewPath("versions").Index(ix).Child("name"), version, "can not be empty")) allErrs = append(allErrs, field.Invalid(field.NewPath("versions").Index(ix).Child("name"), version, "can not be empty"))
} }
if versions.Has(version.Name) { if versions.Has(version.Name) {
allErrs = append(allErrs, field.NewDuplicateError(field.NewPath("versions").Index(ix).Child("name"), version)) allErrs = append(allErrs, field.Duplicate(field.NewPath("versions").Index(ix).Child("name"), version))
} }
versions.Insert(version.Name) versions.Insert(version.Name)
} }
...@@ -173,7 +173,7 @@ func ValidateDaemonSetTemplateUpdate(podTemplate, oldPodTemplate *api.PodTemplat ...@@ -173,7 +173,7 @@ func ValidateDaemonSetTemplateUpdate(podTemplate, oldPodTemplate *api.PodTemplat
// In particular, we do not allow updates to container images at this point. // In particular, we do not allow updates to container images at this point.
if !api.Semantic.DeepEqual(oldPodTemplate.Spec, podSpec) { if !api.Semantic.DeepEqual(oldPodTemplate.Spec, podSpec) {
// TODO: Pinpoint the specific field that causes the invalid error after we have strategic merge diff // TODO: Pinpoint the specific field that causes the invalid error after we have strategic merge diff
allErrs = append(allErrs, field.NewInvalidError(fldPath.Child("spec"), "content of spec is not printed out, please refer to the \"details\"", "may not update fields other than spec.nodeSelector")) allErrs = append(allErrs, field.Invalid(fldPath.Child("spec"), "content of spec is not printed out, please refer to the \"details\"", "may not update fields other than spec.nodeSelector"))
} }
return allErrs return allErrs
} }
...@@ -185,13 +185,13 @@ func ValidateDaemonSetSpec(spec *extensions.DaemonSetSpec, fldPath *field.Path) ...@@ -185,13 +185,13 @@ func ValidateDaemonSetSpec(spec *extensions.DaemonSetSpec, fldPath *field.Path)
allErrs = append(allErrs, ValidateLabelSelector(spec.Selector, fldPath.Child("selector"))...) allErrs = append(allErrs, ValidateLabelSelector(spec.Selector, fldPath.Child("selector"))...)
if spec.Template == nil { if spec.Template == nil {
allErrs = append(allErrs, field.NewRequiredError(fldPath.Child("template"))) allErrs = append(allErrs, field.Required(fldPath.Child("template")))
return allErrs return allErrs
} }
selector, err := extensions.LabelSelectorAsSelector(spec.Selector) selector, err := extensions.LabelSelectorAsSelector(spec.Selector)
if err == nil && !selector.Matches(labels.Set(spec.Template.Labels)) { if err == nil && !selector.Matches(labels.Set(spec.Template.Labels)) {
allErrs = append(allErrs, field.NewInvalidError(fldPath.Child("template", "metadata", "labels"), spec.Template.Labels, "selector does not match template")) allErrs = append(allErrs, field.Invalid(fldPath.Child("template", "metadata", "labels"), spec.Template.Labels, "selector does not match template"))
} }
allErrs = append(allErrs, apivalidation.ValidatePodTemplateSpec(spec.Template, fldPath.Child("template"))...) allErrs = append(allErrs, apivalidation.ValidatePodTemplateSpec(spec.Template, fldPath.Child("template"))...)
...@@ -199,7 +199,7 @@ func ValidateDaemonSetSpec(spec *extensions.DaemonSetSpec, fldPath *field.Path) ...@@ -199,7 +199,7 @@ func ValidateDaemonSetSpec(spec *extensions.DaemonSetSpec, fldPath *field.Path)
allErrs = append(allErrs, apivalidation.ValidateReadOnlyPersistentDisks(spec.Template.Spec.Volumes, fldPath.Child("template", "spec", "volumes"))...) allErrs = append(allErrs, apivalidation.ValidateReadOnlyPersistentDisks(spec.Template.Spec.Volumes, fldPath.Child("template", "spec", "volumes"))...)
// RestartPolicy has already been first-order validated as per ValidatePodTemplateSpec(). // RestartPolicy has already been first-order validated as per ValidatePodTemplateSpec().
if spec.Template.Spec.RestartPolicy != api.RestartPolicyAlways { if spec.Template.Spec.RestartPolicy != api.RestartPolicyAlways {
allErrs = append(allErrs, field.NewNotSupportedError(fldPath.Child("template", "spec", "restartPolicy"), spec.Template.Spec.RestartPolicy, []string{string(api.RestartPolicyAlways)})) allErrs = append(allErrs, field.NotSupported(fldPath.Child("template", "spec", "restartPolicy"), spec.Template.Spec.RestartPolicy, []string{string(api.RestartPolicyAlways)}))
} }
return allErrs return allErrs
...@@ -221,7 +221,7 @@ func ValidatePositiveIntOrPercent(intOrPercent intstr.IntOrString, fldPath *fiel ...@@ -221,7 +221,7 @@ func ValidatePositiveIntOrPercent(intOrPercent intstr.IntOrString, fldPath *fiel
allErrs := field.ErrorList{} allErrs := field.ErrorList{}
if intOrPercent.Type == intstr.String { if intOrPercent.Type == intstr.String {
if !validation.IsValidPercent(intOrPercent.StrVal) { if !validation.IsValidPercent(intOrPercent.StrVal) {
allErrs = append(allErrs, field.NewInvalidError(fldPath, intOrPercent, "value should be int(5) or percentage(5%)")) allErrs = append(allErrs, field.Invalid(fldPath, intOrPercent, "value should be int(5) or percentage(5%)"))
} }
} else if intOrPercent.Type == intstr.Int { } else if intOrPercent.Type == intstr.Int {
allErrs = append(allErrs, apivalidation.ValidatePositiveField(int64(intOrPercent.IntValue()), fldPath)...) allErrs = append(allErrs, apivalidation.ValidatePositiveField(int64(intOrPercent.IntValue()), fldPath)...)
...@@ -251,7 +251,7 @@ func IsNotMoreThan100Percent(intOrStringValue intstr.IntOrString, fldPath *field ...@@ -251,7 +251,7 @@ func IsNotMoreThan100Percent(intOrStringValue intstr.IntOrString, fldPath *field
if !isPercent || value <= 100 { if !isPercent || value <= 100 {
return nil return nil
} }
allErrs = append(allErrs, field.NewInvalidError(fldPath, intOrStringValue, "should not be more than 100%")) allErrs = append(allErrs, field.Invalid(fldPath, intOrStringValue, "should not be more than 100%"))
return allErrs return allErrs
} }
...@@ -261,7 +261,7 @@ func ValidateRollingUpdateDeployment(rollingUpdate *extensions.RollingUpdateDepl ...@@ -261,7 +261,7 @@ func ValidateRollingUpdateDeployment(rollingUpdate *extensions.RollingUpdateDepl
allErrs = append(allErrs, ValidatePositiveIntOrPercent(rollingUpdate.MaxSurge, fldPath.Child("maxSurge"))...) allErrs = append(allErrs, ValidatePositiveIntOrPercent(rollingUpdate.MaxSurge, fldPath.Child("maxSurge"))...)
if getIntOrPercentValue(rollingUpdate.MaxUnavailable) == 0 && getIntOrPercentValue(rollingUpdate.MaxSurge) == 0 { if getIntOrPercentValue(rollingUpdate.MaxUnavailable) == 0 && getIntOrPercentValue(rollingUpdate.MaxSurge) == 0 {
// Both MaxSurge and MaxUnavailable cannot be zero. // Both MaxSurge and MaxUnavailable cannot be zero.
allErrs = append(allErrs, field.NewInvalidError(fldPath.Child("maxUnavailable"), rollingUpdate.MaxUnavailable, "cannot be 0 when maxSurge is 0 as well")) allErrs = append(allErrs, field.Invalid(fldPath.Child("maxUnavailable"), rollingUpdate.MaxUnavailable, "cannot be 0 when maxSurge is 0 as well"))
} }
// Validate that MaxUnavailable is not more than 100%. // Validate that MaxUnavailable is not more than 100%.
allErrs = append(allErrs, IsNotMoreThan100Percent(rollingUpdate.MaxUnavailable, fldPath.Child("maxUnavailable"))...) allErrs = append(allErrs, IsNotMoreThan100Percent(rollingUpdate.MaxUnavailable, fldPath.Child("maxUnavailable"))...)
...@@ -276,7 +276,7 @@ func ValidateDeploymentStrategy(strategy *extensions.DeploymentStrategy, fldPath ...@@ -276,7 +276,7 @@ func ValidateDeploymentStrategy(strategy *extensions.DeploymentStrategy, fldPath
} }
switch strategy.Type { switch strategy.Type {
case extensions.RecreateDeploymentStrategyType: case extensions.RecreateDeploymentStrategyType:
allErrs = append(allErrs, field.NewForbiddenError(fldPath.Child("rollingUpdate"), "should be nil when strategy type is "+extensions.RecreateDeploymentStrategyType)) allErrs = append(allErrs, field.Forbidden(fldPath.Child("rollingUpdate"), "should be nil when strategy type is "+extensions.RecreateDeploymentStrategyType))
case extensions.RollingUpdateDeploymentStrategyType: case extensions.RollingUpdateDeploymentStrategyType:
allErrs = append(allErrs, ValidateRollingUpdateDeployment(strategy.RollingUpdate, fldPath.Child("rollingUpdate"))...) allErrs = append(allErrs, ValidateRollingUpdateDeployment(strategy.RollingUpdate, fldPath.Child("rollingUpdate"))...)
} }
...@@ -316,7 +316,7 @@ func ValidateThirdPartyResourceDataUpdate(update, old *extensions.ThirdPartyReso ...@@ -316,7 +316,7 @@ func ValidateThirdPartyResourceDataUpdate(update, old *extensions.ThirdPartyReso
func ValidateThirdPartyResourceData(obj *extensions.ThirdPartyResourceData) field.ErrorList { func ValidateThirdPartyResourceData(obj *extensions.ThirdPartyResourceData) field.ErrorList {
allErrs := field.ErrorList{} allErrs := field.ErrorList{}
if len(obj.Name) == 0 { if len(obj.Name) == 0 {
allErrs = append(allErrs, field.NewInvalidError(field.NewPath("name"), obj.Name, "must be non-empty")) allErrs = append(allErrs, field.Invalid(field.NewPath("name"), obj.Name, "must be non-empty"))
} }
return allErrs return allErrs
} }
...@@ -338,7 +338,7 @@ func ValidateJobSpec(spec *extensions.JobSpec, fldPath *field.Path) field.ErrorL ...@@ -338,7 +338,7 @@ func ValidateJobSpec(spec *extensions.JobSpec, fldPath *field.Path) field.ErrorL
allErrs = append(allErrs, apivalidation.ValidatePositiveField(int64(*spec.Completions), fldPath.Child("completions"))...) allErrs = append(allErrs, apivalidation.ValidatePositiveField(int64(*spec.Completions), fldPath.Child("completions"))...)
} }
if spec.Selector == nil { if spec.Selector == nil {
allErrs = append(allErrs, field.NewRequiredError(fldPath.Child("selector"))) allErrs = append(allErrs, field.Required(fldPath.Child("selector")))
} else { } else {
allErrs = append(allErrs, ValidateLabelSelector(spec.Selector, fldPath.Child("selector"))...) allErrs = append(allErrs, ValidateLabelSelector(spec.Selector, fldPath.Child("selector"))...)
} }
...@@ -346,14 +346,14 @@ func ValidateJobSpec(spec *extensions.JobSpec, fldPath *field.Path) field.ErrorL ...@@ -346,14 +346,14 @@ func ValidateJobSpec(spec *extensions.JobSpec, fldPath *field.Path) field.ErrorL
if selector, err := extensions.LabelSelectorAsSelector(spec.Selector); err == nil { if selector, err := extensions.LabelSelectorAsSelector(spec.Selector); err == nil {
labels := labels.Set(spec.Template.Labels) labels := labels.Set(spec.Template.Labels)
if !selector.Matches(labels) { if !selector.Matches(labels) {
allErrs = append(allErrs, field.NewInvalidError(fldPath.Child("template", "metadata", "labels"), spec.Template.Labels, "selector does not match template")) allErrs = append(allErrs, field.Invalid(fldPath.Child("template", "metadata", "labels"), spec.Template.Labels, "selector does not match template"))
} }
} }
allErrs = append(allErrs, apivalidation.ValidatePodTemplateSpec(&spec.Template, fldPath.Child("template"))...) allErrs = append(allErrs, apivalidation.ValidatePodTemplateSpec(&spec.Template, fldPath.Child("template"))...)
if spec.Template.Spec.RestartPolicy != api.RestartPolicyOnFailure && if spec.Template.Spec.RestartPolicy != api.RestartPolicyOnFailure &&
spec.Template.Spec.RestartPolicy != api.RestartPolicyNever { spec.Template.Spec.RestartPolicy != api.RestartPolicyNever {
allErrs = append(allErrs, field.NewNotSupportedError(fldPath.Child("template", "spec", "restartPolicy"), allErrs = append(allErrs, field.NotSupported(fldPath.Child("template", "spec", "restartPolicy"),
spec.Template.Spec.RestartPolicy, []string{string(api.RestartPolicyOnFailure), string(api.RestartPolicyNever)})) spec.Template.Spec.RestartPolicy, []string{string(api.RestartPolicyOnFailure), string(api.RestartPolicyNever)}))
} }
return allErrs return allErrs
...@@ -413,7 +413,7 @@ func ValidateIngressSpec(spec *extensions.IngressSpec, fldPath *field.Path) fiel ...@@ -413,7 +413,7 @@ func ValidateIngressSpec(spec *extensions.IngressSpec, fldPath *field.Path) fiel
if spec.Backend != nil { if spec.Backend != nil {
allErrs = append(allErrs, validateIngressBackend(spec.Backend, fldPath.Child("backend"))...) allErrs = append(allErrs, validateIngressBackend(spec.Backend, fldPath.Child("backend"))...)
} else if len(spec.Rules) == 0 { } else if len(spec.Rules) == 0 {
allErrs = append(allErrs, field.NewInvalidError(fldPath.Child("rules"), spec.Rules, "Either a default backend or a set of host rules are required for ingress.")) allErrs = append(allErrs, field.Invalid(fldPath.Child("rules"), spec.Rules, "Either a default backend or a set of host rules are required for ingress."))
} }
if len(spec.Rules) > 0 { if len(spec.Rules) > 0 {
allErrs = append(allErrs, validateIngressRules(spec.Rules, fldPath.Child("rules"))...) allErrs = append(allErrs, validateIngressRules(spec.Rules, fldPath.Child("rules"))...)
...@@ -438,17 +438,17 @@ func ValidateIngressStatusUpdate(ingress, oldIngress *extensions.Ingress) field. ...@@ -438,17 +438,17 @@ func ValidateIngressStatusUpdate(ingress, oldIngress *extensions.Ingress) field.
func validateIngressRules(IngressRules []extensions.IngressRule, fldPath *field.Path) field.ErrorList { func validateIngressRules(IngressRules []extensions.IngressRule, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{} allErrs := field.ErrorList{}
if len(IngressRules) == 0 { if len(IngressRules) == 0 {
return append(allErrs, field.NewRequiredError(fldPath)) return append(allErrs, field.Required(fldPath))
} }
for i, ih := range IngressRules { for i, ih := range IngressRules {
if len(ih.Host) > 0 { if len(ih.Host) > 0 {
// TODO: Ports and ips are allowed in the host part of a url // TODO: Ports and ips are allowed in the host part of a url
// according to RFC 3986, consider allowing them. // according to RFC 3986, consider allowing them.
if valid, errMsg := apivalidation.NameIsDNSSubdomain(ih.Host, false); !valid { if valid, errMsg := apivalidation.NameIsDNSSubdomain(ih.Host, false); !valid {
allErrs = append(allErrs, field.NewInvalidError(fldPath.Index(i).Child("host"), ih.Host, errMsg)) allErrs = append(allErrs, field.Invalid(fldPath.Index(i).Child("host"), ih.Host, errMsg))
} }
if isIP := (net.ParseIP(ih.Host) != nil); isIP { if isIP := (net.ParseIP(ih.Host) != nil); isIP {
allErrs = append(allErrs, field.NewInvalidError(fldPath.Index(i).Child("host"), ih.Host, "Host must be a DNS name, not ip address")) allErrs = append(allErrs, field.Invalid(fldPath.Index(i).Child("host"), ih.Host, "Host must be a DNS name, not ip address"))
} }
} }
allErrs = append(allErrs, validateIngressRuleValue(&ih.IngressRuleValue, fldPath.Index(0))...) allErrs = append(allErrs, validateIngressRuleValue(&ih.IngressRuleValue, fldPath.Index(0))...)
...@@ -467,12 +467,12 @@ func validateIngressRuleValue(ingressRule *extensions.IngressRuleValue, fldPath ...@@ -467,12 +467,12 @@ func validateIngressRuleValue(ingressRule *extensions.IngressRuleValue, fldPath
func validateHTTPIngressRuleValue(httpIngressRuleValue *extensions.HTTPIngressRuleValue, fldPath *field.Path) field.ErrorList { func validateHTTPIngressRuleValue(httpIngressRuleValue *extensions.HTTPIngressRuleValue, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{} allErrs := field.ErrorList{}
if len(httpIngressRuleValue.Paths) == 0 { if len(httpIngressRuleValue.Paths) == 0 {
allErrs = append(allErrs, field.NewRequiredError(fldPath.Child("paths"))) allErrs = append(allErrs, field.Required(fldPath.Child("paths")))
} }
for i, rule := range httpIngressRuleValue.Paths { for i, rule := range httpIngressRuleValue.Paths {
if len(rule.Path) > 0 { if len(rule.Path) > 0 {
if !strings.HasPrefix(rule.Path, "/") { if !strings.HasPrefix(rule.Path, "/") {
allErrs = append(allErrs, field.NewInvalidError(fldPath.Child("paths").Index(i).Child("path"), rule.Path, "must begin with /")) allErrs = append(allErrs, field.Invalid(fldPath.Child("paths").Index(i).Child("path"), rule.Path, "must begin with /"))
} }
// TODO: More draconian path regex validation. // TODO: More draconian path regex validation.
// Path must be a valid regex. This is the basic requirement. // Path must be a valid regex. This is the basic requirement.
...@@ -485,7 +485,7 @@ func validateHTTPIngressRuleValue(httpIngressRuleValue *extensions.HTTPIngressRu ...@@ -485,7 +485,7 @@ func validateHTTPIngressRuleValue(httpIngressRuleValue *extensions.HTTPIngressRu
// the user is confusing url regexes with path regexes. // the user is confusing url regexes with path regexes.
_, err := regexp.CompilePOSIX(rule.Path) _, err := regexp.CompilePOSIX(rule.Path)
if err != nil { if err != nil {
allErrs = append(allErrs, field.NewInvalidError(fldPath.Child("paths").Index(i).Child("path"), rule.Path, "must be a valid regex.")) allErrs = append(allErrs, field.Invalid(fldPath.Child("paths").Index(i).Child("path"), rule.Path, "must be a valid regex."))
} }
} }
allErrs = append(allErrs, validateIngressBackend(&rule.Backend, fldPath.Child("backend"))...) allErrs = append(allErrs, validateIngressBackend(&rule.Backend, fldPath.Child("backend"))...)
...@@ -499,19 +499,19 @@ func validateIngressBackend(backend *extensions.IngressBackend, fldPath *field.P ...@@ -499,19 +499,19 @@ func validateIngressBackend(backend *extensions.IngressBackend, fldPath *field.P
// All backends must reference a single local service by name, and a single service port by name or number. // All backends must reference a single local service by name, and a single service port by name or number.
if len(backend.ServiceName) == 0 { if len(backend.ServiceName) == 0 {
return append(allErrs, field.NewRequiredError(fldPath.Child("serviceName"))) return append(allErrs, field.Required(fldPath.Child("serviceName")))
} else if ok, errMsg := apivalidation.ValidateServiceName(backend.ServiceName, false); !ok { } else if ok, errMsg := apivalidation.ValidateServiceName(backend.ServiceName, false); !ok {
allErrs = append(allErrs, field.NewInvalidError(fldPath.Child("serviceName"), backend.ServiceName, errMsg)) allErrs = append(allErrs, field.Invalid(fldPath.Child("serviceName"), backend.ServiceName, errMsg))
} }
if backend.ServicePort.Type == intstr.String { if backend.ServicePort.Type == intstr.String {
if !validation.IsDNS1123Label(backend.ServicePort.StrVal) { if !validation.IsDNS1123Label(backend.ServicePort.StrVal) {
allErrs = append(allErrs, field.NewInvalidError(fldPath.Child("servicePort"), backend.ServicePort.StrVal, apivalidation.DNS1123LabelErrorMsg)) allErrs = append(allErrs, field.Invalid(fldPath.Child("servicePort"), backend.ServicePort.StrVal, apivalidation.DNS1123LabelErrorMsg))
} }
if !validation.IsValidPortName(backend.ServicePort.StrVal) { if !validation.IsValidPortName(backend.ServicePort.StrVal) {
allErrs = append(allErrs, field.NewInvalidError(fldPath.Child("servicePort"), backend.ServicePort.StrVal, apivalidation.PortNameErrorMsg)) allErrs = append(allErrs, field.Invalid(fldPath.Child("servicePort"), backend.ServicePort.StrVal, apivalidation.PortNameErrorMsg))
} }
} else if !validation.IsValidPortNum(backend.ServicePort.IntValue()) { } else if !validation.IsValidPortNum(backend.ServicePort.IntValue()) {
allErrs = append(allErrs, field.NewInvalidError(fldPath.Child("servicePort"), backend.ServicePort, apivalidation.PortRangeErrorMsg)) allErrs = append(allErrs, field.Invalid(fldPath.Child("servicePort"), backend.ServicePort, apivalidation.PortRangeErrorMsg))
} }
return allErrs return allErrs
} }
...@@ -519,23 +519,23 @@ func validateIngressBackend(backend *extensions.IngressBackend, fldPath *field.P ...@@ -519,23 +519,23 @@ func validateIngressBackend(backend *extensions.IngressBackend, fldPath *field.P
func validateClusterAutoscalerSpec(spec extensions.ClusterAutoscalerSpec, fldPath *field.Path) field.ErrorList { func validateClusterAutoscalerSpec(spec extensions.ClusterAutoscalerSpec, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{} allErrs := field.ErrorList{}
if spec.MinNodes < 0 { if spec.MinNodes < 0 {
allErrs = append(allErrs, field.NewInvalidError(fldPath.Child("minNodes"), spec.MinNodes, `must be non-negative`)) allErrs = append(allErrs, field.Invalid(fldPath.Child("minNodes"), spec.MinNodes, `must be non-negative`))
} }
if spec.MaxNodes < spec.MinNodes { if spec.MaxNodes < spec.MinNodes {
allErrs = append(allErrs, field.NewInvalidError(fldPath.Child("maxNodes"), spec.MaxNodes, `must be greater than or equal to minNodes`)) allErrs = append(allErrs, field.Invalid(fldPath.Child("maxNodes"), spec.MaxNodes, `must be greater than or equal to minNodes`))
} }
if len(spec.TargetUtilization) == 0 { if len(spec.TargetUtilization) == 0 {
allErrs = append(allErrs, field.NewRequiredError(fldPath.Child("targetUtilization"))) allErrs = append(allErrs, field.Required(fldPath.Child("targetUtilization")))
} }
for _, target := range spec.TargetUtilization { for _, target := range spec.TargetUtilization {
if len(target.Resource) == 0 { if len(target.Resource) == 0 {
allErrs = append(allErrs, field.NewRequiredError(fldPath.Child("targetUtilization", "resource"))) allErrs = append(allErrs, field.Required(fldPath.Child("targetUtilization", "resource")))
} }
if target.Value <= 0 { if target.Value <= 0 {
allErrs = append(allErrs, field.NewInvalidError(fldPath.Child("targetUtilization", "value"), target.Value, "must be greater than 0")) allErrs = append(allErrs, field.Invalid(fldPath.Child("targetUtilization", "value"), target.Value, "must be greater than 0"))
} }
if target.Value > 1 { if target.Value > 1 {
allErrs = append(allErrs, field.NewInvalidError(fldPath.Child("targetUtilization", "value"), target.Value, "must be less or equal 1")) allErrs = append(allErrs, field.Invalid(fldPath.Child("targetUtilization", "value"), target.Value, "must be less or equal 1"))
} }
} }
return allErrs return allErrs
...@@ -544,10 +544,10 @@ func validateClusterAutoscalerSpec(spec extensions.ClusterAutoscalerSpec, fldPat ...@@ -544,10 +544,10 @@ func validateClusterAutoscalerSpec(spec extensions.ClusterAutoscalerSpec, fldPat
func ValidateClusterAutoscaler(autoscaler *extensions.ClusterAutoscaler) field.ErrorList { func ValidateClusterAutoscaler(autoscaler *extensions.ClusterAutoscaler) field.ErrorList {
allErrs := field.ErrorList{} allErrs := field.ErrorList{}
if autoscaler.Name != "ClusterAutoscaler" { if autoscaler.Name != "ClusterAutoscaler" {
allErrs = append(allErrs, field.NewInvalidError(field.NewPath("metadata", "name"), autoscaler.Name, `name must be ClusterAutoscaler`)) allErrs = append(allErrs, field.Invalid(field.NewPath("metadata", "name"), autoscaler.Name, `name must be ClusterAutoscaler`))
} }
if autoscaler.Namespace != api.NamespaceDefault { if autoscaler.Namespace != api.NamespaceDefault {
allErrs = append(allErrs, field.NewInvalidError(field.NewPath("metadata", "namespace"), autoscaler.Namespace, `namespace must be default`)) allErrs = append(allErrs, field.Invalid(field.NewPath("metadata", "namespace"), autoscaler.Namespace, `namespace must be default`))
} }
allErrs = append(allErrs, validateClusterAutoscalerSpec(autoscaler.Spec, field.NewPath("spec"))...) allErrs = append(allErrs, validateClusterAutoscalerSpec(autoscaler.Spec, field.NewPath("spec"))...)
return allErrs return allErrs
...@@ -570,14 +570,14 @@ func ValidateLabelSelectorRequirement(sr extensions.LabelSelectorRequirement, fl ...@@ -570,14 +570,14 @@ func ValidateLabelSelectorRequirement(sr extensions.LabelSelectorRequirement, fl
switch sr.Operator { switch sr.Operator {
case extensions.LabelSelectorOpIn, extensions.LabelSelectorOpNotIn: case extensions.LabelSelectorOpIn, extensions.LabelSelectorOpNotIn:
if len(sr.Values) == 0 { if len(sr.Values) == 0 {
allErrs = append(allErrs, field.NewInvalidError(fldPath.Child("values"), sr.Values, "must be non-empty when operator is In or NotIn")) allErrs = append(allErrs, field.Invalid(fldPath.Child("values"), sr.Values, "must be non-empty when operator is In or NotIn"))
} }
case extensions.LabelSelectorOpExists, extensions.LabelSelectorOpDoesNotExist: case extensions.LabelSelectorOpExists, extensions.LabelSelectorOpDoesNotExist:
if len(sr.Values) > 0 { if len(sr.Values) > 0 {
allErrs = append(allErrs, field.NewInvalidError(fldPath.Child("values"), sr.Values, "must be empty when operator is Exists or DoesNotExist")) allErrs = append(allErrs, field.Invalid(fldPath.Child("values"), sr.Values, "must be empty when operator is Exists or DoesNotExist"))
} }
default: default:
allErrs = append(allErrs, field.NewInvalidError(fldPath.Child("operator"), sr.Operator, "not a valid pod selector operator")) allErrs = append(allErrs, field.Invalid(fldPath.Child("operator"), sr.Operator, "not a valid pod selector operator"))
} }
allErrs = append(allErrs, apivalidation.ValidateLabelName(sr.Key, fldPath.Child("key"))...) allErrs = append(allErrs, apivalidation.ValidateLabelName(sr.Key, fldPath.Child("key"))...)
return allErrs return allErrs
...@@ -588,7 +588,7 @@ func ValidateScale(scale *extensions.Scale) field.ErrorList { ...@@ -588,7 +588,7 @@ func ValidateScale(scale *extensions.Scale) field.ErrorList {
allErrs = append(allErrs, apivalidation.ValidateObjectMeta(&scale.ObjectMeta, true, apivalidation.NameIsDNSSubdomain, field.NewPath("metadata"))...) allErrs = append(allErrs, apivalidation.ValidateObjectMeta(&scale.ObjectMeta, true, apivalidation.NameIsDNSSubdomain, field.NewPath("metadata"))...)
if scale.Spec.Replicas < 0 { if scale.Spec.Replicas < 0 {
allErrs = append(allErrs, field.NewInvalidError(field.NewPath("spec", "replicas"), scale.Spec.Replicas, "must be non-negative")) allErrs = append(allErrs, field.Invalid(field.NewPath("spec", "replicas"), scale.Spec.Replicas, "must be non-negative"))
} }
return allErrs return allErrs
......
...@@ -274,11 +274,11 @@ func TestCheckInvalidErr(t *testing.T) { ...@@ -274,11 +274,11 @@ func TestCheckInvalidErr(t *testing.T) {
expected string expected string
}{ }{
{ {
errors.NewInvalid("Invalid1", "invalidation", field.ErrorList{field.NewInvalidError(field.NewPath("field"), "single", "details")}), errors.NewInvalid("Invalid1", "invalidation", field.ErrorList{field.Invalid(field.NewPath("field"), "single", "details")}),
`Error from server: Invalid1 "invalidation" is invalid: field: invalid value 'single', Details: details`, `Error from server: Invalid1 "invalidation" is invalid: field: invalid value 'single', Details: details`,
}, },
{ {
errors.NewInvalid("Invalid2", "invalidation", field.ErrorList{field.NewInvalidError(field.NewPath("field1"), "multi1", "details"), field.NewInvalidError(field.NewPath("field2"), "multi2", "details")}), errors.NewInvalid("Invalid2", "invalidation", field.ErrorList{field.Invalid(field.NewPath("field1"), "multi1", "details"), field.Invalid(field.NewPath("field2"), "multi2", "details")}),
`Error from server: Invalid2 "invalidation" is invalid: [field1: invalid value 'multi1', Details: details, field2: invalid value 'multi2', Details: details]`, `Error from server: Invalid2 "invalidation" is invalid: [field1: invalid value 'multi1', Details: details, field2: invalid value 'multi2', Details: details]`,
}, },
{ {
......
...@@ -319,7 +319,7 @@ func filterInvalidPods(pods []*api.Pod, source string, recorder record.EventReco ...@@ -319,7 +319,7 @@ func filterInvalidPods(pods []*api.Pod, source string, recorder record.EventReco
if names.Has(name) { if names.Has(name) {
// TODO: when validation becomes versioned, this gets a bit // TODO: when validation becomes versioned, this gets a bit
// more complicated. // more complicated.
errlist = append(errlist, field.NewDuplicateError(field.NewPath("metadata", "name"), pod.Name)) errlist = append(errlist, field.Duplicate(field.NewPath("metadata", "name"), pod.Name))
} else { } else {
names.Insert(name) names.Insert(name)
} }
......
...@@ -135,11 +135,11 @@ func (r *BindingREST) Create(ctx api.Context, obj runtime.Object) (out runtime.O ...@@ -135,11 +135,11 @@ func (r *BindingREST) Create(ctx api.Context, obj runtime.Object) (out runtime.O
// TODO: move me to a binding strategy // TODO: move me to a binding strategy
if len(binding.Target.Kind) != 0 && binding.Target.Kind != "Node" { if len(binding.Target.Kind) != 0 && binding.Target.Kind != "Node" {
// TODO: When validation becomes versioned, this gets more complicated. // TODO: When validation becomes versioned, this gets more complicated.
return nil, errors.NewInvalid("binding", binding.Name, field.ErrorList{field.NewNotSupportedError(field.NewPath("target", "kind"), binding.Target.Kind, []string{"Node", ""})}) return nil, errors.NewInvalid("binding", binding.Name, field.ErrorList{field.NotSupported(field.NewPath("target", "kind"), binding.Target.Kind, []string{"Node", ""})})
} }
if len(binding.Target.Name) == 0 { if len(binding.Target.Name) == 0 {
// TODO: When validation becomes versioned, this gets more complicated. // TODO: When validation becomes versioned, this gets more complicated.
return nil, errors.NewInvalid("binding", binding.Name, field.ErrorList{field.NewRequiredError(field.NewPath("target", "name"))}) return nil, errors.NewInvalid("binding", binding.Name, field.ErrorList{field.Required(field.NewPath("target", "name"))})
} }
err = r.assignPod(ctx, binding.Name, binding.Target.Name, binding.Annotations) err = r.assignPod(ctx, binding.Name, binding.Target.Name, binding.Annotations)
out = &unversioned.Status{Status: unversioned.StatusSuccess} out = &unversioned.Status{Status: unversioned.StatusSuccess}
......
...@@ -95,7 +95,7 @@ func (rs *REST) Create(ctx api.Context, obj runtime.Object) (runtime.Object, err ...@@ -95,7 +95,7 @@ func (rs *REST) Create(ctx api.Context, obj runtime.Object) (runtime.Object, err
// Try to respect the requested IP. // Try to respect the requested IP.
if err := rs.serviceIPs.Allocate(net.ParseIP(service.Spec.ClusterIP)); err != nil { if err := rs.serviceIPs.Allocate(net.ParseIP(service.Spec.ClusterIP)); err != nil {
// TODO: when validation becomes versioned, this gets more complicated. // TODO: when validation becomes versioned, this gets more complicated.
el := field.ErrorList{field.NewInvalidError(field.NewPath("spec", "clusterIP"), service.Spec.ClusterIP, err.Error())} el := field.ErrorList{field.Invalid(field.NewPath("spec", "clusterIP"), service.Spec.ClusterIP, err.Error())}
return nil, errors.NewInvalid("Service", service.Name, el) return nil, errors.NewInvalid("Service", service.Name, el)
} }
releaseServiceIP = true releaseServiceIP = true
...@@ -108,7 +108,7 @@ func (rs *REST) Create(ctx api.Context, obj runtime.Object) (runtime.Object, err ...@@ -108,7 +108,7 @@ func (rs *REST) Create(ctx api.Context, obj runtime.Object) (runtime.Object, err
err := nodePortOp.Allocate(servicePort.NodePort) err := nodePortOp.Allocate(servicePort.NodePort)
if err != nil { if err != nil {
// TODO: when validation becomes versioned, this gets more complicated. // TODO: when validation becomes versioned, this gets more complicated.
el := field.ErrorList{field.NewInvalidError(field.NewPath("spec", "ports").Index(i).Child("nodePort"), servicePort.NodePort, err.Error())} el := field.ErrorList{field.Invalid(field.NewPath("spec", "ports").Index(i).Child("nodePort"), servicePort.NodePort, err.Error())}
return nil, errors.NewInvalid("Service", service.Name, el) return nil, errors.NewInvalid("Service", service.Name, el)
} }
} else if assignNodePorts { } else if assignNodePorts {
...@@ -229,7 +229,7 @@ func (rs *REST) Update(ctx api.Context, obj runtime.Object) (runtime.Object, boo ...@@ -229,7 +229,7 @@ func (rs *REST) Update(ctx api.Context, obj runtime.Object) (runtime.Object, boo
if !contains(oldNodePorts, nodePort) { if !contains(oldNodePorts, nodePort) {
err := nodePortOp.Allocate(nodePort) err := nodePortOp.Allocate(nodePort)
if err != nil { if err != nil {
el := field.ErrorList{field.NewInvalidError(field.NewPath("spec", "ports").Index(i).Child("nodePort"), nodePort, err.Error())} el := field.ErrorList{field.Invalid(field.NewPath("spec", "ports").Index(i).Child("nodePort"), nodePort, err.Error())}
return nil, false, errors.NewInvalid("Service", service.Name, el) return nil, false, errors.NewInvalid("Service", service.Name, el)
} }
} }
......
...@@ -50,7 +50,7 @@ func ParseWatchResourceVersion(resourceVersion string) (uint64, error) { ...@@ -50,7 +50,7 @@ func ParseWatchResourceVersion(resourceVersion string) (uint64, error) {
return 0, errors.NewInvalid("", "", field.ErrorList{ return 0, errors.NewInvalid("", "", field.ErrorList{
// Validation errors are supposed to return version-specific field // Validation errors are supposed to return version-specific field
// paths, but this is probably close enough. // paths, but this is probably close enough.
field.NewInvalidError(field.NewPath("resourceVersion"), resourceVersion, err.Error()), field.Invalid(field.NewPath("resourceVersion"), resourceVersion, err.Error()),
}) })
} }
return version + 1, nil return version + 1, nil
......
...@@ -72,22 +72,22 @@ const ( ...@@ -72,22 +72,22 @@ const (
// NewRequiredError. // NewRequiredError.
ErrorTypeRequired ErrorType = "FieldValueRequired" ErrorTypeRequired ErrorType = "FieldValueRequired"
// ErrorTypeDuplicate is used to report collisions of values that must be // ErrorTypeDuplicate is used to report collisions of values that must be
// unique (e.g. unique IDs). See NewDuplicateError. // unique (e.g. unique IDs). See Duplicate().
ErrorTypeDuplicate ErrorType = "FieldValueDuplicate" ErrorTypeDuplicate ErrorType = "FieldValueDuplicate"
// ErrorTypeInvalid is used to report malformed values (e.g. failed regex // ErrorTypeInvalid is used to report malformed values (e.g. failed regex
// match, too long, out of bounds). See NewInvalidError. // match, too long, out of bounds). See Invalid().
ErrorTypeInvalid ErrorType = "FieldValueInvalid" ErrorTypeInvalid ErrorType = "FieldValueInvalid"
// ErrorTypeNotSupported is used to report unknown values for enumerated // ErrorTypeNotSupported is used to report unknown values for enumerated
// fields (e.g. a list of valid values). See NewNotSupportedError. // fields (e.g. a list of valid values). See NotSupported().
ErrorTypeNotSupported ErrorType = "FieldValueNotSupported" ErrorTypeNotSupported ErrorType = "FieldValueNotSupported"
// ErrorTypeForbidden is used to report valid (as per formatting rules) // ErrorTypeForbidden is used to report valid (as per formatting rules)
// values which would be accepted under some conditions, but which are not // values which would be accepted under some conditions, but which are not
// permitted by the current conditions (such as security policy). See // permitted by the current conditions (such as security policy). See
// NewForbiddenError. // Forbidden().
ErrorTypeForbidden ErrorType = "FieldValueForbidden" ErrorTypeForbidden ErrorType = "FieldValueForbidden"
// ErrorTypeTooLong is used to report that the given value is too long. // ErrorTypeTooLong is used to report that the given value is too long.
// This is similar to ErrorTypeInvalid, but the error will not include the // This is similar to ErrorTypeInvalid, but the error will not include the
// too-long value. See NewTooLongError. // too-long value. See TooLong().
ErrorTypeTooLong ErrorType = "FieldValueTooLong" ErrorTypeTooLong ErrorType = "FieldValueTooLong"
// ErrorTypeInternal is used to report other errors that are not related // ErrorTypeInternal is used to report other errors that are not related
// to user input. // to user input.
...@@ -121,33 +121,33 @@ func (t ErrorType) String() string { ...@@ -121,33 +121,33 @@ func (t ErrorType) String() string {
// NewNotFoundError returns a *Error indicating "value not found". This is // NewNotFoundError returns a *Error indicating "value not found". This is
// used to report failure to find a requested value (e.g. looking up an ID). // used to report failure to find a requested value (e.g. looking up an ID).
func NewNotFoundError(field *Path, value interface{}) *Error { func NotFound(field *Path, value interface{}) *Error {
return &Error{ErrorTypeNotFound, field.String(), value, ""} return &Error{ErrorTypeNotFound, field.String(), value, ""}
} }
// NewRequiredError returns a *Error indicating "value required". This is used // NewRequiredError returns a *Error indicating "value required". This is used
// to report required values that are not provided (e.g. empty strings, null // to report required values that are not provided (e.g. empty strings, null
// values, or empty arrays). // values, or empty arrays).
func NewRequiredError(field *Path) *Error { func Required(field *Path) *Error {
return &Error{ErrorTypeRequired, field.String(), "", ""} return &Error{ErrorTypeRequired, field.String(), "", ""}
} }
// NewDuplicateError returns a *Error indicating "duplicate value". This is // NewDuplicateError returns a *Error indicating "duplicate value". This is
// used to report collisions of values that must be unique (e.g. names or IDs). // used to report collisions of values that must be unique (e.g. names or IDs).
func NewDuplicateError(field *Path, value interface{}) *Error { func Duplicate(field *Path, value interface{}) *Error {
return &Error{ErrorTypeDuplicate, field.String(), value, ""} return &Error{ErrorTypeDuplicate, field.String(), value, ""}
} }
// NewInvalidError returns a *Error indicating "invalid value". This is used // NewInvalidError returns a *Error indicating "invalid value". This is used
// to report malformed values (e.g. failed regex match, too long, out of bounds). // to report malformed values (e.g. failed regex match, too long, out of bounds).
func NewInvalidError(field *Path, value interface{}, detail string) *Error { func Invalid(field *Path, value interface{}, detail string) *Error {
return &Error{ErrorTypeInvalid, field.String(), value, detail} return &Error{ErrorTypeInvalid, field.String(), value, detail}
} }
// NewNotSupportedError returns a *Error indicating "unsupported value". // NewNotSupportedError returns a *Error indicating "unsupported value".
// This is used to report unknown values for enumerated fields (e.g. a list of // This is used to report unknown values for enumerated fields (e.g. a list of
// valid values). // valid values).
func NewNotSupportedError(field *Path, value interface{}, validValues []string) *Error { func NotSupported(field *Path, value interface{}, validValues []string) *Error {
detail := "" detail := ""
if validValues != nil && len(validValues) > 0 { if validValues != nil && len(validValues) > 0 {
detail = "supported values: " + strings.Join(validValues, ", ") detail = "supported values: " + strings.Join(validValues, ", ")
...@@ -159,7 +159,7 @@ func NewNotSupportedError(field *Path, value interface{}, validValues []string) ...@@ -159,7 +159,7 @@ func NewNotSupportedError(field *Path, value interface{}, validValues []string)
// report valid (as per formatting rules) values which would be accepted under // report valid (as per formatting rules) values which would be accepted under
// some conditions, but which are not permitted by current conditions (e.g. // some conditions, but which are not permitted by current conditions (e.g.
// security policy). // security policy).
func NewForbiddenError(field *Path, value interface{}) *Error { func Forbidden(field *Path, value interface{}) *Error {
return &Error{ErrorTypeForbidden, field.String(), value, ""} return &Error{ErrorTypeForbidden, field.String(), value, ""}
} }
...@@ -167,14 +167,14 @@ func NewForbiddenError(field *Path, value interface{}) *Error { ...@@ -167,14 +167,14 @@ func NewForbiddenError(field *Path, value interface{}) *Error {
// report that the given value is too long. This is similar to // report that the given value is too long. This is similar to
// NewInvalidError, but the returned error will not include the too-long // NewInvalidError, but the returned error will not include the too-long
// value. // value.
func NewTooLongError(field *Path, value interface{}, maxLength int) *Error { func TooLong(field *Path, value interface{}, maxLength int) *Error {
return &Error{ErrorTypeTooLong, field.String(), value, fmt.Sprintf("must have at most %d characters", maxLength)} return &Error{ErrorTypeTooLong, field.String(), value, fmt.Sprintf("must have at most %d characters", maxLength)}
} }
// NewInternalError returns a *Error indicating "internal error". This is used // NewInternalError returns a *Error indicating "internal error". This is used
// to signal that an error was found that was not directly related to user // to signal that an error was found that was not directly related to user
// input. The err argument must be non-nil. // input. The err argument must be non-nil.
func NewInternalError(field *Path, err error) *Error { func InternalError(field *Path, err error) *Error {
return &Error{ErrorTypeInternal, field.String(), nil, err.Error()} return &Error{ErrorTypeInternal, field.String(), nil, err.Error()}
} }
......
...@@ -28,27 +28,27 @@ func TestMakeFuncs(t *testing.T) { ...@@ -28,27 +28,27 @@ func TestMakeFuncs(t *testing.T) {
expected ErrorType expected ErrorType
}{ }{
{ {
func() *Error { return NewInvalidError(NewPath("f"), "v", "d") }, func() *Error { return Invalid(NewPath("f"), "v", "d") },
ErrorTypeInvalid, ErrorTypeInvalid,
}, },
{ {
func() *Error { return NewNotSupportedError(NewPath("f"), "v", nil) }, func() *Error { return NotSupported(NewPath("f"), "v", nil) },
ErrorTypeNotSupported, ErrorTypeNotSupported,
}, },
{ {
func() *Error { return NewDuplicateError(NewPath("f"), "v") }, func() *Error { return Duplicate(NewPath("f"), "v") },
ErrorTypeDuplicate, ErrorTypeDuplicate,
}, },
{ {
func() *Error { return NewNotFoundError(NewPath("f"), "v") }, func() *Error { return NotFound(NewPath("f"), "v") },
ErrorTypeNotFound, ErrorTypeNotFound,
}, },
{ {
func() *Error { return NewRequiredError(NewPath("f")) }, func() *Error { return Required(NewPath("f")) },
ErrorTypeRequired, ErrorTypeRequired,
}, },
{ {
func() *Error { return NewInternalError(NewPath("f"), fmt.Errorf("e")) }, func() *Error { return InternalError(NewPath("f"), fmt.Errorf("e")) },
ErrorTypeInternal, ErrorTypeInternal,
}, },
} }
...@@ -62,7 +62,7 @@ func TestMakeFuncs(t *testing.T) { ...@@ -62,7 +62,7 @@ func TestMakeFuncs(t *testing.T) {
} }
func TestErrorUsefulMessage(t *testing.T) { func TestErrorUsefulMessage(t *testing.T) {
s := NewInvalidError(NewPath("foo"), "bar", "deet").Error() s := Invalid(NewPath("foo"), "bar", "deet").Error()
t.Logf("message: %v", s) t.Logf("message: %v", s)
for _, part := range []string{"foo", "bar", "deet", ErrorTypeInvalid.String()} { for _, part := range []string{"foo", "bar", "deet", ErrorTypeInvalid.String()} {
if !strings.Contains(s, part) { if !strings.Contains(s, part) {
...@@ -76,7 +76,7 @@ func TestErrorUsefulMessage(t *testing.T) { ...@@ -76,7 +76,7 @@ func TestErrorUsefulMessage(t *testing.T) {
Inner interface{} Inner interface{}
KV map[string]int KV map[string]int
} }
s = NewInvalidError( s = Invalid(
NewPath("foo"), NewPath("foo"),
&complicated{ &complicated{
Baz: 1, Baz: 1,
...@@ -102,8 +102,8 @@ func TestToAggregate(t *testing.T) { ...@@ -102,8 +102,8 @@ func TestToAggregate(t *testing.T) {
testCases := []ErrorList{ testCases := []ErrorList{
nil, nil,
{}, {},
{NewInvalidError(NewPath("f"), "v", "d")}, {Invalid(NewPath("f"), "v", "d")},
{NewInvalidError(NewPath("f"), "v", "d"), NewInternalError(NewPath(""), fmt.Errorf("e"))}, {Invalid(NewPath("f"), "v", "d"), InternalError(NewPath(""), fmt.Errorf("e"))},
} }
for i, tc := range testCases { for i, tc := range testCases {
agg := tc.ToAggregate() agg := tc.ToAggregate()
...@@ -121,9 +121,9 @@ func TestToAggregate(t *testing.T) { ...@@ -121,9 +121,9 @@ func TestToAggregate(t *testing.T) {
func TestErrListFilter(t *testing.T) { func TestErrListFilter(t *testing.T) {
list := ErrorList{ list := ErrorList{
NewInvalidError(NewPath("test.field"), "", ""), Invalid(NewPath("test.field"), "", ""),
NewInvalidError(NewPath("field.test"), "", ""), Invalid(NewPath("field.test"), "", ""),
NewDuplicateError(NewPath("test"), "value"), Duplicate(NewPath("test"), "value"),
} }
if len(list.Filter(NewErrorTypeMatcher(ErrorTypeDuplicate))) != 2 { if len(list.Filter(NewErrorTypeMatcher(ErrorTypeDuplicate))) != 2 {
t.Errorf("should not filter") t.Errorf("should not filter")
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment