Debian Codegraph @

tutorials/whatsup/main.go

raw
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/tutorials/whatsup/internal"
40 )
41
42 func main() {
43 opts, err := internal.ParseOptions(os.Args)
44 if err != nil {
45 log.Fatalf("Error: %v", err)
46 }
47
48 if err := runMain(opts); err != nil {
49 // Use %+v for github.com/efficientgo/core/errors error to print with stack.
50 log.Fatalf("Error: %+v", errors.Wrapf(err, "%s", flag.Arg(0)))
51 }
52 }
53
54 func runMain(opts internal.Config) (err error) {
55 // Create tracer, so the application can be instrumented with traces.
56 var exporter tracing.ExporterBuilder
57 switch opts.TraceEndpoint {
58 case "stdout":
59 exporter = tracing.NewWriterExporter(os.Stdout)
60 default:
61 exporter = otlp.Exporter(opts.TraceEndpoint, otlp.WithInsecure())
62 }
63 tracer, closeFn, err := tracing.NewTracer(
64 exporter,
65 tracing.WithSampler(tracing.TraceIDRatioBasedSampler(opts.TraceSamplingRatio)),
66 tracing.WithServiceName("client_golang-tutorial:whatsup"),
67 )
68 if err != nil {
69 return err
70 }
71 defer errcapture.Do(&err, closeFn, "close tracers")
72
73 m := http.NewServeMux()
74 // Create HTTP handler for Prometheus metrics.
75 // TODO
76 //m.Handle("/metrics", ...
77
78 promClient, err := api.NewClient(api.Config{
79 Client: &http.Client{Transport: instrumentRoundTripper(nil, "prometheus", http.DefaultTransport)},
80 Address: opts.PrometheusAddr,
81 })
82 if err != nil {
83 return err
84 }
85 apiClient := v1.NewAPI(promClient)
86
87 // Create HTTP handler for our whatsup implementation.
88 m.HandleFunc(instrumentHandlerFunc(tracer, nil, "/whatsup", whatsUpHandler(
89 apiClient,
90 )))
91
92 // Debug profiling endpoints.
93 m.HandleFunc("/debug/pprof/", httppprof.Index)
94 m.HandleFunc("/debug/pprof/cmdline", httppprof.Cmdline)
95 m.HandleFunc("/debug/pprof/profile", httppprof.Profile)
96 m.HandleFunc("/debug/pprof/symbol", httppprof.Symbol)
97
98 srv := http.Server{Addr: fmt.Sprintf(":%v", internal.WhatsupPort), Handler: m}
99
100 g := &run.Group{}
101 g.Add(func() error {
102 log.Println("Starting HTTP server", "addr", internal.WhatsupPort)
103 if err := srv.ListenAndServe(); err != nil {
104 return errors.Wrap(err, "starting web server")
105 }
106 return nil
107 }, func(error) {
108 if err := srv.Close(); err != nil {
109 log.Println("Error: Failed to stop web server", "err", err)
110 }
111 })
112 g.Add(run.SignalHandler(context.Background(), syscall.SIGINT, syscall.SIGTERM))
113 return g.Run()
114 }
115
116 type response struct {
117 Error error `json:",omitempty"`
118 Instances []string
119 }
120
121 // whatsUpHandler returns all services that currently monitored by Prometheus.
122 // It uses prometheus client_golang client code to request PromQL query against given Prometheus server
123 // to return answer.
124 func whatsUpHandler(
125 apiClient v1.API,
126 ) http.HandlerFunc {
127 return func(w http.ResponseWriter, r *http.Request) {
128 ctx := r.Context()
129 w.Header().Set("Content-Type", "application/json")
130
131 var upResponse model.Value
132 if err := tracing.DoInSpan(ctx, "query Prometheus", func(ctx context.Context) error {
133 res, warn, err := apiClient.Query(ctx, "up", time.Now())
134 if err != nil {
135 return err
136 }
137
138 if len(warn) > 0 {
139 return errors.Newf("got warnings from Prometheus %v", warn)
140 }
141 upResponse = res
142 return nil
143 }); err != nil {
144 // We return OK status, so browser can render nice result.
145 w.WriteHeader(http.StatusOK)
146 // NOTE: Pass-through error might be not always safe, sanitize on production.
147 b, _ := json.Marshal(response{Error: err})
148 _, _ = fmt.Fprintln(w, string(b))
149 return
150 }
151
152 resp := response{}
153 switch r := upResponse.(type) {
154 case model.Vector:
155 for _, s := range r {
156 resp.Instances = append(resp.Instances, string(s.Metric["instance"]))
157 }
158 }
159
160 w.WriteHeader(http.StatusOK)
161 b, _ := json.Marshal(resp)
162 _, _ = fmt.Fprintln(w, string(b))
163 }
164 }
165
166 func getExemplarFn(ctx context.Context) prometheus.Labels {
167 if spanCtx := tracing.GetSpan(ctx); spanCtx.Context().IsSampled() {
168 return prometheus.Labels{"traceID": spanCtx.Context().TraceID()}
169 }
170 return nil
171 }
172
173 func instrumentHandlerFunc(tracer *tracing.Tracer, _ prometheus.Registerer, handlerName string, handler http.Handler) (string, http.HandlerFunc) {
174 // Wrap with tracing. This will be visited as a first middleware.
175 base := tracinghttp.NewMiddleware(tracer).WrapHandler(handlerName, http.HandlerFunc(func(writer http.ResponseWriter, r *http.Request) {
176 handler.ServeHTTP(writer, r)
177 }))
178 return handlerName, base.ServeHTTP
179 }
180
181 func instrumentRoundTripper(_ prometheus.Registerer, clientName string, rt http.RoundTripper) http.RoundTripper {
182 // Wrap with tracing. This will be visited as a first middleware.
183 return tracinghttp.NewTripperware().WrapRoundTipper(clientName, rt)
184 }