// updateNFSNetworkStats collects statistics for network packets/connections.
768735
func (c *nfsCollector) updateNFSNetworkStats(ch chan<- prometheus.Metric, s *nfs.Network) {
	ch <- prometheus.MustNewConstMetric(c.nfsNetReadsDesc, prometheus.CounterValue,
		float64(s.UDPCount), "udp")
	ch <- prometheus.MustNewConstMetric(c.nfsNetReadsDesc, prometheus.CounterValue,
		float64(s.TCPCount), "tcp")
	ch <- prometheus.MustNewConstMetric(c.nfsNetConnectionsDesc, prometheus.CounterValue,
		float64(s.TCPConnect))
}
429773
func (c *nfsdCollector) updateNFSdReplyCacheStats(ch chan<- prometheus.Metric, s *nfs.ReplyCache) {
	ch <- prometheus.MustNewConstMetric(
		prometheus.NewDesc(
			prometheus.BuildFQName(namespace, nfsdSubsystem, "reply_cache_hits_total"),
			"Total number of NFSd Reply Cache hits (client lost server response).",
			nil,
			nil,
		),
		prometheus.CounterValue,
		float64(s.Hits))
	ch <- prometheus.MustNewConstMetric(
		prometheus.NewDesc(
			prometheus.BuildFQName(namespace, nfsdSubsystem, "reply_cache_misses_total"),
			"Total number of NFSd Reply Cache an operation that requires caching (idempotent).",
			nil,
			nil,
		),
		prometheus.CounterValue,
		float64(s.Misses))
	ch <- prometheus.MustNewConstMetric(
		prometheus.NewDesc(
			prometheus.BuildFQName(namespace, nfsdSubsystem, "reply_cache_nocache_total"),
			"Total number of NFSd Reply Cache non-idempotent operations (rename/delete/…).",
			nil,
			nil,
		),
		prometheus.CounterValue,
		float64(s.NoCache))
}
583846
func (n *Node) UpdateStatus(args *structs.NodeUpdateStatusRequest, reply *structs.NodeUpdateResponse) error {
	if done, err := n.srv.forward("Node.UpdateStatus", args, args, reply); done {
		// We have a valid node connection since there is no error from the
		// forwarded server, so add the mapping to cache the
		// connection and allow the server to send RPCs to the client.
		if err == nil && n.ctx != nil && n.ctx.NodeID == "" {
			n.ctx.NodeID = args.NodeID
			n.srv.addNodeConn(n.ctx)
		}

		return err
	}
	defer metrics.MeasureSince([]string{"nomad", "client", "update_status"}, time.Now())

	// Verify the arguments
	if args.NodeID == "" {
		return fmt.Errorf("missing node ID for client status update")
	}
	if !structs.ValidNodeStatus(args.Status) {
		return fmt.Errorf("invalid status for node")
	}

	// Look for the node
	snap, err := n.srv.fsm.State().Snapshot()
	if err != nil {
		return err
	}

	ws := memdb.NewWatchSet()
	node, err := snap.NodeByID(ws, args.NodeID)
	if err != nil {
		return err
	}
	if node == nil {
		return fmt.Errorf("node not found")
	}

	// We have a valid node connection, so add the mapping to cache the
	// connection and allow the server to send RPCs to the client. We only cache
	// the connection if it is not being forwarded from another server.
	if n.ctx != nil && n.ctx.NodeID == "" && !args.IsForwarded() {
		n.ctx.NodeID = args.NodeID
		n.srv.addNodeConn(n.ctx)
	}

	// XXX: Could use the SecretID here but have to update the heartbeat system
	// to track SecretIDs.

	// Update the timestamp of when the node status was updated
	node.StatusUpdatedAt = time.Now().Unix()

	// Commit this update via Raft
	var index uint64
	if node.Status != args.Status {
		// Attach an event if we are updating the node status to ready when it
		// is down via a heartbeat
		if node.Status == structs.NodeStatusDown && args.NodeEvent == nil {
			args.NodeEvent = structs.NewNodeEvent().
				SetSubsystem(structs.NodeEventSubsystemCluster).
				SetMessage(NodeHeartbeatEventReregistered)
		}

		_, index, err = n.srv.raftApply(structs.NodeUpdateStatusRequestType, args)
		if err != nil {
			n.logger.Error("status update failed", "error", err)
			return err
		}
		reply.NodeModifyIndex = index
	}

	// Check if we should trigger evaluations
	transitionToReady := transitionedToReady(args.Status, node.Status)
	if structs.ShouldDrainNode(args.Status) || transitionToReady {
		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
	}

	// Check if we need to setup a heartbeat
	switch args.Status {
	case structs.NodeStatusDown:
		// Determine if there are any Vault accessors on the node
		accessors, err := n.srv.State().VaultAccessorsByNode(ws, args.NodeID)
		if err != nil {
			n.logger.Error("looking up accessors for node failed", "node_id", args.NodeID, "error", err)
			return err
		}

		if l := len(accessors); l != 0 {
			n.logger.Debug("revoking accessors on node due to down state", "num_accessors", l, "node_id", args.NodeID)
			if err := n.srv.vault.RevokeTokens(context.Background(), accessors, true); err != nil {
				n.logger.Error("revoking accessors for node failed", "node_id", args.NodeID, "error", err)
				return err
			}
		}
	default:
		ttl, err := n.srv.resetHeartbeatTimer(args.NodeID)
		if err != nil {
			n.logger.Error("heartbeat reset failed", "error", err)
			return err
		}
		reply.HeartbeatTTL = ttl
	}

	// Set the reply index and leader
	reply.Index = index
	n.srv.peerLock.RLock()
	defer n.srv.peerLock.RUnlock()
	if err := n.constructNodeServerInfoResponse(snap, reply); err != nil {
		n.logger.Error("failed to populate NodeUpdateResponse", "error", err)
		return err
	}

	return nil
}
654324
func (c *nfsCollector) updateNFSClientRPCStats(ch chan<- prometheus.Metric, s *nfs.ClientRPC) {
	ch <- prometheus.MustNewConstMetric(c.nfsRPCOperationsDesc, prometheus.CounterValue,
		float64(s.RPCCount))
	ch <- prometheus.MustNewConstMetric(c.nfsRPCRetransmissionsDesc, prometheus.CounterValue,
		float64(s.Retransmissions))
	ch <- prometheus.MustNewConstMetric(c.nfsRPCAuthenticationRefreshesDesc, prometheus.CounterValue,
		float64(s.AuthRefreshes))
}
1058965
func (b *buildStats) update(p page.Page) {
	if p.Draft() {
		b.draftCount++
	}

	if resource.IsFuture(p) {
		b.futureCount++
	}

	if resource.IsExpired(p) {
		b.expiredCount++
	}
}
1158076
func updateSandboxNetworkSettings(c *container.Container, sb libnetwork.Sandbox) error {
	c.NetworkSettings.SandboxID = sb.ID()
	c.NetworkSettings.SandboxKey = sb.Key()
	return nil
}
934047
func (r Network_Vlan_Firewall) GetNetworkFirewallUpdateRequests() (resp []datatypes.Network_Firewall_Update_Request, err error) {
	err = r.Session.DoRequest("SoftLayer_Network_Vlan_Firewall", "getNetworkFirewallUpdateRequests", nil, &r.Options, &resp)
	return
}
697871
func (c *Client) updateConns(conns []*conn) {
	c.connsMu.Lock()

	newConns := make([]*conn, 0)

	// Build up new connections:
	// If we find an existing connection, use that (including no. of failures etc.).
	// If we find a new connection, add it.
	for _, conn := range conns {
		var found bool
		for _, oldConn := range c.conns {
			if oldConn.NodeID() == conn.NodeID() {
				// Take over the old connection
				newConns = append(newConns, oldConn)
				found = true
				break
			}
		}
		if !found {
			// New connection didn't exist, so add it to our list of new conns.
			c.errorf("elastic: %s joined the cluster", conn.URL())
			newConns = append(newConns, conn)
		}
	}

	c.conns = newConns
	c.cindex = -1
	c.connsMu.Unlock()
}
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
}
51599
func (rd *remoteRelationData) updateIngressNetworks(cidrs []string) error {
	logger.Debugf("ingress cidrs for %v: %+v", rd.tag, cidrs)
	change := &remoteRelationNetworkChange{
		relationTag:         rd.tag,
		localApplicationTag: rd.localApplicationTag,
		networks:            set.NewStrings(cidrs...),
		ingressRequired:     len(cidrs) > 0,
	}
	select {
	case <-rd.catacomb.Dying():
		return rd.catacomb.ErrDying()
	case rd.fw.localRelationsChange <- change:
	}
	return nil
}
1224826
func (h *Handle) UpdateTableStats(tables []*statistics.Table, deletedIDs []int64) {
	newCache := h.copyFromOldCache()
	for _, tbl := range tables {
		id := tbl.PhysicalID
		newCache[id] = tbl
	}
	for _, id := range deletedIDs {
		delete(newCache, id)
	}
	h.StatsCache.Store(newCache)
}
95461
func (m *model) ConnectionStats() map[string]interface{} {
	m.fmut.RLock()
	m.pmut.RLock()
	defer m.pmut.RUnlock()
	defer m.fmut.RUnlock()

	res := make(map[string]interface{})
	devs := m.cfg.Devices()
	conns := make(map[string]ConnectionInfo, len(devs))
	for device, deviceCfg := range devs {
		hello := m.helloMessages[device]
		versionString := hello.ClientVersion
		if hello.ClientName != "syncthing" {
			versionString = hello.ClientName + " " + hello.ClientVersion
		}
		ci := ConnectionInfo{
			ClientVersion: strings.TrimSpace(versionString),
			Paused:        deviceCfg.Paused,
		}
		if conn, ok := m.conn[device]; ok {
			ci.Type = conn.Type()
			ci.Crypto = conn.Crypto()
			ci.Connected = ok
			ci.Statistics = conn.Statistics()
			if addr := conn.RemoteAddr(); addr != nil {
				ci.Address = addr.String()
			}
		}

		conns[device.String()] = ci
	}

	res["connections"] = conns

	in, out := protocol.TotalInOut()
	res["total"] = ConnectionInfo{
		Statistics: protocol.Statistics{
			At:            time.Now(),
			InBytesTotal:  in,
			OutBytesTotal: out,
		},
	}

	return res
}
122283
func (o HostNetworkSystem) UpdatePhysicalNicLinkSpeed(ctx context.Context, device string, linkSpeed *types.PhysicalNicLinkInfo) error {
	req := types.UpdatePhysicalNicLinkSpeed{
		This:      o.Reference(),
		Device:    device,
		LinkSpeed: linkSpeed,
	}

	_, err := methods.UpdatePhysicalNicLinkSpeed(ctx, o.c, &req)
	if err != nil {
		return err
	}

	return nil
}
945460
func (s *Stat) NetIOStats() []*NetIOStats {
	s.Lock()
	defer s.Unlock()

	var res []*NetIOStats

	do(func() {
		var nSize C.size_t
		var cArray *C.sg_network_io_stats = C.sg_get_network_io_stats_diff(&nSize)
		length := int(nSize)
		slice := (*[1 << 16]C.sg_network_io_stats)(unsafe.Pointer(cArray))[:length:length]

		for _, v := range slice {
			n := &NetIOStats{
				IntName:    C.GoString(v.interface_name),
				TX:         int(v.tx),
				RX:         int(v.rx),
				IPackets:   int(v.ipackets),
				OPackets:   int(v.opackets),
				IErrors:    int(v.ierrors),
				OErrors:    int(v.oerrors),
				Collisions: int(v.collisions),
				Period:     time.Duration(int(v.systime)) * time.Second,
				TimeTaken:  time.Now(),
			}

			res = append(res, n)
		}
	})
	return res
}
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)
	}
}
1121276
func (observer *Observer) UpdateQueueStats(queue string) {
	queueStats := &QueueStat{ConsumerStats: make(map[string]*ConsumerStat)}

	queueStats.InputRateSecond = observer.fetchStat(queueInputRateKey(queue), 1)
	queueStats.InputSizeSecond = observer.fetchStat(queueInputSizeKey(queue), 1)
	queueStats.FailSizeSecond = observer.fetchStat(queueFailedSizeKey(queue), 1)

	queueStats.InputRateMinute = observer.fetchStat(queueInputRateKey(queue), 60)
	queueStats.InputSizeMinute = observer.fetchStat(queueInputSizeKey(queue), 60)
	queueStats.FailSizeMinute = observer.fetchStat(queueFailedSizeKey(queue), 60)

	queueStats.InputRateHour = observer.fetchStat(queueInputRateKey(queue), 3600)
	queueStats.InputSizeHour = observer.fetchStat(queueInputSizeKey(queue), 3600)
	queueStats.FailSizeHour = observer.fetchStat(queueFailedSizeKey(queue), 3600)

	queueStats.WorkRateSecond = 0
	queueStats.WorkRateMinute = 0
	queueStats.WorkRateHour = 0

	consumers, err := observer.getConsumers(queue)
	if err != nil {
		log.Fatalf("ERROR FETCHING CONSUMERS for %s %s", queue, err.Error())
		return
	}

	for _, consumer := range consumers {
		stat := &ConsumerStat{}

		stat.WorkRateSecond = observer.fetchStat(consumerWorkingRateKey(queue, consumer), 1)
		stat.WorkRateMinute = observer.fetchStat(consumerWorkingRateKey(queue, consumer), 60)
		stat.WorkRateHour = observer.fetchStat(consumerWorkingRateKey(queue, consumer), 3600)

		queueStats.WorkRateSecond += stat.WorkRateSecond
		queueStats.WorkRateMinute += stat.WorkRateMinute
		queueStats.WorkRateHour += stat.WorkRateHour

		queueStats.ConsumerStats[consumer] = stat
	}

	observer.Stats[queue] = queueStats
}
233573
func (st *HTTPStats) updateStats(r *http.Request, w *httpResponseRecorder, durationSecs float64) {
	// A successful request has a 2xx response code
	successReq := (w.respStatusCode >= 200 && w.respStatusCode < 300)
	// Update stats according to method verb
	switch r.Method {
	case "HEAD":
		st.totalHEADs.Counter.Inc()
		st.totalHEADs.Duration.Add(durationSecs)
		if successReq {
			st.successHEADs.Counter.Inc()
			st.successHEADs.Duration.Add(durationSecs)
		}
	case "GET":
		st.totalGETs.Counter.Inc()
		st.totalGETs.Duration.Add(durationSecs)
		if successReq {
			st.successGETs.Counter.Inc()
			st.successGETs.Duration.Add(durationSecs)
		}
	case "PUT":
		st.totalPUTs.Counter.Inc()
		st.totalPUTs.Duration.Add(durationSecs)
		if successReq {
			st.successPUTs.Counter.Inc()
			st.totalPUTs.Duration.Add(durationSecs)
		}
	case "POST":
		st.totalPOSTs.Counter.Inc()
		st.totalPOSTs.Duration.Add(durationSecs)
		if successReq {
			st.successPOSTs.Counter.Inc()
			st.totalPOSTs.Duration.Add(durationSecs)
		}
	case "DELETE":
		st.totalDELETEs.Counter.Inc()
		st.totalDELETEs.Duration.Add(durationSecs)
		if successReq {
			st.successDELETEs.Counter.Inc()
			st.successDELETEs.Duration.Add(durationSecs)
		}
	}
	// Increment the prometheus http request response histogram with appropriate label
	httpRequestsDuration.With(prometheus.Labels{"request_type": r.Method}).Observe(durationSecs)
}