// ValidateService tests if required fields/annotations of a Service are valid.
193826
func ValidateService(service *core.Service) field.ErrorList {
	allErrs := ValidateObjectMeta(&service.ObjectMeta, true, ValidateServiceName, field.NewPath("metadata"))

	specPath := field.NewPath("spec")
	isHeadlessService := service.Spec.ClusterIP == core.ClusterIPNone
	if len(service.Spec.Ports) == 0 && !isHeadlessService && service.Spec.Type != core.ServiceTypeExternalName {
		allErrs = append(allErrs, field.Required(specPath.Child("ports"), ""))
	}
	switch service.Spec.Type {
	case core.ServiceTypeLoadBalancer:
		for ix := range service.Spec.Ports {
			port := &service.Spec.Ports[ix]
			// This is a workaround for broken cloud environments that
			// over-open firewalls.  Hopefully it can go away when more clouds
			// understand containers better.
			if port.Port == ports.KubeletPort {
				portPath := specPath.Child("ports").Index(ix)
				allErrs = append(allErrs, field.Invalid(portPath, port.Port, fmt.Sprintf("may not expose port %v externally since it is used by kubelet", ports.KubeletPort)))
			}
		}
		if service.Spec.ClusterIP == "None" {
			allErrs = append(allErrs, field.Invalid(specPath.Child("clusterIP"), service.Spec.ClusterIP, "may not be set to 'None' for LoadBalancer services"))
		}
	case core.ServiceTypeNodePort:
		if service.Spec.ClusterIP == "None" {
			allErrs = append(allErrs, field.Invalid(specPath.Child("clusterIP"), service.Spec.ClusterIP, "may not be set to 'None' for NodePort services"))
		}
	case core.ServiceTypeExternalName:
		if service.Spec.ClusterIP != "" {
			allErrs = append(allErrs, field.Forbidden(specPath.Child("clusterIP"), "must be empty for ExternalName services"))
		}
		if len(service.Spec.ExternalName) > 0 {
			allErrs = append(allErrs, ValidateDNS1123Subdomain(service.Spec.ExternalName, specPath.Child("externalName"))...)
		} else {
			allErrs = append(allErrs, field.Required(specPath.Child("externalName"), ""))
		}
	}

	allPortNames := sets.String{}
	portsPath := specPath.Child("ports")
	for i := range service.Spec.Ports {
		portPath := portsPath.Index(i)
		allErrs = append(allErrs, validateServicePort(&service.Spec.Ports[i], len(service.Spec.Ports) > 1, isHeadlessService, &allPortNames, portPath)...)
	}

	if service.Spec.Selector != nil {
		allErrs = append(allErrs, unversionedvalidation.ValidateLabels(service.Spec.Selector, specPath.Child("selector"))...)
	}

	if len(service.Spec.SessionAffinity) == 0 {
		allErrs = append(allErrs, field.Required(specPath.Child("sessionAffinity"), ""))
	} else if !supportedSessionAffinityType.Has(string(service.Spec.SessionAffinity)) {
		allErrs = append(allErrs, field.NotSupported(specPath.Child("sessionAffinity"), service.Spec.SessionAffinity, supportedSessionAffinityType.List()))
	}

	if service.Spec.SessionAffinity == core.ServiceAffinityClientIP {
		allErrs = append(allErrs, validateClientIPAffinityConfig(service.Spec.SessionAffinityConfig, specPath.Child("sessionAffinityConfig"))...)
	} else if service.Spec.SessionAffinity == core.ServiceAffinityNone {
		if service.Spec.SessionAffinityConfig != nil {
			allErrs = append(allErrs, field.Forbidden(specPath.Child("sessionAffinityConfig"), fmt.Sprintf("must not be set when session affinity is %s", string(core.ServiceAffinityNone))))
		}
	}

	if helper.IsServiceIPSet(service) {
		if ip := net.ParseIP(service.Spec.ClusterIP); ip == nil {
			allErrs = append(allErrs, field.Invalid(specPath.Child("clusterIP"), service.Spec.ClusterIP, "must be empty, 'None', or a valid IP address"))
		}
	}

	ipPath := specPath.Child("externalIPs")
	for i, ip := range service.Spec.ExternalIPs {
		idxPath := ipPath.Index(i)
		if msgs := validation.IsValidIP(ip); len(msgs) != 0 {
			for i := range msgs {
				allErrs = append(allErrs, field.Invalid(idxPath, ip, msgs[i]))
			}
		} else {
			allErrs = append(allErrs, validateNonSpecialIP(ip, idxPath)...)
		}
	}

	if len(service.Spec.Type) == 0 {
		allErrs = append(allErrs, field.Required(specPath.Child("type"), ""))
	} else if !supportedServiceType.Has(string(service.Spec.Type)) {
		allErrs = append(allErrs, field.NotSupported(specPath.Child("type"), service.Spec.Type, supportedServiceType.List()))
	}

	if service.Spec.Type == core.ServiceTypeLoadBalancer {
		portsPath := specPath.Child("ports")
		includeProtocols := sets.NewString()
		for i := range service.Spec.Ports {
			portPath := portsPath.Index(i)
			if !supportedPortProtocols.Has(string(service.Spec.Ports[i].Protocol)) {
				allErrs = append(allErrs, field.Invalid(portPath.Child("protocol"), service.Spec.Ports[i].Protocol, "cannot create an external load balancer with non-TCP/UDP/SCTP ports"))
			} else {
				includeProtocols.Insert(string(service.Spec.Ports[i].Protocol))
			}
		}
		if includeProtocols.Len() > 1 {
			allErrs = append(allErrs, field.Invalid(portsPath, service.Spec.Ports, "cannot create an external load balancer with mix protocols"))
		}
	}

	if service.Spec.Type == core.ServiceTypeClusterIP {
		portsPath := specPath.Child("ports")
		for i := range service.Spec.Ports {
			portPath := portsPath.Index(i)
			if service.Spec.Ports[i].NodePort != 0 {
				allErrs = append(allErrs, field.Forbidden(portPath.Child("nodePort"), "may not be used when `type` is 'ClusterIP'"))
			}
		}
	}

	// Check for duplicate NodePorts, considering (protocol,port) pairs
	portsPath = specPath.Child("ports")
	nodePorts := make(map[core.ServicePort]bool)
	for i := range service.Spec.Ports {
		port := &service.Spec.Ports[i]
		if port.NodePort == 0 {
			continue
		}
		portPath := portsPath.Index(i)
		var key core.ServicePort
		key.Protocol = port.Protocol
		key.NodePort = port.NodePort
		_, found := nodePorts[key]
		if found {
			allErrs = append(allErrs, field.Duplicate(portPath.Child("nodePort"), port.NodePort))
		}
		nodePorts[key] = true
	}

	// Check for duplicate Ports, considering (protocol,port) pairs
	portsPath = specPath.Child("ports")
	ports := make(map[core.ServicePort]bool)
	for i, port := range service.Spec.Ports {
		portPath := portsPath.Index(i)
		key := core.ServicePort{Protocol: port.Protocol, Port: port.Port}
		_, found := ports[key]
		if found {
			allErrs = append(allErrs, field.Duplicate(portPath, key))
		}
		ports[key] = true
	}

	// Validate SourceRange field and annotation
	_, ok := service.Annotations[core.AnnotationLoadBalancerSourceRangesKey]
	if len(service.Spec.LoadBalancerSourceRanges) > 0 || ok {
		var fieldPath *field.Path
		var val string
		if len(service.Spec.LoadBalancerSourceRanges) > 0 {
			fieldPath = specPath.Child("LoadBalancerSourceRanges")
			val = fmt.Sprintf("%v", service.Spec.LoadBalancerSourceRanges)
		} else {
			fieldPath = field.NewPath("metadata", "annotations").Key(core.AnnotationLoadBalancerSourceRangesKey)
			val = service.Annotations[core.AnnotationLoadBalancerSourceRangesKey]
		}
		if service.Spec.Type != core.ServiceTypeLoadBalancer {
			allErrs = append(allErrs, field.Forbidden(fieldPath, "may only be used when `type` is 'LoadBalancer'"))
		}
		_, err := apiservice.GetLoadBalancerSourceRanges(service)
		if err != nil {
			allErrs = append(allErrs, field.Invalid(fieldPath, val, "must be a list of IP ranges. For example, 10.240.0.0/24,10.250.0.0/24 "))
		}
	}

	allErrs = append(allErrs, validateServiceExternalTrafficFieldsValue(service)...)

	return allErrs
}
96256
func (s *SnapshotGetService) Validate() error {
	var invalid []string
	if s.repository == "" {
		invalid = append(invalid, "Repository")
	}
	if len(invalid) > 0 {
		return fmt.Errorf("missing required fields: %v", invalid)
	}
	return nil
}
229729
func (config Config) Validate() error {
	if config.ControllerUUID == "" {
		return errors.NotValidf("missing ControllerUUID")
	}
	if config.ModelUUID == "" {
		return errors.NotValidf("missing ModelUUID")
	}
	if config.ApplicationGetter == nil {
		return errors.NotValidf("missing ApplicationGetter")
	}
	if config.ServiceExposer == nil {
		return errors.NotValidf("missing ServiceExposer")
	}
	if config.LifeGetter == nil {
		return errors.NotValidf("missing LifeGetter")
	}
	return nil
}
716297
func validateServiceName(requestService, responseService string) error {
	// an empty service string means that we're talking to an older YARPC
	// TChannel client
	if responseService == "" || requestService == responseService {
		return nil
	}
	return yarpcerrors.InternalErrorf(
		"service name sent from the request does not match the service name "+
			"received in the response: sent %q, got: %q", requestService, responseService)
}
1334581
func (v KnownServiceValue) Validate() error {
	switch v {
	case SSHRule, JujuControllerRule, JujuApplicationOfferRule:
		return nil
	}
	return errors.NotValidf("known service %q", v)
}
1039489
func (st *ServiceTemplate) ValidEntity() error {
	//	trimmedID := strings.TrimSpace(st.ID)
	violations := validation.NewValidationError()
	violations.Add(validation.NotEmpty("ServiceTemplate.ID", st.ID))
	//	violations.Add(validation.StringsEqual(st.ID, trimmedID, "leading and trailing spaces not allowed for service template id"))

	//TODO: check name, description, config files.
	//TODO: do servicedefinition names need to be unique?

	//TODO: Is there any special validation if more than one top level service definition?
	for _, sd := range st.Services {
		if err := sd.ValidEntity(); err != nil {
			violations.Add(err)
		}
	}

	//keep track of seen vhosts
	vhosts := make(map[string]struct{})

	//grab the vhost from every endpoing
	visit := func(sd *servicedefinition.ServiceDefinition) error {
		for _, ep := range sd.Endpoints {
			for _, vhost := range ep.VHostList {
				if _, found := vhosts[vhost.Name]; found {
					return fmt.Errorf("duplicate vhost found: %s; ServiceDefintion %s", vhost.Name, sd)
				}
				vhosts[vhost.Name] = struct{}{}
			}
		}
		return nil
	}

	for _, sd := range st.Services {
		violations.Add(servicedefinition.Walk(&sd, visit))
	}

	if len(violations.Errors) > 0 {
		return violations
	}
	return nil
}
441497
func (server *Server) HasService(id string) bool {
	_, ok := server.Services[id]
	return ok
}
666002
func ValidateServiceLB(obj *ServiceLB) error {
	collections.serviceLBMutex.Lock()
	defer collections.serviceLBMutex.Unlock()

	// Validate key is correct
	keyStr := obj.TenantName + ":" + obj.ServiceName
	if obj.Key != keyStr {
		log.Errorf("Expecting ServiceLB Key: %s. Got: %s", keyStr, obj.Key)
		return errors.New("Invalid Key")
	}

	// Validate each field

	if len(obj.IpAddress) > 15 {
		return errors.New("ipAddress string too long")
	}

	ipAddressMatch := regexp.MustCompile("^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])(\\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])){3})?$")
	if ipAddressMatch.MatchString(obj.IpAddress) == false {
		return errors.New("ipAddress string invalid format")
	}

	if len(obj.NetworkName) > 64 {
		return errors.New("networkName string too long")
	}

	networkNameMatch := regexp.MustCompile("^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]*[a-zA-Z0-9])\\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\\-]*[A-Za-z0-9])$")
	if networkNameMatch.MatchString(obj.NetworkName) == false {
		return errors.New("networkName string invalid format")
	}

	if len(obj.ServiceName) > 256 {
		return errors.New("serviceName string too long")
	}

	serviceNameMatch := regexp.MustCompile("^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]*[a-zA-Z0-9])\\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\\-]*[A-Za-z0-9])$")
	if serviceNameMatch.MatchString(obj.ServiceName) == false {
		return errors.New("serviceName string invalid format")
	}

	if len(obj.TenantName) > 64 {
		return errors.New("tenantName string too long")
	}

	tenantNameMatch := regexp.MustCompile("^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]*[a-zA-Z0-9])\\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\\-]*[A-Za-z0-9])$")
	if tenantNameMatch.MatchString(obj.TenantName) == false {
		return errors.New("tenantName string invalid format")
	}

	return nil
}
722981
func ValidateServiceUpdate(service, oldService *api.Service) validation.ErrorList {
	allErrs := validation.ErrorList{}
	allErrs = append(allErrs, ValidateObjectMetaUpdate(&service.ObjectMeta, &oldService.ObjectMeta, validation.NewFieldPath("metadata"))...)

	if api.IsServiceIPSet(oldService) {
		allErrs = append(allErrs, ValidateImmutableField(service.Spec.ClusterIP, oldService.Spec.ClusterIP, validation.NewFieldPath("spec", "clusterIP"))...)
	}

	allErrs = append(allErrs, ValidateService(service)...)
	return allErrs
}
1137199
func (f *Facade) validateServiceMigration(ctx datastore.Context, svcs []service.Service, tenantID string) error {
	svcParentMapNameMap := make(map[string]map[string]struct{})
	endpointMap := make(map[string]string)
	for _, svc := range svcs {
		// check for name uniqueness within the set of new/modified/deployed services
		if svcNameMap, ok := svcParentMapNameMap[svc.ParentServiceID]; ok {
			if _, ok := svcNameMap[svc.Name]; ok {
				glog.Errorf("Found a collision for service name %s and parent %s", svc.Name, svc.ParentServiceID)
				return ErrServiceCollision
			}
			svcParentMapNameMap[svc.ParentServiceID][svc.Name] = struct{}{}
		} else {
			svcParentMapNameMap[svc.ParentServiceID] = make(map[string]struct{})
		}

		// check for endpoint name uniqueness within the set of new/modified/deployed services
		for _, ep := range svc.Endpoints {
			if ep.Purpose == "export" {
				if _, ok := endpointMap[ep.Application]; ok {
					glog.Errorf("Endpoint %s in migrated service %s is a duplicate of an endpoint in one of the other migrated services", ep.Application, svc.Name)
					return ErrServiceDuplicateEndpoint
				}
				endpointMap[ep.Application] = svc.ID
			}
		}
	}

	// check for endpoint name uniqueness btwn the migrated service and the services already defined in
	// the parent application.
	alleps, err := f.GetServiceExportedEndpoints(ctx, tenantID, true)
	if err != nil {
		glog.Errorf("Error looking up exported endpoints for tenant %s: %s", tenantID, err)
		return err
	}
	for _, ep := range alleps {
		if _, ok := endpointMap[ep.Application]; ok {
			if ep.ServiceID != endpointMap[ep.Application] {
				glog.Errorf("Endpoint %s in migrated service is a duplicate of an endpoint already in the application", ep.Application)
				return ErrServiceDuplicateEndpoint
			}
		}
	}

	return nil
}
1346127
func ValidateAnnotations(annotations map[string]string, fldPath *field.Path) field.ErrorList {
	allErrs := field.ErrorList{}
	var totalSize int64
	for k, v := range annotations {
		if !validation.IsQualifiedName(strings.ToLower(k)) {
			allErrs = append(allErrs, field.Invalid(fldPath, k, qualifiedNameErrorMsg))
		}
		totalSize += (int64)(len(k)) + (int64)(len(v))
	}
	if totalSize > (int64)(totalAnnotationSizeLimitB) {
		allErrs = append(allErrs, field.TooLong(fldPath, "", totalAnnotationSizeLimitB))
	}

	if annotations[api.AffinityAnnotationKey] != "" {
		allErrs = append(allErrs, ValidateAffinityInPodAnnotations(annotations, fldPath)...)
	}
	return allErrs
}
1325313
func (s Service) Validate(renderer shell.Renderer) error {
	if s.Name == "" {
		return errors.New("missing Name")
	}

	if err := s.Conf.Validate(renderer); err != nil {
		return errors.Trace(err)
	}

	return nil
}
1016848
func (key AnnotationKey) Validate(_ interface{}) error {
	if annotationKeyRegex.Match([]byte(key)) {
		return nil
	}

	return errInvalidAnnotationKey
}
244061
func (serviceStatusStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {
	return validation.ValidateServiceStatusUpdate(obj.(*api.Service), old.(*api.Service))
}
817079
func parseService(svc *structs.ServiceQuery) error {
	// Service is required.
	if svc.Service == "" {
		return fmt.Errorf("Must provide a Service name to query")
	}

	// NearestN can be 0 which means "don't fail over by RTT".
	if svc.Failover.NearestN < 0 {
		return fmt.Errorf("Bad NearestN '%d', must be >= 0", svc.Failover.NearestN)
	}

	// Make sure the metadata filters are valid
	if err := structs.ValidateMetadata(svc.NodeMeta, true); err != nil {
		return err
	}

	// We skip a few fields:
	// - There's no validation for Datacenters; we skip any unknown entries
	//   at execution time.
	// - OnlyPassing is just a boolean so doesn't need further validation.
	// - Tags is a free-form list of tags and doesn't need further validation.

	return nil
}
301878
func ValidateServiceAccountUpdate(newServiceAccount, oldServiceAccount *api.ServiceAccount) field.ErrorList {
	allErrs := ValidateObjectMetaUpdate(&newServiceAccount.ObjectMeta, &oldServiceAccount.ObjectMeta, field.NewPath("metadata"))
	allErrs = append(allErrs, ValidateServiceAccount(newServiceAccount)...)
	return allErrs
}
1236866
func (as AnnotationSeries) Validate() error {
	if len(as.Annotations) == 0 {
		return fmt.Errorf("annotation series requires annotations to be set and not empty")
	}
	return nil
}