// updateNonTerminalAllocsToLost updates the allocations which are in pending/running state on tainted node
// to lost
16216
func updateNonTerminalAllocsToLost(plan *structs.Plan, tainted map[string]*structs.Node, allocs []*structs.Allocation) {
	for _, alloc := range allocs {
		node, ok := tainted[alloc.NodeID]
		if !ok {
			continue
		}

		// Only handle down nodes or nodes that are gone (node == nil)
		if node != nil && node.Status != structs.NodeStatusDown {
			continue
		}

		// If the scheduler has marked it as stop already but the alloc wasn't
		// terminal on the client change the status to lost.
		if alloc.DesiredStatus == structs.AllocDesiredStatusStop &&
			(alloc.ClientStatus == structs.AllocClientStatusRunning ||
				alloc.ClientStatus == structs.AllocClientStatusPending) {
			plan.AppendStoppedAlloc(alloc, allocLost, structs.AllocClientStatusLost)
		}
	}
}
128384
func (c *Client) updateNodeStatus() error {
	start := time.Now()
	req := structs.NodeUpdateStatusRequest{
		NodeID:       c.NodeID(),
		Status:       structs.NodeStatusReady,
		WriteRequest: structs.WriteRequest{Region: c.Region()},
	}
	var resp structs.NodeUpdateResponse
	if err := c.RPC("Node.UpdateStatus", &req, &resp); err != nil {
		c.triggerDiscovery()
		return fmt.Errorf("failed to update status: %v", err)
	}
	end := time.Now()

	if len(resp.EvalIDs) != 0 {
		c.logger.Debug("evaluations triggered by node update", "num_evals", len(resp.EvalIDs))
	}

	// Update the last heartbeat and the new TTL, capturing the old values
	c.heartbeatLock.Lock()
	last := c.lastHeartbeat
	oldTTL := c.heartbeatTTL
	haveHeartbeated := c.haveHeartbeated
	c.lastHeartbeat = time.Now()
	c.heartbeatTTL = resp.HeartbeatTTL
	c.haveHeartbeated = true
	c.heartbeatLock.Unlock()
	c.logger.Trace("next heartbeat", "period", resp.HeartbeatTTL)

	if resp.Index != 0 {
		c.logger.Debug("state updated", "node_status", req.Status)

		// We have potentially missed our TTL log how delayed we were
		if haveHeartbeated {
			c.logger.Warn("missed heartbeat",
				"req_latency", end.Sub(start), "heartbeat_ttl", oldTTL, "since_last_heartbeat", time.Since(last))
		}
	}

	// Update the number of nodes in the cluster so we can adjust our server
	// rebalance rate.
	c.servers.SetNumNodes(resp.NumNodes)

	// Convert []*NodeServerInfo to []*servers.Server
	nomadServers := make([]*servers.Server, 0, len(resp.Servers))
	for _, s := range resp.Servers {
		addr, err := resolveServer(s.RPCAdvertiseAddr)
		if err != nil {
			c.logger.Warn("ignoring invalid server", "error", err, "server", s.RPCAdvertiseAddr)
			continue
		}
		e := &servers.Server{DC: s.Datacenter, Addr: addr}
		nomadServers = append(nomadServers, e)
	}
	if len(nomadServers) == 0 {
		return fmt.Errorf("heartbeat response returned no valid servers")
	}
	c.servers.SetServers(nomadServers)

	// Begin polling Consul if there is no Nomad leader.  We could be
	// heartbeating to a Nomad server that is in the minority of a
	// partition of the Nomad server quorum, but this Nomad Agent still
	// has connectivity to the existing majority of Nomad Servers, but
	// only if it queries Consul.
	if resp.LeaderRPCAddr == "" {
		c.triggerDiscovery()
	}

	return nil
}
448678
func (n *Node) UpdateEligibility(args *structs.NodeUpdateEligibilityRequest,
	reply *structs.NodeEligibilityUpdateResponse) error {
	if done, err := n.srv.forward("Node.UpdateEligibility", args, args, reply); done {
		return err
	}
	defer metrics.MeasureSince([]string{"nomad", "client", "update_eligibility"}, time.Now())

	// Check node write permissions
	if aclObj, err := n.srv.ResolveToken(args.AuthToken); err != nil {
		return err
	} else if aclObj != nil && !aclObj.AllowNodeWrite() {
		return structs.ErrPermissionDenied
	}

	// Verify the arguments
	if args.NodeID == "" {
		return fmt.Errorf("missing node ID for setting scheduling eligibility")
	}
	if args.NodeEvent != nil {
		return fmt.Errorf("node event must not be set")
	}

	// Check that only allowed types are set
	switch args.Eligibility {
	case structs.NodeSchedulingEligible, structs.NodeSchedulingIneligible:
	default:
		return fmt.Errorf("invalid scheduling eligibility %q", args.Eligibility)
	}

	// Look for the node
	snap, err := n.srv.fsm.State().Snapshot()
	if err != nil {
		return err
	}
	node, err := snap.NodeByID(nil, args.NodeID)
	if err != nil {
		return err
	}
	if node == nil {
		return fmt.Errorf("node not found")
	}

	if node.DrainStrategy != nil && args.Eligibility == structs.NodeSchedulingEligible {
		return fmt.Errorf("can not set node's scheduling eligibility to eligible while it is draining")
	}

	switch args.Eligibility {
	case structs.NodeSchedulingEligible, structs.NodeSchedulingIneligible:
	default:
		return fmt.Errorf("invalid scheduling eligibility %q", args.Eligibility)
	}

	// Construct the node event
	args.NodeEvent = structs.NewNodeEvent().SetSubsystem(structs.NodeEventSubsystemCluster)
	if node.SchedulingEligibility == args.Eligibility {
		return nil // Nothing to do
	} else if args.Eligibility == structs.NodeSchedulingEligible {
		args.NodeEvent.SetMessage(NodeEligibilityEventEligible)
	} else {
		args.NodeEvent.SetMessage(NodeEligibilityEventIneligible)
	}

	// Commit this update via Raft
	outErr, index, err := n.srv.raftApply(structs.NodeUpdateEligibilityRequestType, args)
	if err != nil {
		n.logger.Error("eligibility update failed", "error", err)
		return err
	}
	if outErr != nil {
		if err, ok := outErr.(error); ok && err != nil {
			n.logger.Error("eligibility update failed", "error", err)
			return err
		}
	}

	// If the node is transitioning to be eligible, create Node evaluations
	// because there may be a System job registered that should be evaluated.
	if node.SchedulingEligibility == structs.NodeSchedulingIneligible && args.Eligibility == structs.NodeSchedulingEligible {
		evalIDs, evalIndex, err := n.createNodeEvals(args.NodeID, index)
		if err != nil {
			n.logger.Error("eval creation failed", "error", err)
			return err
		}
		reply.EvalIDs = evalIDs
		reply.EvalCreateIndex = evalIndex
	}

	// Set the reply index
	reply.Index = index
	return nil
}
673723
func (m *ExpirationManager) updatePendingInternal(le *leaseEntry, leaseTotal time.Duration) {
	// Check for an existing timer
	pending, ok := m.pending[le.LeaseID]

	// If there is no expiry time, don't do anything
	if le.ExpireTime.IsZero() {
		// if the timer happened to exist, stop the time and delete it from the
		// pending timers.
		if ok {
			pending.timer.Stop()
			delete(m.pending, le.LeaseID)
		}
		return
	}

	// Create entry if it does not exist or reset if it does
	if ok {
		pending.timer.Reset(leaseTotal)
	} else {
		timer := time.AfterFunc(leaseTotal, func() {
			m.expireFunc(m.quitContext, m, le)
		})
		pending = pendingInfo{
			timer: timer,
		}
	}

	// Extend the timer by the lease total
	pending.exportLeaseTimes = m.leaseTimesForExport(le)

	m.pending[le.LeaseID] = pending
}
714671
func (op *updateOp) updateNodeFromAlias(ctx context.Context, sync *NodeSync, node *v1.Node, aliasRange *net.IPNet) error {
	if sync.mode != SyncFromCloud {
		sync.kubeAPI.EmitNodeWarningEvent(node.Name, InvalidModeEvent,
			"Cannot sync from cloud in mode %q", sync.mode)
		return fmt.Errorf("cannot sync from cloud in mode %q", sync.mode)
	}

	klog.V(2).Infof("Updating node spec with alias range, node.PodCIDR = %v", aliasRange)

	if err := sync.set.Occupy(aliasRange); err != nil {
		klog.Errorf("Error occupying range %v for node %v", aliasRange, sync.nodeName)
		return err
	}

	if err := sync.kubeAPI.UpdateNodePodCIDR(ctx, node, aliasRange); err != nil {
		klog.Errorf("Could not update node %q PodCIDR to %v: %v", node.Name, aliasRange, err)
		return err
	}

	klog.V(2).Infof("Node %q PodCIDR set to %v", node.Name, aliasRange)

	if err := sync.kubeAPI.UpdateNodeNetworkUnavailable(node.Name, false); err != nil {
		klog.Errorf("Could not update node NetworkUnavailable status to false: %v", err)
		return err
	}

	klog.V(2).Infof("Updated node %q PodCIDR from cloud alias %v", node.Name, aliasRange)

	return nil
}
494483
func (c *nfsdCollector) updateNFSdReadAheadCacheStats(ch chan<- prometheus.Metric, s *nfs.ReadAheadCache) {
	ch <- prometheus.MustNewConstMetric(
		prometheus.NewDesc(
			prometheus.BuildFQName(namespace, nfsdSubsystem, "read_ahead_cache_size_blocks"),
			"How large the read ahead cache is in blocks.",
			nil,
			nil,
		),
		prometheus.GaugeValue,
		float64(s.CacheSize))
	ch <- prometheus.MustNewConstMetric(
		prometheus.NewDesc(
			prometheus.BuildFQName(namespace, nfsdSubsystem, "read_ahead_cache_not_found_total"),
			"Total number of NFSd read ahead cache not found.",
			nil,
			nil,
		),
		prometheus.CounterValue,
		float64(s.NotFound))
}
93289
func (a *StorageAPI) UpdatePool(p params.StoragePoolArgs) (params.ErrorResults, error) {
	results := params.ErrorResults{
		Results: make([]params.ErrorResult, len(p.Pools)),
	}
	if err := a.checkCanWrite(); err != nil {
		return results, errors.Trace(err)
	}
	for i, pool := range p.Pools {
		err := a.poolManager.Replace(pool.Name, pool.Provider, pool.Attrs)
		if err != nil {
			results.Results[i].Error = common.ServerError(err)
		}
	}
	return results, nil
}
255727
func (ncs *nodeCacheStandard) UpdateUnlinkedDirEntry(
	node Node, newDe data.DirEntry) {
	ncs.lock.Lock()
	defer ncs.lock.Unlock()

	ns, ok := node.Unwrap().(*nodeStandard)
	if !ok {
		return
	}

	ns.core.cachedDe = newDe
}
386189
func (s *StateStore) UpdateNodeDrain(index uint64, nodeID string,
	drain *structs.DrainStrategy, markEligible bool, event *structs.NodeEvent) error {

	txn := s.db.Txn(true)
	defer txn.Abort()
	if err := s.updateNodeDrainImpl(txn, index, nodeID, drain, markEligible, event); err != nil {
		return err
	}
	txn.Commit()
	return nil
}
298957
func (s *StateStore) UpdateNodeStatus(index uint64, nodeID, status string, event *structs.NodeEvent) error {
	txn := s.db.Txn(true)
	defer txn.Abort()

	// Lookup the node
	existing, err := txn.First("nodes", "id", nodeID)
	if err != nil {
		return fmt.Errorf("node lookup failed: %v", err)
	}
	if existing == nil {
		return fmt.Errorf("node not found")
	}

	// Copy the existing node
	existingNode := existing.(*structs.Node)
	copyNode := existingNode.Copy()

	// Add the event if given
	if event != nil {
		appendNodeEvents(index, copyNode, []*structs.NodeEvent{event})
	}

	// Update the status in the copy
	copyNode.Status = status
	copyNode.ModifyIndex = index

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

	txn.Commit()
	return nil
}
848740
func (ar *allocRunner) Update(update *structs.Allocation) {
	select {
	// Drain queued update from the channel if possible, and check the modify
	// index
	case oldUpdate := <-ar.allocUpdatedCh:
		// If the old update is newer than the replacement, then skip the new one
		// and return. This case shouldn't happen, but may in the case of a bug
		// elsewhere inside the system.
		if oldUpdate.AllocModifyIndex > update.AllocModifyIndex {
			ar.logger.Debug("Discarding allocation update due to newer alloc revision in queue",
				"old_modify_index", oldUpdate.AllocModifyIndex,
				"new_modify_index", update.AllocModifyIndex)
			ar.allocUpdatedCh <- oldUpdate
			return
		} else {
			ar.logger.Debug("Discarding allocation update",
				"skipped_modify_index", oldUpdate.AllocModifyIndex,
				"new_modify_index", update.AllocModifyIndex)
		}
	case <-ar.waitCh:
		ar.logger.Trace("AllocRunner has terminated, skipping alloc update",
			"modify_index", update.AllocModifyIndex)
		return
	default:
	}

	// Queue the new update
	ar.allocUpdatedCh <- update
}
968905
func (s *SecurityConfig) UpdateTLSCredentials(certificate *tls.Certificate, issuerInfo *IssuerInfo) error {
	s.mu.Lock()
	defer s.mu.Unlock()
	return s.updateTLSCredentials(certificate, issuerInfo)
}
91217
func (n *NodeDrainer) batchDrainAllocs(allocs []*structs.Allocation) (uint64, error) {
	// Add this to the batch
	n.batcher.Lock()
	n.batcher.updates = append(n.batcher.updates, allocs...)

	// Start a new batch if none
	future := n.batcher.updateFuture
	if future == nil {
		future = structs.NewBatchFuture()
		n.batcher.updateFuture = future
		n.batcher.updateTimer = time.AfterFunc(n.batcher.batchWindow, func() {
			// Get the pending updates
			n.batcher.Lock()
			updates := n.batcher.updates
			future := n.batcher.updateFuture
			n.batcher.updates = nil
			n.batcher.updateFuture = nil
			n.batcher.updateTimer = nil
			n.batcher.Unlock()

			// Perform the batch update
			n.drainAllocs(future, updates)
		})
	}
	n.batcher.Unlock()

	if err := future.Wait(); err != nil {
		return 0, err
	}

	return future.Index(), nil
}
98903
func (m *Model) UpdateLastModelConnection(user names.UserTag) error {
	return m.updateLastModelConnection(user, m.st.nowToTheSecond())
}
354201
func (c *nfsdCollector) updateNFSdRequestsv4Stats(ch chan<- prometheus.Metric, s *nfs.V4Ops) {
	const proto = "4"
	ch <- prometheus.MustNewConstMetric(c.requestsDesc, prometheus.CounterValue,
		float64(s.Access), proto, "Access")
	ch <- prometheus.MustNewConstMetric(c.requestsDesc, prometheus.CounterValue,
		float64(s.Close), proto, "Close")
	ch <- prometheus.MustNewConstMetric(c.requestsDesc, prometheus.CounterValue,
		float64(s.Commit), proto, "Commit")
	ch <- prometheus.MustNewConstMetric(c.requestsDesc, prometheus.CounterValue,
		float64(s.Create), proto, "Create")
	ch <- prometheus.MustNewConstMetric(c.requestsDesc, prometheus.CounterValue,
		float64(s.DelegPurge), proto, "DelegPurge")
	ch <- prometheus.MustNewConstMetric(c.requestsDesc, prometheus.CounterValue,
		float64(s.DelegReturn), proto, "DelegReturn")
	ch <- prometheus.MustNewConstMetric(c.requestsDesc, prometheus.CounterValue,
		float64(s.GetAttr), proto, "GetAttr")
	ch <- prometheus.MustNewConstMetric(c.requestsDesc, prometheus.CounterValue,
		float64(s.GetFH), proto, "GetFH")
	ch <- prometheus.MustNewConstMetric(c.requestsDesc, prometheus.CounterValue,
		float64(s.Link), proto, "Link")
	ch <- prometheus.MustNewConstMetric(c.requestsDesc, prometheus.CounterValue,
		float64(s.Lock), proto, "Lock")
	ch <- prometheus.MustNewConstMetric(c.requestsDesc, prometheus.CounterValue,
		float64(s.Lockt), proto, "Lockt")
	ch <- prometheus.MustNewConstMetric(c.requestsDesc, prometheus.CounterValue,
		float64(s.Locku), proto, "Locku")
	ch <- prometheus.MustNewConstMetric(c.requestsDesc, prometheus.CounterValue,
		float64(s.Lookup), proto, "Lookup")
	ch <- prometheus.MustNewConstMetric(c.requestsDesc, prometheus.CounterValue,
		float64(s.LookupRoot), proto, "LookupRoot")
	ch <- prometheus.MustNewConstMetric(c.requestsDesc, prometheus.CounterValue,
		float64(s.Nverify), proto, "Nverify")
	ch <- prometheus.MustNewConstMetric(c.requestsDesc, prometheus.CounterValue,
		float64(s.Open), proto, "Open")
	ch <- prometheus.MustNewConstMetric(c.requestsDesc, prometheus.CounterValue,
		float64(s.OpenAttr), proto, "OpenAttr")
	ch <- prometheus.MustNewConstMetric(c.requestsDesc, prometheus.CounterValue,
		float64(s.OpenConfirm), proto, "OpenConfirm")
	ch <- prometheus.MustNewConstMetric(c.requestsDesc, prometheus.CounterValue,
		float64(s.OpenDgrd), proto, "OpenDgrd")
	ch <- prometheus.MustNewConstMetric(c.requestsDesc, prometheus.CounterValue,
		float64(s.PutFH), proto, "PutFH")
	ch <- prometheus.MustNewConstMetric(c.requestsDesc, prometheus.CounterValue,
		float64(s.Read), proto, "Read")
	ch <- prometheus.MustNewConstMetric(c.requestsDesc, prometheus.CounterValue,
		float64(s.ReadDir), proto, "ReadDir")
	ch <- prometheus.MustNewConstMetric(c.requestsDesc, prometheus.CounterValue,
		float64(s.ReadLink), proto, "ReadLink")
	ch <- prometheus.MustNewConstMetric(c.requestsDesc, prometheus.CounterValue,
		float64(s.Remove), proto, "Remove")
	ch <- prometheus.MustNewConstMetric(c.requestsDesc, prometheus.CounterValue,
		float64(s.Rename), proto, "Rename")
	ch <- prometheus.MustNewConstMetric(c.requestsDesc, prometheus.CounterValue,
		float64(s.Renew), proto, "Renew")
	ch <- prometheus.MustNewConstMetric(c.requestsDesc, prometheus.CounterValue,
		float64(s.RestoreFH), proto, "RestoreFH")
	ch <- prometheus.MustNewConstMetric(c.requestsDesc, prometheus.CounterValue,
		float64(s.SaveFH), proto, "SaveFH")
	ch <- prometheus.MustNewConstMetric(c.requestsDesc, prometheus.CounterValue,
		float64(s.SecInfo), proto, "SecInfo")
	ch <- prometheus.MustNewConstMetric(c.requestsDesc, prometheus.CounterValue,
		float64(s.SetAttr), proto, "SetAttr")
	ch <- prometheus.MustNewConstMetric(c.requestsDesc, prometheus.CounterValue,
		float64(s.Verify), proto, "Verify")
	ch <- prometheus.MustNewConstMetric(c.requestsDesc, prometheus.CounterValue,
		float64(s.Write), proto, "Write")
	ch <- prometheus.MustNewConstMetric(c.requestsDesc, prometheus.CounterValue,
		float64(s.RelLockOwner), proto, "RelLockOwner")
}
585491
func (q *Query) UpdateNotNull(scan ...interface{}) (Result, error) {
	return q.update(scan, true)
}
979647
func (c *nfsCollector) updateNFSRequestsv2Stats(ch chan<- prometheus.Metric, s *nfs.V2Stats) {
	const proto = "2"

	v := reflect.ValueOf(s).Elem()
	for i := 0; i < v.NumField(); i++ {
		field := v.Field(i)

		ch <- prometheus.MustNewConstMetric(c.nfsProceduresDesc, prometheus.CounterValue,
			float64(field.Uint()), proto, v.Type().Field(i).Name)
	}
}