// newMetricsCollector returns a collector for the metrics gathered in the
// hashicorp/raft library code.
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
}
746978
func newFileMetrics(labels prometheus.Labels) *fileMetrics {
	var names []string
	for k := range labels {
		names = append(names, k)
	}
	names = append(names, "level")
	sort.Strings(names)

	return &fileMetrics{
		DiskSize: prometheus.NewGaugeVec(prometheus.GaugeOpts{
			Namespace: namespace,
			Subsystem: fileStoreSubsystem,
			Name:      "disk_bytes",
			Help:      "Number of bytes TSM files using on disk.",
		}, names),
		Files: prometheus.NewGaugeVec(prometheus.GaugeOpts{
			Namespace: namespace,
			Subsystem: fileStoreSubsystem,
			Name:      "total",
			Help:      "Number of files.",
		}, names),
	}
}
693750
func NewMetricsEvent(ts int64, path string, records int) Event {
	e := &metricsEvent{
		Ts:      ts,
		Kind:    "metrics",
		Path:    path,
		Records: records,
	}
	return e
}
531272
func NewGoMetricsWith(eng *stats.Engine) *GoMetrics {
	g := &GoMetrics{
		engine:  eng,
		version: runtime.Version(),
	}

	g.memstats.total.memtype = "total"
	g.memstats.heap.memtype = "heap"
	g.memstats.stack.memtype = "stack"
	g.memstats.mspan.memtype = "mspan"
	g.memstats.mcache.memtype = "mcache"
	g.memstats.buckhash.memtype = "bucket_hash_table"
	g.memstats.gc.memtype = "gc"
	g.memstats.other.memtype = "other"
	return g
}
925013
func newJSONMetricsByWorker(metrics []samplers.JSONMetric, numWorkers int) *jsonMetricsByWorker {
	ret := &jsonMetricsByWorker{
		sjm: newSortableJSONMetrics(metrics, numWorkers),
	}
	sort.Sort(ret.sjm)
	return ret
}
1026013
func NewCCacheMetric(mkey schema.MKey) *CCacheMetric {
	return &CCacheMetric{
		MKey:   mkey,
		chunks: make(map[uint32]*CCacheChunk),
	}
}
1327055
func NewMetricsFile(fs *FS, entryValid *time.Duration) *SpecialReadFile {
	*entryValid = 0
	return &SpecialReadFile{read: libfs.GetEncodedMetrics(fs.config)}
}
1363488
func (m *fileMetrics) PrometheusCollectors() []prometheus.Collector {
	return []prometheus.Collector{
		m.DiskSize,
		m.Files,
	}
}
344988
func NewMetrics() *Metrics {
	m := &Metrics{
		TimeMetrics:   make(map[string]*TimeStats),
		NumberMetrics: make(map[string]*NumberStats),
		BoolMetrics:   make(map[string]*BoolStats),
	}
	return m
}
1131701
func NewMetricType(namespace core.Namespace, timestamp time.Time, tags map[string]string, unit string, data interface{}) *MetricType {
	return &MetricType{
		Namespace_:          namespace,
		Tags_:               tags,
		Data_:               data,
		Timestamp_:          timestamp,
		LastAdvertisedTime_: timestamp,
		Unit_:               unit,
	}
}
213893
func NewHostStatsCollector(logger hclog.Logger, allocDir string, deviceStatsCollector DeviceStatsCollector) *HostStatsCollector {
	logger = logger.Named("host_stats")
	numCores := runtime.NumCPU()
	statsCalculator := make(map[string]*HostCpuStatsCalculator)
	collector := &HostStatsCollector{
		statsCalculator:      statsCalculator,
		numCores:             numCores,
		logger:               logger,
		allocDir:             allocDir,
		badParts:             make(map[string]struct{}),
		deviceStatsCollector: deviceStatsCollector,
	}
	return collector
}
535121
func NewCachedBlobStatterWithMetrics(cache distribution.BlobDescriptorService, backend distribution.BlobDescriptorService, tracker MetricsTracker) distribution.BlobStatter {
	return &cachedBlobStatter{
		cache:   cache,
		backend: backend,
		tracker: tracker,
	}
}
174475
func newAPIServerMetricsServer() *http.Server {
	mux := http.NewServeMux()
	mux.Handle("/metrics", promhttp.Handler())
	return &http.Server{
		Addr:    fmt.Sprintf("0.0.0.0:%d", common.PortArgoCDAPIServerMetrics),
		Handler: mux,
	}
}
999393
func NewPrometheusResourceMetricCollector(provider SummaryProvider, config ResourceMetricsConfig) prometheus.Collector {
	return &resourceMetricCollector{
		provider: provider,
		config:   config,
		errors: prometheus.NewGauge(prometheus.GaugeOpts{
			Name: "scrape_error",
			Help: "1 if there was an error while getting container metrics, 0 otherwise",
		}),
	}
}
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
}
227856
func NewAccountingMetrics(r metrics.Registry, d time.Duration, path string) *AccountingMetrics {
	var val = make([]byte, 8)
	var err error

	//Create the LevelDB
	db, err := leveldb.OpenFile(path, nil)
	if err != nil {
		log.Error(err.Error())
		return nil
	}

	//Check for all defined metrics that there is a value in the DB
	//If there is, assign it to the metric. This means that the node
	//has been running before and that metrics have been persisted.
	metricsMap := map[string]metrics.Counter{
		"account.balance.credit": mBalanceCredit,
		"account.balance.debit":  mBalanceDebit,
		"account.bytes.credit":   mBytesCredit,
		"account.bytes.debit":    mBytesDebit,
		"account.msg.credit":     mMsgCredit,
		"account.msg.debit":      mMsgDebit,
		"account.peerdrops":      mPeerDrops,
		"account.selfdrops":      mSelfDrops,
	}
	//iterate the map and get the values
	for key, metric := range metricsMap {
		val, err = db.Get([]byte(key), nil)
		//until the first time a value is being written,
		//this will return an error.
		//it could be beneficial though to log errors later,
		//but that would require a different logic
		if err == nil {
			metric.Inc(int64(binary.BigEndian.Uint64(val)))
		}
	}

	//create the reporter
	rep := &reporter{
		reg:      r,
		interval: d,
		db:       db,
		quit:     make(chan struct{}),
		done:     make(chan struct{}),
	}

	//run the go routine
	go rep.run()

	m := &AccountingMetrics{
		reporter: rep,
	}

	return m
}
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
}