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

	rand.Seed(time.Now().UTC().UnixNano())
	metrics := []plugin.MetricType{}
	for i := range mts {
		if c, ok := mts[i].Config().Table()["long_stdout_log"]; ok && c.(ctypes.ConfigValueBool).Value {
			letterBytes := "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
			longLine := []byte{}
			for i := 0; i < bufio.MaxScanTokenSize; i++ {
				longLine = append(longLine, letterBytes[rand.Intn(len(letterBytes))])
			}
			fmt.Fprintln(os.Stdout, string(longLine))
		}

		if c, ok := mts[i].Config().Table()["long_stderr_log"]; ok && c.(ctypes.ConfigValueBool).Value {
			letterBytes := "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
			longLine := []byte{}
			for i := 0; i < bufio.MaxScanTokenSize; i++ {
				longLine = append(longLine, letterBytes[rand.Intn(len(letterBytes))])
			}
			fmt.Fprintln(os.Stderr, string(longLine))
		}

		if c, ok := mts[i].Config().Table()["panic"]; ok && c.(ctypes.ConfigValueBool).Value {
			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 := make([]core.NamespaceElement, len(mts[i].Namespace()))
				copy(ns, mts[i].Namespace())
				ns[2].Value = host

				// metric with set data, ns, timestamp and the version of the plugin
				mt := plugin.MetricType{
					Data_:      data,
					Namespace_: ns,
					Timestamp_: time.Now(),
					Unit_:      mts[i].Unit(),
					Version_:   mts[i].Version(),
				}
				metrics = append(metrics, mt)
			}
		} else if strings.Contains(mts[i].Namespace().String(), "all") {
			mts[i].Data_ = 1001
			mts[i].Timestamp_ = time.Now()
			metrics = append(metrics, mts[i])
		} else {
			data := randInt(65, 90) + 1000
			mts[i].Data_ = data
			mts[i].Timestamp_ = time.Now()
			metrics = append(metrics, mts[i])
		}
	}
	return metrics, nil
}
947324
func (p *pluginControl) FetchMetrics(ns core.Namespace, version int) ([]core.CatalogedMetric, error) {
	mts, err := p.metricCatalog.Fetch(ns)
	if err != nil {
		return nil, err
	}
	cmt := make([]core.CatalogedMetric, 0, len(mts))
	nsMap := map[string]struct{}{}
	for _, mt := range mts {
		if version > 0 {
			// a version is specified
			if mt.version == version {
				cmt = append(cmt, mt)
			}
		} else if version < 0 {
			// -1 (or less) is specified meaning return the latest
			if _, ok := nsMap[mt.Namespace().String()]; !ok {
				mt, err = p.metricCatalog.GetMetric(mt.Namespace(), version)
				if err != nil {
					return nil, err
				}
				cmt = append(cmt, mt)
				nsMap[mt.Namespace().String()] = struct{}{}
			}
		} else {
			// no version is specified return all metric versions
			cmt = append(cmt, mt)

		}
	}
	return cmt, nil
}
779339
func newMetricsCollector() (prometheus.Collector, error) {
	sink, err := pmetrics.NewPrometheusSink()
	if err != nil {
		return nil, errors.Trace(err)
	}
	// go-metrics always registers the sink it returns in the default
	// registry, which we don't collect metrics from - unregister it
	// so subsequent calls don't fail because it's already registered
	// there.
	prometheus.DefaultRegisterer.Unregister(sink)
	config := metrics.DefaultConfig("juju")
	config.EnableRuntimeMetrics = false
	_, err = metrics.NewGlobal(config, sink)
	if err != nil {
		return nil, errors.Trace(err)
	}
	return sink, nil
}
1219589
func NewMetrics() Metrics {

	return Metrics{
		TotalPushCount: prometheus.NewDesc(
			namespace+"total_push_count",
			"Number of push count",
			nil, nil,
		),
		IosSuccess: prometheus.NewDesc(
			namespace+"ios_success",
			"Number of iOS success count",
			nil, nil,
		),
		IosError: prometheus.NewDesc(
			namespace+"ios_error",
			"Number of iOS fail count",
			nil, nil,
		),
		AndroidSuccess: prometheus.NewDesc(
			namespace+"android_success",
			"Number of android success count",
			nil, nil,
		),
		AndroidError: prometheus.NewDesc(
			namespace+"android_fail",
			"Number of android fail count",
			nil, nil,
		),
		QueueUsage: prometheus.NewDesc(
			namespace+"queue_usage",
			"Length of internal queue",
			nil, nil,
		),
	}
}
333420
func (f *Mock) CollectMetrics(mts []plugin.MetricType) ([]plugin.MetricType, error) {
	metrics := []plugin.MetricType{}
	rand.Seed(time.Now().UTC().UnixNano())
	for i, p := range mts {
		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 {
				data := randInt(65, 90)
				ns := make([]core.NamespaceElement, len(mts[i].Namespace()))
				copy(ns, mts[i].Namespace())
				ns[2].Value = host
				mt := plugin.MetricType{
					Data_:      data,
					Namespace_: ns,
					Timestamp_: time.Now(),
					Unit_:      mts[i].Unit(),
					Version_:   mts[i].Version(),
				}
				metrics = append(metrics, mt)
			}

		} else {
			if cv, ok := p.Config().Table()["test"]; ok {
				p.Data_ = fmt.Sprintf("The mock collected data! config data: name=%s password=%s test=%v", p.Config().Table()["name"], p.Config().Table()["password"], cv.(ctypes.ConfigValueBool).Value)
			} else {
				p.Data_ = fmt.Sprintf("The mock collected data! config data: name=%s password=%s", p.Config().Table()["name"], p.Config().Table()["password"])
			}
			p.Timestamp_ = time.Now()
			metrics = append(metrics, p)
		}
	}
	return metrics, nil
}
713839
func (mc *metricFuncCollector) Collect(ch chan<- prometheus.Metric) {
	ch <- prometheus.MustNewConstMetric(mc.desc, mc.vt, float64(mc.f()))
}
597506
func (s *Server) tallyMetrics(percentiles []float64) ([]WorkerMetrics, metricsSummary) {
	// allocating this long array to count up the sizes is cheaper than appending
	// the []WorkerMetrics together one at a time
	tempMetrics := make([]WorkerMetrics, 0, len(s.Workers))

	ms := metricsSummary{}

	for i, w := range s.Workers {
		log.WithField("worker", i).Debug("Flushing")
		wm := w.Flush()
		tempMetrics = append(tempMetrics, wm)

		ms.totalCounters += len(wm.counters)
		ms.totalGauges += len(wm.gauges)
		ms.totalHistograms += len(wm.histograms)
		ms.totalSets += len(wm.sets)
		ms.totalTimers += len(wm.timers)

		ms.totalGlobalCounters += len(wm.globalCounters)
		ms.totalGlobalGauges += len(wm.globalGauges)
		ms.totalGlobalHistograms += len(wm.globalHistograms)
		ms.totalGlobalTimers += len(wm.globalTimers)

		ms.totalLocalHistograms += len(wm.localHistograms)
		ms.totalLocalSets += len(wm.localSets)
		ms.totalLocalTimers += len(wm.localTimers)

		ms.totalLocalStatusChecks += len(wm.localStatusChecks)
	}

	ms.totalLength = ms.totalCounters + ms.totalGauges +
		// histograms and timers each report a metric point for each percentile
		// plus a point for each of their aggregates
		(ms.totalTimers+ms.totalHistograms)*(s.HistogramAggregates.Count+len(percentiles)) +
		// local-only histograms will be flushed with percentiles, so we intentionally
		// use the original percentile list here.
		// remember that both the global veneur and the local instances have
		// 'local-only' histograms.
		ms.totalLocalSets + (ms.totalLocalTimers+ms.totalLocalHistograms)*(s.HistogramAggregates.Count+len(s.HistogramPercentiles))

	// Global instances also flush sets and global counters, so be sure and add
	// them to the total size
	if !s.IsLocal() {
		ms.totalLength += ms.totalSets
		ms.totalLength += ms.totalGlobalCounters
		ms.totalLength += ms.totalGlobalGauges
		ms.totalLength += ms.totalGlobalHistograms * (s.HistogramAggregates.Count + len(s.HistogramPercentiles))
		ms.totalLength += ms.totalGlobalTimers * (s.HistogramAggregates.Count + len(s.HistogramPercentiles))
	}

	return tempMetrics, ms
}
1208994
func (c *Client) GetMetrics(tags ...string) ([]params.MetricResult, error) {
	entities := make([]params.Entity, len(tags))
	for i, tag := range tags {
		entities[i] = params.Entity{Tag: tag}
	}
	p := params.Entities{Entities: entities}
	results := new(params.MetricResults)
	if err := c.facade.FacadeCall("GetMetrics", p, results); err != nil {
		return nil, errors.Trace(err)
	}
	if err := results.OneError(); err != nil {
		return nil, errors.Trace(err)
	}
	metrics := []params.MetricResult{}
	for _, r := range results.Results {
		metrics = append(metrics, r.Metrics...)
	}
	return metrics, nil
}
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
}
944912
func (md *cachedMetrics) GetMetrics() (*Metrics, error) {
	md.once.cache(func() error {
		md.resultMetrics, md.resultError = md.wrapped.GetMetrics()
		return md.resultError
	})
	return md.resultMetrics, md.resultError
}
200874
func NewMetrics() *Metrics {
	return &Metrics{
		store:      make(map[string]*int64),
		rates:      make(map[string]*rate),
		storeGuard: new(sync.RWMutex),
		rateGuard:  new(sync.RWMutex),
	}
}
1365339
func (api *MetricsManagerAPI) SendMetrics(args params.Entities) (params.ErrorResults, error) {
	if err := api.AddJujuMachineMetrics(); err != nil {
		logger.Warningf("failed to add juju-machines metrics: %v", err)
	}
	result := params.ErrorResults{
		Results: make([]params.ErrorResult, len(args.Entities)),
	}
	if len(args.Entities) == 0 {
		return result, nil
	}
	canAccess, err := api.accessModel()
	if err != nil {
		return result, err
	}
	for i, arg := range args.Entities {
		tag, err := names.ParseModelTag(arg.Tag)
		if err != nil {
			result.Results[i].Error = common.ServerError(err)
			continue
		}
		if !canAccess(tag) {
			result.Results[i].Error = common.ServerError(common.ErrPerm)
			continue
		}
		modelState, release, err := api.getModelState(tag)
		if err != nil {
			result.Results[i].Error = common.ServerError(err)
			continue
		}
		defer release()

		txVendorMetrics, err := transmitVendorMetrics(api.model)
		if err != nil {
			result.Results[i].Error = common.ServerError(err)
			continue
		}

		model, err := modelState.Model()
		if err != nil {
			return result, errors.Trace(err)
		}
		err = metricsender.SendMetrics(modelBackend{modelState, model}, api.sender, api.clock, maxBatchesPerSend, txVendorMetrics)
		if err != nil {
			err = errors.Annotatef(err, "failed to send metrics for %s", tag)
			logger.Warningf("%v", err)
			result.Results[i].Error = common.ServerError(err)
			continue
		}
	}
	return result, nil
}
1178890
func (md *metricsStatFS) GetMetrics() (*Metrics, error) {
	metrics := &Metrics{Time: metav1.Now()}
	if md.path == "" {
		return metrics, NewNoPathDefinedError()
	}

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

	return metrics, nil
}
367644
func (r *reader) SetMetrics(metrics []telegraf.Metric) {
	r.metrics = metrics
	r.offset = 0
	r.buf.Reset()
}
1170357
func (h *HTTPReporter) GetMetrics() *vegeta.Metrics {
	h.Lock()
	defer h.Unlock()
	return h.metrics
}
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,
	}
}
1327715
func (c *metricsFuncWithMultiLabelsCollector) Collect(ch chan<- prometheus.Metric) {
	for lvs, val := range c.cfml.Counts() {
		labelValues := strings.Split(lvs, ".")
		value := float64(val)
		ch <- prometheus.MustNewConstMetric(c.desc, c.vt, value, labelValues...)
	}
}