labels.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. // Copyright The OpenTelemetry Authors
  2. // SPDX-License-Identifier: Apache-2.0
  3. package collectd // import "github.com/open-telemetry/opentelemetry-collector-contrib/internal/collectd"
  4. import (
  5. "strings"
  6. )
  7. // LabelsFromName tries to pull out dimensions out of name in the format
  8. // "name[k=v,f=x]-more_name".
  9. // For the example above it would return "name-more_name" and extract dimensions
  10. // (k,v) and (f,x).
  11. // If something unexpected is encountered it returns the original metric name.
  12. //
  13. // The code tries to avoid allocation by using local slices and avoiding calls
  14. // to functions like strings.Slice.
  15. func LabelsFromName(val *string) (metricName string, labels map[string]string) {
  16. metricName = *val
  17. index := strings.Index(*val, "[")
  18. if index > -1 {
  19. left := (*val)[:index]
  20. rest := (*val)[index+1:]
  21. index = strings.Index(rest, "]")
  22. if index > -1 {
  23. working := make(map[string]string)
  24. dimensions := rest[:index]
  25. rest = rest[index+1:]
  26. cindex := strings.Index(dimensions, ",")
  27. prev := 0
  28. for {
  29. if cindex < prev {
  30. cindex = len(dimensions)
  31. }
  32. piece := dimensions[prev:cindex]
  33. tindex := strings.Index(piece, "=")
  34. if tindex == -1 || strings.Contains(piece[tindex+1:], "=") {
  35. return
  36. }
  37. working[piece[:tindex]] = piece[tindex+1:]
  38. if cindex == len(dimensions) {
  39. break
  40. }
  41. prev = cindex + 1
  42. cindex = strings.Index(dimensions[prev:], ",") + prev
  43. }
  44. labels = working
  45. metricName = left + rest
  46. }
  47. }
  48. return
  49. }