| 1 |
// Copyright 2016 The Prometheus Authors |
| 2 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 3 |
// you may not use this file except in compliance with the License. |
| 4 |
// You may obtain a copy of the License at |
| 5 |
// |
| 6 |
// http://www.apache.org/licenses/LICENSE-2.0 |
| 7 |
// |
| 8 |
// Unless required by applicable law or agreed to in writing, software |
| 9 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 10 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 11 |
// See the License for the specific language governing permissions and |
| 12 |
// limitations under the License. |
| 13 |
|
| 14 |
// Package graphite provides a bridge to push Prometheus metrics to a Graphite |
| 15 |
// server. |
| 16 |
package graphite |
| 17 |
|
| 18 |
import ( |
| 19 |
"bufio" |
| 20 |
"context" |
| 21 |
"errors" |
| 22 |
"fmt" |
| 23 |
"io" |
| 24 |
"net" |
| 25 |
"sort" |
| 26 |
"time" |
| 27 |
|
| 28 |
"github.com/prometheus/common/expfmt" |
| 29 |
"github.com/prometheus/common/model" |
| 30 |
|
| 31 |
dto "github.com/prometheus/client_model/go" |
| 32 |
|
| 33 |
"github.com/prometheus/client_golang/prometheus" |
| 34 |
) |
| 35 |
|
| 36 |
const ( |
| 37 |
defaultInterval = 15 * time.Second |
| 38 |
millisecondsPerSecond = 1000 |
| 39 |
) |
| 40 |
|
| 41 |
// HandlerErrorHandling defines how a Handler serving metrics will handle |
| 42 |
// errors. |
| 43 |
type HandlerErrorHandling int |
| 44 |
|
| 45 |
// These constants cause handlers serving metrics to behave as described if |
| 46 |
// errors are encountered. |
| 47 |
const ( |
| 48 |
// Ignore errors and try to push as many metrics to Graphite as possible. |
| 49 |
ContinueOnError HandlerErrorHandling = iota |
| 50 |
|
| 51 |
// Abort the push to Graphite upon the first error encountered. |
| 52 |
AbortOnError |
| 53 |
) |
| 54 |
|
| 55 |
// Config defines the Graphite bridge config. |
| 56 |
type Config struct { |
| 57 |
// Whether to use Graphite tags or not. Defaults to false. |
| 58 |
UseTags bool |
| 59 |
|
| 60 |
// The url to push data to. Required. |
| 61 |
URL string |
| 62 |
|
| 63 |
// The prefix for the pushed Graphite metrics. Defaults to empty string. |
| 64 |
Prefix string |
| 65 |
|
| 66 |
// The interval to use for pushing data to Graphite. Defaults to 15 seconds. |
| 67 |
Interval time.Duration |
| 68 |
|
| 69 |
// The timeout for pushing metrics to Graphite. Defaults to 15 seconds. |
| 70 |
Timeout time.Duration |
| 71 |
|
| 72 |
// The Gatherer to use for metrics. Defaults to prometheus.DefaultGatherer. |
| 73 |
Gatherer prometheus.Gatherer |
| 74 |
|
| 75 |
// The logger that messages are written to. Defaults to no logging. |
| 76 |
Logger Logger |
| 77 |
|
| 78 |
// ErrorHandling defines how errors are handled. Note that errors are |
| 79 |
// logged regardless of the configured ErrorHandling provided Logger |
| 80 |
// is not nil. |
| 81 |
ErrorHandling HandlerErrorHandling |
| 82 |
} |
| 83 |
|
| 84 |
// Bridge pushes metrics to the configured Graphite server. |
| 85 |
type Bridge struct { |
| 86 |
useTags bool |
| 87 |
url string |
| 88 |
prefix string |
| 89 |
interval time.Duration |
| 90 |
timeout time.Duration |
| 91 |
|
| 92 |
errorHandling HandlerErrorHandling |
| 93 |
logger Logger |
| 94 |
|
| 95 |
g prometheus.Gatherer |
| 96 |
} |
| 97 |
|
| 98 |
// Logger is the minimal interface Bridge needs for logging. Note that |
| 99 |
// log.Logger from the standard library implements this interface, and it is |
| 100 |
// easy to implement by custom loggers, if they don't do so already anyway. |
| 101 |
type Logger interface { |
| 102 |
Println(v ...interface{}) |
| 103 |
} |
| 104 |
|
| 105 |
// NewBridge returns a pointer to a new Bridge struct. |
| 106 |
func NewBridge(c *Config) (*Bridge, error) { |
| 107 |
b := &Bridge{} |
| 108 |
|
| 109 |
b.useTags = c.UseTags |
| 110 |
|
| 111 |
if c.URL == "" { |
| 112 |
return nil, errors.New("missing URL") |
| 113 |
} |
| 114 |
b.url = c.URL |
| 115 |
|
| 116 |
if c.Gatherer == nil { |
| 117 |
b.g = prometheus.DefaultGatherer |
| 118 |
} else { |
| 119 |
b.g = c.Gatherer |
| 120 |
} |
| 121 |
|
| 122 |
if c.Logger != nil { |
| 123 |
b.logger = c.Logger |
| 124 |
} |
| 125 |
|
| 126 |
if c.Prefix != "" { |
| 127 |
b.prefix = c.Prefix |
| 128 |
} |
| 129 |
|
| 130 |
var z time.Duration |
| 131 |
if c.Interval == z { |
| 132 |
b.interval = defaultInterval |
| 133 |
} else { |
| 134 |
b.interval = c.Interval |
| 135 |
} |
| 136 |
|
| 137 |
if c.Timeout == z { |
| 138 |
b.timeout = defaultInterval |
| 139 |
} else { |
| 140 |
b.timeout = c.Timeout |
| 141 |
} |
| 142 |
|
| 143 |
b.errorHandling = c.ErrorHandling |
| 144 |
|
| 145 |
return b, nil |
| 146 |
} |
| 147 |
|
| 148 |
// Run starts the event loop that pushes Prometheus metrics to Graphite at the |
| 149 |
// configured interval. |
| 150 |
func (b *Bridge) Run(ctx context.Context) { |
| 151 |
ticker := time.NewTicker(b.interval) |
| 152 |
defer ticker.Stop() |
| 153 |
for { |
| 154 |
select { |
| 155 |
case <-ticker.C: |
| 156 |
if err := b.Push(); err != nil && b.logger != nil { |
| 157 |
b.logger.Println("error pushing to Graphite:", err) |
| 158 |
} |
| 159 |
case <-ctx.Done(): |
| 160 |
return |
| 161 |
} |
| 162 |
} |
| 163 |
} |
| 164 |
|
| 165 |
// Push pushes Prometheus metrics to the configured Graphite server. |
| 166 |
func (b *Bridge) Push() error { |
| 167 |
mfs, err := b.g.Gather() |
| 168 |
if err != nil || len(mfs) == 0 { |
| 169 |
switch b.errorHandling { |
| 170 |
case AbortOnError: |
| 171 |
return err |
| 172 |
case ContinueOnError: |
| 173 |
if b.logger != nil { |
| 174 |
b.logger.Println("continue on error:", err) |
| 175 |
} |
| 176 |
default: |
| 177 |
panic("unrecognized error handling value") |
| 178 |
} |
| 179 |
} |
| 180 |
|
| 181 |
conn, err := net.DialTimeout("tcp", b.url, b.timeout) |
| 182 |
if err != nil { |
| 183 |
return err |
| 184 |
} |
| 185 |
defer conn.Close() |
| 186 |
|
| 187 |
return writeMetrics(conn, mfs, b.useTags, b.prefix, model.Now()) |
| 188 |
} |
| 189 |
|
| 190 |
func writeMetrics(w io.Writer, mfs []*dto.MetricFamily, useTags bool, prefix string, now model.Time) error { |
| 191 |
vec, err := expfmt.ExtractSamples(&expfmt.DecodeOptions{ |
| 192 |
Timestamp: now, |
| 193 |
}, mfs...) |
| 194 |
if err != nil { |
| 195 |
return err |
| 196 |
} |
| 197 |
|
| 198 |
buf := bufio.NewWriter(w) |
| 199 |
for _, s := range vec { |
| 200 |
if prefix != "" { |
| 201 |
for _, c := range prefix { |
| 202 |
if _, err := buf.WriteRune(c); err != nil { |
| 203 |
return err |
| 204 |
} |
| 205 |
} |
| 206 |
if err := buf.WriteByte('.'); err != nil { |
| 207 |
return err |
| 208 |
} |
| 209 |
} |
| 210 |
if err := writeMetric(buf, s.Metric, useTags); err != nil { |
| 211 |
return err |
| 212 |
} |
| 213 |
if _, err := fmt.Fprintf(buf, " %g %d\n", s.Value, int64(s.Timestamp)/millisecondsPerSecond); err != nil { |
| 214 |
return err |
| 215 |
} |
| 216 |
if err := buf.Flush(); err != nil { |
| 217 |
return err |
| 218 |
} |
| 219 |
} |
| 220 |
|
| 221 |
return nil |
| 222 |
} |
| 223 |
|
| 224 |
func writeMetric(buf *bufio.Writer, m model.Metric, useTags bool) error { |
| 225 |
metricName, hasName := m[model.MetricNameLabel] |
| 226 |
numLabels := len(m) - 1 |
| 227 |
if !hasName { |
| 228 |
numLabels = len(m) |
| 229 |
} |
| 230 |
|
| 231 |
var err error |
| 232 |
switch numLabels { |
| 233 |
case 0: |
| 234 |
if hasName { |
| 235 |
return writeSanitized(buf, string(metricName)) |
| 236 |
} |
| 237 |
default: |
| 238 |
if err = writeSanitized(buf, string(metricName)); err != nil { |
| 239 |
return err |
| 240 |
} |
| 241 |
if useTags { |
| 242 |
return writeTags(buf, m) |
| 243 |
} |
| 244 |
return writeLabels(buf, m, numLabels) |
| 245 |
} |
| 246 |
return nil |
| 247 |
} |
| 248 |
|
| 249 |
func writeTags(buf *bufio.Writer, m model.Metric) error { |
| 250 |
for label, value := range m { |
| 251 |
if label != model.MetricNameLabel { |
| 252 |
buf.WriteRune(';') |
| 253 |
if _, err := buf.WriteString(string(label)); err != nil { |
| 254 |
return err |
| 255 |
} |
| 256 |
buf.WriteRune('=') |
| 257 |
if _, err := buf.WriteString(string(value)); err != nil { |
| 258 |
return err |
| 259 |
} |
| 260 |
} |
| 261 |
} |
| 262 |
return nil |
| 263 |
} |
| 264 |
|
| 265 |
func writeLabels(buf *bufio.Writer, m model.Metric, numLabels int) error { |
| 266 |
labelStrings := make([]string, 0, numLabels) |
| 267 |
for label, value := range m { |
| 268 |
if label != model.MetricNameLabel { |
| 269 |
labelString := string(label) + " " + string(value) |
| 270 |
labelStrings = append(labelStrings, labelString) |
| 271 |
} |
| 272 |
} |
| 273 |
sort.Strings(labelStrings) |
| 274 |
for _, s := range labelStrings { |
| 275 |
if err := buf.WriteByte('.'); err != nil { |
| 276 |
return err |
| 277 |
} |
| 278 |
if err := writeSanitized(buf, s); err != nil { |
| 279 |
return err |
| 280 |
} |
| 281 |
} |
| 282 |
return nil |
| 283 |
} |
| 284 |
|
| 285 |
func writeSanitized(buf *bufio.Writer, s string) error { |
| 286 |
prevUnderscore := false |
| 287 |
|
| 288 |
for _, c := range s { |
| 289 |
c = replaceInvalidRune(c) |
| 290 |
if c == '_' { |
| 291 |
if prevUnderscore { |
| 292 |
continue |
| 293 |
} |
| 294 |
prevUnderscore = true |
| 295 |
} else { |
| 296 |
prevUnderscore = false |
| 297 |
} |
| 298 |
if _, err := buf.WriteRune(c); err != nil { |
| 299 |
return err |
| 300 |
} |
| 301 |
} |
| 302 |
|
| 303 |
return nil |
| 304 |
} |
| 305 |
|
| 306 |
func replaceInvalidRune(c rune) rune { |
| 307 |
if c == ' ' { |
| 308 |
return '.' |
| 309 |
} |
| 310 |
// TODO: Apply De Morgan's law to the condition. Make sure to test the condition first. |
| 311 |
if !((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || c == ':' || c == '-' || (c >= '0' && c <= '9')) { //nolint:staticcheck |
| 312 |
return '_' |
| 313 |
} |
| 314 |
return c |
| 315 |
} |