-
Notifications
You must be signed in to change notification settings - Fork 474
/
main.go
165 lines (139 loc) · 5.66 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
// Copyright 2014 The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"net"
"net/http"
"net/http/pprof"
"net/url"
"os"
"os/signal"
"path"
"path/filepath"
"strings"
"syscall"
"time"
"github.com/julienschmidt/httprouter"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/prometheus/common/log"
"github.com/prometheus/common/version"
"gopkg.in/alecthomas/kingpin.v2"
dto "github.com/prometheus/client_model/go"
"github.com/prometheus/pushgateway/asset"
"github.com/prometheus/pushgateway/handler"
"github.com/prometheus/pushgateway/storage"
)
func init() {
prometheus.MustRegister(version.NewCollector("pushgateway"))
}
func main() {
var (
app = kingpin.New(filepath.Base(os.Args[0]), "The Pushgateway")
listenAddress = app.Flag("web.listen-address", "Address to listen on for the web interface, API, and telemetry.").Default(":9091").String()
metricsPath = app.Flag("web.telemetry-path", "Path under which to expose metrics.").Default("/metrics").String()
externalURL = app.Flag("web.external-url", "The URL under which the Pushgateway is externally reachable.").Default("").URL()
routePrefix = app.Flag("web.route-prefix", "Prefix for the internal routes of web endpoints. Defaults to the path of --web.external-url.").Default("").String()
persistenceFile = app.Flag("persistence.file", "File to persist metrics. If empty, metrics are only kept in memory.").Default("").String()
persistenceInterval = app.Flag("persistence.interval", "The minimum interval at which to write out the persistence file.").Default("5m").Duration()
)
log.AddFlags(app)
app.Version(version.Print("pushgateway"))
app.HelpFlag.Short('h')
kingpin.MustParse(app.Parse(os.Args[1:]))
*routePrefix = computeRoutePrefix(*routePrefix, *externalURL)
log.Infoln("Starting pushgateway", version.Info())
log.Infoln("Build context", version.BuildContext())
log.Debugf("Prefix path is '%s'", *routePrefix)
log.Debugf("External URL is '%s'", *externalURL)
(*externalURL).Path = ""
flags := map[string]string{}
for _, f := range app.Model().Flags {
flags[f.Name] = f.Value.String()
}
ms := storage.NewDiskMetricStore(*persistenceFile, *persistenceInterval, prometheus.DefaultGatherer)
// Inject the metric families returned by ms.GetMetricFamilies into the default Gatherer:
prometheus.DefaultGatherer = prometheus.Gatherers{
prometheus.DefaultGatherer,
prometheus.GathererFunc(func() ([]*dto.MetricFamily, error) { return ms.GetMetricFamilies(), nil }),
}
r := httprouter.New()
r.Handler("GET", *routePrefix+"/-/healthy", handler.Healthy(ms))
r.Handler("GET", *routePrefix+"/-/ready", handler.Ready(ms))
r.Handler("GET", path.Join(*routePrefix, *metricsPath), promhttp.Handler())
// Handlers for pushing and deleting metrics.
pushAPIPath := *routePrefix + "/metrics"
r.PUT(pushAPIPath+"/job/:job/*labels", handler.Push(ms, true))
r.POST(pushAPIPath+"/job/:job/*labels", handler.Push(ms, false))
r.DELETE(pushAPIPath+"/job/:job/*labels", handler.Delete(ms))
r.PUT(pushAPIPath+"/job/:job", handler.Push(ms, true))
r.POST(pushAPIPath+"/job/:job", handler.Push(ms, false))
r.DELETE(pushAPIPath+"/job/:job", handler.Delete(ms))
r.Handler("GET", *routePrefix+"/static/*filepath", handler.Static(asset.Assets, *routePrefix))
statusHandler := handler.Status(ms, asset.Assets, flags)
r.Handler("GET", *routePrefix+"/status", statusHandler)
r.Handler("GET", *routePrefix+"/", statusHandler)
// Re-enable pprof.
r.GET(*routePrefix+"/debug/pprof/*pprof", handlePprof)
log.Infof("Listening on %s.", *listenAddress)
l, err := net.Listen("tcp", *listenAddress)
if err != nil {
log.Fatal(err)
}
go interruptHandler(l)
err = (&http.Server{Addr: *listenAddress, Handler: r}).Serve(l)
log.Errorln("HTTP server stopped:", err)
// To give running connections a chance to submit their payload, we wait
// for 1sec, but we don't want to wait long (e.g. until all connections
// are done) to not delay the shutdown.
time.Sleep(time.Second)
if err := ms.Shutdown(); err != nil {
log.Errorln("Problem shutting down metric storage:", err)
}
}
func handlePprof(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
switch p.ByName("pprof") {
case "/cmdline":
pprof.Cmdline(w, r)
case "/profile":
pprof.Profile(w, r)
case "/symbol":
pprof.Symbol(w, r)
default:
pprof.Index(w, r)
}
}
// computeRoutePrefix returns the effective route prefix based on the
// provided flag values for --web.route-prefix and
// --web.external-url. With prefix empty, the path of externalURL is
// used instead. A prefix "/" results in an empty returned prefix. Any
// non-empty prefix is normalized to start, but not to end, with "/".
func computeRoutePrefix(prefix string, externalURL *url.URL) string {
if prefix == "" {
prefix = externalURL.Path
}
if prefix == "/" {
prefix = ""
}
if prefix != "" {
prefix = "/" + strings.Trim(prefix, "/")
}
return prefix
}
func interruptHandler(l net.Listener) {
notifier := make(chan os.Signal, 1)
signal.Notify(notifier, os.Interrupt, syscall.SIGTERM)
<-notifier
log.Info("Received SIGINT/SIGTERM; exiting gracefully...")
l.Close()
}