// checkSanitizedMetricName errors out if invalid characters are found in the metric name, since InfluxDB
// does not widely support bound parameters yet, and we need to sanitize our inputs.
504159
func (sink *influxdbSink) checkSanitizedMetricName(name string) error {
	if !metricAllowedChars.MatchString(name) {
		return fmt.Errorf("Invalid metric name %q", name)
	}

	return nil
}
775090
func (ung *uniqueNameGenerator) ensureValidName(name string) (string, error) {
	names := ung.names

	// Ensure that name meets length requirements
	if len(name) < 2 {
		return "", fmt.Errorf("invalid name: %s", name)
	}

	if !IsParameterizableValue(name) {

		// Make all names lowercase
		name = strings.ToLower(name)

		// Remove everything except [-0-9a-z]
		name = invalidNameCharactersRegexp.ReplaceAllString(name, "")

		// Remove leading hyphen(s) that may be introduced by the previous step
		name = strings.TrimLeft(name, "-")

		if len(name) > kvalidation.DNS1123SubdomainMaxLength {
			klog.V(4).Infof("Trimming %s to maximum allowable length (%d)\n", name, kvalidation.DNS1123SubdomainMaxLength)
			name = name[:kvalidation.DNS1123SubdomainMaxLength]
		}
	}

	count, existing := names[name]
	if !existing {
		names[name] = 0
		return name, nil
	}
	count++
	names[name] = count
	newName := apihelpers.GetName(name, strconv.Itoa(count), kvalidation.DNS1123SubdomainMaxLength)
	return newName, nil
}
452555
func (s *FinalHyperParameterTuningJobObjectiveMetric) SetMetricName(v string) *FinalHyperParameterTuningJobObjectiveMetric {
	s.MetricName = &v
	return s
}
708608
func NewDatadogMetricSink(interval float64, flushMaxPerBody int, hostname string, tags []string, ddHostname string, apiKey string, httpClient *http.Client, log *logrus.Logger) (*DatadogMetricSink, error) {
	return &DatadogMetricSink{
		HTTPClient:      httpClient,
		APIKey:          apiKey,
		DDHostname:      ddHostname,
		interval:        interval,
		flushMaxPerBody: flushMaxPerBody,
		hostname:        hostname,
		tags:            tags,
		log:             log,
	}, nil
}
487576
func processMetric(
	metric Metric,
	metricFamiliesByName map[string]*dto.MetricFamily,
	metricHashes map[uint64]struct{},
	registeredDescIDs map[uint64]struct{},
) error {
	desc := metric.Desc()
	// Wrapped metrics collected by an unchecked Collector can have an
	// invalid Desc.
	if desc.err != nil {
		return desc.err
	}
	dtoMetric := &dto.Metric{}
	if err := metric.Write(dtoMetric); err != nil {
		return fmt.Errorf("error collecting metric %v: %s", desc, err)
	}
	metricFamily, ok := metricFamiliesByName[desc.fqName]
	if ok { // Existing name.
		if metricFamily.GetHelp() != desc.help {
			return fmt.Errorf(
				"collected metric %s %s has help %q but should have %q",
				desc.fqName, dtoMetric, desc.help, metricFamily.GetHelp(),
			)
		}
		// TODO(beorn7): Simplify switch once Desc has type.
		switch metricFamily.GetType() {
		case dto.MetricType_COUNTER:
			if dtoMetric.Counter == nil {
				return fmt.Errorf(
					"collected metric %s %s should be a Counter",
					desc.fqName, dtoMetric,
				)
			}
		case dto.MetricType_GAUGE:
			if dtoMetric.Gauge == nil {
				return fmt.Errorf(
					"collected metric %s %s should be a Gauge",
					desc.fqName, dtoMetric,
				)
			}
		case dto.MetricType_SUMMARY:
			if dtoMetric.Summary == nil {
				return fmt.Errorf(
					"collected metric %s %s should be a Summary",
					desc.fqName, dtoMetric,
				)
			}
		case dto.MetricType_UNTYPED:
			if dtoMetric.Untyped == nil {
				return fmt.Errorf(
					"collected metric %s %s should be Untyped",
					desc.fqName, dtoMetric,
				)
			}
		case dto.MetricType_HISTOGRAM:
			if dtoMetric.Histogram == nil {
				return fmt.Errorf(
					"collected metric %s %s should be a Histogram",
					desc.fqName, dtoMetric,
				)
			}
		default:
			panic("encountered MetricFamily with invalid type")
		}
	} else { // New name.
		metricFamily = &dto.MetricFamily{}
		metricFamily.Name = proto.String(desc.fqName)
		metricFamily.Help = proto.String(desc.help)
		// TODO(beorn7): Simplify switch once Desc has type.
		switch {
		case dtoMetric.Gauge != nil:
			metricFamily.Type = dto.MetricType_GAUGE.Enum()
		case dtoMetric.Counter != nil:
			metricFamily.Type = dto.MetricType_COUNTER.Enum()
		case dtoMetric.Summary != nil:
			metricFamily.Type = dto.MetricType_SUMMARY.Enum()
		case dtoMetric.Untyped != nil:
			metricFamily.Type = dto.MetricType_UNTYPED.Enum()
		case dtoMetric.Histogram != nil:
			metricFamily.Type = dto.MetricType_HISTOGRAM.Enum()
		default:
			return fmt.Errorf("empty metric collected: %s", dtoMetric)
		}
		if err := checkSuffixCollisions(metricFamily, metricFamiliesByName); err != nil {
			return err
		}
		metricFamiliesByName[desc.fqName] = metricFamily
	}
	if err := checkMetricConsistency(metricFamily, dtoMetric, metricHashes); err != nil {
		return err
	}
	if registeredDescIDs != nil {
		// Is the desc registered at all?
		if _, exist := registeredDescIDs[desc.id]; !exist {
			return fmt.Errorf(
				"collected metric %s %s with unregistered descriptor %s",
				metricFamily.GetName(), dtoMetric, desc,
			)
		}
		if err := checkDescConsistency(metricFamily, dtoMetric, desc); err != nil {
			return err
		}
	}
	metricFamily.Metric = append(metricFamily.Metric, dtoMetric)
	return nil
}
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
}
992452
func (p *TextParser) readingMetricName() stateFn {
	if p.readTokenAsMetricName(); p.err != nil {
		return nil
	}
	if p.currentToken.Len() == 0 {
		p.parseError("invalid metric name")
		return nil
	}
	p.setOrCreateCurrentMF()
	// Now is the time to fix the type if it hasn't happened yet.
	if p.currentMF.Type == nil {
		p.currentMF.Type = dto.MetricType_UNTYPED.Enum()
	}
	p.currentMetric = &dto.Metric{}
	// Do not append the newly created currentMetric to
	// currentMF.Metric right now. First wait if this is a summary,
	// and the metric exists already, which we can only know after
	// having read all the labels.
	if p.skipBlankTabIfCurrentBlankTab(); p.err != nil {
		return nil // Unexpected end of input.
	}
	return p.readingLabels
}
455739
func validateMetricNamespace(ns core.Namespace) error {
	value := ""
	for _, i := range ns {
		// A dynamic element requires the name while a static element does not.
		if i.Name != "" && i.Value != "*" {
			return errorMetricStaticElementHasName(i.Value, i.Name, ns.String())
		}
		if i.Name == "" && i.Value == "*" {
			return errorMetricDynamicElementHasNoName(i.Value, ns.String())
		}
		if isTuple(i.Value) {
			return errorMetricElementHasTuple(i.Value, ns.String())
		}
		value += i.Value
	}
	// plugin should NOT advertise metrics ending with a wildcard
	if strings.HasSuffix(value, "*") {
		return errorMetricEndsWithAsterisk(ns.String())
	}
	return nil
}
1146456
func (s *MetricDatum) SetMetricName(v string) *MetricDatum {
	s.MetricName = &v
	return s
}
863538
func IsValidName(name string) bool {
	// doesn't contain the prefix
	if !strings.HasPrefix(name, Prefix) {
		return false
	}
	// it's required to have at least the following chars `x-x-0`
	suffix := name[len(Prefix):]
	if len(suffix) < 5 {
		return false
	}
	// lastly check the last part is a number
	lastHyphen := strings.LastIndex(suffix, "-")
	revision := suffix[lastHyphen+1:]
	_, err := strconv.Atoi(revision)
	return err == nil
}
18878
func checkInternalName(fqdn string) bool {
	if ip := net.ParseIP(fqdn); ip != nil {
		return checkInternalIP(ip)
	}

	suffix := strings.Split(strings.ToLower(fqdn), ".")
	_, icann := psl.PublicSuffix(suffix[len(suffix)-1])
	if icann {
		return false
	}
	return true
}
997969
func InitMetrics(statsd string) error {
	hostname, err := os.Hostname()
	if err != nil {
		return err
	}
	Client = Metrics{StatsdAddr: statsd, Hostname: utils.CleanStatsdMetrics(hostname)}

	Client.MemoryCapacity = prometheus.NewGaugeVec(prometheus.GaugeOpts{
		Name: "memory_capacity",
		Help: "node available memory.",
	}, []string{"nodename"})

	Client.DeployCount = prometheus.NewCounterVec(prometheus.CounterOpts{
		Name: "core_deploy",
		Help: "core deploy counter",
	}, []string{"hostname"})

	Client.CPUMap = prometheus.NewGaugeVec(prometheus.GaugeOpts{
		Name: "cpu_map",
		Help: "node available cpu.",
	}, []string{"nodename", "cpuid"})

	prometheus.MustRegister(Client.DeployCount, Client.MemoryCapacity, Client.CPUMap)
	return nil
}
1344174
func CheckName(stat string) error {
	if !safeName.MatchString(stat) {
		return fmt.Errorf("invalid stat name: %s", stat)
	}
	return nil
}
542507
func (f *FilteredForwarder) FilterMetricName(metricName string) bool {
	denied := false
	for _, a := range f.deny {
		if a.Match([]byte(metricName)) {
			denied = true
			break
		}
	}
	found := false
	for _, a := range f.allow {
		if a.Match([]byte(metricName)) {
			denied = false
			found = true
			break
		}
	}
	return found || (len(f.allow) == 0 && !denied)
}
1089566
func (s *CloudwatchMetricAction) SetMetricName(v string) *CloudwatchMetricAction {
	s.MetricName = &v
	return s
}
551358
func getReasonableMetricName(point *JSONWriteFormat, index uint, dimensions map[string]string) (string, bool) {
	usedDsName := false
	parts := make([]byte, 0, len(*point.TypeS)+len(*point.TypeInstance))
	if !isNilOrEmpty(point.TypeS) {
		parts = append(parts, *point.TypeS...)
	}
	parts = pointTypeInstance(point, dimensions, parts)
	if point.Dsnames != nil && !isNilOrEmpty(point.Dsnames[index]) && len(point.Dsnames) > 1 {
		if len(parts) > 0 {
			parts = append(parts, '.')
		}
		parts = append(parts, *point.Dsnames[index]...)
		usedDsName = true
	}
	return string(parts), usedDsName
}
125897
func (s *ListMetricsInput) SetMetricName(v string) *ListMetricsInput {
	s.MetricName = &v
	return s
}