// nodeMetrics returns a metric timeseries for a metric of the Node entity.
487974
func (a *Api) nodeMetrics(request *restful.Request, response *restful.Response) {
	a.processMetricRequest(core.NodeKey(request.PathParameter("node-name")),
		request, response)
}
1208994
func (c *Client) GetMetrics(tags ...string) ([]params.MetricResult, error) {
	entities := make([]params.Entity, len(tags))
	for i, tag := range tags {
		entities[i] = params.Entity{Tag: tag}
	}
	p := params.Entities{Entities: entities}
	results := new(params.MetricResults)
	if err := c.facade.FacadeCall("GetMetrics", p, results); err != nil {
		return nil, errors.Trace(err)
	}
	if err := results.OneError(); err != nil {
		return nil, errors.Trace(err)
	}
	metrics := []params.MetricResult{}
	for _, r := range results.Results {
		metrics = append(metrics, r.Metrics...)
	}
	return metrics, nil
}
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
}
624589
func Convert_v1alpha1_NodeMetricsList_To_metrics_NodeMetricsList(in *NodeMetricsList, out *metrics.NodeMetricsList, s conversion.Scope) error {
	return autoConvert_v1alpha1_NodeMetricsList_To_metrics_NodeMetricsList(in, out, s)
}
126889
func publishMetrics(customDimensionMap map[string]string) {
	currentTime := time.Now()

	// https://docs.aws.amazon.com/lambda/latest/dg/current-supported-versions.html
	functionName := os.Getenv("AWS_LAMBDA_FUNCTION_NAME")
	cpuMetrics, cpuMetricsErr := gopsutilCPU.Percent(0, false)
	// https://docs.aws.amazon.com/lambda/latest/dg/limits.html
	diskMetrics, diskMetricsErr := gopsutilDisk.Usage("/tmp")
	uptime, uptimeErr := gopsutilHost.Uptime()
	loadMetrics, loadMetricsErr := gopsutilLoad.Avg()
	netMetrics, netMetricsErr := gopsutilNet.IOCounters(false)

	// For now, just log everything...
	logger, _ := sparta.NewLogger("info")
	logger.WithFields(logrus.Fields{
		"functionName":   functionName,
		"cpuMetrics":     cpuMetrics,
		"cpuMetricsErr":  cpuMetricsErr,
		"diskMetrics":    diskMetrics,
		"diskMetricsErr": diskMetricsErr,
		"uptime":         uptime,
		"uptimeErr":      uptimeErr,
		"loadMetrics":    loadMetrics,
		"loadMetricsErr": loadMetricsErr,
		"netMetrics":     netMetrics,
		"netMetricsErr":  netMetricsErr,
	}).Info("Metric info")

	// Return the array of metricDatum for the item
	metricDatum := func(name string, value float64, unit MetricUnit) []*awsCloudWatch.MetricDatum {
		defaultDatum := []*awsCloudWatch.MetricDatum{{
			MetricName: aws.String(name),
			Dimensions: []*awsCloudWatch.Dimension{{
				Name:  aws.String("Name"),
				Value: aws.String(sparta.StampedServiceName),
			}},
			Value:     aws.Float64(value),
			Timestamp: &currentTime,
			Unit:      aws.String(string(unit)),
		},
		}
		if len(customDimensionMap) != 0 {
			metricDimension := []*awsCloudWatch.Dimension{{
				Name:  aws.String("Name"),
				Value: aws.String(sparta.StampedServiceName),
			}}
			for eachKey, eachValue := range customDimensionMap {
				metricDimension = append(metricDimension, &awsCloudWatch.Dimension{
					Name:  aws.String(eachKey),
					Value: aws.String(eachValue),
				})
			}
			defaultDatum = append(defaultDatum, &awsCloudWatch.MetricDatum{
				MetricName: aws.String(name),
				Dimensions: metricDimension,
				Value:      aws.Float64(value),
				Timestamp:  &currentTime,
				Unit:       aws.String(string(unit)),
			})
		}
		return defaultDatum
	}
	// Publish all the metrics...
	// https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_MetricDatum.html
	metricData := []*awsCloudWatch.MetricDatum{}
	// CPU?
	if len(cpuMetrics) == 1 {
		metricData = append(metricData, metricDatum("CPUPercent", cpuMetrics[0], UnitPercent)...)
	}
	if diskMetricsErr == nil {
		metricData = append(metricData, metricDatum("DiskUsedPercent", diskMetrics.UsedPercent, UnitPercent)...)
	}
	if uptimeErr == nil {
		metricData = append(metricData, metricDatum("Uptime", float64(uptime), UnitMilliseconds)...)
	}
	if loadMetricsErr == nil {
		metricData = append(metricData, metricDatum("Load1", loadMetrics.Load1, UnitNone)...)
		metricData = append(metricData, metricDatum("Load5", loadMetrics.Load5, UnitNone)...)
		metricData = append(metricData, metricDatum("Load15", loadMetrics.Load15, UnitNone)...)
	}
	if netMetricsErr == nil && len(netMetrics) == 1 {
		metricData = append(metricData, metricDatum("NetBytesSent", float64(netMetrics[0].BytesSent), UnitBytes)...)
		metricData = append(metricData, metricDatum("NetBytesRecv", float64(netMetrics[0].BytesRecv), UnitBytes)...)
		metricData = append(metricData, metricDatum("NetErrin", float64(netMetrics[0].Errin), UnitCount)...)
		metricData = append(metricData, metricDatum("NetErrout", float64(netMetrics[0].Errout), UnitCount)...)
	}
	putMetricInput := &awsCloudWatch.PutMetricDataInput{
		MetricData: metricData,
		Namespace:  aws.String(sparta.ProperName),
	}
	session := spartaAWS.NewSession(logger)
	awsCloudWatchSvc := awsCloudWatch.New(session)
	putMetricResponse, putMetricResponseErr := awsCloudWatchSvc.PutMetricData(putMetricInput)
	if putMetricResponseErr != nil {
		logger.WithField("Error", putMetricResponseErr).Error("Failed to submit CloudWatch Metric data")
	} else {
		logger.WithField("Response", putMetricResponse).Info("CloudWatch Metric response")
	}
}
854799
func (a *AllocMetric) ScoreNode(node *Node, name string, score float64) {
	// Create nodeScoreMeta lazily if its the first time or if its a new node
	if a.nodeScoreMeta == nil || a.nodeScoreMeta.NodeID != node.ID {
		a.nodeScoreMeta = &NodeScoreMeta{
			NodeID: node.ID,
			Scores: make(map[string]float64),
		}
	}
	if name == NormScorerName {
		a.nodeScoreMeta.NormScore = score
		// Once we have the normalized score we can push to the heap
		// that tracks top K by normalized score

		// Create the heap if its not there already
		if a.topScores == nil {
			a.topScores = kheap.NewScoreHeap(MaxRetainedNodeScores)
		}
		heap.Push(a.topScores, a.nodeScoreMeta)

		// Clear out this entry because its now in the heap
		a.nodeScoreMeta = nil
	} else {
		a.nodeScoreMeta.Scores[name] = score
	}
}
1267241
func (c *Performance) GetMetrics() ([]*PerformanceMetric, error) {
	resp, err := gcdmessage.SendCustomReturn(c.target, c.target.GetSendCh(), &gcdmessage.ParamRequest{Id: c.target.GetId(), Method: "Performance.getMetrics"})
	if err != nil {
		return nil, err
	}

	var chromeData struct {
		Result struct {
			Metrics []*PerformanceMetric
		}
	}

	if resp == nil {
		return nil, &gcdmessage.ChromeEmptyResponseErr{}
	}

	// test if error first
	cerr := &gcdmessage.ChromeErrorResponse{}
	json.Unmarshal(resp.Data, cerr)
	if cerr != nil && cerr.Error != nil {
		return nil, &gcdmessage.ChromeRequestErr{Resp: cerr}
	}

	if err := json.Unmarshal(resp.Data, &chromeData); err != nil {
		return nil, err
	}

	return chromeData.Result.Metrics, nil
}
866383
func (e *Endpoint) ReadMetrics(em *EndpointMetrics) {
	e.metrics.Lock()
	defer e.metrics.Unlock()

	*em = e.metrics.EndpointMetrics
	// Map still need to copied in a threadsafe manner.
	em.Statuses = make(map[string]int)
	for k, v := range e.metrics.Statuses {
		em.Statuses[k] = v
	}
}
1154591
func (sdk *FabricSDK) initMetrics(configs *configs) {
	if configs == nil {
		return
	}
	if sdk.system == nil {
		sdk.system = newOperationsSystem(configs)

		err := sdk.system.Start()
		if err != nil {
			panic("metrics failed to start: " + err.Error())
		}

		// for now NewClientMetrics supports channel client. TODO: if other client types require metrics tracking, update this function
		sdk.clientMetrics = metrics.NewClientMetrics(sdk.system.Provider)
	}
}
205816
func (s *NodesStatsService) IndexMetric(indexMetric ...string) *NodesStatsService {
	s.indexMetric = append(s.indexMetric, indexMetric...)
	return s
}
75426
func (a *HistoricalApi) clusterMetrics(request *restful.Request, response *restful.Response) {
	key := core.HistoricalKey{ObjectType: core.MetricSetTypeCluster}
	a.processMetricRequest(key, request, response)
}
1237823
func (c *Client) emitClientMetrics() {
	nodeID := c.NodeID()

	c.setGaugeForAllocationStats(nodeID)

	// Emit allocation metrics
	blocked, migrating, pending, running, terminal := 0, 0, 0, 0, 0
	for _, ar := range c.getAllocRunners() {
		switch ar.AllocState().ClientStatus {
		case structs.AllocClientStatusPending:
			switch {
			case ar.IsWaiting():
				blocked++
			case ar.IsMigrating():
				migrating++
			default:
				pending++
			}
		case structs.AllocClientStatusRunning:
			running++
		case structs.AllocClientStatusComplete, structs.AllocClientStatusFailed:
			terminal++
		}
	}

	if !c.config.DisableTaggedMetrics {
		metrics.SetGaugeWithLabels([]string{"client", "allocations", "migrating"}, float32(migrating), c.baseLabels)
		metrics.SetGaugeWithLabels([]string{"client", "allocations", "blocked"}, float32(blocked), c.baseLabels)
		metrics.SetGaugeWithLabels([]string{"client", "allocations", "pending"}, float32(pending), c.baseLabels)
		metrics.SetGaugeWithLabels([]string{"client", "allocations", "running"}, float32(running), c.baseLabels)
		metrics.SetGaugeWithLabels([]string{"client", "allocations", "terminal"}, float32(terminal), c.baseLabels)
	}

	if c.config.BackwardsCompatibleMetrics {
		metrics.SetGauge([]string{"client", "allocations", "migrating", nodeID}, float32(migrating))
		metrics.SetGauge([]string{"client", "allocations", "blocked", nodeID}, float32(blocked))
		metrics.SetGauge([]string{"client", "allocations", "pending", nodeID}, float32(pending))
		metrics.SetGauge([]string{"client", "allocations", "running", nodeID}, float32(running))
		metrics.SetGauge([]string{"client", "allocations", "terminal", nodeID}, float32(terminal))
	}
}
1117371
func (c *CloudWatch) gatherMetrics(
	params *cloudwatch.GetMetricDataInput,
) ([]*cloudwatch.MetricDataResult, error) {
	results := []*cloudwatch.MetricDataResult{}

	for {
		resp, err := c.client.GetMetricData(params)
		if err != nil {
			return nil, fmt.Errorf("failed to get metric data: %v", err)
		}

		results = append(results, resp.MetricDataResults...)
		if resp.NextToken == nil {
			break
		}
		params.NextToken = resp.NextToken
	}

	return results, nil
}
768168
func newBlockMetrics(labels prometheus.Labels) *blockMetrics {
	return &blockMetrics{
		labels:            labels,
		compactionMetrics: newCompactionMetrics(labels),
		fileMetrics:       newFileMetrics(labels),
		cacheMetrics:      newCacheMetrics(labels),
	}
}
663521
func RegisterMetrics() {
	registerMetricsOnce.Do(func() {
		prometheus.MustRegister(SyncProxyRulesLatency)
		prometheus.MustRegister(DeprecatedSyncProxyRulesLatency)
		prometheus.MustRegister(NetworkProgrammingLatency)
	})
}
898425
func Convert_metrics_NodeMetricsList_To_v1alpha1_NodeMetricsList(in *metrics.NodeMetricsList, out *NodeMetricsList, s conversion.Scope) error {
	return autoConvert_metrics_NodeMetricsList_To_v1alpha1_NodeMetricsList(in, out, s)
}
667985
func (w *Worker) ProcessMetric(m *samplers.UDPMetric) {
	w.mutex.Lock()
	defer w.mutex.Unlock()
	w.processed++
	w.wm.Upsert(m.MetricKey, m.Scope, m.Tags)

	switch m.Type {
	case counterTypeName:
		if m.Scope == samplers.GlobalOnly {
			w.wm.globalCounters[m.MetricKey].Sample(m.Value.(float64), m.SampleRate)
		} else {
			w.wm.counters[m.MetricKey].Sample(m.Value.(float64), m.SampleRate)
		}
	case gaugeTypeName:
		if m.Scope == samplers.GlobalOnly {
			w.wm.globalGauges[m.MetricKey].Sample(m.Value.(float64), m.SampleRate)
		} else {
			w.wm.gauges[m.MetricKey].Sample(m.Value.(float64), m.SampleRate)
		}
	case histogramTypeName:
		if m.Scope == samplers.LocalOnly {
			w.wm.localHistograms[m.MetricKey].Sample(m.Value.(float64), m.SampleRate)
		} else if m.Scope == samplers.GlobalOnly {
			w.wm.globalHistograms[m.MetricKey].Sample(m.Value.(float64), m.SampleRate)
		} else {
			w.wm.histograms[m.MetricKey].Sample(m.Value.(float64), m.SampleRate)
		}
	case setTypeName:
		if m.Scope == samplers.LocalOnly {
			w.wm.localSets[m.MetricKey].Sample(m.Value.(string), m.SampleRate)
		} else {
			w.wm.sets[m.MetricKey].Sample(m.Value.(string), m.SampleRate)
		}
	case timerTypeName:
		if m.Scope == samplers.LocalOnly {
			w.wm.localTimers[m.MetricKey].Sample(m.Value.(float64), m.SampleRate)
		} else if m.Scope == samplers.GlobalOnly {
			w.wm.globalTimers[m.MetricKey].Sample(m.Value.(float64), m.SampleRate)
		} else {
			w.wm.timers[m.MetricKey].Sample(m.Value.(float64), m.SampleRate)
		}
	case statusTypeName:
		v := float64(m.Value.(ssf.SSFSample_Status))
		w.wm.localStatusChecks[m.MetricKey].Sample(v, m.SampleRate, m.Message, m.HostName)
	default:
		log.WithField("type", m.Type).Error("Unknown metric type for processing")
	}
}