// NewMetrics initialises prometheus metrics for tracking an RHH hashmap.
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),
	}
}
1368188
func newDbMetrics(dbMap *gorp.DbMap, scope metrics.Scope) *dbMetrics {
	maxOpenConns := prometheus.NewGauge(prometheus.GaugeOpts{
		Name: "db_max_open_connections",
		Help: "Maximum number of DB connections allowed.",
	})
	scope.MustRegister(maxOpenConns)

	openConns := prometheus.NewGauge(prometheus.GaugeOpts{
		Name: "db_open_connections",
		Help: "Number of established DB connections (in-use and idle).",
	})
	scope.MustRegister(openConns)

	inUse := prometheus.NewGauge(prometheus.GaugeOpts{
		Name: "db_inuse",
		Help: "Number of DB connections currently in use.",
	})
	scope.MustRegister(inUse)

	idle := prometheus.NewGauge(prometheus.GaugeOpts{
		Name: "db_idle",
		Help: "Number of idle DB connections.",
	})
	scope.MustRegister(idle)

	waitCount := prometheus.NewCounter(prometheus.CounterOpts{
		Name: "db_wait_count",
		Help: "Total number of DB connections waited for.",
	})
	scope.MustRegister(waitCount)

	waitDuration := prometheus.NewCounter(prometheus.CounterOpts{
		Name: "db_wait_duration_seconds",
		Help: "The total time blocked waiting for a new connection.",
	})
	scope.MustRegister(waitDuration)

	maxIdleClosed := prometheus.NewCounter(prometheus.CounterOpts{
		Name: "db_max_idle_closed",
		Help: "Total number of connections closed due to SetMaxIdleConns.",
	})
	scope.MustRegister(maxIdleClosed)

	maxLifetimeClosed := prometheus.NewCounter(prometheus.CounterOpts{
		Name: "db_max_lifetime_closed",
		Help: "Total number of connections closed due to SetConnMaxLifetime.",
	})
	scope.MustRegister(maxLifetimeClosed)

	// Construct a dbMetrics instance with all of the registered metrics and the
	// gorp DBMap
	return &dbMetrics{
		dbMap:              dbMap,
		maxOpenConnections: maxOpenConns,
		openConnections:    openConns,
		inUse:              inUse,
		idle:               idle,
		waitCount:          waitCount,
		waitDuration:       waitDuration,
		maxIdleClosed:      maxIdleClosed,
		maxLifetimeClosed:  maxLifetimeClosed,
	}
}
117761
func NewMetricsCollector(controller *Controller) *Collector {
	return &Collector{
		controller: controller,
		scrapeDuration: prometheus.NewGauge(
			prometheus.GaugeOpts{
				Namespace: metricsNamespace,
				Name:      "scrape_duration_seconds",
				Help:      "Amount of time taken to collect state metrics.",
			},
		),
		scrapeErrors: prometheus.NewGauge(
			prometheus.GaugeOpts{
				Namespace: metricsNamespace,
				Name:      "scrape_errors",
				Help:      "Number of errors observed while collecting state metrics.",
			},
		),

		models: prometheus.NewGaugeVec(
			prometheus.GaugeOpts{
				Namespace: metricsNamespace,
				Name:      "models",
				Help:      "Number of models in the controller.",
			},
			modelLabelNames,
		),
		machines: prometheus.NewGaugeVec(
			prometheus.GaugeOpts{
				Namespace: metricsNamespace,
				Name:      "machines",
				Help:      "Number of machines managed by the controller.",
			},
			machineLabelNames,
		),
		applications: prometheus.NewGaugeVec(
			prometheus.GaugeOpts{
				Namespace: metricsNamespace,
				Name:      "applications",
				Help:      "Number of applications managed by the controller.",
			},
			applicationLabelNames,
		),
		units: prometheus.NewGaugeVec(
			prometheus.GaugeOpts{
				Namespace: metricsNamespace,
				Name:      "units",
				Help:      "Number of units managed by the controller.",
			},
			unitLabelNames,
		),
		users: prometheus.NewGaugeVec(
			prometheus.GaugeOpts{
				Namespace: metricsNamespace,
				Name:      "users",
				Help:      "Number of local users in the controller.",
			},
			userLabelNames,
		),
	}
}
62568
func NewMetricKeyFromMetric(m *metricpb.Metric) MetricKey {
	return MetricKey{
		Name:       m.Name,
		Type:       strings.ToLower(m.Type.String()),
		JoinedTags: strings.Join(m.Tags, ","),
	}
}
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()
}
811011
func (s *SegmentDimensions) SetMetrics(v map[string]*MetricDimension) *SegmentDimensions {
	s.Metrics = v
	return s
}
1231402
func newMetricsManager(client metricsmanager.MetricsManagerClient, notify chan string) (*worker.Runner, error) {
	// TODO(fwereade): break this out into separate manifolds (with their own facades).

	// Periodic workers automatically retry so none should return an error. If they do
	// it's ok to restart them individually.
	isFatal := func(error) bool {
		return false
	}
	runner := worker.NewRunner(worker.RunnerParams{
		IsFatal:      isFatal,
		RestartDelay: jworker.RestartDelay,
	})
	err := runner.StartWorker("sender", func() (worker.Worker, error) {
		return newSender(client, notify), nil
	})

	if err != nil {
		return nil, errors.Trace(err)
	}

	err = runner.StartWorker("cleanup", func() (worker.Worker, error) {
		return newCleanup(client, notify), nil
	})
	if err != nil {
		return nil, errors.Trace(err)
	}
	return runner, nil
}
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()
}
89082
func NewMetricsServer(addr string, appLister applister.ApplicationLister) *MetricsServer {
	mux := http.NewServeMux()
	appRegistry := NewAppRegistry(appLister)
	appRegistry.MustRegister(prometheus.NewProcessCollector(prometheus.ProcessCollectorOpts{}))
	appRegistry.MustRegister(prometheus.NewGoCollector())
	mux.Handle(MetricsPath, promhttp.HandlerFor(appRegistry, promhttp.HandlerOpts{}))

	syncCounter := prometheus.NewCounterVec(
		prometheus.CounterOpts{
			Name: "argocd_app_sync_total",
			Help: "Number of application syncs.",
		},
		append(descAppDefaultLabels, "phase"),
	)
	appRegistry.MustRegister(syncCounter)
	k8sRequestCounter := prometheus.NewCounterVec(
		prometheus.CounterOpts{
			Name: "argocd_app_k8s_request_total",
			Help: "Number of kubernetes requests executed during application reconciliation.",
		},
		append(descAppDefaultLabels, "response_code"),
	)
	appRegistry.MustRegister(k8sRequestCounter)

	reconcileHistogram := prometheus.NewHistogramVec(
		prometheus.HistogramOpts{
			Name: "argocd_app_reconcile",
			Help: "Application reconciliation performance.",
			// Buckets chosen after observing a ~2100ms mean reconcile time
			Buckets: []float64{0.25, .5, 1, 2, 4, 8, 16},
		},
		append(descAppDefaultLabels),
	)

	appRegistry.MustRegister(reconcileHistogram)

	return &MetricsServer{
		Server: &http.Server{
			Addr:    addr,
			Handler: mux,
		},
		syncCounter:        syncCounter,
		k8sRequestCounter:  k8sRequestCounter,
		reconcileHistogram: reconcileHistogram,
	}
}
481859
func (s *GetReservationCoverageInput) SetMetrics(v []*string) *GetReservationCoverageInput {
	s.Metrics = v
	return s
}
451048
func (s *Stackdriver) newListMetricDescriptorsFilters() []string {
	if len(s.MetricTypePrefixInclude) == 0 {
		return nil
	}

	metricTypeFilters := make([]string, len(s.MetricTypePrefixInclude))
	for i, metricTypePrefix := range s.MetricTypePrefixInclude {
		metricTypeFilters[i] = fmt.Sprintf(`metric.type = starts_with(%q)`, metricTypePrefix)
	}
	return metricTypeFilters
}
516230
func (ctx *HookContext) AddMetric(key, value string, created time.Time) error {
	return errors.New("metrics not allowed in this context")
}
1097038
func NewHashMap(opt Options) *HashMap {
	if opt.Metrics == nil {
		opt.Metrics = NewMetrics("", "", nil)
	}

	m := &HashMap{
		capacity:   pow2(opt.Capacity), // Limited to 2^64.
		loadFactor: opt.LoadFactor,
		tracker:    newRHHTracker(opt.Metrics, opt.Labels),
	}
	m.tracker.enabled = opt.MetricsEnabled

	m.alloc()
	return m
}
115088
func NewMetricsCollector() *Collector {
	return &Collector{
		TotalConnections: prometheus.NewCounter(prometheus.CounterOpts{
			Namespace: apiserverMetricsNamespace,
			Subsystem: apiserverSubsystemNamespace,
			Name:      "connections_total",
			Help:      "Total number of apiserver connections ever made",
		}),

		APIConnections: prometheus.NewGaugeVec(prometheus.GaugeOpts{
			Namespace: apiserverMetricsNamespace,
			Subsystem: apiserverSubsystemNamespace,
			Name:      "connections",
			Help:      "Current number of active apiserver connections for api handlers",
		}, MetricAPIConnectionsLabelNames),
		LoginAttempts: prometheus.NewGauge(prometheus.GaugeOpts{
			Namespace: apiserverMetricsNamespace,
			Subsystem: apiserverSubsystemNamespace,
			Name:      "active_login_attempts",
			Help:      "Current number of active agent login attempts",
		}),
		APIRequestDuration: prometheus.NewSummaryVec(prometheus.SummaryOpts{
			Namespace: apiserverMetricsNamespace,
			Subsystem: apiserverSubsystemNamespace,
			Name:      "request_duration_seconds",
			Help:      "Latency of Juju API requests in seconds.",
		}, metricobserver.MetricLabelNames),
		PingFailureCount: prometheus.NewCounterVec(prometheus.CounterOpts{
			Namespace: apiserverMetricsNamespace,
			Subsystem: apiserverSubsystemNamespace,
			Name:      "ping_failure_count",
			Help:      "Current number of ping failures",
		}, MetricPingFailureLabelNames),
		LogWriteCount: prometheus.NewCounterVec(prometheus.CounterOpts{
			Namespace: apiserverMetricsNamespace,
			Subsystem: apiserverSubsystemNamespace,
			Name:      "log_write_count",
			Help:      "Current number of log writes",
		}, MetricLogLabelNames),
		LogReadCount: prometheus.NewCounterVec(prometheus.CounterOpts{
			Namespace: apiserverMetricsNamespace,
			Subsystem: apiserverSubsystemNamespace,
			Name:      "log_read_count",
			Help:      "Current number of log reads",
		}, MetricLogLabelNames),

		// TODO (stickupkid): remove post 2.6 release
		DeprecatedAPIConnections: prometheus.NewGauge(prometheus.GaugeOpts{
			Namespace: apiserverMetricsNamespace,
			Subsystem: apiserverSubsystemNamespace,
			Name:      "connection_count",
			Help:      "Current number of active apiserver connections",
		}),
		DeprecatedAPIRequestsTotal: prometheus.NewCounterVec(prometheus.CounterOpts{
			Namespace: apiserverMetricsNamespace,
			Subsystem: deprecatedSubsystemNamespace,
			Name:      "requests_total",
			Help:      "Number of Juju API requests served.",
		}, metricobserver.MetricLabelNames),
		DeprecatedAPIRequestDuration: prometheus.NewSummaryVec(prometheus.SummaryOpts{
			Namespace: apiserverMetricsNamespace,
			Subsystem: deprecatedSubsystemNamespace,
			Name:      "request_duration_seconds",
			Help:      "Latency of Juju API requests in seconds.",
		}, metricobserver.MetricLabelNames),
	}
}
365181
func newCacheMetrics(labels prometheus.Labels) *cacheMetrics {
	var names []string
	for k := range labels {
		names = append(names, k)
	}
	sort.Strings(names)

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

	return &cacheMetrics{
		MemSize: prometheus.NewGaugeVec(prometheus.GaugeOpts{
			Namespace: namespace,
			Subsystem: cacheSubsystem,
			Name:      "inuse_bytes",
			Help:      "In-memory size of cache.",
		}, names),
		DiskSize: prometheus.NewGaugeVec(prometheus.GaugeOpts{
			Namespace: namespace,
			Subsystem: cacheSubsystem,
			Name:      "disk_bytes",
			Help:      "Number of bytes on disk used by snapshot data.",
		}, names),
		SnapshotsActive: prometheus.NewGaugeVec(prometheus.GaugeOpts{
			Namespace: namespace,
			Subsystem: cacheSubsystem,
			Name:      "snapshots_active",
			Help:      "Number of active concurrent snapshots (>1 when splitting the cache).",
		}, names),
		Age: prometheus.NewGaugeVec(prometheus.GaugeOpts{
			Namespace: namespace,
			Subsystem: cacheSubsystem,
			Name:      "age_seconds",
			Help:      "Age in seconds of the current cache (time since last snapshot or initialisation).",
		}, names),
		SnapshottedBytes: prometheus.NewCounterVec(prometheus.CounterOpts{
			Namespace: namespace,
			Subsystem: cacheSubsystem,
			Name:      "snapshot_bytes",
			Help:      "Number of bytes snapshotted.",
		}, names),
		WrittenBytes: prometheus.NewCounterVec(prometheus.CounterOpts{
			Namespace: namespace,
			Subsystem: cacheSubsystem,
			Name:      "written_bytes",
			Help:      "Number of bytes successfully written to the Cache.",
		}, writeNames),
		Writes: prometheus.NewCounterVec(prometheus.CounterOpts{
			Namespace: namespace,
			Subsystem: cacheSubsystem,
			Name:      "writes_total",
			Help:      "Number of writes to the Cache.",
		}, writeNames),
	}
}
25189
func NewMetric(m *Metric, subsystem string) prometheus.Collector {
	var metric prometheus.Collector
	switch m.Type {
	case "counter_vec":
		metric = prometheus.NewCounterVec(
			prometheus.CounterOpts{
				Subsystem: subsystem,
				Name:      m.Name,
				Help:      m.Description,
			},
			m.Args,
		)
	case "counter":
		metric = prometheus.NewCounter(
			prometheus.CounterOpts{
				Subsystem: subsystem,
				Name:      m.Name,
				Help:      m.Description,
			},
		)
	case "gauge_vec":
		metric = prometheus.NewGaugeVec(
			prometheus.GaugeOpts{
				Subsystem: subsystem,
				Name:      m.Name,
				Help:      m.Description,
			},
			m.Args,
		)
	case "gauge":
		metric = prometheus.NewGauge(
			prometheus.GaugeOpts{
				Subsystem: subsystem,
				Name:      m.Name,
				Help:      m.Description,
			},
		)
	case "histogram_vec":
		metric = prometheus.NewHistogramVec(
			prometheus.HistogramOpts{
				Subsystem: subsystem,
				Name:      m.Name,
				Help:      m.Description,
			},
			m.Args,
		)
	case "histogram":
		metric = prometheus.NewHistogram(
			prometheus.HistogramOpts{
				Subsystem: subsystem,
				Name:      m.Name,
				Help:      m.Description,
			},
		)
	case "summary_vec":
		metric = prometheus.NewSummaryVec(
			prometheus.SummaryOpts{
				Subsystem: subsystem,
				Name:      m.Name,
				Help:      m.Description,
			},
			m.Args,
		)
	case "summary":
		metric = prometheus.NewSummary(
			prometheus.SummaryOpts{
				Subsystem: subsystem,
				Name:      m.Name,
				Help:      m.Description,
			},
		)
	}
	return metric
}
1074336
func newMetricVec(desc *Desc, newMetric func(lvs ...string) Metric) *metricVec {
	return &metricVec{
		metricMap: &metricMap{
			metrics:   map[uint64][]metricWithLabelValues{},
			desc:      desc,
			newMetric: newMetric,
		},
		hashAdd:     hashAdd,
		hashAddByte: hashAddByte,
	}
}