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
14package push_test
15
16import (
17	"fmt"
18	"time"
19
20	"github.com/prometheus/client_golang/prometheus"
21	"github.com/prometheus/client_golang/prometheus/push"
22)
23
24var (
25	completionTime = prometheus.NewGauge(prometheus.GaugeOpts{
26		Name: "db_backup_last_completion_timestamp_seconds",
27		Help: "The timestamp of the last completion of a DB backup, successful or not.",
28	})
29	successTime = prometheus.NewGauge(prometheus.GaugeOpts{
30		Name: "db_backup_last_success_timestamp_seconds",
31		Help: "The timestamp of the last successful completion of a DB backup.",
32	})
33	duration = prometheus.NewGauge(prometheus.GaugeOpts{
34		Name: "db_backup_duration_seconds",
35		Help: "The duration of the last DB backup in seconds.",
36	})
37	records = prometheus.NewGauge(prometheus.GaugeOpts{
38		Name: "db_backup_records_processed",
39		Help: "The number of records processed in the last DB backup.",
40	})
41)
42
43func performBackup() (int, error) {
44	// Perform the backup and return the number of backed up records and any
45	// applicable error.
46	// ...
47	return 42, nil
48}
49
50func ExamplePusher_Add() {
51	// We use a registry here to benefit from the consistency checks that
52	// happen during registration.
53	registry := prometheus.NewRegistry()
54	registry.MustRegister(completionTime, duration, records)
55	// Note that successTime is not registered.
56
57	pusher := push.New("http://pushgateway:9091", "db_backup").Gatherer(registry)
58
59	start := time.Now()
60	n, err := performBackup()
61	records.Set(float64(n))
62	// Note that time.Since only uses a monotonic clock in Go1.9+.
63	duration.Set(time.Since(start).Seconds())
64	completionTime.SetToCurrentTime()
65	if err != nil {
66		fmt.Println("DB backup failed:", err)
67	} else {
68		// Add successTime to pusher only in case of success.
69		// We could as well register it with the registry.
70		// This example, however, demonstrates that you can
71		// mix Gatherers and Collectors when handling a Pusher.
72		pusher.Collector(successTime)
73		successTime.SetToCurrentTime()
74	}
75	// Add is used here rather than Push to not delete a previously pushed
76	// success timestamp in case of a failure of this backup.
77	if err := pusher.Add(); err != nil {
78		fmt.Println("Could not push to Pushgateway:", err)
79	}
80}
81