opentsdb.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. // Copyright 2014 The Cockroach Authors.
  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
  12. // implied. See the License for the specific language governing
  13. // permissions and limitations under the License. See the AUTHORS file
  14. // for names of contributors.
  15. //
  16. // Author: Tyler Neely (t@jujit.su)
  17. package loghisto
  18. import (
  19. "bytes"
  20. "fmt"
  21. "os"
  22. "strings"
  23. )
  24. type openTSDBStat struct {
  25. Metric string
  26. Time int64
  27. Value float64
  28. Tags map[string]string
  29. }
  30. type openTSDBStatArray []*openTSDBStat
  31. func mapToTSDProtocolTags(tagMap map[string]string) string {
  32. tags := make([]string, 0, len(tagMap))
  33. for tag, value := range tagMap {
  34. tags = append(tags, fmt.Sprintf("%s=%s", tag, value))
  35. }
  36. return strings.Join(tags, " ")
  37. }
  38. func (stats openTSDBStatArray) ToRequest() []byte {
  39. var request bytes.Buffer
  40. for _, stat := range stats {
  41. request.Write([]byte(fmt.Sprintf("put %s %d %f %s\n",
  42. stat.Metric,
  43. stat.Time,
  44. stat.Value,
  45. mapToTSDProtocolTags(stat.Tags))))
  46. }
  47. return []byte(request.String())
  48. }
  49. func (metricSet *ProcessedMetricSet) toopenTSDBStats() openTSDBStatArray {
  50. hostname, err := os.Hostname()
  51. if err != nil {
  52. hostname = "unknown"
  53. }
  54. stats := make([]*openTSDBStat, 0, len(metricSet.Metrics))
  55. i := 0
  56. for metric, value := range metricSet.Metrics {
  57. var tags = map[string]string{
  58. "host": hostname,
  59. }
  60. //TODO(tyler) custom tags
  61. stats = append(stats, &openTSDBStat{
  62. Metric: metric,
  63. Time: metricSet.Time.Unix(),
  64. Value: value,
  65. Tags: tags,
  66. })
  67. i++
  68. }
  69. return stats
  70. }
  71. // OpenTSDBProtocol generates a wire representation of a ProcessedMetricSet
  72. // for submission to an OpenTSDB instance.
  73. func OpenTSDBProtocol(ms *ProcessedMetricSet) []byte {
  74. return ms.toopenTSDBStats().ToRequest()
  75. }