// updateState saves current task state
774758
func (b *Backend) updateState(taskState *tasks.TaskState) error {
	message, err := json.Marshal(taskState)
	if err != nil {
		return fmt.Errorf("JSON marshal error: %s", err)
	}

	declareQueueArgs := amqp.Table{
		// Time in milliseconds
		// after that message will expire
		"x-message-ttl": int32(b.getExpiresIn()),
		// Time after that the queue will be deleted.
		"x-expires": int32(b.getExpiresIn()),
	}
	conn, channel, queue, confirmsChan, _, err := b.Connect(
		b.GetConfig().Broker,
		b.GetConfig().TLSConfig,
		b.GetConfig().AMQP.Exchange,     // exchange name
		b.GetConfig().AMQP.ExchangeType, // exchange type
		taskState.TaskUUID,              // queue name
		false,                           // queue durable
		true,                            // queue delete when unused
		taskState.TaskUUID,              // queue binding key
		nil,                             // exchange declare args
		declareQueueArgs,                // queue declare args
		nil,                             // queue binding args
	)
	if err != nil {
		return err
	}
	defer b.Close(channel, conn)

	if err := channel.Publish(
		b.GetConfig().AMQP.Exchange, // exchange
		queue.Name,                  // routing key
		false,                       // mandatory
		false,                       // immediate
		amqp.Publishing{
			ContentType:  "application/json",
			Body:         message,
			DeliveryMode: amqp.Persistent, // Persistent // Transient
		},
	); err != nil {
		return err
	}

	confirmed := <-confirmsChan

	if confirmed.Ack {
		return nil
	}

	return fmt.Errorf("Failed delivery of delivery tag: %d", confirmed.DeliveryTag)
}
254431
func (s *ContactDetail) SetState(v string) *ContactDetail {
	s.State = &v
	return s
}
1168367
func (t *UpdateTaskRequest) UpdateFlux(oldFlux string) error {
	if t.Options.IsZero() {
		return nil
	}
	tu := platform.TaskUpdate{
		Options: t.Options,
		Flux:    &t.Script,
	}
	if err := tu.UpdateFlux(oldFlux); err != nil {
		return err
	}
	t.Script = *tu.Flux
	t.Options.Clear()
	return nil
}
827098
func (agent *ActionAgent) updateState(ctx context.Context, newTablet *topodatapb.Tablet, reason string) {
	oldTablet := agent.Tablet()
	if oldTablet == nil {
		oldTablet = &topodatapb.Tablet{}
	}
	log.Infof("Running tablet callback because: %v", reason)
	agent.changeCallback(ctx, oldTablet, newTablet)
	agent.setTablet(newTablet)
	event.Dispatch(&events.StateChange{
		OldTablet: *oldTablet,
		NewTablet: *newTablet,
		Reason:    reason,
	})
}
274363
func (b *Backend) SetStateFailure(signature *tasks.Signature, err string) error {
	update := bson.M{"state": tasks.StateFailure, "error": err}
	return b.updateState(signature, update)
}
219805
func (l *State) updateSyncState() error {
	// Get all checks and services from the master
	req := structs.NodeSpecificRequest{
		Datacenter:   l.config.Datacenter,
		Node:         l.config.NodeName,
		QueryOptions: structs.QueryOptions{Token: l.tokens.AgentToken()},
	}

	var out1 structs.IndexedNodeServices
	if err := l.Delegate.RPC("Catalog.NodeServices", &req, &out1); err != nil {
		return err
	}

	var out2 structs.IndexedHealthChecks
	if err := l.Delegate.RPC("Health.NodeChecks", &req, &out2); err != nil {
		return err
	}

	// Create useful data structures for traversal
	remoteServices := make(map[string]*structs.NodeService)
	if out1.NodeServices != nil {
		remoteServices = out1.NodeServices.Services
	}

	remoteChecks := make(map[types.CheckID]*structs.HealthCheck, len(out2.HealthChecks))
	for _, rc := range out2.HealthChecks {
		remoteChecks[rc.CheckID] = rc
	}

	// Traverse all checks, services and the node info to determine
	// which entries need to be updated on or removed from the server

	l.Lock()
	defer l.Unlock()

	// Check if node info needs syncing
	if out1.NodeServices == nil || out1.NodeServices.Node == nil ||
		out1.NodeServices.Node.ID != l.config.NodeID ||
		!reflect.DeepEqual(out1.NodeServices.Node.TaggedAddresses, l.config.TaggedAddresses) ||
		!reflect.DeepEqual(out1.NodeServices.Node.Meta, l.metadata) {
		l.nodeInfoInSync = false
	}

	// Check which services need syncing

	// Look for local services that do not exist remotely and mark them for
	// syncing so that they will be pushed to the server later
	for id, s := range l.services {
		if remoteServices[id] == nil {
			s.InSync = false
		}
	}

	// Traverse the list of services from the server.
	// Remote services which do not exist locally have been deregistered.
	// Otherwise, check whether the two definitions are still in sync.
	for id, rs := range remoteServices {
		ls := l.services[id]
		if ls == nil {
			// The consul service is managed automatically and does
			// not need to be deregistered
			if id == structs.ConsulServiceID {
				continue
			}

			// Mark a remote service that does not exist locally as deleted so
			// that it will be removed on the server later.
			l.services[id] = &ServiceState{Deleted: true}
			continue
		}

		// If the service is already scheduled for removal skip it
		if ls.Deleted {
			continue
		}

		// If our definition is different, we need to update it. Make a
		// copy so that we don't retain a pointer to any actual state
		// store info for in-memory RPCs.
		if ls.Service.EnableTagOverride {
			ls.Service.Tags = make([]string, len(rs.Tags))
			copy(ls.Service.Tags, rs.Tags)
		}
		ls.InSync = ls.Service.IsSame(rs)
	}

	// Check which checks need syncing

	// Look for local checks that do not exist remotely and mark them for
	// syncing so that they will be pushed to the server later
	for id, c := range l.checks {
		if remoteChecks[id] == nil {
			c.InSync = false
		}
	}

	// Traverse the list of checks from the server.
	// Remote checks which do not exist locally have been deregistered.
	// Otherwise, check whether the two definitions are still in sync.
	for id, rc := range remoteChecks {
		lc := l.checks[id]

		if lc == nil {
			// The Serf check is created automatically and does not
			// need to be deregistered.
			if id == structs.SerfCheckID {
				l.logger.Printf("[DEBUG] agent: Skipping remote check %q since it is managed automatically", id)
				continue
			}

			// Mark a remote check that does not exist locally as deleted so
			// that it will be removed on the server later.
			l.checks[id] = &CheckState{Deleted: true}
			continue
		}

		// If the check is already scheduled for removal skip it.
		if lc.Deleted {
			continue
		}

		// If our definition is different, we need to update it
		if l.config.CheckUpdateInterval == 0 {
			lc.InSync = lc.Check.IsSame(rc)
			continue
		}

		// Copy the existing check before potentially modifying
		// it before the compare operation.
		lcCopy := lc.Check.Clone()

		// Copy the server's check before modifying, otherwise
		// in-memory RPCs will have side effects.
		rcCopy := rc.Clone()

		// If there's a defer timer active then we've got a
		// potentially spammy check so we don't sync the output
		// during this sweep since the timer will mark the check
		// out of sync for us. Otherwise, it is safe to sync the
		// output now. This is especially important for checks
		// that don't change state after they are created, in
		// which case we'd never see their output synced back ever.
		if lc.DeferCheck != nil {
			lcCopy.Output = ""
			rcCopy.Output = ""
		}
		lc.InSync = lcCopy.IsSame(rcCopy)
	}
	return nil
}
660871
func (s *UpdateLifecyclePolicyInput) SetState(v string) *UpdateLifecyclePolicyInput {
	s.State = &v
	return s
}
1003204
func (tm *taskManager) Update(ctx context.Context, task *api.Task) error {
	select {
	case tm.updateq <- task:
		return nil
	case <-tm.closed:
		return ErrClosed
	case <-ctx.Done():
		return ctx.Err()
	}
}
887011
func (s *WorkspaceImage) SetState(v string) *WorkspaceImage {
	s.State = &v
	return s
}
1360537
func (c *Client) UpdateTask(ctx context.Context, id int64, tu TaskUpdate, opt *Filter) (Task, error) {
	task := new(Task)
	err := c.request(ctx, "PUT", fmt.Sprintf("tasks/%d", id), tu, nil, opt, task)
	return *task, err
}
188358
func (bot *ExchangeBot) updateState() error {
	dcrPrice, volume := bot.processState(bot.currentState.DcrBtc, true)
	btcPrice, _ := bot.processState(bot.currentState.FiatIndices, false)
	if dcrPrice == 0 || btcPrice == 0 {
		bot.failed = true
	} else {
		bot.failed = false
		bot.currentState.Price = dcrPrice * btcPrice
		bot.currentState.BtcPrice = btcPrice
		bot.currentState.Volume = volume
	}

	var jsonBytes []byte
	var err error
	if bot.config.Indent {
		jsonBytes, err = json.MarshalIndent(bot.currentState, "", "    ")
	} else {
		jsonBytes, err = json.Marshal(bot.currentState)
	}
	if err != nil {
		return fmt.Errorf("Failed to write bytes: %v", err)
	}
	bot.currentStateBytes = jsonBytes
	bot.stateCopy = bot.currentState.copy()

	return nil
}
279831
func (s *LoadBalancerTargetGroupState) SetState(v string) *LoadBalancerTargetGroupState {
	s.State = &v
	return s
}
373273
func (e *eventLogger) updateState(event *v1.Event) {
	key := getEventKey(event)
	e.Lock()
	defer e.Unlock()
	// record our new observation
	e.cache.Add(
		key,
		eventLog{
			count:           uint(event.Count),
			firstTimestamp:  event.FirstTimestamp,
			name:            event.Name,
			resourceVersion: event.ResourceVersion,
		},
	)
}
1045948
func (s *InstanceGroupStatus) SetState(v string) *InstanceGroupStatus {
	s.State = &v
	return s
}
103313
func (s *storeImpl) updateCurrentState(serviceID string, currentState string, updatedAt time.Time) error {
	// Validate desired state
	if err := ServiceCurrentState(currentState).Validate(); err != nil {
		plog.WithFields(log.Fields{
			"serviceID":    serviceID,
			"currentState": currentState,
		}).Debug("Invalid Current State")
		return err
	}

	plog.WithFields(log.Fields{
		"serviceID":    serviceID,
		"currentState": currentState,
		"updatedAt":    updatedAt,
	}).Debug("Saving current state in cache")

	s.serviceCacheLock.Lock()
	defer s.serviceCacheLock.Unlock()
	var cacheEntry volatileService

	cacheEntry, ok := s.serviceCache[serviceID]
	if !ok {
		cacheEntry = volatileService{
			ID:           serviceID,
			CurrentState: currentState,
			UpdatedAt:    updatedAt,
		}
	} else {
		cacheEntry.CurrentState = currentState
		cacheEntry.UpdatedAt = updatedAt
	}

	s.serviceCache[serviceID] = cacheEntry

	return nil
}
1099559
func (s *CreateJobQueueInput) SetState(v string) *CreateJobQueueInput {
	s.State = &v
	return s
}
381395
func (d *destination) updateState() {
	// The destination is healthy if the backend is enabled and *all* the checks
	// for that destination are healthy.
	healthy := d.backend.Enabled
	if healthy {
		for _, c := range d.checks {
			if c.status.State != healthcheck.StateHealthy {
				healthy = false
				break
			}
		}
	}

	if d.healthy == healthy {
		return
	}
	d.healthy = healthy

	switch {
	case d.service.active && d.healthy:
		// The service is already active. Bringing up the dest will have no effect
		// on the service or vserver state.
		d.up()

	case d.service.active != d.healthy || d.service.healthy != d.healthy:
		// The service may need to be brought up or down.
		d.service.updateState()
	}
}