// Collect function, called on by Prometheus Client library
// This function is called when a scrape is performed by requesting /metrics
432889
func (e *Exporter) Collect(ch chan<- prometheus.Metric) {
	// Scrape the Data
	var err = e.gatherData()
	if err != nil {
		return
	}
	// Set prometheus gauge metrics using the data gathered
	ch <- prometheus.MustNewConstMetric(
		Height,
		prometheus.CounterValue,
		e.datum.LatestBlockHeight,
		e.chainID,
		e.validatorMoniker,
	)
	ch <- prometheus.MustNewConstMetric(
		UnconfirmedTransactions,
		prometheus.GaugeValue,
		e.datum.UnconfirmedTxs,
		e.chainID,
		e.validatorMoniker,
	)
	ch <- prometheus.MustNewConstMetric(
		TotalPeers,
		prometheus.GaugeValue,
		e.datum.TotalPeers,
		e.chainID,
		e.validatorMoniker,
	)
	ch <- prometheus.MustNewConstMetric(
		InboundPeers,
		prometheus.GaugeValue,
		e.datum.InboundPeers,
		e.chainID,
		e.validatorMoniker,
	)
	ch <- prometheus.MustNewConstMetric(
		OutboundPeers,
		prometheus.GaugeValue,
		e.datum.OutboundPeers,
		e.chainID,
		e.validatorMoniker,
	)
	ch <- prometheus.MustNewConstHistogram(
		TxPerBlock,
		e.datum.BlockSampleSize,
		e.datum.TotalTxs,
		e.datum.TxPerBlockBuckets,
		e.chainID,
		e.validatorMoniker,
	)
	ch <- prometheus.MustNewConstHistogram(
		TimePerBlock,
		// Duration between each block in sample
		e.datum.BlockSampleSize-1,
		e.datum.TotalTime,
		e.datum.TimePerBlockBuckets,
		e.chainID,
		e.validatorMoniker,
	)
	ch <- prometheus.MustNewConstMetric(
		Contracts,
		prometheus.GaugeValue,
		e.datum.AccountsWithCode,
		e.chainID,
		e.validatorMoniker,
	)
	ch <- prometheus.MustNewConstMetric(
		Users,
		prometheus.GaugeValue,
		e.datum.AccountsWithoutCode,
		e.chainID,
		e.validatorMoniker,
	)

	e.logger.InfoMsg("All Metrics successfully collected")
}
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
}
538346
func (c *Collector) Collect(ch chan<- prometheus.Metric) {
	c.TotalConnections.Collect(ch)
	c.APIConnections.Collect(ch)
	c.LoginAttempts.Collect(ch)
	c.APIRequestDuration.Collect(ch)
	c.PingFailureCount.Collect(ch)
	c.LogWriteCount.Collect(ch)
	c.LogReadCount.Collect(ch)

	// TODO (stickupkid): remove post 2.6 release
	c.DeprecatedAPIConnections.Collect(ch)
	c.DeprecatedAPIRequestsTotal.Collect(ch)
	c.DeprecatedAPIRequestDuration.Collect(ch)
}
346021
func (c *timingsCollector) Collect(ch chan<- prometheus.Metric) {
	for cat, his := range c.t.Histograms() {
		ch <- prometheus.MustNewConstHistogram(
			c.desc,
			uint64(his.Count()),
			float64(his.Total())/1000000000,
			makeCumulativeBuckets(c.cutoffs, his.Buckets()),
			cat)
	}
}
33952
func PrometheusCollectors() []prometheus.Collector {
	mmu.RLock()
	defer mmu.RUnlock()

	var collectors []prometheus.Collector
	if bms != nil {
		collectors = append(collectors, bms.compactionMetrics.PrometheusCollectors()...)
		collectors = append(collectors, bms.fileMetrics.PrometheusCollectors()...)
		collectors = append(collectors, bms.cacheMetrics.PrometheusCollectors()...)
	}
	return collectors
}
630581
func (g *gaugesWithSingleLabelCollector) Collect(ch chan<- prometheus.Metric) {
	for tag, val := range g.gauges.Counts() {
		ch <- prometheus.MustNewConstMetric(
			g.desc,
			g.vt,
			float64(val),
			tag)
	}
}
540783
func (c *influxCollector) Collect(ch chan<- prometheus.Metric) {
	ch <- prometheus.MustNewConstMetric(c.influxInfoDesc, prometheus.GaugeValue, 1)

	uptime := time.Since(c.start).Seconds()
	ch <- prometheus.MustNewConstMetric(c.influxUptimeDesc, prometheus.GaugeValue, float64(uptime))
}
1207693
func (m *Metric) Collect() (a AggregatedMetrics) {
	for n := range m.collect(m.gen()) {
		value := aggregate(n.Value)

		switch n.Name {
		case "Duration":
			a.Duration = value
		case "Errors":
			a.Errors = value
		case "Invocations":
			a.Invocations = value
		case "Throttles":
			a.Throttles = value
		}
	}

	return
}
995122
func (p *ProcMetrics) Collect() {
	if m, err := CollectProcInfo(p.pid); err == nil {
		now := time.Now()

		if !p.lastTime.IsZero() {
			ratio := 1.0
			switch {
			case m.CPU.Period > 0 && m.CPU.Quota > 0:
				ratio = float64(m.CPU.Quota) / float64(m.CPU.Period)
			case m.CPU.Shares > 0:
				ratio = float64(m.CPU.Shares) / 1024
			default:
				ratio = 1 / float64(runtime.NumCPU())
			}

			interval := ratio * float64(now.Sub(p.lastTime))

			p.cpu.user.time = m.CPU.User - p.last.CPU.User
			p.cpu.user.percent = 100 * float64(p.cpu.user.time) / interval

			p.cpu.system.time = m.CPU.Sys - p.last.CPU.Sys
			p.cpu.system.percent = 100 * float64(p.cpu.system.time) / interval

			p.cpu.total.time = (m.CPU.User + m.CPU.Sys) - (p.last.CPU.User + p.last.CPU.Sys)
			p.cpu.total.percent = 100 * float64(p.cpu.total.time) / interval

		}

		p.memory.available = m.Memory.Available
		p.memory.size = m.Memory.Size
		p.memory.resident.usage = m.Memory.Resident
		p.memory.resident.percent = 100 * float64(p.memory.resident.usage) / float64(p.memory.available)
		p.memory.shared.usage = m.Memory.Shared
		p.memory.text.usage = m.Memory.Text
		p.memory.data.usage = m.Memory.Data
		p.memory.pagefault.major.count = m.Memory.MajorPageFaults - p.last.Memory.MajorPageFaults
		p.memory.pagefault.minor.count = m.Memory.MinorPageFaults - p.last.Memory.MinorPageFaults

		p.files.open = m.Files.Open
		p.files.max = m.Files.Max

		p.threads.num = m.Threads.Num
		p.threads.switches.voluntary.count = m.Threads.VoluntaryContextSwitches - p.last.Threads.VoluntaryContextSwitches
		p.threads.switches.involuntary.count = m.Threads.InvoluntaryContextSwitches - p.last.Threads.InvoluntaryContextSwitches

		p.last = m
		p.lastTime = now
		p.engine.Report(p)
	}
}
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))
}
836005
func (p *PrometheusSink) Collect(c chan<- prometheus.Metric) {
	p.mu.Lock()
	defer p.mu.Unlock()

	expire := p.expiration != 0
	now := time.Now()
	for k, v := range p.gauges {
		last := p.updates[k]
		if expire && last.Add(p.expiration).Before(now) {
			delete(p.updates, k)
			delete(p.gauges, k)
		} else {
			v.Collect(c)
		}
	}
	for k, v := range p.summaries {
		last := p.updates[k]
		if expire && last.Add(p.expiration).Before(now) {
			delete(p.updates, k)
			delete(p.summaries, k)
		} else {
			v.Collect(c)
		}
	}
	for k, v := range p.counters {
		last := p.updates[k]
		if expire && last.Add(p.expiration).Before(now) {
			delete(p.updates, k)
			delete(p.counters, k)
		} else {
			v.Collect(c)
		}
	}
}
224765
func (h *HttpJson) Gather(acc telegraf.Accumulator) error {
	var wg sync.WaitGroup

	if h.client.HTTPClient() == nil {
		tlsCfg, err := h.ClientConfig.TLSConfig()
		if err != nil {
			return err
		}
		tr := &http.Transport{
			ResponseHeaderTimeout: h.ResponseTimeout.Duration,
			TLSClientConfig:       tlsCfg,
		}
		client := &http.Client{
			Transport: tr,
			Timeout:   h.ResponseTimeout.Duration,
		}
		h.client.SetHTTPClient(client)
	}

	for _, server := range h.Servers {
		wg.Add(1)
		go func(server string) {
			defer wg.Done()
			acc.AddError(h.gatherServer(acc, server))
		}(server)
	}

	wg.Wait()

	return nil
}
879457
func (c *appsCollector) Collect(ch chan<- prometheus.Metric) {
	result, err := c.lister.List(labels.Everything())
	if err != nil {
		klog.V(4).Infof("Collecting metrics for apps failed: %v", err)
		return
	}

	var available, failed, cancelled float64

	latestFailedRollouts := map[string]failedRollout{}

	for _, d := range result {
		dcName := util.DeploymentConfigNameFor(d)
		if len(dcName) == 0 {
			continue
		}
		latestVersion := util.DeploymentVersionFor(d)
		key := d.Namespace + "/" + dcName

		if util.IsTerminatedDeployment(d) {
			if util.IsDeploymentCancelled(d) {
				cancelled++
				continue
			}
			if util.IsFailedDeployment(d) {
				failed++
				// Track the latest failed rollout per deployment config
				// continue only when this is the latest version (add if below)
				if r, exists := latestFailedRollouts[key]; exists && latestVersion <= r.latestVersion {
					continue
				}
				latestFailedRollouts[key] = failedRollout{
					timestamp:     float64(d.CreationTimestamp.Unix()),
					latestVersion: latestVersion,
				}
				continue
			}
			if util.IsCompleteDeployment(d) {
				// If a completed rollout is found AFTER we recorded a failed rollout,
				// do not record the lastFailedRollout as the latest rollout is not
				// failed.
				if r, hasFailedRollout := latestFailedRollouts[key]; hasFailedRollout && r.latestVersion < latestVersion {
					delete(latestFailedRollouts, key)
				}
				available++
				continue
			}
		}

		// TODO: Figure out under what circumstances the phase is not set.
		phase := strings.ToLower(string(util.DeploymentStatusFor(d)))
		if len(phase) == 0 {
			phase = "unknown"
		}

		// Record duration in seconds for active rollouts
		// TODO: possible time skew?
		durationSeconds := c.nowFn().Unix() - d.CreationTimestamp.Unix()
		ch <- prometheus.MustNewConstMetric(
			activeRolloutDurationSecondsDesc,
			prometheus.CounterValue,
			float64(durationSeconds),
			[]string{
				d.Namespace,
				dcName,
				phase,
				fmt.Sprintf("%d", latestVersion),
			}...)
	}

	// Record latest failed rollouts
	for dc, r := range latestFailedRollouts {
		parts := strings.Split(dc, "/")
		ch <- prometheus.MustNewConstMetric(
			lastFailedRolloutTimeDesc,
			prometheus.GaugeValue,
			r.timestamp,
			[]string{
				parts[0],
				parts[1],
				fmt.Sprintf("%d", r.latestVersion),
			}...)
	}

	ch <- prometheus.MustNewConstMetric(completeRolloutCountDesc, prometheus.GaugeValue, available, []string{availablePhase}...)
	ch <- prometheus.MustNewConstMetric(completeRolloutCountDesc, prometheus.GaugeValue, failed, []string{failedPhase}...)
	ch <- prometheus.MustNewConstMetric(completeRolloutCountDesc, prometheus.GaugeValue, cancelled, []string{cancelledPhase}...)
}
248581
func (m *Metrics) PrometheusCollectors() []prometheus.Collector {
	return []prometheus.Collector{
		m.LoadFactor,
		m.Size,
		m.GetDuration,
		m.LastGetDuration,
		m.InsertDuration,
		m.LastInsertDuration,
		m.LastGrowDuration,
		m.MeanProbeCount,
		m.Gets,
		m.Puts,
	}
}
1369046
func (c *TxnCollector) Collect(ch chan<- prometheus.Metric) {
	c.txnOpsTotalCounter.Collect(ch)
}
271238
func (d *DelayMetrics) Collect() {
	if info, err := CollectDelayInfo(d.pid); err == nil {
		d.CPUDelay = info.CPUDelay
		d.BlockIODelay = info.BlockIODelay
		d.SwapInDelay = info.SwapInDelay
		d.FreePagesDelay = info.FreePagesDelay
		d.engine.Report(d)
	}
}
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
}