本文整理汇总了Golang中k8s/io/kubernetes/pkg/util/fielderrors.NewFieldInvalid函数的典型用法代码示例。如果您正苦于以下问题:Golang NewFieldInvalid函数的具体用法?Golang NewFieldInvalid怎么用?Golang NewFieldInvalid使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewFieldInvalid函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: validateSource
func validateSource(input *buildapi.BuildSource) fielderrors.ValidationErrorList {
allErrs := fielderrors.ValidationErrorList{}
switch input.Type {
case buildapi.BuildSourceGit:
if input.Git == nil {
allErrs = append(allErrs, fielderrors.NewFieldRequired("git"))
} else {
allErrs = append(allErrs, validateGitSource(input.Git).Prefix("git")...)
}
if input.Dockerfile != nil {
allErrs = append(allErrs, fielderrors.NewFieldInvalid("dockerfile", "", "may not be set when type is Git"))
}
case buildapi.BuildSourceDockerfile:
if input.Dockerfile == nil {
allErrs = append(allErrs, fielderrors.NewFieldRequired("dockerfile"))
} else {
if len(*input.Dockerfile) > maxDockerfileLengthBytes {
allErrs = append(allErrs, fielderrors.NewFieldInvalid("dockerfile", "", fmt.Sprintf("must be smaller than %d bytes", maxDockerfileLengthBytes)))
}
}
if input.Git != nil {
allErrs = append(allErrs, validateGitSource(input.Git).Prefix("git")...)
}
case "":
allErrs = append(allErrs, fielderrors.NewFieldRequired("type"))
}
allErrs = append(allErrs, validateSecretRef(input.SourceSecret).Prefix("sourceSecret")...)
return allErrs
}
示例2: validateInsecureEdgeTerminationPolicy
// validateInsecureEdgeTerminationPolicy tests fields for different types of
// insecure options. Called by validateTLS.
func validateInsecureEdgeTerminationPolicy(tls *routeapi.TLSConfig) *fielderrors.ValidationError {
// Check insecure option value if specified (empty is ok).
if len(tls.InsecureEdgeTerminationPolicy) == 0 {
return nil
}
// Ensure insecure is set only for edge terminated routes.
if routeapi.TLSTerminationEdge != tls.Termination {
// tls.InsecureEdgeTerminationPolicy option is not supported for a non edge-terminated routes.
return fielderrors.NewFieldInvalid("InsecureEdgeTerminationPolicy", tls.InsecureEdgeTerminationPolicy, "InsecureEdgeTerminationPolicy is only allowed for edge-terminated routes")
}
// It is an edge-terminated route, check insecure option value is
// one of None(for disable), Allow or Redirect.
allowedValues := map[routeapi.InsecureEdgeTerminationPolicyType]struct{}{
routeapi.InsecureEdgeTerminationPolicyNone: {},
routeapi.InsecureEdgeTerminationPolicyAllow: {},
routeapi.InsecureEdgeTerminationPolicyRedirect: {},
}
if _, ok := allowedValues[tls.InsecureEdgeTerminationPolicy]; !ok {
msg := fmt.Sprintf("invalid value for InsecureEdgeTerminationPolicy option, acceptable values are %s, %s, %s, or empty", routeapi.InsecureEdgeTerminationPolicyNone, routeapi.InsecureEdgeTerminationPolicyAllow, routeapi.InsecureEdgeTerminationPolicyRedirect)
return fielderrors.NewFieldInvalid("InsecureEdgeTerminationPolicy", tls.InsecureEdgeTerminationPolicy, msg)
}
return nil
}
示例3: ValidateContainerSecurityContext
// Ensure a container's SecurityContext is in compliance with the given constraints
func (s *simpleProvider) ValidateContainerSecurityContext(pod *api.Pod, container *api.Container) fielderrors.ValidationErrorList {
allErrs := fielderrors.ValidationErrorList{}
if container.SecurityContext == nil {
allErrs = append(allErrs, fielderrors.NewFieldInvalid("securityContext", container.SecurityContext, "No security context is set"))
return allErrs
}
sc := container.SecurityContext
allErrs = append(allErrs, s.runAsUserStrategy.Validate(pod, container)...)
allErrs = append(allErrs, s.seLinuxStrategy.Validate(pod, container)...)
if !s.scc.AllowPrivilegedContainer && *sc.Privileged {
allErrs = append(allErrs, fielderrors.NewFieldInvalid("privileged", *sc.Privileged, "Privileged containers are not allowed"))
}
allErrs = append(allErrs, s.capabilitiesStrategy.Validate(pod, container)...)
if !s.scc.AllowHostDirVolumePlugin {
for _, v := range pod.Spec.Volumes {
if v.HostPath != nil {
allErrs = append(allErrs, fielderrors.NewFieldInvalid("VolumeMounts", v.Name, "Host Volumes are not allowed to be used"))
}
}
}
if !s.scc.AllowHostPorts {
for idx, c := range pod.Spec.Containers {
allErrs = append(allErrs, s.hasHostPort(&c).Prefix(fmt.Sprintf("containers.%d", idx))...)
}
}
return allErrs
}
示例4: Process
// Process transforms Template object into List object. It generates
// Parameter values using the defined set of generators first, and then it
// substitutes all Parameter expression occurrences with their corresponding
// values (currently in the containers' Environment variables only).
func (p *Processor) Process(template *api.Template) fielderrors.ValidationErrorList {
templateErrors := fielderrors.ValidationErrorList{}
if err, badParam := p.GenerateParameterValues(template); err != nil {
return append(templateErrors.Prefix("Template"), fielderrors.NewFieldInvalid("parameters", *badParam, err.Error()))
}
for i, item := range template.Objects {
if obj, ok := item.(*runtime.Unknown); ok {
// TODO: use runtime.DecodeList when it returns ValidationErrorList
decodedObj, err := runtime.UnstructuredJSONScheme.Decode(obj.RawJSON)
if err != nil {
util.ReportError(&templateErrors, i, *fielderrors.NewFieldInvalid("objects", obj, "unable to handle object"))
continue
}
item = decodedObj
}
newItem, err := p.SubstituteParameters(template.Parameters, item)
if err != nil {
util.ReportError(&templateErrors, i, *fielderrors.NewFieldInvalid("parameters", template.Parameters, err.Error()))
}
// If an object definition's metadata includes a namespace field, the field will be stripped out of
// the definition during template instantiation. This is necessary because all objects created during
// instantiation are placed into the target namespace, so it would be invalid for the object to declare
//a different namespace.
stripNamespace(newItem)
if err := util.AddObjectLabels(newItem, template.ObjectLabels); err != nil {
util.ReportError(&templateErrors, i, *fielderrors.NewFieldInvalid("labels", err, "label could not be applied"))
}
template.Objects[i] = newItem
}
return templateErrors
}
示例5: ValidateAssetConfig
func ValidateAssetConfig(config *api.AssetConfig) ValidationResults {
validationResults := ValidationResults{}
validationResults.Append(ValidateHTTPServingInfo(config.ServingInfo).Prefix("servingInfo"))
if len(config.LogoutURL) > 0 {
_, urlErrs := ValidateURL(config.LogoutURL, "logoutURL")
if len(urlErrs) > 0 {
validationResults.AddErrors(urlErrs...)
}
}
urlObj, urlErrs := ValidateURL(config.PublicURL, "publicURL")
if len(urlErrs) > 0 {
validationResults.AddErrors(urlErrs...)
}
if urlObj != nil {
if !strings.HasSuffix(urlObj.Path, "/") {
validationResults.AddErrors(fielderrors.NewFieldInvalid("publicURL", config.PublicURL, "must have a trailing slash in path"))
}
}
if _, urlErrs := ValidateURL(config.MasterPublicURL, "masterPublicURL"); len(urlErrs) > 0 {
validationResults.AddErrors(urlErrs...)
}
if len(config.LoggingPublicURL) > 0 {
if _, loggingURLErrs := ValidateSecureURL(config.LoggingPublicURL, "loggingPublicURL"); len(loggingURLErrs) > 0 {
validationResults.AddErrors(loggingURLErrs...)
}
}
if len(config.MetricsPublicURL) > 0 {
if _, metricsURLErrs := ValidateSecureURL(config.MetricsPublicURL, "metricsPublicURL"); len(metricsURLErrs) > 0 {
validationResults.AddErrors(metricsURLErrs...)
}
}
for i, scriptFile := range config.ExtensionScripts {
validationResults.AddErrors(ValidateFile(scriptFile, fmt.Sprintf("extensionScripts[%d]", i))...)
}
for i, stylesheetFile := range config.ExtensionStylesheets {
validationResults.AddErrors(ValidateFile(stylesheetFile, fmt.Sprintf("extensionStylesheets[%d]", i))...)
}
nameTaken := map[string]bool{}
for i, extConfig := range config.Extensions {
extConfigErrors := ValidateAssetExtensionsConfig(extConfig).Prefix(fmt.Sprintf("extensions[%d]", i))
validationResults.AddErrors(extConfigErrors...)
if nameTaken[extConfig.Name] {
dupError := fielderrors.NewFieldInvalid(fmt.Sprintf("extensions[%d].name", i), extConfig.Name, "duplicate extension name")
validationResults.AddErrors(dupError)
} else {
nameTaken[extConfig.Name] = true
}
}
return validationResults
}
示例6: Process
// Process transforms Template object into List object. It generates
// Parameter values using the defined set of generators first, and then it
// substitutes all Parameter expression occurrences with their corresponding
// values (currently in the containers' Environment variables only).
func (p *Processor) Process(template *api.Template) fielderrors.ValidationErrorList {
templateErrors := fielderrors.ValidationErrorList{}
if err := p.GenerateParameterValues(template); err != nil {
return append(templateErrors.Prefix("Template"), fielderrors.NewFieldInvalid("parameters", err, "failure to generate parameter value"))
}
for i, item := range template.Objects {
if obj, ok := item.(*runtime.Unknown); ok {
// TODO: use runtime.DecodeList when it returns ValidationErrorList
obj, err := runtime.UnstructuredJSONScheme.Decode(obj.RawJSON)
if err != nil {
util.ReportError(&templateErrors, i, *fielderrors.NewFieldInvalid("objects", err, "unable to handle object"))
continue
}
item = obj
}
newItem, err := p.SubstituteParameters(template.Parameters, item)
if err != nil {
util.ReportError(&templateErrors, i, *fielderrors.NewFieldInvalid("parameters", template.Parameters, err.Error()))
}
stripNamespace(newItem)
if err := util.AddObjectLabels(newItem, template.ObjectLabels); err != nil {
util.ReportError(&templateErrors, i, *fielderrors.NewFieldInvalid("labels", err, "label could not be applied"))
}
template.Objects[i] = newItem
}
return templateErrors
}
示例7: ValidateIdentity
func ValidateIdentity(identity *api.Identity) fielderrors.ValidationErrorList {
allErrs := fielderrors.ValidationErrorList{}
allErrs = append(allErrs, kvalidation.ValidateObjectMeta(&identity.ObjectMeta, false, ValidateIdentityName).Prefix("metadata")...)
if len(identity.ProviderName) == 0 {
allErrs = append(allErrs, fielderrors.NewFieldRequired("providerName"))
} else if ok, msg := ValidateIdentityProviderName(identity.ProviderName); !ok {
allErrs = append(allErrs, fielderrors.NewFieldInvalid("providerName", identity.ProviderName, msg))
}
if len(identity.ProviderUserName) == 0 {
allErrs = append(allErrs, fielderrors.NewFieldRequired("providerUserName"))
} else if ok, msg := ValidateIdentityProviderName(identity.ProviderUserName); !ok {
allErrs = append(allErrs, fielderrors.NewFieldInvalid("providerUserName", identity.ProviderUserName, msg))
}
if len(identity.ProviderName) > 0 && len(identity.ProviderUserName) > 0 {
expectedIdentityName := identity.ProviderName + ":" + identity.ProviderUserName
if identity.Name != expectedIdentityName {
allErrs = append(allErrs, fielderrors.NewFieldInvalid("user.name", identity.User.Name, fmt.Sprintf("must be %s", expectedIdentityName)))
}
}
if ok, msg := ValidateUserName(identity.User.Name, false); !ok {
allErrs = append(allErrs, fielderrors.NewFieldInvalid("user.name", identity.User.Name, msg))
}
if len(identity.User.Name) == 0 && len(identity.User.UID) != 0 {
allErrs = append(allErrs, fielderrors.NewFieldInvalid("user.uid", identity.User.UID, "may not be set if user.name is empty"))
}
if len(identity.User.Name) != 0 && len(identity.User.UID) == 0 {
allErrs = append(allErrs, fielderrors.NewFieldRequired("user.uid"))
}
return allErrs
}
示例8: validateDockerStrategy
func validateDockerStrategy(strategy *buildapi.DockerBuildStrategy) fielderrors.ValidationErrorList {
allErrs := fielderrors.ValidationErrorList{}
if strategy.From != nil {
allErrs = append(allErrs, validateFromImageReference(strategy.From).Prefix("from")...)
}
allErrs = append(allErrs, validateSecretRef(strategy.PullSecret).Prefix("pullSecret")...)
if len(strategy.DockerfilePath) != 0 {
cleaned := path.Clean(strategy.DockerfilePath)
switch {
case strings.HasPrefix(cleaned, "/"):
allErrs = append(allErrs, fielderrors.NewFieldInvalid("dockerfilePath", strategy.DockerfilePath, "dockerfilePath must not be an absolute path"))
case strings.HasPrefix(cleaned, ".."):
allErrs = append(allErrs, fielderrors.NewFieldInvalid("dockerfilePath", strategy.DockerfilePath, "dockerfilePath must not start with .."))
default:
if cleaned == "." {
cleaned = ""
}
strategy.DockerfilePath = cleaned
}
}
return allErrs
}
示例9: validateHTTPIngressRuleValue
func validateHTTPIngressRuleValue(httpIngressRuleValue *extensions.HTTPIngressRuleValue) errs.ValidationErrorList {
allErrs := errs.ValidationErrorList{}
if len(httpIngressRuleValue.Paths) == 0 {
allErrs = append(allErrs, errs.NewFieldRequired("paths"))
}
for _, rule := range httpIngressRuleValue.Paths {
if len(rule.Path) > 0 {
if !strings.HasPrefix(rule.Path, "/") {
allErrs = append(allErrs, errs.NewFieldInvalid("path", rule.Path, "path must begin with /"))
}
// TODO: More draconian path regex validation.
// Path must be a valid regex. This is the basic requirement.
// In addition to this any characters not allowed in a path per
// RFC 3986 section-3.3 cannot appear as a literal in the regex.
// Consider the example: http://host/valid?#bar, everything after
// the last '/' is a valid regex that matches valid#bar, which
// isn't a valid path, because the path terminates at the first ?
// or #. A more sophisticated form of validation would detect that
// the user is confusing url regexes with path regexes.
_, err := regexp.CompilePOSIX(rule.Path)
if err != nil {
allErrs = append(allErrs, errs.NewFieldInvalid("path", rule.Path, "httpIngressRuleValue.path must be a valid regex."))
}
}
allErrs = append(allErrs, validateIngressBackend(&rule.Backend).Prefix("backend")...)
}
return allErrs
}
示例10: Validate
// Validate ensures that the specified values fall within the range of the strategy.
func (s *mustRunAsRange) Validate(pod *api.Pod, container *api.Container) fielderrors.ValidationErrorList {
allErrs := fielderrors.ValidationErrorList{}
if container.SecurityContext == nil {
detail := fmt.Sprintf("unable to validate nil security context for container %s", container.Name)
allErrs = append(allErrs, fielderrors.NewFieldInvalid("securityContext", container.SecurityContext, detail))
return allErrs
}
if container.SecurityContext.RunAsUser == nil {
detail := fmt.Sprintf("unable to validate nil RunAsUser for container %s", container.Name)
allErrs = append(allErrs, fielderrors.NewFieldInvalid("securityContext.runAsUser", container.SecurityContext.RunAsUser, detail))
return allErrs
}
if *container.SecurityContext.RunAsUser < *s.opts.UIDRangeMin || *container.SecurityContext.RunAsUser > *s.opts.UIDRangeMax {
detail := fmt.Sprintf("UID on container %s does not match required range. Found %d, required min: %d max: %d",
container.Name,
*container.SecurityContext.RunAsUser,
*s.opts.UIDRangeMin,
*s.opts.UIDRangeMax)
allErrs = append(allErrs, fielderrors.NewFieldInvalid("securityContext.runAsUser", *container.SecurityContext.RunAsUser, detail))
}
return allErrs
}
示例11: validateRollingParams
func validateRollingParams(params *deployapi.RollingDeploymentStrategyParams) fielderrors.ValidationErrorList {
errs := fielderrors.ValidationErrorList{}
if params.IntervalSeconds != nil && *params.IntervalSeconds < 1 {
errs = append(errs, fielderrors.NewFieldInvalid("intervalSeconds", *params.IntervalSeconds, "must be >0"))
}
if params.UpdatePeriodSeconds != nil && *params.UpdatePeriodSeconds < 1 {
errs = append(errs, fielderrors.NewFieldInvalid("updatePeriodSeconds", *params.UpdatePeriodSeconds, "must be >0"))
}
if params.TimeoutSeconds != nil && *params.TimeoutSeconds < 1 {
errs = append(errs, fielderrors.NewFieldInvalid("timeoutSeconds", *params.TimeoutSeconds, "must be >0"))
}
if params.UpdatePercent != nil {
p := *params.UpdatePercent
if p == 0 || p < -100 || p > 100 {
errs = append(errs, fielderrors.NewFieldInvalid("updatePercent", *params.UpdatePercent, "must be between 1 and 100 or between -1 and -100 (inclusive)"))
}
}
if params.Pre != nil {
errs = append(errs, validateLifecycleHook(params.Pre).Prefix("pre")...)
}
if params.Post != nil {
errs = append(errs, validateLifecycleHook(params.Post).Prefix("post")...)
}
return errs
}
示例12: ValidatePolicyBinding
func ValidatePolicyBinding(policyBinding *authorizationapi.PolicyBinding, isNamespaced bool) fielderrors.ValidationErrorList {
allErrs := fielderrors.ValidationErrorList{}
allErrs = append(allErrs, validation.ValidateObjectMeta(&policyBinding.ObjectMeta, isNamespaced, PolicyBindingNameValidator(policyBinding.PolicyRef.Namespace)).Prefix("metadata")...)
if !isNamespaced {
if len(policyBinding.PolicyRef.Namespace) > 0 {
allErrs = append(allErrs, fielderrors.NewFieldInvalid("policyRef.namespace", policyBinding.PolicyRef.Namespace, "may not reference another namespace"))
}
}
for roleBindingKey, roleBinding := range policyBinding.RoleBindings {
if roleBinding == nil {
allErrs = append(allErrs, fielderrors.NewFieldRequired("roleBindings."+roleBindingKey))
}
if roleBinding.RoleRef.Namespace != policyBinding.PolicyRef.Namespace {
allErrs = append(allErrs, fielderrors.NewFieldInvalid("roleBindings."+roleBindingKey+".roleRef.namespace", policyBinding.PolicyRef.Namespace, "must be "+policyBinding.PolicyRef.Namespace))
}
if roleBindingKey != roleBinding.Name {
allErrs = append(allErrs, fielderrors.NewFieldInvalid("roleBindings."+roleBindingKey+".metadata.name", roleBinding.Name, "must be "+roleBindingKey))
}
allErrs = append(allErrs, ValidateRoleBinding(roleBinding, isNamespaced).Prefix("roleBindings."+roleBindingKey)...)
}
return allErrs
}
示例13: ValidateServingInfo
func ValidateServingInfo(info api.ServingInfo) ValidationResults {
validationResults := ValidationResults{}
validationResults.AddErrors(ValidateHostPort(info.BindAddress, "bindAddress")...)
validationResults.AddErrors(ValidateCertInfo(info.ServerCert, false)...)
if len(info.NamedCertificates) > 0 && len(info.ServerCert.CertFile) == 0 {
validationResults.AddErrors(fielderrors.NewFieldInvalid("namedCertificates", "", "a default certificate and key is required in certFile/keyFile in order to use namedCertificates"))
}
validationResults.Append(ValidateNamedCertificates("namedCertificates", info.NamedCertificates))
switch info.BindNetwork {
case "tcp", "tcp4", "tcp6":
default:
validationResults.AddErrors(fielderrors.NewFieldInvalid("bindNetwork", info.BindNetwork, "must be 'tcp', 'tcp4', or 'tcp6'"))
}
if len(info.ServerCert.CertFile) > 0 {
if len(info.ClientCA) > 0 {
validationResults.AddErrors(ValidateFile(info.ClientCA, "clientCA")...)
}
} else {
if len(info.ClientCA) > 0 {
validationResults.AddErrors(fielderrors.NewFieldInvalid("clientCA", info.ClientCA, "cannot specify a clientCA without a certFile"))
}
}
return validationResults
}
示例14: TestCheckInvalidErr
func TestCheckInvalidErr(t *testing.T) {
tests := []struct {
err error
expected string
}{
{
errors.NewInvalid("Invalid1", "invalidation", fielderrors.ValidationErrorList{fielderrors.NewFieldInvalid("Cause", "single", "details")}),
`Error from server: Invalid1 "invalidation" is invalid: Cause: invalid value 'single', Details: details`,
},
{
errors.NewInvalid("Invalid2", "invalidation", fielderrors.ValidationErrorList{fielderrors.NewFieldInvalid("Cause", "multi1", "details"), fielderrors.NewFieldInvalid("Cause", "multi2", "details")}),
`Error from server: Invalid2 "invalidation" is invalid: [Cause: invalid value 'multi1', Details: details, Cause: invalid value 'multi2', Details: details]`,
},
{
errors.NewInvalid("Invalid3", "invalidation", fielderrors.ValidationErrorList{}),
`Error from server: Invalid3 "invalidation" is invalid: <nil>`,
},
}
var errReturned string
errHandle := func(err string) {
errReturned = err
}
for _, test := range tests {
checkErr(test.err, errHandle)
if errReturned != test.expected {
t.Fatalf("Got: %s, expected: %s", errReturned, test.expected)
}
}
}
示例15: ValidateJobSpec
func ValidateJobSpec(spec *experimental.JobSpec) errs.ValidationErrorList {
allErrs := errs.ValidationErrorList{}
if spec.Parallelism != nil && *spec.Parallelism < 0 {
allErrs = append(allErrs, errs.NewFieldInvalid("parallelism", spec.Parallelism, isNegativeErrorMsg))
}
if spec.Completions != nil && *spec.Completions < 0 {
allErrs = append(allErrs, errs.NewFieldInvalid("completions", spec.Completions, isNegativeErrorMsg))
}
selector := labels.Set(spec.Selector).AsSelector()
if selector.Empty() {
allErrs = append(allErrs, errs.NewFieldRequired("selector"))
}
if spec.Template == nil {
allErrs = append(allErrs, errs.NewFieldRequired("template"))
} else {
labels := labels.Set(spec.Template.Labels)
if !selector.Matches(labels) {
allErrs = append(allErrs, errs.NewFieldInvalid("template.labels", spec.Template.Labels, "selector does not match template"))
}
allErrs = append(allErrs, apivalidation.ValidatePodTemplateSpec(spec.Template).Prefix("template")...)
if spec.Template.Spec.RestartPolicy != api.RestartPolicyOnFailure &&
spec.Template.Spec.RestartPolicy != api.RestartPolicyNever {
allErrs = append(allErrs, errs.NewFieldValueNotSupported("template.spec.restartPolicy",
spec.Template.Spec.RestartPolicy, []string{string(api.RestartPolicyOnFailure), string(api.RestartPolicyNever)}))
}
}
return allErrs
}