// called on GetMetric
482788
func (metric *EventMetric) fillMetric() *EventMetric {
	metric.Count = metric.meter.Count()
	metric.Rate1 = metric.meter.Rate1()
	metric.Rate5 = metric.meter.Rate5()
	metric.Rate15 = metric.meter.Rate15()
	metric.RateMean = metric.meter.RateMean()
	return metric
}
434839
func (_class HostClass) GetMetrics(sessionID SessionRef, self HostRef) (_retval HostMetricsRef, _err error) {
	_method := "host.get_metrics"
	_sessionIDArg, _err := convertSessionRefToXen(fmt.Sprintf("%s(%s)", _method, "session_id"), sessionID)
	if _err != nil {
		return
	}
	_selfArg, _err := convertHostRefToXen(fmt.Sprintf("%s(%s)", _method, "self"), self)
	if _err != nil {
		return
	}
	_result, _err := _class.client.APICall(_method, _sessionIDArg, _selfArg)
	if _err != nil {
		return
	}
	_retval, _err = convertHostMetricsRefToGo(_method + " -> ", _result.Value)
	return
}
882455
func (ms *MetricSender) ContainerMetric(appID string, instance int32, cpu float64, mem, disk uint64) ContainerMetricChainer {
	chainer := containerMetricChainer{}
	chainer.emitter = ms.eventEmitter
	chainer.envelope = &events.Envelope{
		Origin:    proto.String(ms.eventEmitter.Origin()),
		EventType: events.Envelope_ContainerMetric.Enum(),
		ContainerMetric: &events.ContainerMetric{
			ApplicationId: proto.String(appID),
			InstanceIndex: proto.Int32(instance),
			CpuPercentage: proto.Float64(cpu),
			MemoryBytes:   proto.Uint64(mem),
			DiskBytes:     proto.Uint64(disk),
		},
	}
	return chainer
}
120577
func (l *throttlingListener) connRateMetric() int {
	l.Lock()
	defer l.Unlock()

	var (
		earliestConnTime *time.Time
		connCount        float64
	)
	// Figure out the most recent connection timestamp.
	startIndex := l.nextSlot - 1
	if startIndex < 0 {
		startIndex = len(l.connAcceptTimes) - 1
	}
	latestConnTime := l.connAcceptTimes[startIndex]
	if latestConnTime == nil {
		return 0
	}
	// Loop backwards to get the earlier known connection timestamp.
	for index := startIndex; index != l.nextSlot; {
		if connTime := l.connAcceptTimes[index]; connTime == nil {
			break
		} else {
			earliestConnTime = connTime
		}
		connCount++
		// Stop if we have reached the maximum window in terms how long
		// ago the earliest connection was, to avoid stale data skewing results.
		if latestConnTime.Sub(*earliestConnTime) > l.lookbackWindow {
			break
		}
		index--
		if index < 0 {
			index = len(l.connAcceptTimes) - 1
		}
	}
	if connCount < 2 {
		return 0
	}
	// We use as a metric how many connections per 10ms
	connRate := connCount * float64(time.Second) / (1.0 + float64(latestConnTime.Sub(*earliestConnTime)))
	logger.Tracef("server listener has received %d connections per second", int(connRate))
	return int(connRate)
}
1124494
func (s *MetricStat) SetMetric(v *Metric) *MetricStat {
	s.Metric = v
	return s
}
574698
func (c *resourceMetricsClient) GetResourceMetric(resource v1.ResourceName, namespace string, selector labels.Selector) (PodMetricsInfo, time.Time, error) {
	metrics, err := c.client.PodMetricses(namespace).List(metav1.ListOptions{LabelSelector: selector.String()})
	if err != nil {
		return nil, time.Time{}, fmt.Errorf("unable to fetch metrics from resource metrics API: %v", err)
	}

	if len(metrics.Items) == 0 {
		return nil, time.Time{}, fmt.Errorf("no metrics returned from resource metrics API")
	}

	res := make(PodMetricsInfo, len(metrics.Items))

	for _, m := range metrics.Items {
		podSum := int64(0)
		missing := len(m.Containers) == 0
		for _, c := range m.Containers {
			resValue, found := c.Usage[v1.ResourceName(resource)]
			if !found {
				missing = true
				klog.V(2).Infof("missing resource metric %v for container %s in pod %s/%s", resource, c.Name, namespace, m.Name)
				break // containers loop
			}
			podSum += resValue.MilliValue()
		}

		if !missing {
			res[m.Name] = PodMetric{
				Timestamp: m.Timestamp.Time,
				Window:    m.Window.Duration,
				Value:     int64(podSum),
			}
		}
	}

	timestamp := metrics.Items[0].Timestamp.Time

	return res, timestamp, nil
}
297007
func (met *Metrics) ResetMetrics() {
	met.storeGuard.Lock()
	for key := range met.store {
		switch key {
		case MetricProcessStart, MetricGoRoutines, MetricGoVersion:
			// ignore
		default:
			*met.store[key] = 0
		}
	}
	met.storeGuard.Unlock()

	met.rateGuard.Lock()
	for _, rate := range met.rates {
		rate.lastSample = 0
		rate.value = 0
		rate.index = 0
		rate.samples.Set(0)
	}
	met.rateGuard.Unlock()
}
1302112
func (c *CCache) DelMetric(rawMetric schema.MKey) (int, int) {
	if c == nil {
		return 0, 0
	}
	archives, series := 0, 0

	c.Lock()
	defer c.Unlock()

	archs, ok := c.metricRawKeys[rawMetric]
	if !ok {
		return archives, series
	}

	metric := schema.AMKey{MKey: rawMetric}
	for arch := range archs {
		metric.Archive = arch
		delete(c.metricCache, metric)
		c.accnt.DelMetric(metric)
		archives++
	}

	delete(c.metricRawKeys, rawMetric)
	series++

	return series, archives
}
79623
func (s *HistoricalMetricData) SetMetric(v *HistoricalMetric) *HistoricalMetricData {
	s.Metric = v
	return s
}
200874
func NewMetrics() *Metrics {
	return &Metrics{
		store:      make(map[string]*int64),
		rates:      make(map[string]*rate),
		storeGuard: new(sync.RWMutex),
		rateGuard:  new(sync.RWMutex),
	}
}
197766
func (m *metricMap) getMetricWithHashAndLabelValues(
	h uint64, lvs []string, curry []curriedLabelValue,
) (Metric, bool) {
	metrics, ok := m.metrics[h]
	if ok {
		if i := findMetricWithLabelValues(metrics, lvs, curry); i < len(metrics) {
			return metrics[i].metric, true
		}
	}
	return nil, false
}
54735
func (s *MetricCollectionType) SetMetric(v string) *MetricCollectionType {
	s.Metric = &v
	return s
}
377798
func (s *CurrentMetricData) SetMetric(v *CurrentMetric) *CurrentMetricData {
	s.Metric = v
	return s
}
513773
func (m *metricMap) getOrCreateMetricWithLabels(
	hash uint64, labels Labels, curry []curriedLabelValue,
) Metric {
	m.mtx.RLock()
	metric, ok := m.getMetricWithHashAndLabels(hash, labels, curry)
	m.mtx.RUnlock()
	if ok {
		return metric
	}

	m.mtx.Lock()
	defer m.mtx.Unlock()
	metric, ok = m.getMetricWithHashAndLabels(hash, labels, curry)
	if !ok {
		lvs := extractLabelValues(m.desc, labels, curry)
		metric = m.newMetric(lvs...)
		m.metrics[hash] = append(m.metrics[hash], metricWithLabelValues{values: lvs, metric: metric})
	}
	return metric
}
970307
func InitMetrics() func() {
	if addr := os.Getenv("STATSD_ADDR"); addr != "" {
		metrics.SetEmpireDefaultTags()
		metrics.Reporter, _ = metrics.NewDataDogMetricsReporter(addr)
	}

	return func() {
		metrics.Close()
	}
}
8518
func (f *Mock) GetMetricTypes(cfg plugin.ConfigType) ([]plugin.MetricType, error) {
	mts := []plugin.MetricType{}
	if _, ok := cfg.Table()["test-fail"]; ok {
		return mts, fmt.Errorf("testing")
	}
	if d, ok := cfg.Table()["test-sleep-duration"]; ok {
		duration, err := time.ParseDuration(d.(ctypes.ConfigValueStr).Value)
		if err != nil {
			return nil, err
		}
		time.Sleep(duration)
	}
	if _, ok := cfg.Table()["test"]; ok {
		mts = append(mts, plugin.MetricType{
			Namespace_:   core.NewNamespace("intel", "mock", "test"),
			Description_: "mock description",
			Unit_:        "mock unit",
		})
	}
	if _, ok := cfg.Table()["test-less"]; !ok {
		mts = append(mts, plugin.MetricType{
			Namespace_:   core.NewNamespace("intel", "mock", "foo"),
			Description_: "mock description",
			Unit_:        "mock unit",
		})
	}
	mts = append(mts, plugin.MetricType{
		Namespace_:   core.NewNamespace("intel", "mock", "bar"),
		Description_: "mock description",
		Unit_:        "mock unit",
	})
	mts = append(mts, plugin.MetricType{
		Namespace_: core.NewNamespace("intel", "mock").
			AddDynamicElement("host", "name of the host").
			AddStaticElement("baz"),
		Description_: "mock description",
		Unit_:        "mock unit",
	})
	mts = append(mts, plugin.MetricType{
		Namespace_: core.NewNamespace("intel", "mock").
			AddStaticElement("all").
			AddStaticElement("baz"),
		Description_: "mock description",
		Unit_:        "mock unit",
	})

	return mts, nil
}
816390
func (c *Client) GetMetricVersions(ns string) *GetMetricsResult {
	r := &GetMetricsResult{}
	q := fmt.Sprintf("/metrics?ns=%s", ns)
	resp, err := c.do("GET", q, ContentTypeJSON)
	if err != nil {
		return &GetMetricsResult{Err: err}
	}

	switch resp.Meta.Type {
	case rbody.MetricsReturnedType:
		mc := resp.Body.(*rbody.MetricsReturned)
		r.Catalog = convertCatalog(mc)
	case rbody.ErrorType:
		r.Err = resp.Body.(*rbody.Error)
	default:
		r.Err = ErrAPIResponseMetaType
	}
	return r
}