// CollectProcessMetrics periodically collects various metrics about the running
// process.
181186
func CollectProcessMetrics(refresh time.Duration) {
	// Short circuit if the metrics system is disabled
	if !Enabled {
		return
	}
	// Create the various data collectors
	memstats := make([]*runtime.MemStats, 2)
	diskstats := make([]*DiskStats, 2)
	for i := 0; i < len(memstats); i++ {
		memstats[i] = new(runtime.MemStats)
		diskstats[i] = new(DiskStats)
	}
	// Define the various metrics to collect
	memAllocs := GetOrRegisterMeter("system/memory/allocs", DefaultRegistry)
	memFrees := GetOrRegisterMeter("system/memory/frees", DefaultRegistry)
	memInuse := GetOrRegisterMeter("system/memory/inuse", DefaultRegistry)
	memPauses := GetOrRegisterMeter("system/memory/pauses", DefaultRegistry)

	var diskReads, diskReadBytes, diskWrites, diskWriteBytes Meter
	var diskReadBytesCounter, diskWriteBytesCounter Counter
	if err := ReadDiskStats(diskstats[0]); err == nil {
		diskReads = GetOrRegisterMeter("system/disk/readcount", DefaultRegistry)
		diskReadBytes = GetOrRegisterMeter("system/disk/readdata", DefaultRegistry)
		diskReadBytesCounter = GetOrRegisterCounter("system/disk/readbytes", DefaultRegistry)
		diskWrites = GetOrRegisterMeter("system/disk/writecount", DefaultRegistry)
		diskWriteBytes = GetOrRegisterMeter("system/disk/writedata", DefaultRegistry)
		diskWriteBytesCounter = GetOrRegisterCounter("system/disk/writebytes", DefaultRegistry)
	} else {
		log.Debug("Failed to read disk metrics", "err", err)
	}
	// Iterate loading the different stats and updating the meters
	for i := 1; ; i++ {
		location1 := i % 2
		location2 := (i - 1) % 2

		runtime.ReadMemStats(memstats[location1])
		memAllocs.Mark(int64(memstats[location1].Mallocs - memstats[location2].Mallocs))
		memFrees.Mark(int64(memstats[location1].Frees - memstats[location2].Frees))
		memInuse.Mark(int64(memstats[location1].Alloc - memstats[location2].Alloc))
		memPauses.Mark(int64(memstats[location1].PauseTotalNs - memstats[location2].PauseTotalNs))

		if ReadDiskStats(diskstats[location1]) == nil {
			diskReads.Mark(diskstats[location1].ReadCount - diskstats[location2].ReadCount)
			diskReadBytes.Mark(diskstats[location1].ReadBytes - diskstats[location2].ReadBytes)
			diskWrites.Mark(diskstats[location1].WriteCount - diskstats[location2].WriteCount)
			diskWriteBytes.Mark(diskstats[location1].WriteBytes - diskstats[location2].WriteBytes)

			diskReadBytesCounter.Inc(diskstats[location1].ReadBytes - diskstats[location2].ReadBytes)
			diskWriteBytesCounter.Inc(diskstats[location1].WriteBytes - diskstats[location2].WriteBytes)
		}
		time.Sleep(refresh)
	}
}
845310
func (m *blockMetrics) PrometheusCollectors() []prometheus.Collector {
	var metrics []prometheus.Collector
	metrics = append(metrics, m.compactionMetrics.PrometheusCollectors()...)
	metrics = append(metrics, m.fileMetrics.PrometheusCollectors()...)
	metrics = append(metrics, m.cacheMetrics.PrometheusCollectors()...)
	return metrics
}
1111461
func (t *Twemproxy) processStat(
	acc telegraf.Accumulator,
	tags map[string]string,
	data map[string]interface{},
) {
	if source, ok := data["source"]; ok {
		if val, ok := source.(string); ok {
			tags["source"] = val
		}
	}

	fields := make(map[string]interface{})
	metrics := []string{"total_connections", "curr_connections", "timestamp"}
	for _, m := range metrics {
		if value, ok := data[m]; ok {
			if val, ok := value.(float64); ok {
				fields[m] = val
			}
		}
	}
	acc.AddFields("twemproxy", fields, tags)

	for _, pool := range t.Pools {
		if poolStat, ok := data[pool]; ok {
			if data, ok := poolStat.(map[string]interface{}); ok {
				poolTags := copyTags(tags)
				poolTags["pool"] = pool
				t.processPool(acc, poolTags, data)
			}
		}
	}
}
422634
func (c *DialCollector) Collect(ch chan<- prometheus.Metric) {
	c.dialsTotal.Collect(ch)
	c.dialDuration.Collect(ch)
}
1217476
func (m *cacheMetrics) PrometheusCollectors() []prometheus.Collector {
	return []prometheus.Collector{
		m.MemSize,
		m.DiskSize,
		m.SnapshotsActive,
		m.Age,
		m.SnapshottedBytes,
		m.WrittenBytes,
		m.Writes,
	}
}
899197
func GetProcessMemoryInfo(handle syscall.Handle) (ProcessMemoryCountersEx, error) {
	processMemoryCountersEx := ProcessMemoryCountersEx{cb: sizeofProcessMemoryCountersEx}
	err := _GetProcessMemoryInfo(handle, &processMemoryCountersEx, processMemoryCountersEx.cb)
	if err != nil {
		return ProcessMemoryCountersEx{}, errors.Wrap(err, "GetProcessMemoryInfo failed")
	}

	return processMemoryCountersEx, nil
}
751028
func (collector *procTableCollector) Collect(ch chan<- prometheus.Metric) {
	stats := collector.procTable.Stats()
	addGauge := func(desc *prometheus.Desc, v float64, lv ...string) {
		ch <- prometheus.MustNewConstMetric(desc, prometheus.GaugeValue, v, lv...)
	}
	addGauge(procTableRunning, float64(stats.Running))
	addGauge(procTableSucceeded, float64(stats.Succeeded))
	addGauge(procTableFailed, float64(stats.Failed))
}
1071937
func (p *PUContext) GetProcessKeys() (string, []string, []string) {
	return p.mark, p.tcpPorts, p.udpPorts
}
1180129
func (c *MgoStatsCollector) Collect(ch chan<- prometheus.Metric) {
	stats, prevStats := c.getStats()

	c.clustersGauge.Set(float64(stats.Clusters))
	c.masterConnsGauge.Set(float64(stats.MasterConns))
	c.slaveConnsGauge.Set(float64(stats.SlaveConns))
	if n := stats.SentOps - prevStats.SentOps; n > 0 {
		c.sentOpsCounter.Add(float64(n))
	}
	if n := stats.ReceivedOps - prevStats.ReceivedOps; n > 0 {
		c.receivedOpsCounter.Add(float64(n))
	}
	if n := stats.ReceivedDocs - prevStats.ReceivedDocs; n > 0 {
		c.receivedDocsCounter.Add(float64(n))
	}
	c.socketsAliveGauge.Set(float64(stats.SocketsAlive))
	c.socketsInuseGauge.Set(float64(stats.SocketsInUse))
	c.socketRefsGauge.Set(float64(stats.SocketRefs))

	c.clustersGauge.Collect(ch)
	c.masterConnsGauge.Collect(ch)
	c.slaveConnsGauge.Collect(ch)
	c.sentOpsCounter.Collect(ch)
	c.receivedOpsCounter.Collect(ch)
	c.receivedDocsCounter.Collect(ch)
	c.socketsAliveGauge.Collect(ch)
	c.socketsInuseGauge.Collect(ch)
	c.socketRefsGauge.Collect(ch)
}
153545
func (c *logMetricsCollector) Collect(ch chan<- prometheus.Metric) {
	podStats, err := c.podStats()
	if err != nil {
		klog.Errorf("failed to get pod stats: %v", err)
		return
	}

	for _, ps := range podStats {
		for _, c := range ps.Containers {
			if c.Logs != nil && c.Logs.UsedBytes != nil {
				ch <- prometheus.MustNewConstMetric(
					descLogSize,
					prometheus.GaugeValue,
					float64(*c.Logs.UsedBytes),
					ps.PodRef.Namespace,
					ps.PodRef.Name,
					c.Name,
				)
			}
		}
	}
}
875249
func (mb *SquareMetrics) collectMetrics() {
	var mem runtime.MemStats

	update := func(name string, value uint64) {
		metrics.GetOrRegisterGauge(name, mb.Registry).Update(int64(value))
	}

	updateFloat := func(name string, value float64) {
		metrics.GetOrRegisterGaugeFloat64(name, mb.Registry).Update(value)
	}

	sample := metrics.NewExpDecaySample(1028, 0.015)
	gcHistogram := metrics.GetOrRegisterHistogram("runtime.mem.gc.duration", mb.Registry, sample)

	var observedPauses uint32
	for range time.Tick(mb.interval) {
		runtime.ReadMemStats(&mem)

		update("runtime.mem.alloc", mem.Alloc)
		update("runtime.mem.total-alloc", mem.TotalAlloc)
		update("runtime.mem.sys", mem.Sys)
		update("runtime.mem.lookups", mem.Lookups)
		update("runtime.mem.mallocs", mem.Mallocs)
		update("runtime.mem.frees", mem.Frees)

		update("runtime.mem.heap.alloc", mem.HeapAlloc)
		update("runtime.mem.heap.sys", mem.HeapSys)
		update("runtime.mem.heap.idle", mem.HeapIdle)
		update("runtime.mem.heap.inuse", mem.HeapInuse)
		update("runtime.mem.heap.released", mem.HeapReleased)
		update("runtime.mem.heap.objects", mem.HeapObjects)

		update("runtime.mem.stack.inuse", mem.StackInuse)
		update("runtime.mem.stack.sys", mem.StackSys)

		update("runtime.goroutines", uint64(runtime.NumGoroutine()))
		update("runtime.cgo-calls", uint64(runtime.NumCgoCall()))

		update("runtime.mem.gc.num-gc", uint64(mem.NumGC))
		updateFloat("runtime.mem.gc.cpu-fraction", mem.GCCPUFraction)

		// Update histogram of GC pauses
		for ; observedPauses < mem.NumGC; observedPauses++ {
			gcHistogram.Update(int64(mem.PauseNs[(observedPauses+1)%256]))
		}

		// Update gauges
		mb.mutex.Lock()
		for _, gauge := range mb.gauges {
			gauge.gauge.Update(gauge.callback())
		}
		mb.mutex.Unlock()
	}
}
213783
func (h *HostStatsCollector) Collect() error {
	h.hostStatsLock.Lock()
	defer h.hostStatsLock.Unlock()
	return h.collectLocked()
}
1283819
func collectHeapProfile(filename string) (done func()) {
	heapProf, err := os.Create(filename)
	if err != nil {
		fmt.Fprintf(os.Stderr, "failed to create file for heap profile: %v\n", err)
		return
	}
	return func() {
		runtime.GC() // get up-to-date statistics
		if err := pprof.WriteHeapProfile(heapProf); err != nil {
			_ = heapProf.Close()
			fmt.Fprintf(os.Stderr, "failed to write heap profile to file: %v\n", err)
			return
		}
		if err := heapProf.Close(); err != nil {
			fmt.Fprintf(os.Stderr, "failed to close file for heap profile: %v\n", err)
			return
		}
	}
}
1117371
func (c *CloudWatch) gatherMetrics(
	params *cloudwatch.GetMetricDataInput,
) ([]*cloudwatch.MetricDataResult, error) {
	results := []*cloudwatch.MetricDataResult{}

	for {
		resp, err := c.client.GetMetricData(params)
		if err != nil {
			return nil, fmt.Errorf("failed to get metric data: %v", err)
		}

		results = append(results, resp.MetricDataResults...)
		if resp.NextToken == nil {
			break
		}
		params.NextToken = resp.NextToken
	}

	return results, nil
}
1155819
func CollectProcessInfoWithChildren(pid int32) []Composer {
	var results []Composer
	parent, err := process.NewProcess(pid)
	if err != nil {
		return results
	}

	parentMsg := &ProcessInfo{}
	parentMsg.loggable = true
	parentMsg.populate(parent)
	results = append(results, parentMsg)

	for _, child := range getChildrenRecursively(parent) {
		cm := &ProcessInfo{}
		cm.loggable = true
		cm.populate(child)
		results = append(results, cm)
	}

	return results
}
704963
func (a *Agent) applyProcessors(m telegraf.Metric) []telegraf.Metric {
	metrics := []telegraf.Metric{m}
	for _, processor := range a.Config.Processors {
		metrics = processor.Apply(metrics...)
	}

	return metrics
}
942558
func (p *pluginControl) CollectMetrics(id string, allTags map[string]map[string]string) (metrics []core.Metric, errs []error) {
	// If control is not started we don't want tasks to be able to
	// go through a workflow.
	if !p.Started {
		return nil, []error{ErrControllerNotStarted}
	}

	// Subscription groups are processed anytime a plugin is loaded/unloaded.
	pluginToMetricMap, serrs, err := p.subscriptionGroups.Get(id)
	if err != nil {
		controlLogger.WithFields(log.Fields{
			"_block":                "CollectorMetrics",
			"subscription-group-id": id,
		}).Error(err)
		errs = append(errs, err)
		return
	}
	// If We received errors when the requested metrics were last processed
	// against the metric catalog we need to return them to the caller.
	if serrs != nil {
		for _, e := range serrs {
			errs = append(errs, e)
		}
	}

	for ns, nsTags := range allTags {
		for k, v := range nsTags {
			log.WithFields(log.Fields{
				"_module": "control",
				"block":   "CollectMetrics",
				"type":    "pluginCollector",
				"ns":      ns,
				"tag-key": k,
				"tag-val": v,
			}).Debug("Tags in CollectMetrics")
		}
	}

	cMetrics := make(chan []core.Metric)
	cError := make(chan error)
	var wg sync.WaitGroup

	// For each available plugin call available plugin using RPC client and wait for response (goroutines)
	for pluginKey, pmt := range pluginToMetricMap {
		// merge global plugin config into the config for the metric
		for _, mt := range pmt.metricTypes {
			if mt.Config() != nil {
				mt.Config().ReverseMergeInPlace(p.Config.Plugins.getPluginConfigDataNode(core.CollectorPluginType, pmt.plugin.Name(), pmt.plugin.Version()))
			}
		}

		wg.Add(1)

		go func(pluginKey string, mt []core.Metric) {
			mts, err := p.pluginRunner.AvailablePlugins().collectMetrics(pluginKey, mt, id)
			if err != nil {
				cError <- err
			} else {
				cMetrics <- mts
			}
		}(pluginKey, pmt.metricTypes)
	}

	go func() {
		for m := range cMetrics {
			// Reapply standard tags after collection as a precaution.  It is common for
			// plugin authors to inadvertently overwrite or not pass along the data
			// passed to CollectMetrics so we will help them out here.
			for i := range m {
				m[i] = p.pluginManager.AddStandardAndWorkflowTags(m[i], allTags)
			}
			metrics = append(metrics, m...)
			wg.Done()
		}
	}()

	go func() {
		for e := range cError {
			errs = append(errs, e)
			wg.Done()
		}
	}()

	wg.Wait()
	close(cMetrics)
	close(cError)

	if len(errs) > 0 {
		return nil, errs
	}
	return
}