metrics.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // Copyright 2019 Yunion
  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. package influxdb
  15. import (
  16. "fmt"
  17. "sort"
  18. "strconv"
  19. "strings"
  20. "time"
  21. )
  22. type SKeyValue struct {
  23. Key string
  24. Value string
  25. }
  26. func (kv SKeyValue) String() string {
  27. k := strings.ReplaceAll(strings.ReplaceAll(strings.Trim(kv.Key, " "), ",", ""), " ", "+")
  28. v := strings.ReplaceAll(strings.ReplaceAll(strings.Trim(kv.Value, ""), " ", "+"), ",", "+")
  29. return fmt.Sprintf("%s=%s", k, v)
  30. }
  31. type TKeyValuePairs []SKeyValue
  32. func (a TKeyValuePairs) Len() int { return len(a) }
  33. func (a TKeyValuePairs) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
  34. func (a TKeyValuePairs) Less(i, j int) bool { return a[i].Key < a[j].Key }
  35. type SMetricData struct {
  36. Name string
  37. Tags TKeyValuePairs
  38. Metrics TKeyValuePairs
  39. Timestamp time.Time
  40. }
  41. func (m *SMetricData) Line() string {
  42. sort.Sort(m.Tags)
  43. sort.Sort(m.Metrics)
  44. line := strings.Builder{}
  45. line.WriteString(m.Name)
  46. keys := map[string]bool{}
  47. for i := range m.Tags {
  48. if _, ok := keys[m.Tags[i].Key]; !ok && len(m.Tags[i].Key) > 0 && len(m.Tags[i].Value) > 0 {
  49. line.WriteByte(',')
  50. line.WriteString(m.Tags[i].String())
  51. keys[m.Tags[i].Key] = true
  52. }
  53. }
  54. line.WriteByte(' ')
  55. for i := range m.Metrics {
  56. if i > 0 {
  57. line.WriteByte(',')
  58. }
  59. line.WriteString(m.Metrics[i].String())
  60. }
  61. line.WriteByte(' ')
  62. if m.Timestamp.IsZero() {
  63. m.Timestamp = time.Now()
  64. }
  65. line.WriteString(strconv.FormatInt(m.Timestamp.UnixNano()/1000000, 10))
  66. return line.String()
  67. }