// NewRTMetrics returns new instance of metrics collector.
169691
func NewRTMetrics(settings ...rrOptSetter) (*RTMetrics, error) {
	m := &RTMetrics{
		statusCodes:     make(map[int]*RollingCounter),
		statusCodesLock: sync.RWMutex{},
	}
	for _, s := range settings {
		if err := s(m); err != nil {
			return nil, err
		}
	}

	if m.clock == nil {
		m.clock = &timetools.RealTime{}
	}

	if m.newCounter == nil {
		m.newCounter = func() (*RollingCounter, error) {
			return NewCounter(counterBuckets, counterResolution, CounterClock(m.clock))
		}
	}

	if m.newHist == nil {
		m.newHist = func() (*RollingHDRHistogram, error) {
			return NewRollingHDRHistogram(histMin, histMax, histSignificantFigures, histPeriod, histBuckets, RollingClock(m.clock))
		}
	}

	h, err := m.newHist()
	if err != nil {
		return nil, err
	}

	netErrors, err := m.newCounter()
	if err != nil {
		return nil, err
	}

	total, err := m.newCounter()
	if err != nil {
		return nil, err
	}

	m.histogram = h
	m.netErrors = netErrors
	m.total = total
	return m, nil
}
479252
func NewMethodMetrics(scope tally.Scope, methodName string, samplingRate float64) MethodMetrics {
	return MethodMetrics{
		Errors:         scope.Counter(methodName + ".errors"),
		Success:        scope.Counter(methodName + ".success"),
		ErrorsLatency:  MustCreateSampledTimer(scope.Timer(methodName+".errors-latency"), samplingRate),
		SuccessLatency: MustCreateSampledTimer(scope.Timer(methodName+".success-latency"), samplingRate),
	}
}
1049572
func (u *Unit) AddMetrics(metrics []params.Metric) error {
	var result params.ErrorResults
	args := params.MetricsParams{
		Metrics: []params.MetricsParam{{
			Tag:     u.tag.String(),
			Metrics: metrics,
		}},
	}
	err := u.st.facade.FacadeCall("AddMetrics", args, &result)
	if err != nil {
		return errors.Annotate(err, "unable to add metric")
	}
	return result.OneError()
}
77778
func (met *Metrics) InitSystemMetrics() {
	met.New(MetricProcessStart)
	met.New(MetricGoRoutines)
	met.New(MetricGoVersion)
	met.New(MetricMemoryAllocated)
	met.New(MetricMemoryNumObjects)
	met.New(MetricMemoryGCEnabled)
	met.Set(MetricProcessStart, ProcessStartTime.Unix())

	version := runtime.Version()
	if version[0] == 'g' && version[1] == 'o' {
		parts := strings.Split(version[2:], ".")
		numericVersion := make([]uint64, tmath.MaxI(3, len(parts)))
		for i, p := range parts {
			numericVersion[i], _ = strconv.ParseUint(p, 10, 64)
		}

		met.SetI(MetricGoVersion, int(numericVersion[0]*10000+numericVersion[1]*100+numericVersion[2]))
	}

	met.UpdateSystemMetrics()
}
958317
func (s *PublicEndpoint) SetMetrics(v map[string]*float64) *PublicEndpoint {
	s.Metrics = v
	return s
}
988885
func (s *DisableMetricsCollectionInput) SetMetrics(v []*string) *DisableMetricsCollectionInput {
	s.Metrics = v
	return s
}
152669
func NewMetrics() *Metrics {
	return &Metrics{Status: StatusUp, Health: 1, Uptime: 0, lastTs: time.Now()}
}
312517
func NewCustomMetricsSpec(config *config.Config) (*CustomMetricsSpec, error) {
	var spec CustomMetricsSpec

	err := config.UnmarshalKey("pitaya.metrics.custom", &spec)
	if err != nil {
		return nil, err
	}

	return &spec, nil
}
864927
func NewMetricConfigBuilder(RequestURI, Method string) (*MetricBuilder, error) {
	//strip leading '/' it's added back below
	requestURI := RequestURI
	if len(RequestURI) > 0 && RequestURI[0] == '/' {
		requestURI = RequestURI[1:]
	}

	logger := plog.WithFields(log.Fields{
		"url": RequestURI,
		"method": Method,
	})

	//use url.Parse to ensure proper RequestURI. 'http://localhost' is removed when Config is built
	url, err := url.Parse("http://localhost/" + requestURI)
	if err != nil {
		logger.WithError(err).Debug("Invalid URL")
		return nil, err
	}

	method := strings.ToUpper(Method)
	switch method {
	case "GET":
	case "PUT":
	case "POST":
	default:
		logger.WithError(err).Debug("Invalid HTTP method")
		return nil, errors.New("invalid method")
	}

	return &MetricBuilder{
		url:     url,
		method:  Method,
		metrics: make([]MetricMetricBuilder, 0),
	}, 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
}
557943
func (s *GetCostAndUsageInput) SetMetrics(v []*string) *GetCostAndUsageInput {
	s.Metrics = v
	return s
}
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()
}
1043218
func StartupMetrics(listenAddr, enabledCollectors string) {
	if listenAddr == "" {
		listenAddr = ":9100"
	}
	if enabledCollectors == "" {
		enabledCollectors = FilterAvailableCollectors(DefaultCollectors)
	}
	collectors, err := LoadCollectors(enabledCollectors)
	if err != nil {
		log.Fatalf("Couldn't load collectors: %s", err)
	}
	nodeCollector := New(collectors)
	prometheus.MustRegister(nodeCollector)
	http.Handle("/metrics", prometheus.Handler())
	go http.ListenAndServe(listenAddr, nil)
}
491689
func NewMetrics(namespace, subsystem string, labels prometheus.Labels) *Metrics {
	var names []string
	for k := range labels {
		names = append(names, k)
	}
	sort.Strings(names)

	getPutNames := append(append([]string(nil), names...), "status")
	sort.Strings(getPutNames)

	return &Metrics{
		LoadFactor: prometheus.NewGaugeVec(prometheus.GaugeOpts{
			Namespace: namespace,
			Subsystem: subsystem,
			Name:      "load_percent",
			Help:      "Load factor of the hashmap.",
		}, names),
		Size: prometheus.NewGaugeVec(prometheus.GaugeOpts{
			Namespace: namespace,
			Subsystem: subsystem,
			Name:      "size",
			Help:      "Number of items in the hashmap.",
		}, names),
		GetDuration: prometheus.NewHistogramVec(prometheus.HistogramOpts{
			Namespace: namespace,
			Subsystem: subsystem,
			Name:      "get_duration_ns",
			Help:      "Times taken to retrieve elements in nanoseconds (sampled every 10% of retrievals).",
			// 15 buckets spaced exponentially between 100 and ~30,000.
			Buckets: prometheus.ExponentialBuckets(100., 1.5, 15),
		}, names),
		LastGetDuration: prometheus.NewGaugeVec(prometheus.GaugeOpts{
			Namespace: namespace,
			Subsystem: subsystem,
			Name:      "get_duration_last_ns",
			Help:      "Last retrieval duration in nanoseconds (sampled every 10% of retrievals)",
		}, names),
		InsertDuration: prometheus.NewHistogramVec(prometheus.HistogramOpts{
			Namespace: namespace,
			Subsystem: subsystem,
			Name:      "put_duration_ns",
			Help:      "Times taken to insert elements in nanoseconds (sampled every 10% of insertions).",
			// 15 buckets spaced exponentially between 100 and ~30,000.
			Buckets: prometheus.ExponentialBuckets(100., 1.5, 15),
		}, names),
		LastInsertDuration: prometheus.NewGaugeVec(prometheus.GaugeOpts{
			Namespace: namespace,
			Subsystem: subsystem,
			Name:      "put_duration_last_ns",
			Help:      "Last insertion duration in nanoseconds (sampled every 10% of insertions)",
		}, names),
		LastGrowDuration: prometheus.NewGaugeVec(prometheus.GaugeOpts{
			Namespace: namespace,
			Subsystem: subsystem,
			Name:      "grow_duration_s",
			Help:      "Time in seconds to last grow the hashmap.",
		}, names),
		MeanProbeCount: prometheus.NewGaugeVec(prometheus.GaugeOpts{
			Namespace: namespace,
			Subsystem: subsystem,
			Name:      "mean_probes",
			Help:      "Average probe count of all elements (sampled every 0.5% of insertions).",
		}, names),

		Gets: prometheus.NewCounterVec(prometheus.CounterOpts{
			Namespace: namespace,
			Subsystem: subsystem,
			Name:      "get_total",
			Help:      "Number of times elements retrieved.",
		}, getPutNames),
		Puts: prometheus.NewCounterVec(prometheus.CounterOpts{
			Namespace: namespace,
			Subsystem: subsystem,
			Name:      "put_total",
			Help:      "Number of times elements inserted.",
		}, getPutNames),
	}
}
73867
func (mtt *mttNode) GetMetric(ns []string, ver int) (*metricType, error) {
	mts, err := mtt.GetMetrics(ns, ver)
	if err != nil {
		return nil, err
	}
	// there is an expectation that only one metric should be fitted
	if len(mts) > 1 {
		return nil, fmt.Errorf("Incoming namespace `%s` is too ambiguous (version: %d)", "/"+strings.Join(ns, "/"), ver)
	}
	return mts[0], nil
}
846243
func (s *MetricAlarm) SetMetrics(v []*MetricDataQuery) *MetricAlarm {
	s.Metrics = v
	return s
}