// TrackMetrics decorates a MessageHandler to collect metrics about successes, failures and runtime reports in ms*10.
519471
func TrackMetrics(successes, failures *expvar.Int, timing *expvar.Float) MessageHandlerDecorator {
	ema := movingaverage.New(5 * time.Second)

	return func(fn sqsconsumer.MessageHandlerFunc) sqsconsumer.MessageHandlerFunc {
		return func(ctx context.Context, msg string) error {
			start := time.Now()
			defer func() {
				v := ema.Update(time.Since(start).Seconds() * 1000)
				timing.Set(v)
			}()

			err := fn(ctx, msg)
			if err != nil {
				failures.Add(1)
			} else {
				successes.Add(1)
			}
			return err
		}
	}
}
54610
func (s *Server) SendMetrics(ctx context.Context, mlist *forwardrpc.MetricList) (*empty.Empty, error) {
	span, _ := trace.StartSpanFromContext(ctx, "veneur.opentracing.importsrv.handle_send_metrics")
	span.SetTag("protocol", "grpc")
	defer span.ClientFinish(s.opts.traceClient)

	dests := make([][]*metricpb.Metric, len(s.metricOuts))

	// group metrics by their destination
	groupStart := time.Now()
	for _, m := range mlist.Metrics {
		workerIdx := s.hashMetric(m) % uint32(len(dests))
		dests[workerIdx] = append(dests[workerIdx], m)
	}
	span.Add(ssf.Timing(responseDurationMetric, time.Since(groupStart), time.Nanosecond, responseGroupTags))

	// send each set of metrics to its destination.  Since this is typically
	// implemented with channels, batching the metrics together avoids
	// repeated channel send operations
	sendStart := time.Now()
	for i, ms := range dests {
		if len(ms) > 0 {
			s.metricOuts[i].IngestMetrics(ms)
		}
	}

	span.Add(
		ssf.Timing(responseDurationMetric, time.Since(sendStart), time.Nanosecond, responseSendTags),
		ssf.Count("import.metrics_total", float32(len(mlist.Metrics)), grpcTags),
	)

	return &empty.Empty{}, nil
}
199763
func NewMetricSystem(interval time.Duration, sysStats bool) *MetricSystem {
	ms := &MetricSystem{
		percentiles: map[string]float64{
			"%s_min":   0,
			"%s_50":    .5,
			"%s_75":    .75,
			"%s_90":    .9,
			"%s_95":    .95,
			"%s_99":    .99,
			"%s_99.9":  .999,
			"%s_99.99": .9999,
			"%s_max":   1,
		},
		interval:                        interval,
		subscribeToRawMetrics:           make(chan chan *RawMetricSet, 64),
		unsubscribeFromRawMetrics:       make(chan chan *RawMetricSet, 64),
		subscribeToProcessedMetrics:     make(chan chan *ProcessedMetricSet, 64),
		unsubscribeFromProcessedMetrics: make(chan chan *ProcessedMetricSet, 64),
		rawSubscribers:                  make(map[chan *RawMetricSet]struct{}),
		rawBadSubscribers:               make(map[chan *RawMetricSet]int),
		processedSubscribers:            make(map[chan *ProcessedMetricSet]struct{}),
		processedBadSubscribers:         make(map[chan *ProcessedMetricSet]int),
		counterStore:                    make(map[string]*uint64),
		counterCache:                    make(map[string]*uint64),
		histogramCache:                  make(map[string]map[int16]*uint64),
		histogramCountStore:             make(map[string]*uint64),
		gaugeFuncs:                      make(map[string]func() float64),
		shutdownChan:                    make(chan struct{}),
	}
	if sysStats {
		ms.gaugeFuncsMu.Lock()
		ms.gaugeFuncs["sys.Alloc"] = func() float64 {
			memStats := new(runtime.MemStats)
			runtime.ReadMemStats(memStats)
			return float64(memStats.Alloc)
		}
		ms.gaugeFuncs["sys.NumGC"] = func() float64 {
			memStats := new(runtime.MemStats)
			runtime.ReadMemStats(memStats)
			return float64(memStats.NumGC)
		}
		ms.gaugeFuncs["sys.PauseTotalNs"] = func() float64 {
			memStats := new(runtime.MemStats)
			runtime.ReadMemStats(memStats)
			return float64(memStats.PauseTotalNs)
		}
		ms.gaugeFuncs["sys.NumGoroutine"] = func() float64 {
			return float64(runtime.NumGoroutine())
		}
		ms.gaugeFuncsMu.Unlock()
	}
	return ms
}
142542
func (p *pluginControl) ProcessMetrics(metrics []core.Metric, config map[string]ctypes.ConfigValue, taskID, pluginName string, pluginVersion int) ([]core.Metric, []error) {
	// If control is not started we don't want tasks to be able to
	// go through a workflow.
	if !p.Started {
		return nil, []error{ErrControllerNotStarted}
	}
	// merge global plugin config into the config for this request
	// without over-writing the task specific config
	cfg := p.Config.Plugins.getPluginConfigDataNode(core.ProcessorPluginType, pluginName, pluginVersion).Table()
	merged := make(map[string]ctypes.ConfigValue)
	for k, v := range cfg {
		merged[k] = v
	}
	for k, v := range config {
		merged[k] = v
	}

	return p.pluginRunner.AvailablePlugins().processMetrics(metrics, pluginName, pluginVersion, merged, taskID)
}
846243
func (s *MetricAlarm) SetMetrics(v []*MetricDataQuery) *MetricAlarm {
	s.Metrics = v
	return s
}
699211
func requestMetrics(l *log.Logger) service {
	return func(h http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			start := time.Now()
			h.ServeHTTP(w, r)
			l.Printf("%s request to %s took %vns.", r.Method, r.URL.Path, time.Now().Sub(start).Nanoseconds())
		})
	}
}
958317
func (s *PublicEndpoint) SetMetrics(v map[string]*float64) *PublicEndpoint {
	s.Metrics = v
	return s
}
641394
func (api *MetricsDebugAPI) GetMetrics(args params.Entities) (params.MetricResults, error) {
	results := params.MetricResults{
		Results: make([]params.EntityMetrics, len(args.Entities)),
	}
	if len(args.Entities) == 0 {
		batches, err := api.state.MetricBatchesForModel()
		if err != nil {
			return results, errors.Annotate(err, "failed to get metrics")
		}
		return params.MetricResults{
			Results: []params.EntityMetrics{{
				Metrics: api.filterLastValuePerKeyPerUnit(batches),
			}},
		}, nil
	}
	for i, arg := range args.Entities {
		tag, err := names.ParseTag(arg.Tag)
		if err != nil {
			results.Results[i].Error = common.ServerError(err)
			continue
		}
		var batches []state.MetricBatch
		switch tag.Kind() {
		case names.UnitTagKind:
			batches, err = api.state.MetricBatchesForUnit(tag.Id())
			if err != nil {
				err = errors.Annotate(err, "failed to get metrics")
				results.Results[i].Error = common.ServerError(err)
				continue
			}
		case names.ApplicationTagKind:
			batches, err = api.state.MetricBatchesForApplication(tag.Id())
			if err != nil {
				err = errors.Annotate(err, "failed to get metrics")
				results.Results[i].Error = common.ServerError(err)
				continue
			}
		default:
			err := errors.Errorf("invalid tag %v", arg.Tag)
			results.Results[i].Error = common.ServerError(err)
		}
		results.Results[i].Metrics = api.filterLastValuePerKeyPerUnit(batches)
	}
	return results, nil
}
1051626
func (c *Client) DebugEnableMetrics() (string, error) {
	result := ""
	err := c.call("DebugEnableMetrics", empty, &result)
	if err != nil {
		return "", err
	}
	return result, nil
}
912652
func (r Network_Bandwidth_Version1_Allotment) GetMetricTrackingObject() (resp datatypes.Metric_Tracking_Object_VirtualDedicatedRack, err error) {
	err = r.Session.DoRequest("SoftLayer_Network_Bandwidth_Version1_Allotment", "getMetricTrackingObject", nil, &r.Options, &resp)
	return
}
254086
func getMetricsForever(m *Aggregator) {
	for {
		m.metricStream <- m.get()
		time.Sleep(m.produceInterval * time.Second)
	}
}
1121840
func (c *Collector) metricsMessages() (out []producers.MetricsMessage) {
	var msg producers.MetricsMessage
	t := time.Unix(c.timestamp, 0)

	for _, cm := range c.containerMetrics {
		datapoints, err := c.createContainerDatapoints(cm)
		if err == ErrNoStatistics {
			c.log.Warnf("Container ID %q did not supply any statistics; no metrics message will be sent", cm.ContainerID)
			continue
		}
		if err != nil {
			c.log.Errorf("Could not retrieve datapoints for container ID %q: %s", cm.ContainerID, err)
			continue
		}
		msg = producers.MetricsMessage{
			Name:       producers.ContainerMetricPrefix,
			Datapoints: datapoints,
			Timestamp:  t.UTC().Unix(),
		}

		fi := getFrameworkInfoByFrameworkID(cm.FrameworkID, c.agentState.Frameworks)
		if fi == nil {
			c.log.Warnf("Did not find FrameworkInfo for framework ID %s, skipping!", cm.FrameworkID)
			continue
		}

		ei := getExecutorInfoByExecutorID(cm.ExecutorID, fi.Executors)
		if ei == nil {
			c.log.Warnf("Did not find ExecutorInfo for executor ID %s, skipping!", cm.ExecutorID)
			continue
		}

		ti := getTaskInfoByContainerID(cm.ContainerID, ei.Tasks)
		if ti == nil {
			// This is not a warning because task ID is not guaranteed to be set, eg
			// a custom executor is a container with no associated task.
			c.log.Debugf("Did not find TaskInfo for container ID %s.", cm.ContainerID)
		}

		msg.Dimensions = producers.Dimensions{
			MesosID:            c.nodeInfo.MesosID,
			ClusterID:          c.nodeInfo.ClusterID,
			Hostname:           c.nodeInfo.Hostname,
			ContainerID:        cm.ContainerID,
			ExecutorID:         cm.ExecutorID,
			FrameworkID:        cm.FrameworkID,
			FrameworkName:      fi.Name,
			FrameworkRole:      fi.Role,
			FrameworkPrincipal: fi.Principal,
			Labels:             getLabelsByContainerID(cm.ContainerID, c.agentState.Frameworks, c.log),
		}

		if ti != nil {
			msg.Dimensions.TaskID = ti.ID
			msg.Dimensions.TaskName = ti.Name
		}
		out = append(out, msg)
	}
	return out
}
267594
func WithGroupTracking(metric []telegraf.Metric, fn NotifyFunc) ([]telegraf.Metric, telegraf.TrackingID) {
	return newTrackingMetricGroup(metric, fn)
}
1223253
func NewGetMetrics(ctx *middleware.Context, handler GetMetricsHandler) *GetMetrics {
	return &GetMetrics{Context: ctx, Handler: handler}
}
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
}
271398
func (h *TrackHandler) Track(ctx context.Context, arg keybase1.TrackArg) (keybase1.ConfirmResult, error) {
	earg := engine.TrackEngineArg{
		UserAssertion:    arg.UserAssertion,
		Options:          arg.Options,
		ForceRemoteCheck: arg.ForceRemoteCheck,
	}
	uis := libkb.UIs{
		IdentifyUI: h.NewRemoteIdentifyUI(arg.SessionID, h.G()),
		SecretUI:   h.getSecretUI(arg.SessionID, h.G()),
		SessionID:  arg.SessionID,
	}
	eng := engine.NewTrackEngine(h.G(), &earg)
	m := libkb.NewMetaContext(ctx, h.G()).WithUIs(uis)
	err := engine.RunEngine2(m, eng)
	res := eng.ConfirmResult()
	return res, err
}
875249
func (mb *SquareMetrics) collectMetrics() {
	var mem runtime.MemStats

	update := func(name string, value uint64) {
		metrics.GetOrRegisterGauge(name, mb.Registry).Update(int64(value))
	}

	updateFloat := func(name string, value float64) {
		metrics.GetOrRegisterGaugeFloat64(name, mb.Registry).Update(value)
	}

	sample := metrics.NewExpDecaySample(1028, 0.015)
	gcHistogram := metrics.GetOrRegisterHistogram("runtime.mem.gc.duration", mb.Registry, sample)

	var observedPauses uint32
	for range time.Tick(mb.interval) {
		runtime.ReadMemStats(&mem)

		update("runtime.mem.alloc", mem.Alloc)
		update("runtime.mem.total-alloc", mem.TotalAlloc)
		update("runtime.mem.sys", mem.Sys)
		update("runtime.mem.lookups", mem.Lookups)
		update("runtime.mem.mallocs", mem.Mallocs)
		update("runtime.mem.frees", mem.Frees)

		update("runtime.mem.heap.alloc", mem.HeapAlloc)
		update("runtime.mem.heap.sys", mem.HeapSys)
		update("runtime.mem.heap.idle", mem.HeapIdle)
		update("runtime.mem.heap.inuse", mem.HeapInuse)
		update("runtime.mem.heap.released", mem.HeapReleased)
		update("runtime.mem.heap.objects", mem.HeapObjects)

		update("runtime.mem.stack.inuse", mem.StackInuse)
		update("runtime.mem.stack.sys", mem.StackSys)

		update("runtime.goroutines", uint64(runtime.NumGoroutine()))
		update("runtime.cgo-calls", uint64(runtime.NumCgoCall()))

		update("runtime.mem.gc.num-gc", uint64(mem.NumGC))
		updateFloat("runtime.mem.gc.cpu-fraction", mem.GCCPUFraction)

		// Update histogram of GC pauses
		for ; observedPauses < mem.NumGC; observedPauses++ {
			gcHistogram.Update(int64(mem.PauseNs[(observedPauses+1)%256]))
		}

		// Update gauges
		mb.mutex.Lock()
		for _, gauge := range mb.gauges {
			gauge.gauge.Update(gauge.callback())
		}
		mb.mutex.Unlock()
	}
}