github.com/galamsiva2020/kubernetes-heapster-monitoring@v0.0.0-20210823134957-3c1baa7c1e70/metrics/sinks/statsd/influxstatsd_formatter.go (about) 1 // Copyright 2016 Google Inc. All Rights Reserved. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package statsd 16 17 import ( 18 "bytes" 19 "fmt" 20 "github.com/golang/glog" 21 "k8s.io/heapster/metrics/core" 22 "sort" 23 "strings" 24 ) 25 26 type InfluxstatsdFormatter struct { 27 delimReplacer *strings.Replacer 28 } 29 30 func (formatter *InfluxstatsdFormatter) Format(prefix string, name string, labels map[string]string, customizeLabel CustomizeLabel, metricValue core.MetricValue) (res string, err error) { 31 var buffer bytes.Buffer 32 buffer.WriteString(fmt.Sprintf("%s%s", formatter.delimReplacer.Replace(prefix), formatter.delimReplacer.Replace(name))) 33 expandedLabels := formatter.expandUserLabels(labels) 34 keys := make([]string, len(expandedLabels)) 35 for k := range expandedLabels { 36 keys = append(keys, k) 37 } 38 sort.Strings(keys) 39 for _, k := range keys { 40 v := expandedLabels[k] 41 if v != "" { 42 buffer.WriteString(fmt.Sprintf(",%s=%s", customizeLabel(formatter.delimReplacer.Replace(k)), formatter.delimReplacer.Replace(v))) 43 } 44 } 45 buffer.WriteString(fmt.Sprintf(":%v|g", metricValue.GetValue())) 46 47 return buffer.String(), nil 48 } 49 50 func (formatter *InfluxstatsdFormatter) expandUserLabels(labels map[string]string) map[string]string { 51 res := make(map[string]string) 52 var userLabelStr string 53 for k, v := range labels { 54 if k == core.LabelLabels.Key { 55 userLabelStr = v 56 } else { 57 res[k] = v 58 } 59 } 60 kvPairs := strings.Split(userLabelStr, ",") 61 for _, kvPair := range kvPairs { 62 kv := strings.Split(kvPair, ":") 63 if len(kv) >= 2 { 64 res[kv[0]] = kv[1] 65 } 66 } 67 return res 68 } 69 70 func NewInfluxstatsdFormatter() Formatter { 71 glog.V(2).Info("influxstatsd formatter is created") 72 return &InfluxstatsdFormatter{ 73 delimReplacer: strings.NewReplacer(",", "_", ":", "_", "=", "_", "|", "_"), 74 } 75 }