// ParseMetric converts the incoming packet from Datadog DogStatsD
// Datagram format in to a Metric. http://docs.datadoghq.com/guides/dogstatsd/#datagram-format
555062
func ParseMetric(packet []byte) (*UDPMetric, error) {
	ret := &UDPMetric{
		SampleRate: 1.0,
	}
	pipeSplitter := NewSplitBytes(packet, '|')
	pipeSplitter.Next() // first split always succeeds, since there are at least zero pipes

	startingColon := bytes.IndexByte(pipeSplitter.Chunk(), ':')
	if startingColon == -1 {
		return nil, errors.New("Invalid metric packet, need at least 1 colon")
	}
	nameChunk := pipeSplitter.Chunk()[:startingColon]
	valueChunk := pipeSplitter.Chunk()[startingColon+1:]
	if len(nameChunk) == 0 {
		return nil, errors.New("Invalid metric packet, name cannot be empty")
	}

	if !pipeSplitter.Next() {
		return nil, errors.New("Invalid metric packet, need at least 1 pipe for type")
	}
	typeChunk := pipeSplitter.Chunk()
	if len(typeChunk) == 0 {
		// avoid panicking on malformed packets missing a type
		// (eg "foo:1||")
		return nil, errors.New("Invalid metric packet, metric type not specified")
	}

	h := fnv1a.Init32

	ret.Name = string(nameChunk)
	h = fnv1a.AddString32(h, ret.Name)

	// Decide on a type
	switch typeChunk[0] {
	case 'c':
		ret.Type = "counter"
	case 'g':
		ret.Type = "gauge"
	case 'd', 'h': // consider DogStatsD's "distribution" to be a histogram
		ret.Type = "histogram"
	case 'm': // We can ignore the s in "ms"
		ret.Type = "timer"
	case 's':
		ret.Type = "set"
	default:
		return nil, invalidMetricTypeError
	}
	// Add the type to the digest
	h = fnv1a.AddString32(h, ret.Type)

	// Now convert the metric's value
	if ret.Type == "set" {
		ret.Value = string(valueChunk)
	} else {
		v, err := strconv.ParseFloat(string(valueChunk), 64)
		if err != nil || math.IsNaN(v) || math.IsInf(v, 0) {
			return nil, fmt.Errorf("Invalid number for metric value: %s", valueChunk)
		}
		ret.Value = v
	}

	// each of these sections can only appear once in the packet
	foundSampleRate := false
	for pipeSplitter.Next() {
		if len(pipeSplitter.Chunk()) == 0 {
			// avoid panicking on malformed packets that have too many pipes
			// (eg "foo:1|g|" or "foo:1|c||@0.1")
			return nil, errors.New("Invalid metric packet, empty string after/between pipes")
		}
		switch pipeSplitter.Chunk()[0] {
		case '@':
			if foundSampleRate {
				return nil, errors.New("Invalid metric packet, multiple sample rates specified")
			}
			// sample rate!
			sr := string(pipeSplitter.Chunk()[1:])
			sampleRate, err := strconv.ParseFloat(sr, 32)
			if err != nil {
				return nil, fmt.Errorf("Invalid float for sample rate: %s", sr)
			}
			if sampleRate <= 0 || sampleRate > 1 {
				return nil, fmt.Errorf("Sample rate %f must be >0 and <=1", sampleRate)
			}
			ret.SampleRate = float32(sampleRate)
			foundSampleRate = true

		case '#':
			// tags!
			if ret.Tags != nil {
				return nil, errors.New("Invalid metric packet, multiple tag sections specified")
			}
			// should we be filtering known key tags from here?
			// in order to prevent extremely high cardinality in the global stats?
			// see worker.go line 273
			tags := strings.Split(string(pipeSplitter.Chunk()[1:]), ",")
			sort.Strings(tags)
			for i, tag := range tags {
				// we use this tag as an escape hatch for metrics that always
				// want to be host-local
				if strings.HasPrefix(tag, "veneurlocalonly") {
					// delete the tag from the list
					tags = append(tags[:i], tags[i+1:]...)
					ret.Scope = LocalOnly
					break
				} else if strings.HasPrefix(tag, "veneurglobalonly") {
					// delete the tag from the list
					tags = append(tags[:i], tags[i+1:]...)
					ret.Scope = GlobalOnly
					break
				}
			}
			ret.Tags = tags
			// we specifically need the sorted version here so that hashing over
			// tags behaves deterministically
			ret.JoinedTags = strings.Join(tags, ",")
			h = fnv1a.AddString32(h, ret.JoinedTags)

		default:
			return nil, fmt.Errorf("Invalid metric packet, contains unknown section %q", pipeSplitter.Chunk())
		}
	}

	ret.Digest = h

	return ret, nil
}
716086
func UnmarshallMetricTypes(contentType string, payload []byte) ([]MetricType, error) {
	switch contentType {
	case SnapGOBContentType:
		var metrics []MetricType
		r := bytes.NewBuffer(payload)
		err := gob.NewDecoder(r).Decode(&metrics)
		if err != nil {
			log.WithFields(log.Fields{
				"_module": "control-plugin",
				"block":   "unmarshal-content-type",
				"error":   err.Error(),
			}).Error("error while unmarshalling")
			return nil, err
		}
		return metrics, nil
	case SnapJSONContentType:
		var metrics []MetricType
		err := json.Unmarshal(payload, &metrics)
		if err != nil {
			log.WithFields(log.Fields{
				"_module": "control-plugin",
				"block":   "unmarshal-content-type",
				"error":   err.Error(),
			}).Error("error while unmarshalling")
			return nil, err
		}
		return metrics, nil
	default:
		// We don't recognize this content type as one we can unmarshal. Log and return error.
		es := fmt.Sprintf("invalid snap content type for unmarshalling: %s", contentType)
		log.WithFields(log.Fields{
			"_module": "control-plugin",
			"block":   "unmarshal-content-type",
			"error":   es,
		}).Error("error while unmarshalling")
		return nil, errors.New(es)
	}
}
851454
func (_m *API) PostMetric(metricName string, metricValue string) (string, error) {
	ret := _m.Called(metricName, metricValue)

	var r0 string
	if rf, ok := ret.Get(0).(func(string, string) string); ok {
		r0 = rf(metricName, metricValue)
	} else {
		r0 = ret.Get(0).(string)
	}

	var r1 error
	if rf, ok := ret.Get(1).(func(string, string) error); ok {
		r1 = rf(metricName, metricValue)
	} else {
		r1 = ret.Error(1)
	}

	return r0, r1
}
164213
func (a *Api) namespaceMetrics(request *restful.Request, response *restful.Response) {
	a.processMetricRequest(core.NamespaceKey(request.PathParameter("namespace-name")),
		request, response)
}
197451
func (s *HTTPServer) MetricsRequest(resp http.ResponseWriter, req *http.Request) (interface{}, error) {
	if req.Method != "GET" {
		return nil, CodedError(405, ErrInvalidMethod)
	}

	if format := req.URL.Query().Get("format"); format == "prometheus" {
		s.prometheusHandler().ServeHTTP(resp, req)
		return nil, nil
	}

	return s.agent.InmemSink.DisplayMetrics(resp, req)
}
750567
func NewPCPInstanceMetric(vals Instances, name string, indom *PCPInstanceDomain, t MetricType, s MetricSemantics, u MetricUnit, desc ...string) (*PCPInstanceMetric, error) {
	d, err := newpcpMetricDesc(name, t, s, u, desc...)
	if err != nil {
		return nil, err
	}

	im, err := newpcpInstanceMetric(vals, indom, d)
	if err != nil {
		return nil, err
	}

	return &PCPInstanceMetric{im, sync.RWMutex{}}, nil
}
495090
func (m *metricExtractionSink) sendMetrics(metrics []samplers.UDPMetric) {
	for _, metric := range metrics {
		m.workers[metric.Digest%uint32(len(m.workers))].IngestUDP(metric)
	}
}
1050493
func (c *Client) GetMetricsSnapshot(pid *Pid) (*MetricsSnapshot, error) {
	u := c.GetURLForMetricsSnapshotPid(*pid)
	resp, err := c.GetHTTPResponse(&u)
	return c.parseMetricsSnapshotResponse(resp, err)
}
1105755
func ToRequestedMetrics(mts []*Metric) []core.RequestedMetric {
	metrics := make([]core.RequestedMetric, len(mts))
	for i, mt := range mts {
		metrics[i] = ToCoreMetric(mt)
	}
	return metrics
}
944912
func (md *cachedMetrics) GetMetrics() (*Metrics, error) {
	md.once.cache(func() error {
		md.resultMetrics, md.resultError = md.wrapped.GetMetrics()
		return md.resultError
	})
	return md.resultMetrics, md.resultError
}
1170357
func (h *HTTPReporter) GetMetrics() *vegeta.Metrics {
	h.Lock()
	defer h.Unlock()
	return h.metrics
}
22270
func (s *Server) ReadMetricSocket(serverConn net.PacketConn, packetPool *sync.Pool) {
	for {
		buf := packetPool.Get().([]byte)
		n, _, err := serverConn.ReadFrom(buf)
		if err != nil {
			log.WithError(err).Error("Error reading from UDP metrics socket")
			continue
		}
		s.processMetricPacket(n, buf, packetPool)
	}
}
595416
func ReadMetric(m prometheus.Metric) *Metric {
	pb := &dto.Metric{}
	if err := m.Write(pb); err != nil {
		panic(err)
	}

	name, help := getNameAndHelp(m.Desc())
	labels := make(prometheus.Labels, len(pb.Label))
	for _, v := range pb.Label {
		labels[v.GetName()] = v.GetValue()
	}
	if pb.Gauge != nil {
		return &Metric{name, help, labels, dto.MetricType_GAUGE, pb.GetGauge().GetValue()}
	}
	if pb.Counter != nil {
		return &Metric{name, help, labels, dto.MetricType_COUNTER, pb.GetCounter().GetValue()}
	}
	if pb.Untyped != nil {
		return &Metric{name, help, labels, dto.MetricType_UNTYPED, pb.GetUntyped().GetValue()}
	}
	panic("Unsupported metric type")
}
120577
func (l *throttlingListener) connRateMetric() int {
	l.Lock()
	defer l.Unlock()

	var (
		earliestConnTime *time.Time
		connCount        float64
	)
	// Figure out the most recent connection timestamp.
	startIndex := l.nextSlot - 1
	if startIndex < 0 {
		startIndex = len(l.connAcceptTimes) - 1
	}
	latestConnTime := l.connAcceptTimes[startIndex]
	if latestConnTime == nil {
		return 0
	}
	// Loop backwards to get the earlier known connection timestamp.
	for index := startIndex; index != l.nextSlot; {
		if connTime := l.connAcceptTimes[index]; connTime == nil {
			break
		} else {
			earliestConnTime = connTime
		}
		connCount++
		// Stop if we have reached the maximum window in terms how long
		// ago the earliest connection was, to avoid stale data skewing results.
		if latestConnTime.Sub(*earliestConnTime) > l.lookbackWindow {
			break
		}
		index--
		if index < 0 {
			index = len(l.connAcceptTimes) - 1
		}
	}
	if connCount < 2 {
		return 0
	}
	// We use as a metric how many connections per 10ms
	connRate := connCount * float64(time.Second) / (1.0 + float64(latestConnTime.Sub(*earliestConnTime)))
	logger.Tracef("server listener has received %d connections per second", int(connRate))
	return int(connRate)
}
686400
func ParseMetricSSF(metric *ssf.SSFSample) (UDPMetric, error) {
	ret := UDPMetric{
		SampleRate: 1.0,
	}
	h := fnv1a.Init32
	h = fnv1a.AddString32(h, metric.Name)
	ret.Name = metric.Name
	switch metric.Metric {
	case ssf.SSFSample_COUNTER:
		ret.Type = "counter"
	case ssf.SSFSample_GAUGE:
		ret.Type = "gauge"
	case ssf.SSFSample_HISTOGRAM:
		ret.Type = "histogram"
	case ssf.SSFSample_SET:
		ret.Type = "set"
	case ssf.SSFSample_STATUS:
		ret.Type = "status"
	default:
		return UDPMetric{}, invalidMetricTypeError
	}
	h = fnv1a.AddString32(h, ret.Type)
	switch metric.Metric {
	case ssf.SSFSample_SET:
		ret.Value = metric.Message
	case ssf.SSFSample_STATUS:
		ret.Value = metric.Status
	default:
		ret.Value = float64(metric.Value)
	}
	ret.SampleRate = metric.SampleRate
	tempTags := make([]string, 0, len(metric.Tags))
	for key, value := range metric.Tags {
		if key == "veneurlocalonly" {
			ret.Scope = LocalOnly
			continue
		}
		if key == "veneurglobalonly" {
			ret.Scope = GlobalOnly
			continue
		}
		tempTags = append(tempTags, key+":"+value)
	}
	sort.Strings(tempTags)
	ret.Tags = tempTags
	ret.JoinedTags = strings.Join(tempTags, ",")
	h = fnv1a.AddString32(h, ret.JoinedTags)
	ret.Digest = h
	return ret, nil
}
804635
func FromMetric(other telegraf.Metric) telegraf.Metric {
	m := &metric{
		name:      other.Name(),
		tags:      make([]*telegraf.Tag, len(other.TagList())),
		fields:    make([]*telegraf.Field, len(other.FieldList())),
		tm:        other.Time(),
		tp:        other.Type(),
		aggregate: other.IsAggregate(),
	}

	for i, tag := range other.TagList() {
		m.tags[i] = &telegraf.Tag{Key: tag.Key, Value: tag.Value}
	}

	for i, field := range other.FieldList() {
		m.fields[i] = &telegraf.Field{Key: field.Key, Value: field.Value}
	}
	return m
}
1063999
func NopMetrics() *Metrics {
	return &Metrics{
		Peers:                 discard.NewGauge(),
		PeerReceiveBytesTotal: discard.NewCounter(),
		PeerSendBytesTotal:    discard.NewCounter(),
		PeerPendingSendBytes:  discard.NewGauge(),
		NumTxs:                discard.NewGauge(),
	}
}