// ConvertSpanUniquenessMetrics takes a trace span and computes
// uniqueness metrics about it, returning UDPMetrics sampled at
// rate. Currently, the only metric returned is a Set counting the
// unique names per indicator span/service.
172690
func ConvertSpanUniquenessMetrics(span *ssf.SSFSpan, rate float32) ([]UDPMetric, error) {
	if span.Service == "" {
		return []UDPMetric{}, nil
	}
	ssfMetrics := []*ssf.SSFSample{}
	ssfMetrics = append(ssfMetrics,
		ssf.RandomlySample(rate,
			ssf.Set("ssf.names_unique", span.Name, map[string]string{
				"indicator": strconv.FormatBool(span.Indicator),
				"service":   span.Service,
				"root_span": strconv.FormatBool(span.Id == span.TraceId),
			}))...)
	metrics := make([]UDPMetric, 0, len(ssfMetrics))
	for _, m := range ssfMetrics {
		udpM, err := ParseMetricSSF(m)
		if err != nil {
			return []UDPMetric{}, err
		}
		metrics = append(metrics, udpM)
	}
	return metrics, nil
}
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
}
873526
func normalizeMetric(name string) string {
	// Special cases
	r := strings.NewReplacer("VSchema", "vschema", "VtGate", "vtgate")
	name = r.Replace(name)

	return stats.GetSnakeName(name)
}
739521
func (t *Trace) SSFSpan() *ssf.SSFSpan {
	name := t.Name

	span := &ssf.SSFSpan{
		StartTimestamp: t.Start.UnixNano(),
		Error:          t.error,
		TraceId:        t.TraceID,
		Id:             t.SpanID,
		ParentId:       t.ParentID,
		EndTimestamp:   t.End.UnixNano(),
		Name:           name,
		Tags:           t.Tags,
		Service:        Service,
		Metrics:        t.Samples,
		Indicator:      t.Indicator,
	}

	return span
}
1303680
func (m *Metrics) PollGoMetrics() {
	m.GoMetricsRegistry.Each(func(name string, value interface{}) {
		recordMeter := func(prefix, label string, gauge metrics.Gauge) bool {
			if !strings.HasPrefix(name, prefix) {
				return false
			}

			meter, ok := value.(gometrics.Meter)
			if !ok {
				logger.Panicf("Expected metric with name %s to be of type Meter but was of type %T", name, value)
			}

			labelValue := name[len(prefix):]
			gauge.With(label, labelValue).Set(meter.Snapshot().Rate1())

			return true
		}

		recordHistogram := func(prefix, label string, gauge metrics.Gauge) bool {
			if !strings.HasPrefix(name, prefix) {
				return false
			}

			histogram, ok := value.(gometrics.Histogram)
			if !ok {
				logger.Panicf("Expected metric with name %s to be of type Histogram but was of type %T", name, value)
			}

			labelValue := name[len(prefix):]
			gauge.With(label, labelValue).Set(histogram.Snapshot().Mean())

			return true
		}

		switch {
		case recordMeter(IncomingByteRateName, "broker_id", m.IncomingByteRate):
		case recordMeter(OutgoingByteRateName, "broker_id", m.OutgoingByteRate):
		case recordMeter(RequestRateName, "broker_id", m.RequestRate):
		case recordHistogram(RequestSizeName, "broker_id", m.RequestSize):
		case recordHistogram(RequestLatencyName, "broker_id", m.RequestLatency):
		case recordMeter(ResponseRateName, "broker_id", m.ResponseRate):
		case recordHistogram(ResponseSizeName, "broker_id", m.ResponseSize):
		case recordHistogram(BatchSizeName, "topic", m.BatchSize):
		case recordMeter(RecordSendRateName, "topic", m.RecordSendRate):
		case recordHistogram(RecordsPerRequestName, "topic", m.RecordsPerRequest):
		case recordHistogram(CompressionRatioName, "topic", m.CompressionRatio):
		default:
			// Ignore unknown metrics
		}
	})
}
1166094
func Convert_v1beta1_PodMetrics_To_metrics_PodMetrics(in *PodMetrics, out *metrics.PodMetrics, s conversion.Scope) error {
	return autoConvert_v1beta1_PodMetrics_To_metrics_PodMetrics(in, out, s)
}
1114326
func Convert_autoscaling_MetricStatus_To_v2beta1_MetricStatus(in *autoscaling.MetricStatus, out *v2beta1.MetricStatus, s conversion.Scope) error {
	return autoConvert_autoscaling_MetricStatus_To_v2beta1_MetricStatus(in, out, s)
}
815185
func makemetric(
	metric telegraf.Metric,
	nameOverride string,
	namePrefix string,
	nameSuffix string,
	tags map[string]string,
	globalTags map[string]string,
) telegraf.Metric {
	if len(nameOverride) != 0 {
		metric.SetName(nameOverride)
	}

	if len(namePrefix) != 0 {
		metric.AddPrefix(namePrefix)
	}
	if len(nameSuffix) != 0 {
		metric.AddSuffix(nameSuffix)
	}

	// Apply plugin-wide tags
	for k, v := range tags {
		if _, ok := metric.GetTag(k); !ok {
			metric.AddTag(k, v)
		}
	}
	// Apply global tags
	for k, v := range globalTags {
		if _, ok := metric.GetTag(k); !ok {
			metric.AddTag(k, v)
		}
	}

	return metric
}
277226
func newpcpInstanceMetric(vals Instances, indom *PCPInstanceDomain, desc *pcpMetricDesc) (*pcpInstanceMetric, error) {
	if len(vals) != indom.InstanceCount() {
		return nil, errors.New("values for all instances in the instance domain only should be passed")
	}

	mvals := make(map[string]*instanceValue)

	for name := range indom.instances {
		val, present := vals[name]
		if !present {
			return nil, errors.Errorf("Instance %v not initialized", name)
		}

		if !desc.t.IsCompatible(val) {
			return nil, errors.Errorf("value %v is incompatible with type %v for Instance %v", val, desc.t, name)
		}

		val = desc.t.resolve(val)
		mvals[name] = newinstanceValue(val)
	}

	return &pcpInstanceMetric{desc, indom, mvals}, nil
}
304934
func unmarshalMetricsFromHTTP(ctx context.Context, client *trace.Client, w http.ResponseWriter, r *http.Request) (*trace.Span, []samplers.JSONMetric, error) {
	var (
		jsonMetrics []samplers.JSONMetric
		body        io.ReadCloser
		err         error
		encoding    = r.Header.Get("Content-Encoding")
		span        *trace.Span
	)
	span, err = tracer.ExtractRequestChild("/import", r, "veneur.opentracing.import")
	if err != nil {
		log.WithError(err).Debug("Could not extract span from request")
		span = tracer.StartSpan("veneur.opentracing.import").(*trace.Span)
	} else {
		log.WithField("trace", span.Trace).Debug("Extracted span from request")
	}
	defer span.ClientFinish(client)

	innerLogger := log.WithField("client", r.RemoteAddr)

	switch encLogger := innerLogger.WithField("encoding", encoding); encoding {
	case "":
		body = r.Body
		encoding = "identity"
	case "deflate":
		body, err = zlib.NewReader(r.Body)
		if err != nil {
			http.Error(w, err.Error(), http.StatusBadRequest)
			span.Error(err)
			encLogger.WithError(err).Error("Could not read compressed request body")
			span.Add(ssf.Count("import.request_error_total", 1, map[string]string{"cause": "deflate"}))
			return span, nil, err
		}
		defer body.Close()
	default:
		http.Error(w, encoding, http.StatusUnsupportedMediaType)
		span.Error(errors.New("Could not determine content-encoding of request"))
		encLogger.Error("Could not determine content-encoding of request")
		span.Add(ssf.Count("import.request_error_total", 1, map[string]string{"cause": "unknown_content_encoding"}))
		return span, nil, err
	}
	span.Add(ssf.Count("import.bytes", float32(r.ContentLength), nil))

	if err = json.NewDecoder(body).Decode(&jsonMetrics); err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		span.Error(err)
		innerLogger.WithError(err).Error("Could not decode /import request")
		span.Add(ssf.Count("import.request_error_total", 1, map[string]string{"cause": "json"}))
		return span, nil, err
	}

	if len(jsonMetrics) == 0 {
		const msg = "Received empty /import request"
		http.Error(w, msg, http.StatusBadRequest)
		span.Error(errors.New(msg))
		innerLogger.WithError(err).Error(msg)
		return span, nil, err
	}

	// We want to make sure we have at least one entry
	// that is not empty (ie, all fields are the zero value)
	// because that is usually the sign that we are unmarshalling
	// into the wrong struct type

	if !nonEmpty(span.Attach(ctx), client, jsonMetrics) {
		const msg = "Received empty or improperly-formed metrics"
		http.Error(w, msg, http.StatusBadRequest)
		span.Error(errors.New(msg))
		innerLogger.Error(msg)
		return nil, nil, err
	}

	w.WriteHeader(http.StatusAccepted)
	span.Add(ssf.RandomlySample(0.1,
		ssf.Timing("import.response_duration_ns", time.Since(span.Start),
			time.Nanosecond, map[string]string{
				"part":     "request",
				"encoding": encoding,
			}))...)
	return span, jsonMetrics, nil
}
1323160
func (ts *traceState) CreateSpan(desc string) (report ReportFunc) {
	ts.mu.Lock()
	defer ts.mu.Unlock()

	index := len(ts.spans)
	ts.spans = append(ts.spans, &span{desc: desc, start: time.Now()})

	report = func(err error) { ts.report(index, err) }
	return
}
164213
func (a *Api) namespaceMetrics(request *restful.Request, response *restful.Response) {
	a.processMetricRequest(core.NamespaceKey(request.PathParameter("namespace-name")),
		request, response)
}
66365
func (mb *SquareMetrics) SerializeMetrics() []map[string]interface{} {
	nvs := []tuple{}

	mb.Registry.Each(func(name string, i interface{}) {
		switch metric := i.(type) {
		case metrics.Counter:
			nvs = append(nvs, tuple{name, metric.Count()})
		case metrics.Gauge:
			nvs = append(nvs, tuple{name, metric.Value()})
		case metrics.GaugeFloat64:
			nvs = append(nvs, tuple{name, metric.Value()})
		case metrics.Histogram:
			histogram := metric.Snapshot()
			nvs = append(nvs, []tuple{
				{fmt.Sprintf("%s.count", name), histogram.Count()},
				{fmt.Sprintf("%s.min", name), histogram.Min()},
				{fmt.Sprintf("%s.max", name), histogram.Max()},
				{fmt.Sprintf("%s.mean", name), histogram.Mean()},
				{fmt.Sprintf("%s.50-percentile", name), histogram.Percentile(0.5)},
				{fmt.Sprintf("%s.75-percentile", name), histogram.Percentile(0.75)},
				{fmt.Sprintf("%s.95-percentile", name), histogram.Percentile(0.95)},
				{fmt.Sprintf("%s.99-percentile", name), histogram.Percentile(0.99)},
			}...)
		case metrics.Timer:
			timer := metric.Snapshot()
			nvs = append(nvs, []tuple{
				{fmt.Sprintf("%s.count", name), timer.Count()},
				{fmt.Sprintf("%s.min", name), timer.Min()},
				{fmt.Sprintf("%s.max", name), timer.Max()},
				{fmt.Sprintf("%s.mean", name), timer.Mean()},
				{fmt.Sprintf("%s.50-percentile", name), timer.Percentile(0.5)},
				{fmt.Sprintf("%s.75-percentile", name), timer.Percentile(0.75)},
				{fmt.Sprintf("%s.95-percentile", name), timer.Percentile(0.95)},
				{fmt.Sprintf("%s.99-percentile", name), timer.Percentile(0.99)},
			}...)
		}
	})

	now := time.Now().Unix()
	out := []map[string]interface{}{}
	for _, nv := range nvs {
		out = append(out, mb.serializeMetric(now, nv))
	}

	return out
}
868113
func ValidMetric(sample UDPMetric) bool {
	ret := true
	ret = ret && sample.Name != ""
	ret = ret && sample.Value != nil
	return ret
}
235985
func Convert_v1alpha1_NodeMetrics_To_metrics_NodeMetrics(in *NodeMetrics, out *metrics.NodeMetrics, s conversion.Scope) error {
	return autoConvert_v1alpha1_NodeMetrics_To_metrics_NodeMetrics(in, out, s)
}
1144256
func (b *Builder) checkAttributeUniqueness(obj Slice) error {
	vpackAssert(b.BuilderOptions.CheckAttributeUniqueness)
	n, err := obj.Length()
	if err != nil {
		return WithStack(err)
	}

	if obj.IsSorted() {
		// object attributes are sorted
		previous, err := obj.KeyAt(0)
		if err != nil {
			return WithStack(err)
		}
		p, err := previous.GetString()
		if err != nil {
			return WithStack(err)
		}

		// compare each two adjacent attribute names
		for i := ValueLength(1); i < n; i++ {
			current, err := obj.KeyAt(i)
			if err != nil {
				return WithStack(err)
			}
			// keyAt() guarantees a string as returned type
			vpackAssert(current.IsString())

			q, err := current.GetString()
			if err != nil {
				return WithStack(err)
			}

			if p == q {
				// identical key
				return WithStack(DuplicateAttributeNameError)
			}
			// re-use already calculated values for next round
			p = q
		}
	} else {
		keys := make(map[string]struct{})

		for i := ValueLength(0); i < n; i++ {
			// note: keyAt() already translates integer attributes
			key, err := obj.KeyAt(i)
			if err != nil {
				return WithStack(err)
			}
			// keyAt() guarantees a string as returned type
			vpackAssert(key.IsString())

			k, err := key.GetString()
			if err != nil {
				return WithStack(err)
			}
			if _, found := keys[k]; found {
				return WithStack(DuplicateAttributeNameError)
			}
			keys[k] = struct{}{}
		}
	}
	return nil
}
344988
func NewMetrics() *Metrics {
	m := &Metrics{
		TimeMetrics:   make(map[string]*TimeStats),
		NumberMetrics: make(map[string]*NumberStats),
		BoolMetrics:   make(map[string]*BoolStats),
	}
	return m
}