// CollectMetrics collects metrics for testing
197313
func (f *Mock) CollectMetrics(mts []plugin.Metric) ([]plugin.Metric, error) {
	for _, p := range mts {
		log.Printf("collecting %+v\n", p)
	}

	rand.Seed(time.Now().UTC().UnixNano())
	metrics := []plugin.Metric{}
	for i := range mts {
		if _, err := mts[i].Config.GetBool("long_print"); err == nil {
			letterBytes := "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
			longLine := []byte{}
			for i := 0; i < 8193; i++ {
				longLine = append(longLine, letterBytes[rand.Intn(len(letterBytes))])
			}
			fmt.Println(string(longLine))
		}
		if _, err := mts[i].Config.GetBool("panic"); err == nil {
			panic("Oops!")
		}

		if isDynamic, _ := mts[i].Namespace.IsDynamic(); isDynamic {
			requestedHosts := []string{}

			if mts[i].Namespace[2].Value == "*" {
				// when dynamic element is not specified (equals an asterisk)
				// then consider all available hosts as requested hosts
				requestedHosts = append(requestedHosts, availableHosts...)
			} else {
				// when the dynamic element is specified
				// then consider this specified host as requested hosts
				host := mts[i].Namespace[2].Value

				// check if specified host is available in system
				if contains(availableHosts, host) {
					requestedHosts = append(requestedHosts, host)
				} else {
					return nil, fmt.Errorf("requested hostname `%s` is not available (list of available hosts: %s)", host, availableHosts)
				}

			}
			// collect data for each of requested hosts
			for _, host := range requestedHosts {
				//generate random data
				data := randInt(65, 90) + 1000
				// prepare namespace as a copy of incoming dynamic namespace,
				// but with the set value of dynamic element
				ns := plugin.CopyNamespace(mts[i].Namespace)
				ns[2].Value = host
				// metric with set data, ns, timestamp and the version of the plugin
				mt := plugin.Metric{
					Data:      data,
					Namespace: ns,
					Timestamp: time.Now(),
					Unit:      mts[i].Unit,
					Version:   mts[i].Version,
				}
				metrics = append(metrics, mt)
			}

		} else {
			data := randInt(65, 90) + 1000
			mts[i].Data = data
			mts[i].Timestamp = time.Now()
			metrics = append(metrics, mts[i])
		}
	}
	return metrics, nil
}
120562
func (p proc) GetMetrics() (Metrics, int, error) {
	counts, softerrors, err := p.GetCounts()
	if err != nil {
		return Metrics{}, 0, err
	}

	// We don't need to check for error here because p will have cached
	// the successful result of calling getStat in GetCounts.
	// Since GetMetrics isn't a pointer receiver method, our callers
	// won't see the effect of the caching between calls.
	stat, _ := p.getStat()

	// Ditto for states
	states, _ := p.GetStates()

	// Ditto for status
	status, _ := p.getStatus()

	numfds, err := p.Proc.FileDescriptorsLen()
	if err != nil {
		numfds = -1
		softerrors |= 1
	}

	limits, err := p.Proc.NewLimits()
	if err != nil {
		return Metrics{}, 0, err
	}

	wchan, err := p.getWchan()
	if err != nil {
		softerrors |= 1
	}

	return Metrics{
		Counts: counts,
		Memory: Memory{
			ResidentBytes: uint64(stat.ResidentMemory()),
			VirtualBytes:  uint64(stat.VirtualMemory()),
			VmSwapBytes:   uint64(status.VmSwapKB * 1024),
		},
		Filedesc: Filedesc{
			Open:  int64(numfds),
			Limit: uint64(limits.OpenFiles),
		},
		NumThreads: uint64(stat.NumThreads),
		States:     states,
		Wchan:      wchan,
	}, softerrors, nil
}
682801
func (s *Store) Collect(ch chan<- prometheus.Metric) {
	s.metrics.Collect(ch)
}
56573
func (s *StatusReport) SendMetrics(c context.Context) error {
	c, _ = context.WithTimeout(c, 10*time.Second)
	rep := s.Report()

	metricVersion.Set(c, rep.TokendVersion)
	if rep.ServiceVersion != "" {
		metricServiceVersion.Set(c, rep.ServiceVersion)
	}
	if rep.TokenExpiryTS != 0 {
		metricTokenExpiry.Set(c, rep.TokenExpiryTS*1000000)
	}
	if rep.TokenLastUpdateTS != 0 {
		metricTokenLastUpdate.Set(c, rep.TokenLastUpdateTS*1000000)
	}
	if rep.TokenNextUpdateTS != 0 {
		metricTokenNextUpdate.Set(c, rep.TokenNextUpdateTS*1000000)
	}
	metricUpdateOutcome.Set(c, rep.UpdateOutcome)
	metricUpdateReason.Set(c, rep.UpdateReason)
	metricTotalDuration.Set(c, rep.TotalDuration)
	metricRPCDuration.Set(c, rep.RPCDuration)

	return tsmon.Flush(c)
}
594851
func (c *multiTimingsCollector) Collect(ch chan<- prometheus.Metric) {
	for cat, his := range c.mt.Timings.Histograms() {
		labelValues := strings.Split(cat, ".")
		ch <- prometheus.MustNewConstHistogram(
			c.desc,
			uint64(his.Count()),
			float64(his.Total())/1000000000,
			makeCumulativeBuckets(c.cutoffs, his.Buckets()),
			labelValues...)
	}
}
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()
	}
}
250392
func (c *countersWithSingleLabelCollector) Collect(ch chan<- prometheus.Metric) {
	for tag, val := range c.counters.Counts() {
		ch <- prometheus.MustNewConstMetric(
			c.desc,
			c.vt,
			float64(val),
			tag)
	}
}
1363488
func (m *fileMetrics) PrometheusCollectors() []prometheus.Collector {
	return []prometheus.Collector{
		m.DiskSize,
		m.Files,
	}
}
1293932
func (m *Metrics) Collect() (a map[string]AggregatedMetrics) {
	a = make(map[string]AggregatedMetrics)

	for _, fnName := range m.FunctionNames {
		metric := Metric{
			Config:       m.Config,
			FunctionName: fnName,
		}

		a[fnName] = metric.Collect()
	}

	return
}
484690
func (m *MetricBatch) Metrics() []Metric {
	result := make([]Metric, len(m.doc.Metrics))
	copy(result, m.doc.Metrics)
	return result
}
8060
func (p *Plugin) Metrics() ([]producers.MetricsMessage, error) {
	var messages []producers.MetricsMessage

	// Fetch node metrics
	nodeMetrics, err := p.getNodeMetrics()
	if err != nil {
		return nil, err
	}
	messages = append(messages, nodeMetrics)

	// Master only collects node metrics; return without checking containers
	if p.Role == dcos.RoleMaster {
		return messages, nil
	}

	// Fetch container metrics
	containerMetrics, err := p.getContainerMetrics()
	if err != nil {
		return nil, err
	}
	messages = append(messages, containerMetrics...)
	return messages, nil
}
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)
	}
}
327639
func (gs Gatherers) Gather() ([]*dto.MetricFamily, error) {
	var (
		metricFamiliesByName = map[string]*dto.MetricFamily{}
		metricHashes         = map[uint64]struct{}{}
		errs                 MultiError // The collected errors to return in the end.
	)

	for i, g := range gs {
		mfs, err := g.Gather()
		if err != nil {
			if multiErr, ok := err.(MultiError); ok {
				for _, err := range multiErr {
					errs = append(errs, fmt.Errorf("[from Gatherer #%d] %s", i+1, err))
				}
			} else {
				errs = append(errs, fmt.Errorf("[from Gatherer #%d] %s", i+1, err))
			}
		}
		for _, mf := range mfs {
			existingMF, exists := metricFamiliesByName[mf.GetName()]
			if exists {
				if existingMF.GetHelp() != mf.GetHelp() {
					errs = append(errs, fmt.Errorf(
						"gathered metric family %s has help %q but should have %q",
						mf.GetName(), mf.GetHelp(), existingMF.GetHelp(),
					))
					continue
				}
				if existingMF.GetType() != mf.GetType() {
					errs = append(errs, fmt.Errorf(
						"gathered metric family %s has type %s but should have %s",
						mf.GetName(), mf.GetType(), existingMF.GetType(),
					))
					continue
				}
			} else {
				existingMF = &dto.MetricFamily{}
				existingMF.Name = mf.Name
				existingMF.Help = mf.Help
				existingMF.Type = mf.Type
				if err := checkSuffixCollisions(existingMF, metricFamiliesByName); err != nil {
					errs = append(errs, err)
					continue
				}
				metricFamiliesByName[mf.GetName()] = existingMF
			}
			for _, m := range mf.Metric {
				if err := checkMetricConsistency(existingMF, m, metricHashes); err != nil {
					errs = append(errs, err)
					continue
				}
				existingMF.Metric = append(existingMF.Metric, m)
			}
		}
	}
	return internal.NormalizeMetricFamilies(metricFamiliesByName), errs.MaybeUnwrap()
}
1051626
func (c *Client) DebugEnableMetrics() (string, error) {
	result := ""
	err := c.call("DebugEnableMetrics", empty, &result)
	if err != nil {
		return "", err
	}
	return result, nil
}
933811
func (md *metricsDu) GetMetrics() (*Metrics, error) {
	metrics := &Metrics{Time: metav1.Now()}
	if md.path == "" {
		return metrics, NewNoPathDefinedError()
	}

	err := md.runDiskUsage(metrics)
	if err != nil {
		return metrics, err
	}

	err = md.runFind(metrics)
	if err != nil {
		return metrics, err
	}

	err = md.getFsInfo(metrics)
	if err != nil {
		return metrics, err
	}

	return metrics, nil
}
422634
func (c *DialCollector) Collect(ch chan<- prometheus.Metric) {
	c.dialsTotal.Collect(ch)
	c.dialDuration.Collect(ch)
}
554430
func (m *ServerMetrics) Collect(ch chan<- prom.Metric) {
	m.serverStartedCounter.Collect(ch)
	m.serverHandledCounter.Collect(ch)
	m.serverStreamMsgReceived.Collect(ch)
	m.serverStreamMsgSent.Collect(ch)
	if m.serverHandledHistogramEnabled {
		m.serverHandledHistogram.Collect(ch)
	}
}