// networkStats verifies the status of network components and generates a protip
// configuration set to give users hints on how to do various tasks.
438106
func (w *wizard) networkStats() {
	if len(w.servers) == 0 {
		log.Info("No remote machines to gather stats from")
		return
	}
	// Clear out some previous configs to refill from current scan
	w.conf.ethstats = ""
	w.conf.bootnodes = w.conf.bootnodes[:0]

	// Iterate over all the specified hosts and check their status
	var pend sync.WaitGroup

	stats := make(serverStats)
	for server, pubkey := range w.conf.Servers {
		pend.Add(1)

		// Gather the service stats for each server concurrently
		go func(server string, pubkey []byte) {
			defer pend.Done()

			stat := w.gatherStats(server, pubkey, w.servers[server])

			// All status checks complete, report and check next server
			w.lock.Lock()
			defer w.lock.Unlock()

			delete(w.services, server)
			for service := range stat.services {
				w.services[server] = append(w.services[server], service)
			}
			stats[server] = stat
		}(server, pubkey)
	}
	pend.Wait()

	// Print any collected stats and return
	stats.render()
}
408047
func (o *Enterprise) NetworkPerformanceMeasurements(info *bambou.FetchingInfo) (NetworkPerformanceMeasurementsList, *bambou.Error) {

	var list NetworkPerformanceMeasurementsList
	err := bambou.CurrentSession().FetchChildren(o, NetworkPerformanceMeasurementIdentity, &list, info)
	return list, err
}
176324
func hcsStatsToInterfaceStats(stat hcsshim.NetworkStats) (*statsapi.InterfaceStats, error) {
	endpoint, err := hcsshim.GetHNSEndpointByID(stat.EndpointId)
	if err != nil {
		return nil, err
	}

	return &statsapi.InterfaceStats{
		Name:    endpoint.Name,
		RxBytes: &stat.BytesReceived,
		TxBytes: &stat.BytesSent,
	}, nil
}
1217213
func (s *Stack) NICSubnets() map[tcpip.NICID][]tcpip.Subnet {
	s.mu.RLock()
	defer s.mu.RUnlock()

	nics := map[tcpip.NICID][]tcpip.Subnet{}

	for id, nic := range s.nics {
		nics[id] = append(nics[id], nic.Subnets()...)
	}
	return nics
}
242239
func (c *Client) PoolStats() *PoolStats {
	stats := c.connPool.Stats()
	return (*PoolStats)(stats)
}
546881
func (sr *ServicedStatsReporter) updateStats() {
	// Stats for host.
	sr.updateHostStats()
	// Stats for the containers.
	states, err := zkservice.GetHostStates(sr.conn, "", sr.hostID)
	if err != nil {
		plog.WithFields(logrus.Fields{
			"conn":   sr.conn,
			"hostID": sr.hostID,
		}).WithError(err).Error("Could not get host states from Zookeeper")
	}

	for _, rs := range states {
		if rs.ContainerID != "" {

			containerRegistry := sr.getOrCreateContainerRegistry(rs.ServiceID, rs.InstanceID)
			stats, err := sr.docker.GetContainerStats(rs.ContainerID, 30*time.Second)
			if err != nil || stats == nil { //stats may be nil if service is shutting down
				plog.WithFields(logrus.Fields{
					"serviceID":  rs.ServiceID,
					"instanceID": rs.InstanceID,
				}).WithError(err).Warn("Couldn't get stats from docker")
				continue
			}

			// Check to see if we have the previous stats for this running instance
			usePreviousStats := true
			key := rs.ContainerID
			if _, found := sr.previousStats[key]; !found {
				sr.previousStats[key] = make(map[string]uint64)
				usePreviousStats = false
			}

			// CPU Stats
			// TODO: Consolidate this into a single object that both ISVCS and non-ISVCS can use
			var (
				kernelCPUPercent float64
				userCPUPercent   float64
				totalCPUChange   uint64
			)

			kernelCPU := stats.CPUStats.CPUUsage.UsageInKernelmode
			userCPU := stats.CPUStats.CPUUsage.UsageInUsermode
			totalCPU := stats.CPUStats.SystemCPUUsage

			// Total CPU Cycles
			previousTotalCPU, found := sr.previousStats[key]["totalCPU"]
			if found {
				if totalCPU <= previousTotalCPU {
					plog.WithFields(logrus.Fields{
						"totalCPU":         totalCPU,
						"previousTotalCPU": previousTotalCPU,
					}).Debug("Change in total CPU usage was nonpositive, skipping CPU stats update")
					usePreviousStats = false
				} else {
					totalCPUChange = totalCPU - previousTotalCPU
				}
			} else {
				usePreviousStats = false
			}
			sr.previousStats[key]["totalCPU"] = totalCPU

			// CPU Cycles in Kernel mode
			if previousKernelCPU, found := sr.previousStats[key]["kernelCPU"]; found && usePreviousStats {
				kernelCPUChange := kernelCPU - previousKernelCPU
				kernelCPUPercent = (float64(kernelCPUChange) / float64(totalCPUChange)) * float64(len(stats.CPUStats.CPUUsage.PercpuUsage)) * 100.0
			} else {
				usePreviousStats = false
			}
			sr.previousStats[key]["kernelCPU"] = kernelCPU

			// CPU Cycles in User mode
			if previousUserCPU, found := sr.previousStats[key]["userCPU"]; found && usePreviousStats {
				userCPUChange := userCPU - previousUserCPU
				userCPUPercent = (float64(userCPUChange) / float64(totalCPUChange)) * float64(len(stats.CPUStats.CPUUsage.PercpuUsage)) * 100.0
			} else {
				usePreviousStats = false
			}
			sr.previousStats[key]["userCPU"] = userCPU

			// Update CPU metrics
			if usePreviousStats {
				metrics.GetOrRegisterGaugeFloat64("docker.usageinkernelmode", containerRegistry).Update(kernelCPUPercent)
				metrics.GetOrRegisterGaugeFloat64("docker.usageinusermode", containerRegistry).Update(userCPUPercent)
			} else {
				plog.WithFields(logrus.Fields{
					"serviceID":  rs.ServiceID,
					"instanceID": rs.InstanceID,
				}).Debug("Skipping CPU stats, no previous values to compare to")
			}

			// Memory Stats
			pgFault := int64(stats.MemoryStats.Stats.Pgfault)
			totalRSS := int64(stats.MemoryStats.Stats.TotalRss)
			cache := int64(stats.MemoryStats.Stats.Cache)
			if pgFault < 0 || totalRSS < 0 || cache < 0 {
				plog.WithFields(logrus.Fields{
					"serviceID":  rs.ServiceID,
					"instanceID": rs.InstanceID,
				}).Debug("Memory metric value too big for int64")
			}
			metrics.GetOrRegisterGauge("cgroup.memory.pgmajfault", containerRegistry).Update(pgFault)
			metrics.GetOrRegisterGauge("cgroup.memory.totalrss", containerRegistry).Update(totalRSS)
			metrics.GetOrRegisterGauge("cgroup.memory.cache", containerRegistry).Update(cache)

		} else {
			plog.WithFields(logrus.Fields{
				"serviceID":  rs.ServiceID,
				"instanceID": rs.InstanceID,
			}).Debug("Skipping stats update, no container ID exists")
		}
	}
	// Clean out old container registries
	sr.removeStaleRegistries(states)
}
14880
func newStats() stats {
	s := stats{}
	s.ChannelStats = make(map[string]eventIDStat)
	return s
}
861749
func readSysfsNetworkStats(ethInterface, statsFile string) (uint64, error) {
	data, err := ioutil.ReadFile(filepath.Join("/sys/class/net", ethInterface, "statistics", statsFile))
	if err != nil {
		return 0, err
	}
	return strconv.ParseUint(strings.TrimSpace(string(data)), 10, 64)
}
1170922
func (o *Me) NetworkLayouts(info *bambou.FetchingInfo) (NetworkLayoutsList, *bambou.Error) {

	var list NetworkLayoutsList
	err := bambou.CurrentSession().FetchChildren(o, NetworkLayoutIdentity, &list, info)
	return list, err
}
932604
func hcsStatsToNetworkStats(timestamp time.Time, hcsStats []hcsshim.NetworkStats) *statsapi.NetworkStats {
	result := &statsapi.NetworkStats{
		Time:       metav1.NewTime(timestamp),
		Interfaces: make([]statsapi.InterfaceStats, 0),
	}

	adapters := sets.NewString()
	for _, stat := range hcsStats {
		iStat, err := hcsStatsToInterfaceStats(stat)
		if err != nil {
			klog.Warningf("Failed to get HNS endpoint %q with error '%v', continue to get stats for other endpoints", stat.EndpointId, err)
			continue
		}

		// Only count each adapter once.
		if adapters.Has(iStat.Name) {
			continue
		}

		result.Interfaces = append(result.Interfaces, *iStat)
		adapters.Insert(iStat.Name)
	}

	// TODO(feiskyer): add support of multiple interfaces for getting default interface.
	if len(result.Interfaces) > 0 {
		result.InterfaceStats = result.Interfaces[0]
	}

	return result
}
417844
func (s *Status) RaftStats(args struct{}, reply *autopilot.ServerStats) error {
	stats := s.srv.raft.Stats()

	var err error
	reply.LastContact = stats["last_contact"]
	reply.LastIndex, err = strconv.ParseUint(stats["last_log_index"], 10, 64)
	if err != nil {
		return fmt.Errorf("error parsing server's last_log_index value: %s", err)
	}
	reply.LastTerm, err = strconv.ParseUint(stats["last_log_term"], 10, 64)
	if err != nil {
		return fmt.Errorf("error parsing server's last_log_term value: %s", err)
	}

	return nil
}
615557
func ConnectStats(stats adapter.StatsAPI) (*StatsConnection, error) {
	c := newStatsConnection(stats)

	if err := c.connectClient(); err != nil {
		return nil, err
	}

	return c, nil
}
733985
func (c *Client) Stats() ClientStats {
	c.mutex.Lock()
	defer c.mutex.Unlock()

	return c.stats
}
1373948
func (parser *StandardResultParser) ParseStats(response *SolrResponse, sr *SolrResult) {
	if stats, ok := response.Response["stats"].(map[string]interface{}); ok {
		sr.Stats = stats
	}
}
78742
func NewStatus(nodeHeight uint32, conns int64, apiVersion int, dcrdataVersion, netName string) *Status {
	return &Status{
		height:          nodeHeight,
		nodeConnections: conns,
		api: APIStatus{
			APIVersion:     apiVersion,
			DcrdataVersion: dcrdataVersion,
			NetworkName:    netName,
		},
	}
}
23087
func (c *Client) setGaugeForMemoryStats(nodeID string, hStats *stats.HostStats) {
	if !c.config.DisableTaggedMetrics {
		metrics.SetGaugeWithLabels([]string{"client", "host", "memory", "total"}, float32(hStats.Memory.Total), c.baseLabels)
		metrics.SetGaugeWithLabels([]string{"client", "host", "memory", "available"}, float32(hStats.Memory.Available), c.baseLabels)
		metrics.SetGaugeWithLabels([]string{"client", "host", "memory", "used"}, float32(hStats.Memory.Used), c.baseLabels)
		metrics.SetGaugeWithLabels([]string{"client", "host", "memory", "free"}, float32(hStats.Memory.Free), c.baseLabels)
	}

	if c.config.BackwardsCompatibleMetrics {
		metrics.SetGauge([]string{"client", "host", "memory", nodeID, "total"}, float32(hStats.Memory.Total))
		metrics.SetGauge([]string{"client", "host", "memory", nodeID, "available"}, float32(hStats.Memory.Available))
		metrics.SetGauge([]string{"client", "host", "memory", nodeID, "used"}, float32(hStats.Memory.Used))
		metrics.SetGauge([]string{"client", "host", "memory", nodeID, "free"}, float32(hStats.Memory.Free))
	}
}
1140816
func (node *Node) RequestStats(policy *InfoPolicy) (map[string]string, error) {
	infoMap, err := node.RequestInfo(policy, "statistics")
	if err != nil {
		return nil, err
	}

	res := map[string]string{}

	v, exists := infoMap["statistics"]
	if !exists {
		return res, nil
	}

	values := strings.Split(v, ";")
	for i := range values {
		kv := strings.Split(values[i], "=")
		if len(kv) > 1 {
			res[kv[0]] = kv[1]
		}
	}

	return res, nil
}