コード例 #1
0
// createMetricNamespace returns metric namespace based on given `ns` which is used as a prefix; all dynamic elements
// in the `metricName` are defined based on content of map `dynamicElements`
func (creator *nsCreator) createMetricNamespace(ns core.Namespace, metricName string) (core.Namespace, error) {
	metricName = strings.TrimSpace(metricName)

	if len(metricName) == 0 {
		return nil, errors.New("Cannot create metric namespace: empty metric name")
	}

	elements := strings.Split(metricName, "/")

	// check if metricName contains only static elements
	if !strings.Contains(metricName, "*") {
		ns = ns.AddStaticElements(elements...)
		return ns, nil
	}

	// when metric name contains dynamic element iterate over elements
	for index, element := range elements {
		if element == "*" {
			// the following element is dynamic
			dynamicElement, ok := creator.dynamicElements[elements[index-1]]
			// check if this dynamic element is supported (name and description are available)
			if !ok {
				return nil, fmt.Errorf("Unknown dynamic element in metric `%s` under index %d", metricName, index)
			}
			// add recognize dynamic element (define its name and description)
			ns = ns.AddDynamicElement(dynamicElement.name, dynamicElement.description)

			if len(elements)-1 == index {
				// in case when an asterisk is the last element, add `value` at the end of ns
				ns = ns.AddStaticElement("value")
			}
		} else {
			// the following element is static
			ns = ns.AddStaticElement(element)
		}
	}
	if len(ns) == 0 {
		return nil, fmt.Errorf("Cannot create metric namespace for metric %s", metricName)
	}
	return ns, nil
}