bosun.org@v0.0.0-20210513094433-e25bc3e69a1f/cmd/tsdbrelay/denormalize/denormalization.go (about)

     1  package denormalize
     2  
     3  import (
     4  	"fmt"
     5  	"log"
     6  	"strings"
     7  
     8  	"bosun.org/opentsdb"
     9  )
    10  
    11  type DenormalizationRule struct {
    12  	Metric   string
    13  	TagNames []string
    14  }
    15  
    16  func (d *DenormalizationRule) String() string {
    17  	inputTags, outputTags := "", ""
    18  	val := 'a'
    19  	for i, tagk := range d.TagNames {
    20  		if i != 0 {
    21  			inputTags += ","
    22  			outputTags += "."
    23  		}
    24  		inputTags += fmt.Sprintf("%s=%s", tagk, string(val))
    25  		outputTags += fmt.Sprintf("%s", string(val))
    26  		val++
    27  	}
    28  	return fmt.Sprintf("%s{%s} -> __%s.%s", d.Metric, inputTags, outputTags, d.Metric)
    29  }
    30  
    31  func ParseDenormalizationRules(config string) (map[string]*DenormalizationRule, error) {
    32  	m := make(map[string]*DenormalizationRule)
    33  	rules := strings.Split(config, ",")
    34  	for _, r := range rules {
    35  		parts := strings.Split(r, "__")
    36  		if len(parts) < 2 {
    37  			return nil, fmt.Errorf("Denormalization rules must have at least one tag name specified.")
    38  		}
    39  		rule := &DenormalizationRule{Metric: parts[0]}
    40  		for _, part := range parts[1:] {
    41  			rule.TagNames = append(rule.TagNames, part)
    42  		}
    43  		log.Println("Denormalizing", rule)
    44  		m[rule.Metric] = rule
    45  	}
    46  	return m, nil
    47  }
    48  
    49  func (d *DenormalizationRule) Translate(dp *opentsdb.DataPoint) error {
    50  	tagString := "__"
    51  	for i, tagName := range d.TagNames {
    52  		val, ok := dp.Tags[tagName]
    53  		if !ok {
    54  			return fmt.Errorf("tag %s not present in data point for %s.", tagName, dp.Metric)
    55  		}
    56  		if i > 0 {
    57  			tagString += "."
    58  		}
    59  		tagString += val
    60  	}
    61  	dp.Metric = tagString + "." + dp.Metric
    62  	return nil
    63  }