graphite.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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 graphiteStat struct {
  25. Metric string
  26. Time int64
  27. Value float64
  28. Host string
  29. }
  30. type graphiteStatArray []*graphiteStat
  31. func (stats graphiteStatArray) ToRequest() []byte {
  32. var request bytes.Buffer
  33. for _, stat := range stats {
  34. request.Write([]byte(fmt.Sprintf("cockroach.%s.%s %f %d\n",
  35. stat.Host,
  36. strings.Replace(stat.Metric, "_", ".", -1),
  37. stat.Value,
  38. stat.Time,
  39. )))
  40. }
  41. return []byte(request.String())
  42. }
  43. func (metricSet *ProcessedMetricSet) tographiteStats() graphiteStatArray {
  44. hostname, err := os.Hostname()
  45. if err != nil {
  46. hostname = "unknown"
  47. }
  48. stats := make([]*graphiteStat, 0, len(metricSet.Metrics))
  49. i := 0
  50. for metric, value := range metricSet.Metrics {
  51. //TODO(tyler) custom tags
  52. stats = append(stats, &graphiteStat{
  53. Metric: metric,
  54. Time: metricSet.Time.Unix(),
  55. Value: value,
  56. Host: hostname,
  57. })
  58. i++
  59. }
  60. return stats
  61. }
  62. // GraphiteProtocol generates a wire representation of a ProcessedMetricSet
  63. // for submission to a Graphite Carbon instance using the plaintext protocol.
  64. func GraphiteProtocol(ms *ProcessedMetricSet) []byte {
  65. return ms.tographiteStats().ToRequest()
  66. }