// hcsStatsToInterfaceStats converts hcsshim.NetworkStats to statsapi.InterfaceStats.
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
}
668492
func instanceNetworkInterfaces(
	ctx context.ProviderCallContext,
	resourceGroup string,
	nicClient network.InterfacesClient,
) (map[instance.Id][]network.Interface, error) {
	sdkCtx := stdcontext.Background()
	nicsResult, err := nicClient.ListComplete(sdkCtx, resourceGroup)
	if err != nil {
		return nil, errorutils.HandleCredentialError(errors.Annotate(err, "listing network interfaces"), ctx)
	}
	if nicsResult.Response().IsEmpty() {
		return nil, nil
	}
	instanceNics := make(map[instance.Id][]network.Interface)
	for ; nicsResult.NotDone(); err = nicsResult.NextWithContext(sdkCtx) {
		nic := nicsResult.Value()
		instanceId := instance.Id(to.String(nic.Tags[jujuMachineNameTag]))
		instanceNics[instanceId] = append(instanceNics[instanceId], nic)
	}
	return instanceNics, nil
}
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)
}
709882
func addHTTPStatusMetricsToComponent(component newrelic_platform_go.IComponent, statusCounters map[int]metrics.Counter) {
	for statusCode, counter := range statusCounters {
		component.AddMetrica(&counterByStatusMetrica{
			counter: counter,
			name:    fmt.Sprintf("http/status/%d", statusCode),
			units:   "count",
		})
	}
}
1347403
func (c *Client) emitStats() {
	// Determining NodeClass to be emitted
	var emittedNodeClass string
	if emittedNodeClass = c.Node().NodeClass; emittedNodeClass == "" {
		emittedNodeClass = "none"
	}

	// Assign labels directly before emitting stats so the information expected
	// is ready
	c.baseLabels = []metrics.Label{
		{Name: "node_id", Value: c.NodeID()},
		{Name: "datacenter", Value: c.Datacenter()},
		{Name: "node_class", Value: emittedNodeClass},
	}

	// Start collecting host stats right away and then keep collecting every
	// collection interval
	next := time.NewTimer(0)
	defer next.Stop()
	for {
		select {
		case <-next.C:
			err := c.hostStatsCollector.Collect()
			next.Reset(c.config.StatsCollectionInterval)
			if err != nil {
				c.logger.Warn("error fetching host resource usage stats", "error", err)
				continue
			}

			// Publish Node metrics if operator has opted in
			if c.config.PublishNodeMetrics {
				c.emitHostStats()
			}

			c.emitClientMetrics()
		case <-c.shutdownCh:
			return
		}
	}
}
1226207
func getNetworkInterfaceStats(interfaceName string) (*NetworkInterface, error) {
	out := &NetworkInterface{Name: interfaceName}
	// This can happen if the network runtime information is missing - possible if the
	// container was created by an old version of libcontainer.
	if interfaceName == "" {
		return out, nil
	}
	type netStatsPair struct {
		// Where to write the output.
		Out *uint64
		// The network stats file to read.
		File string
	}
	// Ingress for host veth is from the container. Hence tx_bytes stat on the host veth is actually number of bytes received by the container.
	netStats := []netStatsPair{
		{Out: &out.RxBytes, File: "tx_bytes"},
		{Out: &out.RxPackets, File: "tx_packets"},
		{Out: &out.RxErrors, File: "tx_errors"},
		{Out: &out.RxDropped, File: "tx_dropped"},

		{Out: &out.TxBytes, File: "rx_bytes"},
		{Out: &out.TxPackets, File: "rx_packets"},
		{Out: &out.TxErrors, File: "rx_errors"},
		{Out: &out.TxDropped, File: "rx_dropped"},
	}
	for _, netStat := range netStats {
		data, err := readSysfsNetworkStats(interfaceName, netStat.File)
		if err != nil {
			return nil, err
		}
		*(netStat.Out) = data
	}
	return out, nil
}
493233
func (p *criStatsProvider) ImageFsStats() (*statsapi.FsStats, error) {
	resp, err := p.imageService.ImageFsInfo()
	if err != nil {
		return nil, err
	}

	// CRI may return the stats of multiple image filesystems but we only
	// return the first one.
	//
	// TODO(yguo0905): Support returning stats of multiple image filesystems.
	for _, fs := range resp {
		s := &statsapi.FsStats{
			Time:      metav1.NewTime(time.Unix(0, fs.Timestamp)),
			UsedBytes: &fs.UsedBytes.Value,
		}
		if fs.InodesUsed != nil {
			s.InodesUsed = &fs.InodesUsed.Value
		}
		imageFsInfo := p.getFsInfo(fs.GetFsId())
		if imageFsInfo != nil {
			// The image filesystem id is unknown to the local node or there's
			// an error on retrieving the stats. In these cases, we omit those
			// stats and return the best-effort partial result. See
			// https://github.com/kubernetes/heapster/issues/1793.
			s.AvailableBytes = &imageFsInfo.Available
			s.CapacityBytes = &imageFsInfo.Capacity
			s.InodesFree = imageFsInfo.InodesFree
			s.Inodes = imageFsInfo.Inodes
		}
		return s, nil
	}

	return nil, fmt.Errorf("imageFs information is unavailable")
}
579573
func StaticStats(out []*DeviceGroupStats) StatsFn {
	return func(ctx context.Context, intv time.Duration) (<-chan *StatsResponse, error) {
		outCh := make(chan *StatsResponse, 1)

		go func() {
			ticker := time.NewTimer(0)
			for {
				select {
				case <-ctx.Done():
					return
				case <-ticker.C:
					ticker.Reset(intv)
				}

				outCh <- &StatsResponse{
					Groups: out,
				}
			}
		}()

		return outCh, nil
	}
}
328687
func (nc *Conn) Stats() Statistics {
	// Stats are updated either under connection's mu or subsMu mutexes.
	// Lock both to safely get them.
	nc.mu.Lock()
	nc.subsMu.RLock()
	stats := Statistics{
		InMsgs:     nc.InMsgs,
		InBytes:    nc.InBytes,
		OutMsgs:    nc.OutMsgs,
		OutBytes:   nc.OutBytes,
		Reconnects: nc.Reconnects,
	}
	nc.subsMu.RUnlock()
	nc.mu.Unlock()
	return stats
}
684452
func (*HandlerT) GcStats() *debug.GCStats {
	s := new(debug.GCStats)
	debug.ReadGCStats(s)
	return s
}
733985
func (c *Client) Stats() ClientStats {
	c.mutex.Lock()
	defer c.mutex.Unlock()

	return c.stats
}
431072
func (c *Client) HTTPStats() *httputil.StatsTransport {
	st, _ := c.httpClient.Transport.(*httputil.StatsTransport)
	return st
}
1054118
func (i *instanceManager) DeviceStats(d *structs.AllocatedDeviceResource) *device.DeviceGroupStats {
	i.deviceStatsLock.RLock()
	defer i.deviceStatsLock.RUnlock()

	// Find the device in question and then gather the instance statistics we
	// are interested in
	for _, group := range i.deviceStats {
		if group.Vendor != d.Vendor || group.Type != d.Type || group.Name != d.Name {
			continue
		}

		// We found the group we want so now grab the instance stats
		out := &device.DeviceGroupStats{
			Vendor:        d.Vendor,
			Type:          d.Type,
			Name:          d.Name,
			InstanceStats: make(map[string]*device.DeviceStats, len(d.DeviceIDs)),
		}

		for _, id := range d.DeviceIDs {
			out.InstanceStats[id] = group.InstanceStats[id]
		}

		return out
	}

	return nil
}
158318
func (s *Server) reportStats() {
	_ = metrics.ReportOne(s.opts.traceClient,
		ssf.Gauge("proxy.active_goroutines", float32(atomic.LoadInt64(s.activeProxyHandlers)), globalProtocolTags))
}
249927
func (daemon *Daemon) GetContainerStats(container *container.Container) (*types.StatsJSON, error) {
	stats, err := daemon.stats(container)
	if err != nil {
		return nil, err
	}

	// We already have the network stats on Windows directly from HCS.
	if !container.Config.NetworkDisabled && runtime.GOOS != "windows" {
		if stats.Networks, err = daemon.getNetworkStats(container); err != nil {
			return nil, err
		}
	}

	return stats, nil
}
754557
func (c *StatsConnection) GetNodeStats() (*api.NodeStats, error) {
	stats, err := c.statsClient.DumpStats(NodeStatsPrefix)
	if err != nil {
		return nil, err
	}

	nodeStats := &api.NodeStats{}

	var setPerNode = func(perNode []uint64, fn func(c *api.NodeCounters, v uint64)) {
		if nodeStats.Nodes == nil {
			nodeStats.Nodes = make([]api.NodeCounters, len(perNode))
			for i := range perNode {
				nodeStats.Nodes[i].NodeIndex = uint32(i)
			}
		}
		for i, v := range perNode {
			if len(nodeStats.Nodes) <= i {
				break
			}
			nodeCounters := nodeStats.Nodes[i]
			fn(&nodeCounters, v)
			nodeStats.Nodes[i] = nodeCounters
		}
	}

	for _, stat := range stats {
		switch stat.Name {
		case NodeStats_Names:
			if names, ok := stat.Data.(adapter.NameStat); !ok {
				return nil, fmt.Errorf("invalid stat type for %s", stat.Name)
			} else {
				if nodeStats.Nodes == nil {
					nodeStats.Nodes = make([]api.NodeCounters, len(names))
					for i := range names {
						nodeStats.Nodes[i].NodeIndex = uint32(i)
					}
				}
				for i, name := range names {
					nodeStats.Nodes[i].NodeName = string(name)
				}
			}
		case NodeStats_Clocks:
			setPerNode(reduceSimpleCounterStat(stat.Data), func(c *api.NodeCounters, v uint64) {
				c.Clocks = v
			})
		case NodeStats_Vectors:
			setPerNode(reduceSimpleCounterStat(stat.Data), func(c *api.NodeCounters, v uint64) {
				c.Vectors = v
			})
		case NodeStats_Calls:
			setPerNode(reduceSimpleCounterStat(stat.Data), func(c *api.NodeCounters, v uint64) {
				c.Calls = v
			})
		case NodeStats_Suspends:
			setPerNode(reduceSimpleCounterStat(stat.Data), func(c *api.NodeCounters, v uint64) {
				c.Suspends = v
			})
		}
	}

	return nodeStats, nil
}
1227307
func checkEthstats(client *sshClient, network string) (*ethstatsInfos, error) {
	// Inspect a possible ethstats container on the host
	infos, err := inspectContainer(client, fmt.Sprintf("%s_ethstats_1", network))
	if err != nil {
		return nil, err
	}
	if !infos.running {
		return nil, ErrServiceOffline
	}
	// Resolve the port from the host, or the reverse proxy
	port := infos.portmap["3000/tcp"]
	if port == 0 {
		if proxy, _ := checkNginx(client, network); proxy != nil {
			port = proxy.port
		}
	}
	if port == 0 {
		return nil, ErrNotExposed
	}
	// Resolve the host from the reverse-proxy and configure the connection string
	host := infos.envvars["VIRTUAL_HOST"]
	if host == "" {
		host = client.server
	}
	secret := infos.envvars["WS_SECRET"]
	config := fmt.Sprintf("%s@%s", secret, host)
	if port != 80 && port != 443 {
		config += fmt.Sprintf(":%d", port)
	}
	// Retrieve the IP blacklist
	banned := strings.Split(infos.envvars["BANNED"], ",")

	// Run a sanity check to see if the port is reachable
	if err = checkPort(host, port); err != nil {
		log.Warn("Ethstats service seems unreachable", "server", host, "port", port, "err", err)
	}
	// Container available, assemble and return the useful infos
	return &ethstatsInfos{
		host:   host,
		port:   port,
		secret: secret,
		config: config,
		banned: banned,
	}, nil
}