| 1 |
// Copyright 2023 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 main |
| 15 |
|
| 16 |
import ( |
| 17 |
"context" |
| 18 |
"encoding/json" |
| 19 |
"flag" |
| 20 |
"fmt" |
| 21 |
"log" |
| 22 |
"net/http" |
| 23 |
httppprof "net/http/pprof" |
| 24 |
"os" |
| 25 |
"syscall" |
| 26 |
"time" |
| 27 |
|
| 28 |
"github.com/bwplotka/tracing-go/tracing" |
| 29 |
"github.com/bwplotka/tracing-go/tracing/exporters/otlp" |
| 30 |
tracinghttp "github.com/bwplotka/tracing-go/tracing/http" |
| 31 |
"github.com/efficientgo/core/errcapture" |
| 32 |
"github.com/efficientgo/core/errors" |
| 33 |
"github.com/oklog/run" |
| 34 |
"github.com/prometheus/common/model" |
| 35 |
|
| 36 |
"github.com/prometheus/client_golang/api" |
| 37 |
v1 "github.com/prometheus/client_golang/api/prometheus/v1" |
| 38 |
"github.com/prometheus/client_golang/prometheus" |
| 39 |
"github.com/prometheus/client_golang/prometheus/collectors" |
| 40 |
"github.com/prometheus/client_golang/prometheus/promauto" |
| 41 |
"github.com/prometheus/client_golang/prometheus/promhttp" |
| 42 |
"github.com/prometheus/client_golang/tutorials/whatsup/internal" |
| 43 |
) |
| 44 |
|
| 45 |
func main() { |
| 46 |
opts, err := internal.ParseOptions(os.Args) |
| 47 |
if err != nil { |
| 48 |
log.Fatalf("Error: %v", err) |
| 49 |
} |
| 50 |
|
| 51 |
if err := runMain(opts); err != nil { |
| 52 |
// Use %+v for github.com/efficientgo/core/errors error to print with stack. |
| 53 |
log.Fatalf("Error: %+v", errors.Wrapf(err, "%s", flag.Arg(0))) |
| 54 |
} |
| 55 |
} |
| 56 |
|
| 57 |
func runMain(opts internal.Config) (err error) { |
| 58 |
// Create tracer, so the application can be instrumented with traces. |
| 59 |
var exporter tracing.ExporterBuilder |
| 60 |
switch opts.TraceEndpoint { |
| 61 |
case "stdout": |
| 62 |
exporter = tracing.NewWriterExporter(os.Stdout) |
| 63 |
default: |
| 64 |
exporter = otlp.Exporter(opts.TraceEndpoint, otlp.WithInsecure()) |
| 65 |
} |
| 66 |
tracer, closeFn, err := tracing.NewTracer( |
| 67 |
exporter, |
| 68 |
tracing.WithSampler(tracing.TraceIDRatioBasedSampler(opts.TraceSamplingRatio)), |
| 69 |
tracing.WithServiceName("client_golang-tutorial:whatsup"), |
| 70 |
) |
| 71 |
if err != nil { |
| 72 |
return err |
| 73 |
} |
| 74 |
defer errcapture.Do(&err, closeFn, "close tracers") |
| 75 |
|
| 76 |
// Create registry for Prometheus metrics. |
| 77 |
reg := prometheus.NewRegistry() |
| 78 |
reg.MustRegister( |
| 79 |
collectors.NewGoCollector(), // Metrics from Go runtime. |
| 80 |
collectors.NewProcessCollector(collectors.ProcessCollectorOpts{}), // Metrics about the current UNIX process. |
| 81 |
) |
| 82 |
|
| 83 |
handled := promauto.With(reg).NewCounter(prometheus.CounterOpts{ |
| 84 |
Name: "whatsup_queries_handled_total", |
| 85 |
Help: "Number of queries handed.", |
| 86 |
}) |
| 87 |
lastNumElems := promauto.With(reg).NewGauge(prometheus.GaugeOpts{ |
| 88 |
Name: "whatsup_last_response_elements", |
| 89 |
Help: "Number of elements in response for the last call.", |
| 90 |
}) |
| 91 |
_ = promauto.With(reg).NewGaugeFunc(prometheus.GaugeOpts{ |
| 92 |
Name: "build_info", |
| 93 |
Help: "Build information.", |
| 94 |
ConstLabels: map[string]string{ |
| 95 |
"version": "vYOLO", |
| 96 |
"language": "Go 1.20", |
| 97 |
"owner": "@me", |
| 98 |
}, |
| 99 |
}, func() float64 { |
| 100 |
return 1 |
| 101 |
}) |
| 102 |
handledDuration := promauto.With(reg).NewHistogram( |
| 103 |
prometheus.HistogramOpts{ |
| 104 |
Name: "whatsup_queries_duration_seconds", |
| 105 |
Help: "Tracks the latencies for calls.", |
| 106 |
Buckets: []float64{0.1, 0.3, 0.6, 1, 3, 6, 9, 20}, |
| 107 |
}, |
| 108 |
) |
| 109 |
|
| 110 |
m := http.NewServeMux() |
| 111 |
// Create HTTP handler for Prometheus metrics. |
| 112 |
m.Handle("/metrics", promhttp.HandlerFor( |
| 113 |
reg, |
| 114 |
promhttp.HandlerOpts{ |
| 115 |
// Opt into OpenMetrics e.g. to support exemplars. |
| 116 |
EnableOpenMetrics: true, |
| 117 |
}, |
| 118 |
)) |
| 119 |
|
| 120 |
promClient, err := api.NewClient(api.Config{ |
| 121 |
Client: &http.Client{Transport: instrumentRoundTripper(reg, "prometheus", http.DefaultTransport)}, |
| 122 |
Address: opts.PrometheusAddr, |
| 123 |
}) |
| 124 |
if err != nil { |
| 125 |
return err |
| 126 |
} |
| 127 |
apiClient := v1.NewAPI(promClient) |
| 128 |
|
| 129 |
// Create HTTP handler for our whatsup implementation. |
| 130 |
m.HandleFunc(instrumentHandlerFunc(tracer, reg, "/whatsup", whatsUpHandler( |
| 131 |
apiClient, |
| 132 |
handled, |
| 133 |
lastNumElems, |
| 134 |
handledDuration, |
| 135 |
))) |
| 136 |
|
| 137 |
// Debug profiling endpoints. |
| 138 |
m.HandleFunc("/debug/pprof/", httppprof.Index) |
| 139 |
m.HandleFunc("/debug/pprof/cmdline", httppprof.Cmdline) |
| 140 |
m.HandleFunc("/debug/pprof/profile", httppprof.Profile) |
| 141 |
m.HandleFunc("/debug/pprof/symbol", httppprof.Symbol) |
| 142 |
|
| 143 |
srv := http.Server{Addr: fmt.Sprintf(":%v", internal.WhatsupPort), Handler: m} |
| 144 |
|
| 145 |
g := &run.Group{} |
| 146 |
g.Add(func() error { |
| 147 |
log.Println("Starting HTTP server", "addr", internal.WhatsupPort) |
| 148 |
if err := srv.ListenAndServe(); err != nil { |
| 149 |
return errors.Wrap(err, "starting web server") |
| 150 |
} |
| 151 |
return nil |
| 152 |
}, func(error) { |
| 153 |
if err := srv.Close(); err != nil { |
| 154 |
log.Println("Error: Failed to stop web server", "err", err) |
| 155 |
} |
| 156 |
}) |
| 157 |
g.Add(run.SignalHandler(context.Background(), syscall.SIGINT, syscall.SIGTERM)) |
| 158 |
return g.Run() |
| 159 |
} |
| 160 |
|
| 161 |
type response struct { |
| 162 |
Error error `json:",omitempty"` |
| 163 |
Instances []string |
| 164 |
} |
| 165 |
|
| 166 |
// whatsUpHandler returns all services that currently monitored by Prometheus. |
| 167 |
// It uses prometheus client_golang client code to request PromQL query against given Prometheus server |
| 168 |
// to return answer. |
| 169 |
func whatsUpHandler( |
| 170 |
apiClient v1.API, |
| 171 |
handled prometheus.Counter, |
| 172 |
lastNumElems prometheus.Gauge, |
| 173 |
handledDuration prometheus.Histogram, |
| 174 |
) http.HandlerFunc { |
| 175 |
return func(w http.ResponseWriter, r *http.Request) { |
| 176 |
start := time.Now() |
| 177 |
ctx := r.Context() |
| 178 |
w.Header().Set("Content-Type", "application/json") |
| 179 |
|
| 180 |
var upResponse model.Value |
| 181 |
if err := tracing.DoInSpan(ctx, "query Prometheus", func(ctx context.Context) error { |
| 182 |
res, warn, err := apiClient.Query(ctx, "up", time.Now()) |
| 183 |
if err != nil { |
| 184 |
return err |
| 185 |
} |
| 186 |
|
| 187 |
if len(warn) > 0 { |
| 188 |
return errors.Newf("got warnings from Prometheus %v", warn) |
| 189 |
} |
| 190 |
upResponse = res |
| 191 |
return nil |
| 192 |
}); err != nil { |
| 193 |
// We return OK status, so browser can render nice result. |
| 194 |
w.WriteHeader(http.StatusOK) |
| 195 |
// NOTE: Pass-through error might be not always safe, sanitize on production. |
| 196 |
b, _ := json.Marshal(response{Error: err}) |
| 197 |
_, _ = fmt.Fprintln(w, string(b)) |
| 198 |
return |
| 199 |
} |
| 200 |
|
| 201 |
resp := response{} |
| 202 |
switch r := upResponse.(type) { |
| 203 |
case model.Vector: |
| 204 |
for _, s := range r { |
| 205 |
resp.Instances = append(resp.Instances, string(s.Metric["instance"])) |
| 206 |
} |
| 207 |
} |
| 208 |
|
| 209 |
w.WriteHeader(http.StatusOK) |
| 210 |
b, _ := json.Marshal(resp) |
| 211 |
_, _ = fmt.Fprintln(w, string(b)) |
| 212 |
|
| 213 |
lastNumElems.Set(float64(len(resp.Instances))) |
| 214 |
handled.(prometheus.ExemplarAdder). |
| 215 |
AddWithExemplar(1, getExemplarFn(ctx)) |
| 216 |
handledDuration.(prometheus.ExemplarObserver). |
| 217 |
ObserveWithExemplar(time.Since(start).Seconds(), getExemplarFn(ctx)) |
| 218 |
} |
| 219 |
} |
| 220 |
|
| 221 |
func getExemplarFn(ctx context.Context) prometheus.Labels { |
| 222 |
if spanCtx := tracing.GetSpan(ctx); spanCtx.Context().IsSampled() { |
| 223 |
return prometheus.Labels{"traceID": spanCtx.Context().TraceID()} |
| 224 |
} |
| 225 |
return nil |
| 226 |
} |
| 227 |
|
| 228 |
func instrumentHandlerFunc(tracer *tracing.Tracer, reg prometheus.Registerer, handlerName string, handler http.Handler) (string, http.HandlerFunc) { |
| 229 |
reg = prometheus.WrapRegistererWith(prometheus.Labels{"handler": handlerName}, reg) |
| 230 |
|
| 231 |
requestDuration := promauto.With(reg).NewHistogramVec( |
| 232 |
prometheus.HistogramOpts{ |
| 233 |
Name: "http_request_duration_seconds", |
| 234 |
Help: "Tracks the latencies for HTTP requests.", |
| 235 |
Buckets: []float64{0.1, 0.3, 0.6, 1, 3, 6, 9, 20}, |
| 236 |
}, |
| 237 |
[]string{"method", "code"}, |
| 238 |
) |
| 239 |
requestSize := promauto.With(reg).NewSummaryVec( |
| 240 |
prometheus.SummaryOpts{ |
| 241 |
Name: "http_request_size_bytes", |
| 242 |
Help: "Tracks the size of HTTP requests.", |
| 243 |
}, |
| 244 |
[]string{"method", "code"}, |
| 245 |
) |
| 246 |
requestsTotal := promauto.With(reg).NewCounterVec( |
| 247 |
prometheus.CounterOpts{ |
| 248 |
Name: "http_requests_total", |
| 249 |
Help: "Tracks the number of HTTP requests.", |
| 250 |
}, []string{"method", "code"}, |
| 251 |
) |
| 252 |
responseSize := promauto.With(reg).NewSummaryVec( |
| 253 |
prometheus.SummaryOpts{ |
| 254 |
Name: "http_response_size_bytes", |
| 255 |
Help: "Tracks the size of HTTP responses.", |
| 256 |
}, |
| 257 |
[]string{"method", "code"}, |
| 258 |
) |
| 259 |
|
| 260 |
base := promhttp.InstrumentHandlerRequestSize( |
| 261 |
requestSize, |
| 262 |
promhttp.InstrumentHandlerCounter( |
| 263 |
requestsTotal, |
| 264 |
promhttp.InstrumentHandlerResponseSize( |
| 265 |
responseSize, |
| 266 |
promhttp.InstrumentHandlerDuration( |
| 267 |
requestDuration, |
| 268 |
http.HandlerFunc(func(writer http.ResponseWriter, r *http.Request) { |
| 269 |
handler.ServeHTTP(writer, r) |
| 270 |
}), |
| 271 |
promhttp.WithExemplarFromContext(getExemplarFn), |
| 272 |
), |
| 273 |
), |
| 274 |
promhttp.WithExemplarFromContext(getExemplarFn), |
| 275 |
), |
| 276 |
) |
| 277 |
|
| 278 |
// Wrap with tracing. This will be visited as a first middleware. |
| 279 |
base = tracinghttp.NewMiddleware(tracer).WrapHandler(handlerName, base) |
| 280 |
return handlerName, base.ServeHTTP |
| 281 |
} |
| 282 |
|
| 283 |
func instrumentRoundTripper(reg prometheus.Registerer, clientName string, rt http.RoundTripper) http.RoundTripper { |
| 284 |
reg = prometheus.WrapRegistererWith(prometheus.Labels{"client": clientName}, reg) |
| 285 |
|
| 286 |
requestDuration := promauto.With(reg).NewHistogramVec( |
| 287 |
prometheus.HistogramOpts{ |
| 288 |
Name: "http_client_request_duration_seconds", |
| 289 |
Help: "Tracks the latencies for HTTP requests.", |
| 290 |
Buckets: []float64{0.1, 0.3, 0.6, 1, 3, 6, 9, 20}, |
| 291 |
}, |
| 292 |
[]string{"method", "code"}, |
| 293 |
) |
| 294 |
requestsTotal := promauto.With(reg).NewCounterVec( |
| 295 |
prometheus.CounterOpts{ |
| 296 |
Name: "http_client_requests_total", |
| 297 |
Help: "Tracks the number of HTTP requests.", |
| 298 |
}, []string{"method", "code"}, |
| 299 |
) |
| 300 |
responseInflight := promauto.With(reg).NewGauge( |
| 301 |
prometheus.GaugeOpts{ |
| 302 |
Name: "http_client_requests_inflight", |
| 303 |
Help: "Tracks the number of client requests currently in progress.", |
| 304 |
}, |
| 305 |
) |
| 306 |
|
| 307 |
var base http.RoundTripper |
| 308 |
base = promhttp.InstrumentRoundTripperCounter( |
| 309 |
requestsTotal, |
| 310 |
promhttp.InstrumentRoundTripperInFlight( |
| 311 |
responseInflight, |
| 312 |
promhttp.InstrumentRoundTripperDuration(requestDuration, rt, promhttp.WithExemplarFromContext(getExemplarFn)), |
| 313 |
), |
| 314 |
promhttp.WithExemplarFromContext(getExemplarFn), |
| 315 |
) |
| 316 |
|
| 317 |
// Wrap with tracing. This will be visited as a first middleware. |
| 318 |
return tracinghttp.NewTripperware().WrapRoundTipper(clientName, base) |
| 319 |
} |