// codeDeployLambdaUpdateDecorator is the per-function decorator
// that adds the necessary information for CodeDeploy
503692
func codeDeployLambdaUpdateDecorator(updateType string,
	codeDeployApplicationName string,
	codeDeployRoleName string) sparta.TemplateDecorator {
	return func(serviceName string,
		lambdaResourceName string,
		lambdaResource gocf.LambdaFunction,
		resourceMetadata map[string]interface{},
		S3Bucket string,
		S3Key string,
		buildID string,
		template *gocf.Template,
		context map[string]interface{},
		logger *logrus.Logger) error {

		safeDeployResourceName := func(resType string) string {
			return sparta.CloudFormationResourceName(serviceName,
				lambdaResourceName,
				resType)
		}
		// Create the AWS::Lambda::Version, with DeletionPolicy=Retain
		versionResourceName := safeDeployResourceName("version" + buildID)
		versionResource := &gocf.LambdaVersion{
			FunctionName: gocf.Ref(lambdaResourceName).String(),
		}
		entry := template.AddResource(versionResourceName, versionResource)
		entry.DeletionPolicy = "Retain"

		// Create the AWS::CodeDeploy::DeploymentGroup entry that includes a reference
		// to the IAM role
		codeDeploymentGroupResourceName := safeDeployResourceName("deploymentGroup")
		codeDeploymentGroup := &gocf.CodeDeployDeploymentGroup{
			ApplicationName: gocf.Ref(codeDeployApplicationName).String(),
			AutoRollbackConfiguration: &gocf.CodeDeployDeploymentGroupAutoRollbackConfiguration{
				Enabled: gocf.Bool(true),
				Events: gocf.StringList(gocf.String("DEPLOYMENT_FAILURE"),
					gocf.String("DEPLOYMENT_STOP_ON_ALARM"),
					gocf.String("DEPLOYMENT_STOP_ON_REQUEST")),
			},
			ServiceRoleArn:       gocf.GetAtt(codeDeployRoleName, "Arn"),
			DeploymentConfigName: gocf.String(fmt.Sprintf("CodeDeployDefault.Lambda%s", updateType)),
			DeploymentStyle: &gocf.CodeDeployDeploymentGroupDeploymentStyle{
				DeploymentType:   gocf.String("BLUE_GREEN"),
				DeploymentOption: gocf.String("WITH_TRAFFIC_CONTROL"),
			},
		}
		template.AddResource(codeDeploymentGroupResourceName, codeDeploymentGroup)
		// Create the Alias entry...
		aliasResourceName := safeDeployResourceName("alias")
		aliasResource := &gocf.LambdaAlias{
			FunctionVersion: gocf.GetAtt(versionResourceName, "Version").String(),
			FunctionName:    gocf.Ref(lambdaResourceName).String(),
			Name:            gocf.String("live"),
		}
		aliasEntry := template.AddResource(aliasResourceName, aliasResource)
		aliasEntry.UpdatePolicy = &gocf.UpdatePolicy{
			CodeDeployLambdaAliasUpdate: &gocf.UpdatePolicyCodeDeployLambdaAliasUpdate{
				ApplicationName:     gocf.Ref(codeDeployApplicationName).String(),
				DeploymentGroupName: gocf.Ref(codeDeploymentGroupResourceName).String(),
			},
		}
		return nil
	}
}
1121087
func (f *Function) DeployConfigAndCode(zip []byte) error {
	f.Log.Info("updating config")

	params := &lambda.UpdateFunctionConfigurationInput{
		FunctionName: &f.FunctionName,
		MemorySize:   &f.Memory,
		Timeout:      &f.Timeout,
		Description:  &f.Description,
		Role:         &f.Role,
		Runtime:      &f.Runtime,
		Handler:      &f.Handler,
		KMSKeyArn:    &f.KMSKeyArn,
		Environment:  f.environment(),
		VpcConfig: &lambda.VpcConfig{
			SecurityGroupIds: aws.StringSlice(f.VPC.SecurityGroups),
			SubnetIds:        aws.StringSlice(f.VPC.Subnets),
		},
	}

	if f.DeadLetterARN != "" {
		params.DeadLetterConfig = &lambda.DeadLetterConfig{
			TargetArn: &f.DeadLetterARN,
		}
	}

	_, err := f.Service.UpdateFunctionConfiguration(params)
	if err != nil {
		return err
	}

	return f.Update(zip)
}
68941
func (c *CodebaseController) Update(ctx *app.UpdateCodebaseContext) error {
	codebaseID, err := uuid.FromString(ctx.CodebaseID)
	if err != nil {
		return err
	}
	// see if the user is allowed to update this codebase
	cb, err := c.verifyCodebaseOwner(ctx, codebaseID)
	if err != nil {
		return jsonapi.JSONErrorResponse(ctx, err)
	}

	// set only allowed fields
	reqAttributes := ctx.Payload.Data.Attributes
	if reqAttributes.CveScan != nil {
		cb.CVEScan = *reqAttributes.CveScan
	}
	if reqAttributes.StackID != nil {
		cb.StackID = reqAttributes.StackID
	}
	if reqAttributes.Type != nil {
		cb.Type = *reqAttributes.Type
	}

	var updatedCb *codebase.Codebase
	// now save the object back into the database
	err = application.Transactional(c.db, func(appl application.Application) error {
		updatedCb, err = appl.Codebases().Save(ctx, cb)
		return err
	})
	if err != nil {
		return jsonapi.JSONErrorResponse(ctx, err)
	}

	res := &app.CodebaseSingle{
		Data: ConvertCodebase(ctx.Request, *updatedCb),
	}
	ctx.ResponseData.Header().Set("Location", rest.AbsoluteURL(ctx.Request, app.CodebaseHref(res.Data.ID)))

	return ctx.OK(res)
}
827143
func (s *DiskOfferingService) NewUpdateDiskOfferingParams(id string) *UpdateDiskOfferingParams {
	p := &UpdateDiskOfferingParams{}
	p.p = make(map[string]interface{})
	p.p["id"] = id
	return p
}
235583
func (s *server) applyChannelUpdate(update *lnwire.ChannelUpdate) error {
	pubKey := s.identityPriv.PubKey()
	errChan := s.authGossiper.ProcessLocalAnnouncement(update, pubKey)
	select {
	case err := <-errChan:
		return err
	case <-s.quit:
		return ErrServerShuttingDown
	}
}
1202509
func NewPoolUpdateCommand() cmd.Command {
	cmd := &poolUpdateCommand{}
	cmd.newAPIFunc = func() (PoolUpdateAPI, error) {
		return cmd.NewStorageAPI()
	}
	return modelcmd.Wrap(cmd)
}
1070253
func (mr *MockSwarmAPIClientMockRecorder) SwarmUpdate(ctx, version, swarm, flags interface{}) *gomock.Call {
	return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SwarmUpdate", reflect.TypeOf((*MockSwarmAPIClient)(nil).SwarmUpdate), ctx, version, swarm, flags)
}
906071
func (s *StateStore) updateDeploymentStatusImpl(index uint64, u *structs.DeploymentStatusUpdate, txn *memdb.Txn) error {
	// Retrieve deployment
	ws := memdb.NewWatchSet()
	deployment, err := s.deploymentByIDImpl(ws, u.DeploymentID, txn)
	if err != nil {
		return err
	} else if deployment == nil {
		return fmt.Errorf("Deployment ID %q couldn't be updated as it does not exist", u.DeploymentID)
	} else if !deployment.Active() {
		return fmt.Errorf("Deployment %q has terminal status %q:", deployment.ID, deployment.Status)
	}

	// Apply the new status
	copy := deployment.Copy()
	copy.Status = u.Status
	copy.StatusDescription = u.StatusDescription
	copy.ModifyIndex = index

	// COMPAT 0.7: Upgrade old objects that do not have namespaces
	if copy.Namespace == "" {
		copy.Namespace = structs.DefaultNamespace
	}

	// Insert the deployment
	if err := txn.Insert("deployment", copy); err != nil {
		return err
	}

	// Update the index
	if err := txn.Insert("index", &IndexEntry{"deployment", index}); err != nil {
		return fmt.Errorf("index update failed: %v", err)
	}

	// If the deployment is being marked as complete, set the job to stable.
	if copy.Status == structs.DeploymentStatusSuccessful {
		if err := s.updateJobStabilityImpl(index, copy.Namespace, copy.JobID, copy.JobVersion, true, txn); err != nil {
			return fmt.Errorf("failed to update job stability: %v", err)
		}
	}

	return nil
}
660867
func (statusStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {
	return validation.ValidateDeploymentConfigStatusUpdate(obj.(*appsapi.DeploymentConfig), old.(*appsapi.DeploymentConfig))
}
265684
func (w *deploymentWatcher) getDeploymentStatusUpdate(status, desc string) *structs.DeploymentStatusUpdate {
	return &structs.DeploymentStatusUpdate{
		DeploymentID:      w.deploymentID,
		Status:            status,
		StatusDescription: desc,
	}
}
1144875
func (dc *DeploymentController) updateDeploymentAndClearRollbackTo(d *apps.Deployment) error {
	klog.V(4).Infof("Cleans up rollbackTo of deployment %q", d.Name)
	setRollbackTo(d, nil)
	_, err := dc.client.AppsV1().Deployments(d.Namespace).Update(d)
	return err
}
684614
func (lscc *LifeCycleSysCC) executeDeploy(
	stub shim.ChaincodeStubInterface,
	chainname string,
	cds *pb.ChaincodeDeploymentSpec,
	policy []byte,
	escc []byte,
	vscc []byte,
	cdfs *ccprovider.ChaincodeData,
	ccpackfs ccprovider.CCPackage,
	collectionConfigBytes []byte,
) (*ccprovider.ChaincodeData, error) {
	//just test for existence of the chaincode in the LSCC
	chaincodeName := cds.ChaincodeSpec.ChaincodeId.Name
	_, err := lscc.getCCInstance(stub, chaincodeName)
	if err == nil {
		return nil, ExistsErr(chaincodeName)
	}

	//retain chaincode specific data and fill channel specific ones
	cdfs.Escc = string(escc)
	cdfs.Vscc = string(vscc)
	cdfs.Policy = policy

	// retrieve and evaluate instantiation policy
	cdfs.InstantiationPolicy, err = lscc.Support.GetInstantiationPolicy(chainname, ccpackfs)
	if err != nil {
		return nil, err
	}
	// get the signed instantiation proposal
	signedProp, err := stub.GetSignedProposal()
	if err != nil {
		return nil, err
	}
	err = lscc.Support.CheckInstantiationPolicy(signedProp, chainname, cdfs.InstantiationPolicy)
	if err != nil {
		return nil, err
	}

	err = lscc.putChaincodeData(stub, cdfs)
	if err != nil {
		return nil, err
	}

	err = lscc.putChaincodeCollectionData(stub, cdfs, collectionConfigBytes)
	if err != nil {
		return nil, err
	}

	return cdfs, nil
}
45365
func (u *UnschedulablePodsMap) addOrUpdate(pInfo *podInfo) {
	podID := u.keyFunc(pInfo.pod)
	if _, exists := u.podInfoMap[podID]; !exists && u.metricRecorder != nil {
		u.metricRecorder.Inc()
	}
	u.podInfoMap[podID] = pInfo
}
944553
func applyInPlaceFunctionUpdates(ctx *workflowContext, templateURL string) (*cloudformation.Stack, error) {
	// Get the updates...
	awsCloudFormation := cloudformation.New(ctx.context.awsSession)
	changeSetRequestName := CloudFormationResourceName(fmt.Sprintf("%sInPlaceChangeSet", ctx.userdata.serviceName))
	changes, changesErr := spartaCF.CreateStackChangeSet(changeSetRequestName,
		ctx.userdata.serviceName,
		ctx.context.cfTemplate,
		templateURL,
		nil,
		awsCloudFormation,
		ctx.logger)
	if nil != changesErr {
		return nil, changesErr
	}
	if nil == changes || len(changes.Changes) <= 0 {
		return nil, fmt.Errorf("no changes detected")
	}
	updateCodeRequests := []*lambda.UpdateFunctionCodeInput{}
	invalidInPlaceRequests := []string{}
	for _, eachChange := range changes.Changes {
		resourceChange := eachChange.ResourceChange
		if *resourceChange.Action == "Modify" && *resourceChange.ResourceType == "AWS::Lambda::Function" {
			updateCodeRequest := &lambda.UpdateFunctionCodeInput{
				FunctionName: resourceChange.PhysicalResourceId,
				S3Bucket:     aws.String(ctx.userdata.s3Bucket),
				S3Key:        aws.String(ctx.context.s3CodeZipURL.keyName()),
			}
			if ctx.context.s3CodeZipURL != nil && ctx.context.s3CodeZipURL.version != "" {
				updateCodeRequest.S3ObjectVersion = aws.String(ctx.context.s3CodeZipURL.version)
			}
			updateCodeRequests = append(updateCodeRequests, updateCodeRequest)
		} else {
			invalidInPlaceRequests = append(invalidInPlaceRequests,
				fmt.Sprintf("%s for %s (ResourceType: %s)",
					*resourceChange.Action,
					*resourceChange.LogicalResourceId,
					*resourceChange.ResourceType))
		}
	}
	if len(invalidInPlaceRequests) != 0 {
		return nil, fmt.Errorf("unsupported in-place operations detected:\n\t%s", strings.Join(invalidInPlaceRequests, ",\n\t"))
	}

	ctx.logger.WithFields(logrus.Fields{
		"FunctionCount": len(updateCodeRequests),
	}).Info("Updating Lambda function code")
	ctx.logger.WithFields(logrus.Fields{
		"Updates": updateCodeRequests,
	}).Debug("Update requests")

	// TODO - migrate to the worker pool
	updateTaskMaker := func(lambdaSvc *lambda.Lambda, request *lambda.UpdateFunctionCodeInput) taskFunc {
		return func() workResult {
			_, updateResultErr := lambdaSvc.UpdateFunctionCode(request)
			return newTaskResult("", updateResultErr)
		}
	}
	inPlaceUpdateTasks := make([]*workTask,
		len(updateCodeRequests))
	awsLambda := lambda.New(ctx.context.awsSession)
	for eachIndex, eachUpdateCodeRequest := range updateCodeRequests {
		updateTask := updateTaskMaker(awsLambda, eachUpdateCodeRequest)
		inPlaceUpdateTasks[eachIndex] = newWorkTask(updateTask)
	}

	// Add the request to delete the change set...
	// TODO: add some retry logic in here to handle failures.
	deleteChangeSetTask := func() workResult {
		_, deleteChangeSetResultErr := spartaCF.DeleteChangeSet(ctx.userdata.serviceName,
			changeSetRequestName,
			awsCloudFormation)
		return newTaskResult("", deleteChangeSetResultErr)
	}
	inPlaceUpdateTasks = append(inPlaceUpdateTasks, newWorkTask(deleteChangeSetTask))
	p := newWorkerPool(inPlaceUpdateTasks, len(inPlaceUpdateTasks))
	_, asyncErrors := p.Run()
	if len(asyncErrors) != 0 {
		return nil, fmt.Errorf("failed to update function code: %v", asyncErrors)
	}
	// Describe the stack so that we can satisfy the contract with the
	// normal path using CloudFormation
	describeStacksInput := &cloudformation.DescribeStacksInput{
		StackName: aws.String(ctx.userdata.serviceName),
	}
	describeStackOutput, describeStackOutputErr := awsCloudFormation.DescribeStacks(describeStacksInput)
	if nil != describeStackOutputErr {
		return nil, describeStackOutputErr
	}
	return describeStackOutput.Stacks[0], nil
}
1226591
func (b *AllocUpdateBatcher) CreateUpdate(allocs map[string]*structs.DesiredTransition, eval *structs.Evaluation) *BatchFuture {
	wrapper := &updateWrapper{
		allocs: allocs,
		e:      eval,
		f:      make(chan *BatchFuture, 1),
	}

	b.workCh <- wrapper
	return <-wrapper.f
}
1065648
func (s *StateStore) UpdateDeploymentAllocHealth(index uint64, req *structs.ApplyDeploymentAllocHealthRequest) error {
	txn := s.db.Txn(true)
	defer txn.Abort()

	// Retrieve deployment and ensure it is not terminal and is active
	ws := memdb.NewWatchSet()
	deployment, err := s.deploymentByIDImpl(ws, req.DeploymentID, txn)
	if err != nil {
		return err
	} else if deployment == nil {
		return fmt.Errorf("Deployment ID %q couldn't be updated as it does not exist", req.DeploymentID)
	} else if !deployment.Active() {
		return fmt.Errorf("Deployment %q has terminal status %q:", deployment.ID, deployment.Status)
	}

	// Update the health status of each allocation
	if total := len(req.HealthyAllocationIDs) + len(req.UnhealthyAllocationIDs); total != 0 {
		setAllocHealth := func(id string, healthy bool, ts time.Time) error {
			existing, err := txn.First("allocs", "id", id)
			if err != nil {
				return fmt.Errorf("alloc %q lookup failed: %v", id, err)
			}
			if existing == nil {
				return fmt.Errorf("unknown alloc %q", id)
			}

			old := existing.(*structs.Allocation)
			if old.DeploymentID != req.DeploymentID {
				return fmt.Errorf("alloc %q is not part of deployment %q", id, req.DeploymentID)
			}

			// Set the health
			copy := old.Copy()
			if copy.DeploymentStatus == nil {
				copy.DeploymentStatus = &structs.AllocDeploymentStatus{}
			}
			copy.DeploymentStatus.Healthy = helper.BoolToPtr(healthy)
			copy.DeploymentStatus.Timestamp = ts
			copy.DeploymentStatus.ModifyIndex = index
			copy.ModifyIndex = index

			if err := s.updateDeploymentWithAlloc(index, copy, old, txn); err != nil {
				return fmt.Errorf("error updating deployment: %v", err)
			}

			if err := txn.Insert("allocs", copy); err != nil {
				return fmt.Errorf("alloc insert failed: %v", err)
			}

			return nil
		}

		for _, id := range req.HealthyAllocationIDs {
			if err := setAllocHealth(id, true, req.Timestamp); err != nil {
				return err
			}
		}
		for _, id := range req.UnhealthyAllocationIDs {
			if err := setAllocHealth(id, false, req.Timestamp); err != nil {
				return err
			}
		}

		// Update the indexes
		if err := txn.Insert("index", &IndexEntry{"allocs", index}); err != nil {
			return fmt.Errorf("index update failed: %v", err)
		}
	}

	// Update the deployment status as needed.
	if req.DeploymentUpdate != nil {
		if err := s.updateDeploymentStatusImpl(index, req.DeploymentUpdate, txn); err != nil {
			return err
		}
	}

	// Upsert the job if necessary
	if req.Job != nil {
		if err := s.upsertJobImpl(index, req.Job, false, txn); err != nil {
			return err
		}
	}

	// Upsert the optional eval
	if req.Eval != nil {
		if err := s.nestedUpsertEval(txn, index, req.Eval); err != nil {
			return err
		}
	}

	txn.Commit()
	return nil
}
699018
func UpdateApplyAnnotation(info *resource.Info, codec runtime.Encoder) error {
	if original, err := GetOriginalConfiguration(info); err != nil || len(original) <= 0 {
		return err
	}
	return CreateApplyAnnotation(info, codec)
}