| 1 |
// Copyright 2015 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 push provides functions to push metrics to a Pushgateway. It uses a |
| 15 |
// builder approach. Create a Pusher with New and then add the various options |
| 16 |
// by using its methods, finally calling Add or Push, like this: |
| 17 |
// |
| 18 |
// // Easy case: |
| 19 |
// push.New("http://example.org/metrics", "my_job").Gatherer(myRegistry).Push() |
| 20 |
// |
| 21 |
// // Complex case: |
| 22 |
// push.New("http://example.org/metrics", "my_job"). |
| 23 |
// Collector(myCollector1). |
| 24 |
// Collector(myCollector2). |
| 25 |
// Grouping("zone", "xy"). |
| 26 |
// Client(&myHTTPClient). |
| 27 |
// BasicAuth("top", "secret"). |
| 28 |
// Add() |
| 29 |
// |
| 30 |
// See the examples section for more detailed examples. |
| 31 |
// |
| 32 |
// See the documentation of the Pushgateway to understand the meaning of |
| 33 |
// the grouping key and the differences between Push and Add: |
| 34 |
// https://github.com/prometheus/pushgateway |
| 35 |
package push |
| 36 |
|
| 37 |
import ( |
| 38 |
"bytes" |
| 39 |
"context" |
| 40 |
"encoding/base64" |
| 41 |
"errors" |
| 42 |
"fmt" |
| 43 |
"io" |
| 44 |
"net/http" |
| 45 |
"net/url" |
| 46 |
"strings" |
| 47 |
|
| 48 |
"github.com/prometheus/common/expfmt" |
| 49 |
"github.com/prometheus/common/model" |
| 50 |
|
| 51 |
"github.com/prometheus/client_golang/prometheus" |
| 52 |
) |
| 53 |
|
| 54 |
const ( |
| 55 |
contentTypeHeader = "Content-Type" |
| 56 |
// base64Suffix is appended to a label name in the request URL path to |
| 57 |
// mark the following label value as base64 encoded. |
| 58 |
base64Suffix = "@base64" |
| 59 |
) |
| 60 |
|
| 61 |
var errJobEmpty = errors.New("job name is empty") |
| 62 |
|
| 63 |
// HTTPDoer is an interface for the one method of http.Client that is used by Pusher |
| 64 |
type HTTPDoer interface { |
| 65 |
Do(*http.Request) (*http.Response, error) |
| 66 |
} |
| 67 |
|
| 68 |
// Pusher manages a push to the Pushgateway. Use New to create one, configure it |
| 69 |
// with its methods, and finally use the Add or Push method to push. |
| 70 |
type Pusher struct { |
| 71 |
error error |
| 72 |
|
| 73 |
url, job string |
| 74 |
grouping map[string]string |
| 75 |
|
| 76 |
gatherers prometheus.Gatherers |
| 77 |
registerer prometheus.Registerer |
| 78 |
|
| 79 |
client HTTPDoer |
| 80 |
header http.Header |
| 81 |
useBasicAuth bool |
| 82 |
username, password string |
| 83 |
|
| 84 |
expfmt expfmt.Format |
| 85 |
} |
| 86 |
|
| 87 |
// New creates a new Pusher to push to the provided URL with the provided job |
| 88 |
// name (which must not be empty). You can use just host:port or ip:port as url, |
| 89 |
// in which case “http://” is added automatically. Alternatively, include the |
| 90 |
// schema in the URL. However, do not include the “/metrics/jobs/…” part. |
| 91 |
func New(url, job string) *Pusher { |
| 92 |
var ( |
| 93 |
reg = prometheus.NewRegistry() |
| 94 |
err error |
| 95 |
) |
| 96 |
if job == "" { |
| 97 |
err = errJobEmpty |
| 98 |
} |
| 99 |
if !strings.Contains(url, "://") { |
| 100 |
url = "http://" + url |
| 101 |
} |
| 102 |
url = strings.TrimSuffix(url, "/") |
| 103 |
|
| 104 |
return &Pusher{ |
| 105 |
error: err, |
| 106 |
url: url, |
| 107 |
job: job, |
| 108 |
grouping: map[string]string{}, |
| 109 |
gatherers: prometheus.Gatherers{reg}, |
| 110 |
registerer: reg, |
| 111 |
client: &http.Client{}, |
| 112 |
expfmt: expfmt.NewFormat(expfmt.TypeProtoDelim), |
| 113 |
} |
| 114 |
} |
| 115 |
|
| 116 |
// Push collects/gathers all metrics from all Collectors and Gatherers added to |
| 117 |
// this Pusher. Then, it pushes them to the Pushgateway configured while |
| 118 |
// creating this Pusher, using the configured job name and any added grouping |
| 119 |
// labels as grouping key. All previously pushed metrics with the same job and |
| 120 |
// other grouping labels will be replaced with the metrics pushed by this |
| 121 |
// call. (It uses HTTP method “PUT” to push to the Pushgateway.) |
| 122 |
// |
| 123 |
// Push returns the first error encountered by any method call (including this |
| 124 |
// one) in the lifetime of the Pusher. |
| 125 |
func (p *Pusher) Push() error { |
| 126 |
return p.push(context.Background(), http.MethodPut) |
| 127 |
} |
| 128 |
|
| 129 |
// PushContext is like Push but includes a context. |
| 130 |
// |
| 131 |
// If the context expires before HTTP request is complete, an error is returned. |
| 132 |
func (p *Pusher) PushContext(ctx context.Context) error { |
| 133 |
return p.push(ctx, http.MethodPut) |
| 134 |
} |
| 135 |
|
| 136 |
// Add works like push, but only previously pushed metrics with the same name |
| 137 |
// (and the same job and other grouping labels) will be replaced. (It uses HTTP |
| 138 |
// method “POST” to push to the Pushgateway.) |
| 139 |
func (p *Pusher) Add() error { |
| 140 |
return p.push(context.Background(), http.MethodPost) |
| 141 |
} |
| 142 |
|
| 143 |
// AddContext is like Add but includes a context. |
| 144 |
// |
| 145 |
// If the context expires before HTTP request is complete, an error is returned. |
| 146 |
func (p *Pusher) AddContext(ctx context.Context) error { |
| 147 |
return p.push(ctx, http.MethodPost) |
| 148 |
} |
| 149 |
|
| 150 |
// Gatherer adds a Gatherer to the Pusher, from which metrics will be gathered |
| 151 |
// to push them to the Pushgateway. The gathered metrics must not contain a job |
| 152 |
// label of their own. |
| 153 |
// |
| 154 |
// For convenience, this method returns a pointer to the Pusher itself. |
| 155 |
func (p *Pusher) Gatherer(g prometheus.Gatherer) *Pusher { |
| 156 |
p.gatherers = append(p.gatherers, g) |
| 157 |
return p |
| 158 |
} |
| 159 |
|
| 160 |
// Collector adds a Collector to the Pusher, from which metrics will be |
| 161 |
// collected to push them to the Pushgateway. The collected metrics must not |
| 162 |
// contain a job label of their own. |
| 163 |
// |
| 164 |
// For convenience, this method returns a pointer to the Pusher itself. |
| 165 |
func (p *Pusher) Collector(c prometheus.Collector) *Pusher { |
| 166 |
if p.error == nil { |
| 167 |
p.error = p.registerer.Register(c) |
| 168 |
} |
| 169 |
return p |
| 170 |
} |
| 171 |
|
| 172 |
// Error returns the error that was encountered. |
| 173 |
func (p *Pusher) Error() error { |
| 174 |
return p.error |
| 175 |
} |
| 176 |
|
| 177 |
// Grouping adds a label pair to the grouping key of the Pusher, replacing any |
| 178 |
// previously added label pair with the same label name. Note that setting any |
| 179 |
// labels in the grouping key that are already contained in the metrics to push |
| 180 |
// will lead to an error. |
| 181 |
// |
| 182 |
// For convenience, this method returns a pointer to the Pusher itself. |
| 183 |
func (p *Pusher) Grouping(name, value string) *Pusher { |
| 184 |
if p.error == nil { |
| 185 |
//nolint:staticcheck // TODO: Don't use deprecated model.NameValidationScheme. |
| 186 |
if !model.NameValidationScheme.IsValidLabelName(name) { |
| 187 |
p.error = fmt.Errorf("grouping label has invalid name: %s", name) |
| 188 |
return p |
| 189 |
} |
| 190 |
p.grouping[name] = value |
| 191 |
} |
| 192 |
return p |
| 193 |
} |
| 194 |
|
| 195 |
// Client sets a custom HTTP client for the Pusher. For convenience, this method |
| 196 |
// returns a pointer to the Pusher itself. |
| 197 |
// Pusher only needs one method of the custom HTTP client: Do(*http.Request). |
| 198 |
// Thus, rather than requiring a fully fledged http.Client, |
| 199 |
// the provided client only needs to implement the HTTPDoer interface. |
| 200 |
// Since *http.Client naturally implements that interface, it can still be used normally. |
| 201 |
func (p *Pusher) Client(c HTTPDoer) *Pusher { |
| 202 |
p.client = c |
| 203 |
return p |
| 204 |
} |
| 205 |
|
| 206 |
// Header sets a custom HTTP header for the Pusher's client. For convenience, this method |
| 207 |
// returns a pointer to the Pusher itself. |
| 208 |
func (p *Pusher) Header(header http.Header) *Pusher { |
| 209 |
p.header = header |
| 210 |
return p |
| 211 |
} |
| 212 |
|
| 213 |
// BasicAuth configures the Pusher to use HTTP Basic Authentication with the |
| 214 |
// provided username and password. For convenience, this method returns a |
| 215 |
// pointer to the Pusher itself. |
| 216 |
func (p *Pusher) BasicAuth(username, password string) *Pusher { |
| 217 |
p.useBasicAuth = true |
| 218 |
p.username = username |
| 219 |
p.password = password |
| 220 |
return p |
| 221 |
} |
| 222 |
|
| 223 |
// Format configures the Pusher to use an encoding format given by the |
| 224 |
// provided expfmt.Format. The default format is expfmt.FmtProtoDelim and |
| 225 |
// should be used with the standard Prometheus Pushgateway. Custom |
| 226 |
// implementations may require different formats. For convenience, this |
| 227 |
// method returns a pointer to the Pusher itself. |
| 228 |
func (p *Pusher) Format(format expfmt.Format) *Pusher { |
| 229 |
p.expfmt = format |
| 230 |
return p |
| 231 |
} |
| 232 |
|
| 233 |
// Delete sends a “DELETE” request to the Pushgateway configured while creating |
| 234 |
// this Pusher, using the configured job name and any added grouping labels as |
| 235 |
// grouping key. Any added Gatherers and Collectors added to this Pusher are |
| 236 |
// ignored by this method. |
| 237 |
// |
| 238 |
// Delete returns the first error encountered by any method call (including this |
| 239 |
// one) in the lifetime of the Pusher. |
| 240 |
func (p *Pusher) Delete() error { |
| 241 |
if p.error != nil { |
| 242 |
return p.error |
| 243 |
} |
| 244 |
req, err := http.NewRequest(http.MethodDelete, p.fullURL(), nil) |
| 245 |
if err != nil { |
| 246 |
return err |
| 247 |
} |
| 248 |
if p.header != nil { |
| 249 |
req.Header = p.header |
| 250 |
} |
| 251 |
if p.useBasicAuth { |
| 252 |
req.SetBasicAuth(p.username, p.password) |
| 253 |
} |
| 254 |
resp, err := p.client.Do(req) |
| 255 |
if err != nil { |
| 256 |
return err |
| 257 |
} |
| 258 |
defer resp.Body.Close() |
| 259 |
if resp.StatusCode != http.StatusAccepted { |
| 260 |
body, _ := io.ReadAll(resp.Body) // Ignore any further error as this is for an error message only. |
| 261 |
return fmt.Errorf("unexpected status code %d while deleting %s: %s", resp.StatusCode, p.fullURL(), body) |
| 262 |
} |
| 263 |
return nil |
| 264 |
} |
| 265 |
|
| 266 |
func (p *Pusher) push(ctx context.Context, method string) error { |
| 267 |
if p.error != nil { |
| 268 |
return p.error |
| 269 |
} |
| 270 |
mfs, err := p.gatherers.Gather() |
| 271 |
if err != nil { |
| 272 |
return err |
| 273 |
} |
| 274 |
buf := &bytes.Buffer{} |
| 275 |
enc := expfmt.NewEncoder(buf, p.expfmt) |
| 276 |
// Check for pre-existing grouping labels: |
| 277 |
for _, mf := range mfs { |
| 278 |
for _, m := range mf.GetMetric() { |
| 279 |
for _, l := range m.GetLabel() { |
| 280 |
if l.GetName() == "job" { |
| 281 |
return fmt.Errorf("pushed metric %s (%s) already contains a job label", mf.GetName(), m) |
| 282 |
} |
| 283 |
if _, ok := p.grouping[l.GetName()]; ok { |
| 284 |
return fmt.Errorf( |
| 285 |
"pushed metric %s (%s) already contains grouping label %s", |
| 286 |
mf.GetName(), m, l.GetName(), |
| 287 |
) |
| 288 |
} |
| 289 |
} |
| 290 |
} |
| 291 |
if err := enc.Encode(mf); err != nil { |
| 292 |
return fmt.Errorf( |
| 293 |
"failed to encode metric family %s, error is %w", |
| 294 |
mf.GetName(), err) |
| 295 |
} |
| 296 |
} |
| 297 |
req, err := http.NewRequestWithContext(ctx, method, p.fullURL(), buf) |
| 298 |
if err != nil { |
| 299 |
return err |
| 300 |
} |
| 301 |
if p.header != nil { |
| 302 |
req.Header = p.header |
| 303 |
} |
| 304 |
if p.useBasicAuth { |
| 305 |
req.SetBasicAuth(p.username, p.password) |
| 306 |
} |
| 307 |
req.Header.Set(contentTypeHeader, string(p.expfmt)) |
| 308 |
resp, err := p.client.Do(req) |
| 309 |
if err != nil { |
| 310 |
return err |
| 311 |
} |
| 312 |
defer resp.Body.Close() |
| 313 |
// Depending on version and configuration of the PGW, StatusOK or StatusAccepted may be returned. |
| 314 |
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusAccepted { |
| 315 |
body, _ := io.ReadAll(resp.Body) // Ignore any further error as this is for an error message only. |
| 316 |
return fmt.Errorf("unexpected status code %d while pushing to %s: %s", resp.StatusCode, p.fullURL(), body) |
| 317 |
} |
| 318 |
return nil |
| 319 |
} |
| 320 |
|
| 321 |
// fullURL assembles the URL used to push/delete metrics and returns it as a |
| 322 |
// string. The job name and any grouping label values containing a '/' will |
| 323 |
// trigger a base64 encoding of the affected component and proper suffixing of |
| 324 |
// the preceding component. Similarly, an empty grouping label value will be |
| 325 |
// encoded as base64 just with a single `=` padding character (to avoid an empty |
| 326 |
// path component). If the component does not contain a '/' but other special |
| 327 |
// characters, the usual url.QueryEscape is used for compatibility with older |
| 328 |
// versions of the Pushgateway and for better readability. |
| 329 |
func (p *Pusher) fullURL() string { |
| 330 |
urlComponents := []string{} |
| 331 |
if encodedJob, base64 := encodeComponent(p.job); base64 { |
| 332 |
urlComponents = append(urlComponents, "job"+base64Suffix, encodedJob) |
| 333 |
} else { |
| 334 |
urlComponents = append(urlComponents, "job", encodedJob) |
| 335 |
} |
| 336 |
for ln, lv := range p.grouping { |
| 337 |
if encodedLV, base64 := encodeComponent(lv); base64 { |
| 338 |
urlComponents = append(urlComponents, ln+base64Suffix, encodedLV) |
| 339 |
} else { |
| 340 |
urlComponents = append(urlComponents, ln, encodedLV) |
| 341 |
} |
| 342 |
} |
| 343 |
return fmt.Sprintf("%s/metrics/%s", p.url, strings.Join(urlComponents, "/")) |
| 344 |
} |
| 345 |
|
| 346 |
// encodeComponent encodes the provided string with base64.RawURLEncoding in |
| 347 |
// case it contains '/' and as "=" in case it is empty. If neither is the case, |
| 348 |
// it uses url.QueryEscape instead. It returns true in the former two cases. |
| 349 |
func encodeComponent(s string) (string, bool) { |
| 350 |
if s == "" { |
| 351 |
return "=", true |
| 352 |
} |
| 353 |
if strings.Contains(s, "/") { |
| 354 |
return base64.RawURLEncoding.EncodeToString([]byte(s)), true |
| 355 |
} |
| 356 |
return url.QueryEscape(s), false |
| 357 |
} |