// UpdateAPIServiceSpec updates the api service's OpenAPI spec. It is thread safe.
15680
func (s *specAggregator) UpdateAPIServiceSpec(apiServiceName string, spec *spec.Swagger, etag string) error {
	s.rwMutex.Lock()
	defer s.rwMutex.Unlock()

	specInfo, existingService := s.openAPISpecs[apiServiceName]
	if !existingService {
		return fmt.Errorf("APIService %q does not exists", apiServiceName)
	}

	// For APIServices (non-local) specs, only merge their /apis/ prefixed endpoint as it is the only paths
	// proxy handler delegates.
	if specInfo.apiService.Spec.Service != nil {
		spec = aggregator.FilterSpecByPathsWithoutSideEffects(spec, []string{"/apis/"})
	}

	return s.tryUpdatingServiceSpecs(&openAPISpecInfo{
		apiService: specInfo.apiService,
		spec:       spec,
		handler:    specInfo.handler,
		etag:       etag,
	})
}
880720
func UpdateService(conn client.Connection, svc *service.Service, setLockOnCreate, setLockOnUpdate bool) error {
	return UpdateServices(conn, []*service.Service{svc}, setLockOnCreate, setLockOnUpdate)
}
168348
func (c *FakeServiceAccounts) Update(serviceAccount *corev1.ServiceAccount) (result *corev1.ServiceAccount, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewUpdateAction(serviceaccountsResource, c.ns, serviceAccount), &corev1.ServiceAccount{})

	if obj == nil {
		return nil, err
	}
	return obj.(*corev1.ServiceAccount), err
}
738858
func (_m *API) UpdateService(_a0 io.Reader) (*service.ServiceDetails, error) {
	ret := _m.Called(_a0)

	var r0 *service.ServiceDetails
	if rf, ok := ret.Get(0).(func(io.Reader) *service.ServiceDetails); ok {
		r0 = rf(_a0)
	} else {
		if ret.Get(0) != nil {
			r0 = ret.Get(0).(*service.ServiceDetails)
		}
	}

	var r1 error
	if rf, ok := ret.Get(1).(func(io.Reader) error); ok {
		r1 = rf(_a0)
	} else {
		r1 = ret.Error(1)
	}

	return r0, r1
}
670806
func UpdateServiceMap(serviceMap ServiceMap, changes *ServiceChangeTracker) (result UpdateServiceMapResult) {
	result.UDPStaleClusterIP = sets.NewString()
	serviceMap.apply(changes, result.UDPStaleClusterIP)

	// TODO: If this will appear to be computationally expensive, consider
	// computing this incrementally similarly to serviceMap.
	result.HCServiceNodePorts = make(map[types.NamespacedName]uint16)
	for svcPortName, info := range serviceMap {
		if info.GetHealthCheckNodePort() != 0 {
			result.HCServiceNodePorts[svcPortName.NamespacedName] = uint16(info.GetHealthCheckNodePort())
		}
	}

	return result
}
1342649
func NewUpdateService(client *Client) *UpdateService {
	builder := &UpdateService{
		client:       client,
		scriptParams: make(map[string]interface{}),
		fields:       make([]string, 0),
	}
	return builder
}
212026
func (c *Client) UpdateApplicationService(arg params.UpdateApplicationServiceArg) error {
	var result params.ErrorResults
	args := params.UpdateApplicationServiceArgs{Args: []params.UpdateApplicationServiceArg{arg}}
	if err := c.facade.FacadeCall("UpdateApplicationsService", args, &result); err != nil {
		return errors.Trace(err)
	}
	if len(result.Results) != len(args.Args) {
		return errors.Errorf("expected %d result(s), got %d", len(args.Args), len(result.Results))
	}
	if result.Results[0].Error == nil {
		return nil
	}
	return maybeNotFound(result.Results[0].Error)
}
364159
func (c *autoRegisterController) RemoveAPIServiceToSync(name string) {
	c.apiServicesToSyncLock.Lock()
	defer c.apiServicesToSyncLock.Unlock()

	delete(c.apiServicesToSync, name)
	c.queue.Add(name)
}
1015215
func (serviceStatusStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {
	newService := obj.(*api.Service)
	oldService := old.(*api.Service)
	// status changes are not allowed to update spec
	newService.Spec = oldService.Spec
}
124906
func (c *upgradeSeriesCommand) ensureAPIClient() (api.Connection, error) {
	var apiRoot api.Connection
	if c.upgradeMachineSeriesClient == nil {
		var err error
		apiRoot, err = c.NewAPIRoot()
		if err != nil {
			return nil, errors.Trace(err)
		}
		c.upgradeMachineSeriesClient = machinemanager.NewClient(apiRoot)
	}
	return apiRoot, nil
}
212163
func (s *Service) UpdateService(w http.ResponseWriter, r *http.Request) {
	id, err := paramID("kid", r)
	if err != nil {
		Error(w, http.StatusUnprocessableEntity, err.Error(), s.Logger)
		return
	}

	srcID, err := paramID("id", r)
	if err != nil {
		Error(w, http.StatusUnprocessableEntity, err.Error(), s.Logger)
		return
	}

	ctx := r.Context()
	srv, err := s.Store.Servers(ctx).Get(ctx, id)
	if err != nil || srv.SrcID != srcID || srv.Type == "" {
		notFound(w, id, s.Logger)
		return
	}

	var req patchServiceRequest
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		invalidJSON(w, s.Logger)
		return
	}

	if err := req.Valid(); err != nil {
		invalidData(w, err, s.Logger)
		return
	}

	if req.Name != nil {
		srv.Name = *req.Name
	}
	if req.Type != nil {
		srv.Type = *req.Type
	}
	if req.URL != nil {
		srv.URL = *req.URL
	}
	if req.Password != nil {
		srv.Password = *req.Password
	}
	if req.Username != nil {
		srv.Username = *req.Username
	}
	if req.InsecureSkipVerify != nil {
		srv.InsecureSkipVerify = *req.InsecureSkipVerify
	}
	if req.Metadata != nil {
		srv.Metadata = *req.Metadata
	}

	if srv.Type == "flux" {
		err := pingFlux(ctx, srv.URL, srv.InsecureSkipVerify)
		if err != nil {
			msg := fmt.Sprintf("Unable to reach flux %s: %v", srv.URL, err)
			Error(w, http.StatusGatewayTimeout, msg, s.Logger)
			return
		}
	}

	if err := s.Store.Servers(ctx).Update(ctx, srv); err != nil {
		msg := fmt.Sprintf("Error updating service ID %d", id)
		Error(w, http.StatusInternalServerError, msg, s.Logger)
		return
	}

	res := newService(srv)
	encodeJSON(w, http.StatusOK, res, s.Logger)
}
1254394
func (a *Facade) UpdateApplicationsService(args params.UpdateApplicationServiceArgs) (params.ErrorResults, error) {
	result := params.ErrorResults{
		Results: make([]params.ErrorResult, len(args.Args)),
	}
	if len(args.Args) == 0 {
		return result, nil
	}
	for i, appUpdate := range args.Args {
		appTag, err := names.ParseApplicationTag(appUpdate.ApplicationTag)
		if err != nil {
			result.Results[i].Error = common.ServerError(err)
			continue
		}
		app, err := a.state.Application(appTag.Id())
		if err != nil {
			result.Results[i].Error = common.ServerError(err)
			continue
		}
		if err := app.UpdateCloudService(appUpdate.ProviderId, params.NetworkAddresses(appUpdate.Addresses...)); err != nil {
			result.Results[i].Error = common.ServerError(err)
		}
	}
	return result, nil
}
1300769
func updateService(ctx context.Context, apiClient client.NetworkAPIClient, flags *pflag.FlagSet, spec *swarm.ServiceSpec) error {
	updateBoolPtr := func(flag string, field **bool) {
		if flags.Changed(flag) {
			b, _ := flags.GetBool(flag)
			*field = &b
		}
	}
	updateString := func(flag string, field *string) {
		if flags.Changed(flag) {
			*field, _ = flags.GetString(flag)
		}
	}

	updateInt64Value := func(flag string, field *int64) {
		if flags.Changed(flag) {
			*field = flags.Lookup(flag).Value.(int64Value).Value()
		}
	}

	updateFloatValue := func(flag string, field *float32) {
		if flags.Changed(flag) {
			*field = flags.Lookup(flag).Value.(*floatValue).Value()
		}
	}

	updateDuration := func(flag string, field *time.Duration) {
		if flags.Changed(flag) {
			*field, _ = flags.GetDuration(flag)
		}
	}

	updateDurationOpt := func(flag string, field **time.Duration) {
		if flags.Changed(flag) {
			val := *flags.Lookup(flag).Value.(*opts.DurationOpt).Value()
			*field = &val
		}
	}

	updateUint64 := func(flag string, field *uint64) {
		if flags.Changed(flag) {
			*field, _ = flags.GetUint64(flag)
		}
	}

	updateUint64Opt := func(flag string, field **uint64) {
		if flags.Changed(flag) {
			val := *flags.Lookup(flag).Value.(*Uint64Opt).Value()
			*field = &val
		}
	}

	updateIsolation := func(flag string, field *container.Isolation) error {
		if flags.Changed(flag) {
			val, _ := flags.GetString(flag)
			*field = container.Isolation(val)
		}
		return nil
	}

	cspec := spec.TaskTemplate.ContainerSpec
	task := &spec.TaskTemplate

	taskResources := func() *swarm.ResourceRequirements {
		if task.Resources == nil {
			task.Resources = &swarm.ResourceRequirements{}
		}
		if task.Resources.Limits == nil {
			task.Resources.Limits = &swarm.Resources{}
		}
		if task.Resources.Reservations == nil {
			task.Resources.Reservations = &swarm.Resources{}
		}
		return task.Resources
	}

	updateLabels(flags, &spec.Labels)
	updateContainerLabels(flags, &cspec.Labels)
	updateString("image", &cspec.Image)
	updateStringToSlice(flags, "args", &cspec.Args)
	updateStringToSlice(flags, flagEntrypoint, &cspec.Command)
	updateEnvironment(flags, &cspec.Env)
	updateString(flagWorkdir, &cspec.Dir)
	updateString(flagUser, &cspec.User)
	updateString(flagHostname, &cspec.Hostname)
	updateBoolPtr(flagInit, &cspec.Init)
	if err := updateIsolation(flagIsolation, &cspec.Isolation); err != nil {
		return err
	}
	if err := updateMounts(flags, &cspec.Mounts); err != nil {
		return err
	}

	updateSysCtls(flags, &task.ContainerSpec.Sysctls)

	if anyChanged(flags, flagLimitCPU, flagLimitMemory) {
		taskResources().Limits = spec.TaskTemplate.Resources.Limits
		updateInt64Value(flagLimitCPU, &task.Resources.Limits.NanoCPUs)
		updateInt64Value(flagLimitMemory, &task.Resources.Limits.MemoryBytes)
	}

	if anyChanged(flags, flagReserveCPU, flagReserveMemory) {
		taskResources().Reservations = spec.TaskTemplate.Resources.Reservations
		updateInt64Value(flagReserveCPU, &task.Resources.Reservations.NanoCPUs)
		updateInt64Value(flagReserveMemory, &task.Resources.Reservations.MemoryBytes)
	}

	if err := addGenericResources(flags, task); err != nil {
		return err
	}

	if err := removeGenericResources(flags, task); err != nil {
		return err
	}

	updateDurationOpt(flagStopGracePeriod, &cspec.StopGracePeriod)

	if anyChanged(flags, flagRestartCondition, flagRestartDelay, flagRestartMaxAttempts, flagRestartWindow) {
		if task.RestartPolicy == nil {
			task.RestartPolicy = defaultRestartPolicy()
		}
		if flags.Changed(flagRestartCondition) {
			value, _ := flags.GetString(flagRestartCondition)
			task.RestartPolicy.Condition = swarm.RestartPolicyCondition(value)
		}
		updateDurationOpt(flagRestartDelay, &task.RestartPolicy.Delay)
		updateUint64Opt(flagRestartMaxAttempts, &task.RestartPolicy.MaxAttempts)
		updateDurationOpt(flagRestartWindow, &task.RestartPolicy.Window)
	}

	if anyChanged(flags, flagConstraintAdd, flagConstraintRemove) {
		if task.Placement == nil {
			task.Placement = &swarm.Placement{}
		}
		updatePlacementConstraints(flags, task.Placement)
	}

	if anyChanged(flags, flagPlacementPrefAdd, flagPlacementPrefRemove) {
		if task.Placement == nil {
			task.Placement = &swarm.Placement{}
		}
		updatePlacementPreferences(flags, task.Placement)
	}

	if anyChanged(flags, flagNetworkAdd, flagNetworkRemove) {
		if err := updateNetworks(ctx, apiClient, flags, spec); err != nil {
			return err
		}
	}

	if err := updateReplicas(flags, &spec.Mode); err != nil {
		return err
	}

	if anyChanged(flags, flagMaxReplicas) {
		updateUint64(flagMaxReplicas, &task.Placement.MaxReplicas)
	}

	if anyChanged(flags, flagUpdateParallelism, flagUpdateDelay, flagUpdateMonitor, flagUpdateFailureAction, flagUpdateMaxFailureRatio, flagUpdateOrder) {
		if spec.UpdateConfig == nil {
			spec.UpdateConfig = updateConfigFromDefaults(defaults.Service.Update)
		}
		updateUint64(flagUpdateParallelism, &spec.UpdateConfig.Parallelism)
		updateDuration(flagUpdateDelay, &spec.UpdateConfig.Delay)
		updateDuration(flagUpdateMonitor, &spec.UpdateConfig.Monitor)
		updateString(flagUpdateFailureAction, &spec.UpdateConfig.FailureAction)
		updateFloatValue(flagUpdateMaxFailureRatio, &spec.UpdateConfig.MaxFailureRatio)
		updateString(flagUpdateOrder, &spec.UpdateConfig.Order)
	}

	if anyChanged(flags, flagRollbackParallelism, flagRollbackDelay, flagRollbackMonitor, flagRollbackFailureAction, flagRollbackMaxFailureRatio, flagRollbackOrder) {
		if spec.RollbackConfig == nil {
			spec.RollbackConfig = updateConfigFromDefaults(defaults.Service.Rollback)
		}
		updateUint64(flagRollbackParallelism, &spec.RollbackConfig.Parallelism)
		updateDuration(flagRollbackDelay, &spec.RollbackConfig.Delay)
		updateDuration(flagRollbackMonitor, &spec.RollbackConfig.Monitor)
		updateString(flagRollbackFailureAction, &spec.RollbackConfig.FailureAction)
		updateFloatValue(flagRollbackMaxFailureRatio, &spec.RollbackConfig.MaxFailureRatio)
		updateString(flagRollbackOrder, &spec.RollbackConfig.Order)
	}

	if flags.Changed(flagEndpointMode) {
		value, _ := flags.GetString(flagEndpointMode)
		if spec.EndpointSpec == nil {
			spec.EndpointSpec = &swarm.EndpointSpec{}
		}
		spec.EndpointSpec.Mode = swarm.ResolutionMode(value)
	}

	if anyChanged(flags, flagGroupAdd, flagGroupRemove) {
		if err := updateGroups(flags, &cspec.Groups); err != nil {
			return err
		}
	}

	if anyChanged(flags, flagPublishAdd, flagPublishRemove) {
		if spec.EndpointSpec == nil {
			spec.EndpointSpec = &swarm.EndpointSpec{}
		}
		if err := updatePorts(flags, &spec.EndpointSpec.Ports); err != nil {
			return err
		}
	}

	if anyChanged(flags, flagDNSAdd, flagDNSRemove, flagDNSOptionAdd, flagDNSOptionRemove, flagDNSSearchAdd, flagDNSSearchRemove) {
		if cspec.DNSConfig == nil {
			cspec.DNSConfig = &swarm.DNSConfig{}
		}
		if err := updateDNSConfig(flags, &cspec.DNSConfig); err != nil {
			return err
		}
	}

	if anyChanged(flags, flagHostAdd, flagHostRemove) {
		if err := updateHosts(flags, &cspec.Hosts); err != nil {
			return err
		}
	}

	if err := updateLogDriver(flags, &spec.TaskTemplate); err != nil {
		return err
	}

	force, err := flags.GetBool("force")
	if err != nil {
		return err
	}

	if force {
		spec.TaskTemplate.ForceUpdate++
	}

	if err := updateHealthcheck(flags, cspec); err != nil {
		return err
	}

	if flags.Changed(flagTTY) {
		tty, err := flags.GetBool(flagTTY)
		if err != nil {
			return err
		}
		cspec.TTY = tty
	}

	if flags.Changed(flagReadOnly) {
		readOnly, err := flags.GetBool(flagReadOnly)
		if err != nil {
			return err
		}
		cspec.ReadOnly = readOnly
	}

	updateString(flagStopSignal, &cspec.StopSignal)

	return nil
}
513035
func (proxier *Proxier) updateServiceMap() (result updateServiceMapResult) {
	result.staleServices = sets.NewString()

	var serviceMap proxyServiceMap = proxier.serviceMap
	var changes *serviceChangeMap = &proxier.serviceChanges

	func() {
		changes.lock.Lock()
		defer changes.lock.Unlock()
		for _, change := range changes.items {
			existingPorts := serviceMap.merge(change.current, proxier.endpointsMap)
			serviceMap.unmerge(change.previous, existingPorts, result.staleServices, proxier.endpointsMap)
		}
		changes.items = make(map[types.NamespacedName]*serviceChange)
	}()

	// TODO: If this will appear to be computationally expensive, consider
	// computing this incrementally similarly to serviceMap.
	result.hcServices = make(map[types.NamespacedName]uint16)
	for svcPortName, info := range serviceMap {
		if info.healthCheckNodePort != 0 {
			result.hcServices[svcPortName.NamespacedName] = uint16(info.healthCheckNodePort)
		}
	}

	return result
}
1346514
func (a *api) UpdateService(reader io.Reader) (*service.ServiceDetails, error) {
	// Unmarshal JSON from the reader
	var s service.Service
	if err := json.NewDecoder(reader).Decode(&s); err != nil {
		return nil, fmt.Errorf("could not unmarshal json: %s", err)
	}

	return a.UpdateServiceObj(s)
}
641150
func ValidateAPIServiceUpdate(newAPIService *apiregistration.APIService, oldAPIService *apiregistration.APIService) field.ErrorList {
	allErrs := validation.ValidateObjectMetaUpdate(&newAPIService.ObjectMeta, &oldAPIService.ObjectMeta, field.NewPath("metadata"))
	allErrs = append(allErrs, ValidateAPIService(newAPIService)...)

	return allErrs
}
31710
func (f *Facade) updateServiceConfigs(ctx datastore.Context, serviceID string, configFiles []servicedefinition.ConfigFile, forceDelete bool) error {
	tenantID, servicePath, err := f.getServicePath(ctx, serviceID)
	if err != nil {
		return err
	}
	svcConfigFiles, err := f.configStore.GetConfigFiles(ctx, tenantID, servicePath)
	if err != nil {
		glog.Errorf("Could not load existing configs for service %s: %s", serviceID, err)
		return err
	}
	svcConfigFileMap := make(map[string]*serviceconfigfile.SvcConfigFile)
	for _, svcConfigFile := range svcConfigFiles {
		svcConfigFileMap[svcConfigFile.ConfFile.Filename] = svcConfigFile
	}
	for _, configFile := range configFiles {
		svcConfigFile, ok := svcConfigFileMap[configFile.Filename]
		if ok {
			delete(svcConfigFileMap, configFile.Filename)
			// do not update database if there are no configuration changes
			if reflect.DeepEqual(svcConfigFile.ConfFile, configFile) {
				glog.V(1).Infof("Skipping config file %s", configFile.Filename)
				continue
			}
			svcConfigFile.ConfFile = configFile
			glog.Infof("Updating config file %s for service %s", configFile.Filename, serviceID)
		} else {
			svcConfigFile, err = serviceconfigfile.New(tenantID, servicePath, configFile)
			if err != nil {
				if _, ok := err.(*validation.ValidationError); ok {
					if _, err := os.Stat(configFile.Filename); os.IsNotExist(err) {
						glog.V(1).Infof("%s doesn't exist. Skipping", configFile.Filename)
						continue
					}
				}
				glog.Errorf("Could not create new service config file %s for service %s: %s", configFile.Filename, serviceID, err)
				return err
			}
			glog.Infof("Adding config file %s for service %s", configFile.Filename, serviceID)
		}
		if err := f.configStore.Put(ctx, serviceconfigfile.Key(svcConfigFile.ID), svcConfigFile); err != nil {
			glog.Errorf("Could not update service config file %s for service %s: %s", configFile.Filename, serviceID, err)
			return err
		}
	}
	// delete any nonmatching configurations
	if forceDelete {
		for filename, svcConfigFile := range svcConfigFileMap {
			if err := f.configStore.Delete(ctx, serviceconfigfile.Key(svcConfigFile.ID)); err != nil {
				glog.Errorf("Could not delete service config file %s for service %s: %s", filename, serviceID, err)
				return err
			}
			glog.Infof("Deleting config file %s from service %s", filename, serviceID)
		}
	}
	return nil
}