forked from pyrra-dev/pyrra
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
1693 lines (1489 loc) · 54.1 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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"context"
"crypto/tls"
"embed"
"fmt"
"html/template"
"io"
"io/fs"
"math"
"net/http"
"net/url"
"os"
"sort"
"strconv"
"strings"
"sync"
"syscall"
"time"
"github.com/alecthomas/kong"
"github.com/bufbuild/connect-go"
"github.com/dgraph-io/ristretto"
"github.com/go-chi/chi/v5"
"github.com/go-chi/cors"
"github.com/go-kit/log"
"github.com/go-kit/log/level"
"github.com/oklog/run"
connectprometheus "github.com/polarsignals/connect-go-prometheus"
"github.com/prometheus/client_golang/api"
prometheusapiv1 "github.com/prometheus/client_golang/api/prometheus/v1"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/collectors"
"github.com/prometheus/client_golang/prometheus/promhttp"
promconfig "github.com/prometheus/common/config"
"github.com/prometheus/common/model"
"github.com/prometheus/prometheus/model/labels"
"github.com/prometheus/prometheus/promql/parser"
"golang.org/x/net/http2"
"golang.org/x/net/http2/h2c"
"google.golang.org/protobuf/types/known/durationpb"
objectivesv1alpha1 "github.com/pyrra-dev/pyrra/proto/objectives/v1alpha1"
"github.com/pyrra-dev/pyrra/proto/objectives/v1alpha1/objectivesv1alpha1connect"
"github.com/pyrra-dev/pyrra/proto/prometheus/v1/prometheusv1connect"
"github.com/pyrra-dev/pyrra/slo"
)
//go:embed ui/build
var ui embed.FS
var CLI struct {
LoggerConfig
API struct {
PrometheusURL *url.URL `default:"http://localhost:9090" help:"The URL to the Prometheus to query."`
PrometheusExternalURL *url.URL `help:"The URL for the UI to redirect users to when opening Prometheus. If empty the same as prometheus.url"`
APIURL *url.URL `name:"api-url" default:"http://localhost:9444" help:"The URL to the API service like a Kubernetes Operator."`
RoutePrefix string `default:"" help:"The route prefix Pyrra uses. If run behind a proxy you can change it to something like /pyrra here."`
UIRoutePrefix string `default:"" help:"The route prefix Pyrra's UI uses. This is helpful for when the prefix is stripped by a proxy but still runs on /pyrra. Defaults to --route-prefix"`
PrometheusBearerTokenPath string `default:"" help:"Bearer token path"`
PrometheusBasicAuthUsername string `default:"" help:"The HTTP basic authentication username"`
PrometheusBasicAuthPassword promconfig.Secret `default:"" help:"The HTTP basic authentication password"`
TLSCertFile string `default:"" help:"File containing the default x509 Certificate for HTTPS."`
TLSPrivateKeyFile string `default:"" help:"File containing the default x509 private key matching --tls-cert-file."`
TLSClientCAFile string `default:"" help:"File containing the CA certificate for the client"`
} `cmd:"" help:"Runs Pyrra's API and UI."`
Filesystem struct {
ConfigFiles string `default:"/etc/pyrra/*.yaml" help:"The folder where Pyrra finds the config files to use. Any non yaml files will be ignored."`
PrometheusURL *url.URL `default:"http://localhost:9090" help:"The URL to the Prometheus to query."`
PrometheusFolder string `default:"/etc/prometheus/pyrra/" help:"The folder where Pyrra writes the generates Prometheus rules and alerts."`
GenericRules bool `default:"false" help:"Enabled generic recording rules generation to make it easier for tools like Grafana."`
} `cmd:"" help:"Runs Pyrra's filesystem operator and backend for the API."`
Kubernetes struct {
MetricsAddr string `default:":8080" help:"The address the metric endpoint binds to."`
ConfigMapMode bool `default:"false" help:"If the generated recording rules should instead be saved to config maps in the default Prometheus format."`
GenericRules bool `default:"false" help:"Enabled generic recording rules generation to make it easier for tools like Grafana."`
DisableWebhooks bool `default:"true" env:"DISABLE_WEBHOOKS" help:"Disable webhooks so the controller doesn't try to read certificates"`
TLSCertFile string `default:"" help:"File containing the default x509 Certificate for HTTPS."`
TLSPrivateKeyFile string `default:"" help:"File containing the default x509 private key matching --tls-cert-file."`
} `cmd:"" help:"Runs Pyrra's Kubernetes operator and backend for the API."`
Generate struct {
ConfigFiles string `default:"/etc/pyrra/*.yaml" help:"The folder where Pyrra finds the config files to use."`
PrometheusFolder string `default:"/etc/prometheus/pyrra/" help:"The folder where Pyrra writes the generated Prometheus rules and alerts."`
GenericRules bool `default:"false" help:"Enabled generic recording rules generation to make it easier for tools like Grafana."`
OperatorRule bool `default:"false" help:"Generate rule files as prometheus-operator PrometheusRule: https://prometheus-operator.dev/docs/operator/api/#monitoring.coreos.com/v1.PrometheusRule."`
} `cmd:"" help:"Read SLO config files and rewrites them as Prometheus rules and alerts."`
}
func main() {
ctx := kong.Parse(&CLI)
logger := configureLogger(CLI.LoggerConfig)
reg := prometheus.NewRegistry()
reg.MustRegister(
collectors.NewBuildInfoCollector(),
collectors.NewGoCollector(),
collectors.NewProcessCollector(collectors.ProcessCollectorOpts{}),
)
var prometheusURL *url.URL
switch ctx.Command() {
case "api":
prometheusURL = CLI.API.PrometheusURL
case "filesystem":
prometheusURL = CLI.Filesystem.PrometheusURL
default:
prometheusURL, _ = url.Parse("http://localhost:9090")
}
clientConfig := promconfig.HTTPClientConfig{}
if CLI.API.PrometheusBasicAuthUsername != "" && CLI.API.PrometheusBasicAuthPassword != "" {
clientConfig.BasicAuth = &promconfig.BasicAuth{
Username: CLI.API.PrometheusBasicAuthUsername,
Password: CLI.API.PrometheusBasicAuthPassword,
}
}
if CLI.API.PrometheusBearerTokenPath != "" {
clientConfig.BearerTokenFile = CLI.API.PrometheusBearerTokenPath
}
if CLI.API.TLSClientCAFile != "" {
clientConfig.TLSConfig = promconfig.TLSConfig{CAFile: CLI.API.TLSClientCAFile}
}
roundTripper, err := promconfig.NewRoundTripperFromConfig(clientConfig, "prometheus")
if err != nil {
level.Error(logger).Log("msg", "failed to create API client round tripper", "err", err)
os.Exit(1)
}
client, err := api.NewClient(api.Config{
Address: prometheusURL.String(),
RoundTripper: roundTripper,
})
if err != nil {
level.Error(logger).Log("msg", "failed to create API client", "err", err)
os.Exit(1)
}
// Wrap client to add extra headers for Thanos.
client = newThanosClient(client)
level.Info(logger).Log("msg", "using Prometheus", "url", prometheusURL.String())
if CLI.API.PrometheusExternalURL == nil {
CLI.API.PrometheusExternalURL = prometheusURL
}
var code int
switch ctx.Command() {
case "api":
code = cmdAPI(
logger,
reg,
client,
CLI.API.PrometheusExternalURL,
CLI.API.APIURL,
CLI.API.RoutePrefix,
CLI.API.UIRoutePrefix,
CLI.API.TLSCertFile,
CLI.API.TLSPrivateKeyFile,
)
case "filesystem":
code = cmdFilesystem(
logger,
reg,
client,
CLI.Filesystem.ConfigFiles,
CLI.Filesystem.PrometheusFolder,
CLI.Filesystem.GenericRules,
)
case "kubernetes":
code = cmdKubernetes(
logger,
CLI.Kubernetes.MetricsAddr,
CLI.Kubernetes.ConfigMapMode,
CLI.Kubernetes.GenericRules,
CLI.Kubernetes.DisableWebhooks,
CLI.Kubernetes.TLSCertFile,
CLI.Kubernetes.TLSPrivateKeyFile,
)
case "generate":
code = cmdGenerate(
logger,
CLI.Generate.ConfigFiles,
CLI.Generate.PrometheusFolder,
CLI.Generate.GenericRules,
CLI.Generate.OperatorRule,
)
}
os.Exit(code)
}
func cmdAPI(
logger log.Logger,
reg *prometheus.Registry,
promClient api.Client,
prometheusExternal, apiURL *url.URL,
routePrefix, uiRoutePrefix string,
tlsCertFile, tlsPrivateKeyFile string,
) int {
build, err := fs.Sub(ui, "ui/build")
if err != nil {
level.Error(logger).Log("msg", "failed to read UI build files", "err", err)
return 1
}
// RoutePrefix must always be at least '/'.
routePrefix = "/" + strings.Trim(routePrefix, "/")
if uiRoutePrefix == "" {
uiRoutePrefix = routePrefix
} else {
uiRoutePrefix = "/" + strings.Trim(uiRoutePrefix, "/")
}
level.Info(logger).Log("msg", "UI redirect to Prometheus", "url", prometheusExternal.String())
level.Info(logger).Log("msg", "using API at", "url", apiURL.String())
level.Info(logger).Log("msg", "using route prefix", "prefix", routePrefix)
cache, err := ristretto.NewCache(&ristretto.Config{
NumCounters: 1e7, // number of keys to track frequency of (10M).
MaxCost: 1 << 30, // maximum cost of cache (1GB).
BufferItems: 64, // number of keys per Get buffer.
})
if err != nil {
level.Error(logger).Log("msg", "failed to create cache", "err", err)
return 1
}
defer cache.Close()
promAPI := &promCache{
api: &promLogger{
api: prometheusapiv1.NewAPI(promClient),
logger: logger,
},
cache: cache,
}
tmpl, err := template.ParseFS(build, "index.html")
if err != nil {
level.Error(logger).Log("msg", "failed to parse HTML template", "err", err)
return 1
}
r := chi.NewRouter()
r.Use(cors.Handler(cors.Options{
AllowedHeaders: []string{
"Content-Type",
"Connect-Protocol-Version",
},
})) // TODO: Disable by default
prometheusInterceptor := connectprometheus.NewInterceptor(reg)
r.Route(routePrefix, func(r chi.Router) {
clientConfig := promconfig.HTTPClientConfig{
TLSConfig: promconfig.TLSConfig{
InsecureSkipVerify: true,
},
}
roundTripper, err := promconfig.NewRoundTripperFromConfig(clientConfig, "api")
if err != nil {
level.Error(logger).Log("msg", "failed to create API client round tripper", "err", err)
os.Exit(1)
}
client := &http.Client{
Transport: roundTripper,
}
objectiveService := &objectiveServer{
logger: log.WithPrefix(logger, "service", "objective"),
promAPI: promAPI,
client: newBackendClientCache(
objectivesv1alpha1connect.NewObjectiveBackendServiceClient(
client,
apiURL.String(),
connect.WithInterceptors(prometheusInterceptor),
),
),
}
objectivePath, objectiveHandler := objectivesv1alpha1connect.NewObjectiveServiceHandler(
objectiveService,
connect.WithInterceptors(prometheusInterceptor),
)
prometheusService := &prometheusServer{
logger: log.WithPrefix(logger, "service", "prometheus"),
promAPI: promAPI,
}
prometheusPath, prometheusHandler := prometheusv1connect.NewPrometheusServiceHandler(prometheusService)
if routePrefix != "/" {
r.Mount(objectivePath, http.StripPrefix(routePrefix, objectiveHandler))
r.Mount(prometheusPath, http.StripPrefix(routePrefix, prometheusHandler))
} else {
r.Mount(objectivePath, objectiveHandler)
r.Mount(prometheusPath, prometheusHandler)
}
r.Handle("/metrics", promhttp.HandlerFor(reg, promhttp.HandlerOpts{}))
r.Get("/objectives", func(w http.ResponseWriter, _ *http.Request) {
err := tmpl.Execute(w, struct {
PrometheusURL string
PathPrefix string
APIBasepath string
}{
PrometheusURL: prometheusExternal.String(),
PathPrefix: uiRoutePrefix,
APIBasepath: uiRoutePrefix,
})
if err != nil {
level.Warn(logger).Log("msg", "failed to populate HTML template", "err", err)
}
})
r.Handle("/*", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Trim trailing slash to not care about matching e.g. /pyrra and /pyrra/
if r.URL.Path == "/" || strings.TrimSuffix(r.URL.Path, "/") == routePrefix {
err := tmpl.Execute(w, struct {
PrometheusURL string
PathPrefix string
APIBasepath string
}{
PrometheusURL: prometheusExternal.String(),
PathPrefix: uiRoutePrefix,
APIBasepath: uiRoutePrefix,
})
if err != nil {
level.Warn(logger).Log("msg", "failed to populate HTML template", "err", err)
}
return
}
http.StripPrefix(
routePrefix,
http.FileServer(http.FS(build)),
).ServeHTTP(w, r)
}))
})
if routePrefix != "/" {
// Redirect /pyrra to /pyrra/ for the UI to work properly.
r.HandleFunc(strings.TrimSuffix(routePrefix, "/"), func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, routePrefix+"/", http.StatusPermanentRedirect)
})
}
var (
gr run.Group
ctx = context.Background()
)
gr.Add(run.SignalHandler(ctx, os.Interrupt, syscall.SIGTERM))
{
httpServer := &http.Server{
Addr: ":9099",
Handler: h2c.NewHandler(r, &http2.Server{}),
TLSConfig: &tls.Config{},
}
gr.Add(
func() error {
if tlsCertFile != "" && tlsPrivateKeyFile != "" {
level.Info(logger).Log("msg", "serving using TLS", "cert", tlsCertFile, "key", tlsPrivateKeyFile)
return httpServer.ListenAndServeTLS(tlsCertFile, tlsPrivateKeyFile)
}
return httpServer.ListenAndServe()
},
func(error) {
shutdownCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
_ = httpServer.Shutdown(shutdownCtx)
},
)
}
if err := gr.Run(); err != nil {
if _, ok := err.(run.SignalError); ok {
level.Info(logger).Log("msg", "terminated HTTP server", "reason", err)
return 0
}
level.Error(logger).Log("msg", "failed to run HTTP server", "err", err)
return 2
}
return 0
}
func newBackendClientCache(client objectivesv1alpha1connect.ObjectiveBackendServiceClient) objectivesv1alpha1connect.ObjectiveBackendServiceClient {
cache, err := ristretto.NewCache(&ristretto.Config{
NumCounters: 100,
MaxCost: 10 * 1000, // 10 seconds
BufferItems: 64,
})
if err != nil {
panic(err)
}
return &backendClientCache{client: client, cache: cache}
}
type backendClientCache struct {
client objectivesv1alpha1connect.ObjectiveBackendServiceClient
cache *ristretto.Cache
}
// List calls the backend service and caches the result for 10 seconds if the request is successful.
func (b *backendClientCache) List(ctx context.Context, req *connect.Request[objectivesv1alpha1.ListRequest]) (*connect.Response[objectivesv1alpha1.ListResponse], error) {
key := req.Msg.Expr + req.Msg.Grouping
list, found := b.cache.Get(key)
if found {
return connect.NewResponse(list.(*objectivesv1alpha1.ListResponse)), nil
}
start := time.Now()
resp, err := b.client.List(ctx, req)
if err != nil {
return nil, err
}
_ = b.cache.SetWithTTL(key, resp.Msg, time.Since(start).Milliseconds(), 10*time.Second)
return resp, nil
}
func newThanosClient(client api.Client) api.Client {
return &thanosClient{client: client}
}
// thanosClient wraps the Prometheus Client to inject some headers to disable partial responses
// and enables querying for downsampled data.
type thanosClient struct {
client api.Client
}
func (c *thanosClient) URL(ep string, args map[string]string) *url.URL {
return c.client.URL(ep, args)
}
func (c *thanosClient) Do(ctx context.Context, r *http.Request) (*http.Response, []byte, error) {
if r.Body == nil {
return c.client.Do(ctx, r)
}
body, err := io.ReadAll(r.Body)
if err != nil {
return nil, nil, fmt.Errorf("reading body: %w", err)
}
query, err := url.ParseQuery(string(body))
if err != nil {
return nil, nil, fmt.Errorf("parsing body: %w", err)
}
// We don't want partial responses, especially not when calculating error budgets.
query.Set("partial_response", "false")
r.ContentLength += 23
if strings.HasSuffix(r.URL.Path, "/api/v1/query_range") {
start, err := strconv.ParseFloat(query.Get("start"), 64)
if err != nil {
return nil, nil, fmt.Errorf("parsing start: %w", err)
}
end, err := strconv.ParseFloat(query.Get("end"), 64)
if err != nil {
return nil, nil, fmt.Errorf("parsing end: %w", err)
}
if end-start >= 28*24*60*60 { // request 1h downsamples when range > 28d
query.Set("max_source_resolution", "1h")
r.ContentLength += 25
} else if end-start >= 7*24*60*60 { // request 5m downsamples when range > 1w
query.Set("max_source_resolution", "5m")
r.ContentLength += 25
}
}
encoded := query.Encode()
r.Body = io.NopCloser(strings.NewReader(encoded))
return c.client.Do(ctx, r)
}
type prometheusAPI interface {
// Query performs a query for the given time.
Query(ctx context.Context, query string, ts time.Time, opts ...prometheusapiv1.Option) (model.Value, prometheusapiv1.Warnings, error)
// QueryRange performs a query for the given range.
QueryRange(ctx context.Context, query string, r prometheusapiv1.Range, opts ...prometheusapiv1.Option) (model.Value, prometheusapiv1.Warnings, error)
}
type promLogger struct {
api prometheusAPI
logger log.Logger
}
func (l *promLogger) Query(ctx context.Context, query string, ts time.Time, opts ...prometheusapiv1.Option) (model.Value, prometheusapiv1.Warnings, error) {
level.Debug(l.logger).Log(
"msg", "running instant query",
"query", query,
"ts", ts,
)
return l.api.Query(ctx, query, ts, opts...)
}
func (l *promLogger) QueryRange(ctx context.Context, query string, r prometheusapiv1.Range, opts ...prometheusapiv1.Option) (model.Value, prometheusapiv1.Warnings, error) {
level.Debug(l.logger).Log(
"msg", "running range query",
"query", query,
"start", r.Start,
"end", r.End,
)
return l.api.QueryRange(ctx, query, r, opts...)
}
type promCache struct {
api prometheusAPI
cache *ristretto.Cache
}
type promCacheKeyType string
const promCacheKey promCacheKeyType = "promCache"
func contextSetPromCache(ctx context.Context, t time.Duration) context.Context {
return context.WithValue(ctx, promCacheKey, t)
}
func contextGetPromCache(ctx context.Context) time.Duration {
t, ok := ctx.Value(promCacheKey).(time.Duration)
if ok {
return t
}
return 0
}
func (p *promCache) Query(ctx context.Context, query string, ts time.Time) (model.Value, prometheusapiv1.Warnings, error) {
if value, exists := p.cache.Get(query); exists {
return value.(model.Value), nil, nil
}
start := time.Now()
value, warnings, err := p.api.Query(ctx, query, ts)
duration := time.Since(start)
if err != nil {
return nil, warnings, fmt.Errorf("prometheus query: %w", err)
}
if len(warnings) > 0 {
return value, warnings, nil
}
cacheDuration := contextGetPromCache(ctx)
if cacheDuration > 0 {
if v, ok := value.(model.Vector); ok {
if len(v) > 0 {
_ = p.cache.SetWithTTL(query, value, duration.Milliseconds(), cacheDuration)
}
}
}
return value, warnings, nil
}
func (p *promCache) QueryRange(ctx context.Context, query string, r prometheusapiv1.Range) (model.Value, prometheusapiv1.Warnings, error) {
// Get the full time range of this query from start to end.
// We round by 10s to adjust for small imperfections to increase cache hits.
timeRange := r.End.Sub(r.Start).Round(10 * time.Second)
cacheKey := fmt.Sprintf("%d;%s", timeRange.Milliseconds(), query)
if value, exists := p.cache.Get(cacheKey); exists {
return value.(model.Value), nil, nil
}
start := time.Now()
value, warnings, err := p.api.QueryRange(ctx, query, r)
duration := time.Since(start)
if err != nil {
return nil, warnings, fmt.Errorf("prometheus query range: %w", err)
}
if len(warnings) > 0 {
return value, warnings, nil
}
cacheDuration := contextGetPromCache(ctx)
if cacheDuration > 0 {
if m, ok := value.(model.Matrix); ok {
if len(m) > 0 {
_ = p.cache.SetWithTTL(cacheKey, value, duration.Milliseconds(), cacheDuration)
}
}
}
return value, warnings, nil
}
type objectiveServer struct {
logger log.Logger
promAPI *promCache
client objectivesv1alpha1connect.ObjectiveBackendServiceClient
}
func (s *objectiveServer) getObjective(ctx context.Context, expr string) (slo.Objective, error) {
resp, err := s.client.List(ctx, connect.NewRequest(&objectivesv1alpha1.ListRequest{
Expr: expr,
}))
if err != nil {
return slo.Objective{}, err
}
if len(resp.Msg.Objectives) != 1 {
return slo.Objective{}, connect.NewError(connect.CodeAborted, fmt.Errorf("expr matches more than one SLO, it matches: %d", len(resp.Msg.Objectives)))
}
return objectivesv1alpha1.ToInternal(resp.Msg.Objectives[0]), nil
}
func (s *objectiveServer) List(ctx context.Context, req *connect.Request[objectivesv1alpha1.ListRequest]) (*connect.Response[objectivesv1alpha1.ListResponse], error) {
if expr := req.Msg.Expr; expr != "" {
if _, err := parser.ParseMetricSelector(expr); err != nil {
return nil, connect.NewError(connect.CodeFailedPrecondition, fmt.Errorf("failed to parse expr: %w", err))
}
}
resp, err := s.client.List(ctx, connect.NewRequest(&objectivesv1alpha1.ListRequest{
Expr: req.Msg.Expr,
}))
if err != nil {
return nil, err
}
groupingMatchers := map[string]*labels.Matcher{}
if req.Msg.Grouping != "" {
ms, err := parser.ParseMetricSelector(req.Msg.Grouping)
if err != nil {
return nil, connect.NewError(connect.CodeInvalidArgument, err)
}
for _, m := range ms {
groupingMatchers[m.Name] = m
}
}
for _, o := range resp.Msg.Objectives {
oi := objectivesv1alpha1.ToInternal(o)
// If specific grouping was selected we need to merge the label matchers for the queries.
if len(groupingMatchers) > 0 {
switch oi.IndicatorType() {
case slo.Ratio:
groupingMatchersErrors := make(map[string]*labels.Matcher, len(groupingMatchers))
groupingMatchersTotal := make(map[string]*labels.Matcher, len(groupingMatchers))
for _, matcher := range groupingMatchers {
// We need to copy the matchers to avoid modifying the original later on.
groupingMatchersErrors[matcher.Name] = &labels.Matcher{Type: matcher.Type, Name: matcher.Name, Value: matcher.Value}
groupingMatchersTotal[matcher.Name] = &labels.Matcher{Type: matcher.Type, Name: matcher.Name, Value: matcher.Value}
}
for _, m := range oi.Indicator.Ratio.Errors.LabelMatchers {
if rm, replace := groupingMatchers[m.Name]; replace {
m.Type = rm.Type
m.Value = rm.Value
delete(groupingMatchersErrors, m.Name)
}
}
for _, m := range oi.Indicator.Ratio.Total.LabelMatchers {
if rm, replace := groupingMatchers[m.Name]; replace {
m.Type = rm.Type
m.Value = rm.Value
delete(groupingMatchersTotal, m.Name)
}
}
// Now add the remaining matchers we didn't find before.
for _, m := range groupingMatchersErrors {
oi.Indicator.Ratio.Errors.LabelMatchers = append(oi.Indicator.Ratio.Errors.LabelMatchers, m)
}
for _, m := range groupingMatchersTotal {
oi.Indicator.Ratio.Total.LabelMatchers = append(oi.Indicator.Ratio.Total.LabelMatchers, m)
}
case slo.Latency:
groupingMatchersSuccess := make(map[string]*labels.Matcher, len(groupingMatchers))
groupingMatchersTotal := make(map[string]*labels.Matcher, len(groupingMatchers))
for _, matcher := range groupingMatchers {
// We need to copy the matchers to avoid modifying the original later on.
groupingMatchersSuccess[matcher.Name] = &labels.Matcher{Type: matcher.Type, Name: matcher.Name, Value: matcher.Value}
groupingMatchersTotal[matcher.Name] = &labels.Matcher{Type: matcher.Type, Name: matcher.Name, Value: matcher.Value}
}
for _, m := range oi.Indicator.Latency.Success.LabelMatchers {
if rm, replace := groupingMatchers[m.Name]; replace {
m.Type = rm.Type
m.Value = rm.Value
delete(groupingMatchersSuccess, m.Name)
}
}
for _, m := range oi.Indicator.Latency.Total.LabelMatchers {
if rm, replace := groupingMatchers[m.Name]; replace {
m.Type = rm.Type
m.Value = rm.Value
delete(groupingMatchersTotal, m.Name)
}
}
// Now add the remaining matchers we didn't find before.
for _, m := range groupingMatchersSuccess {
oi.Indicator.Latency.Success.LabelMatchers = append(oi.Indicator.Latency.Success.LabelMatchers, m)
}
for _, m := range groupingMatchersTotal {
oi.Indicator.Latency.Total.LabelMatchers = append(oi.Indicator.Latency.Total.LabelMatchers, m)
}
case slo.LatencyNative:
for _, m := range oi.Indicator.LatencyNative.Total.LabelMatchers {
if rm, replace := groupingMatchers[m.Name]; replace {
m.Type = rm.Type
m.Value = rm.Value
delete(groupingMatchers, m.Name)
}
}
for _, m := range groupingMatchers {
oi.Indicator.LatencyNative.Total.LabelMatchers = append(oi.Indicator.LatencyNative.Total.LabelMatchers, m)
}
case slo.BoolGauge:
for _, m := range oi.Indicator.BoolGauge.LabelMatchers {
if rm, replace := groupingMatchers[m.Name]; replace {
m.Type = rm.Type
m.Value = rm.Value
delete(groupingMatchers, m.Name)
}
}
for _, m := range groupingMatchers {
oi.Indicator.BoolGauge.LabelMatchers = append(oi.Indicator.BoolGauge.LabelMatchers, m)
}
}
}
o.Queries = &objectivesv1alpha1.Queries{
CountTotal: oi.QueryTotal(oi.Window),
CountErrors: oi.QueryErrors(oi.Window),
GraphErrorBudget: oi.QueryErrorBudget(),
GraphRequests: oi.RequestRange(time.Second),
GraphErrors: oi.ErrorsRange(time.Second),
}
}
return connect.NewResponse(&objectivesv1alpha1.ListResponse{
Objectives: resp.Msg.Objectives,
}), nil
}
func (s *objectiveServer) GetStatus(ctx context.Context, req *connect.Request[objectivesv1alpha1.GetStatusRequest]) (*connect.Response[objectivesv1alpha1.GetStatusResponse], error) {
objective, err := s.getObjective(ctx, req.Msg.Expr)
if err != nil {
return nil, err
}
// Merge grouping into objective's query
if req.Msg.Grouping != "" {
groupingMatchers, err := parser.ParseMetricSelector(req.Msg.Grouping)
if err != nil {
return nil, connect.NewError(connect.CodeInvalidArgument, err)
}
if objective.Indicator.Ratio != nil {
for _, m := range groupingMatchers {
objective.Indicator.Ratio.Errors.LabelMatchers = append(objective.Indicator.Ratio.Errors.LabelMatchers, m)
objective.Indicator.Ratio.Total.LabelMatchers = append(objective.Indicator.Ratio.Total.LabelMatchers, m)
}
}
if objective.Indicator.Latency != nil {
for _, m := range groupingMatchers {
objective.Indicator.Latency.Success.LabelMatchers = append(objective.Indicator.Latency.Success.LabelMatchers, m)
objective.Indicator.Latency.Total.LabelMatchers = append(objective.Indicator.Latency.Total.LabelMatchers, m)
}
}
if objective.Indicator.BoolGauge != nil {
objective.Indicator.BoolGauge.LabelMatchers = append(objective.Indicator.BoolGauge.LabelMatchers, groupingMatchers...)
}
}
ts := time.Now()
if req.Msg.Time != nil {
ts = req.Msg.Time.AsTime()
}
queryTotal := objective.QueryTotal(objective.Window)
value, _, err := s.promAPI.Query(contextSetPromCache(ctx, 15*time.Second), queryTotal, ts)
if err != nil {
level.Warn(s.logger).Log("msg", "failed to query total", "query", queryTotal, "err", err)
return nil, connect.NewError(connect.CodeInternal, err)
}
statuses := map[model.Fingerprint]*objectivesv1alpha1.ObjectiveStatus{}
for _, v := range value.(model.Vector) {
ls := make(map[string]string)
for k, v := range v.Metric {
ls[string(k)] = string(v)
}
statuses[v.Metric.Fingerprint()] = &objectivesv1alpha1.ObjectiveStatus{
Labels: ls,
Availability: &objectivesv1alpha1.Availability{
Percentage: 1,
Total: float64(v.Value),
},
}
}
queryErrors := objective.QueryErrors(objective.Window)
value, _, err = s.promAPI.Query(contextSetPromCache(ctx, 15*time.Second), queryErrors, ts)
if err != nil {
level.Warn(s.logger).Log("msg", "failed to query errors", "query", queryErrors, "err", err)
return nil, connect.NewError(connect.CodeInternal, err)
}
for _, v := range value.(model.Vector) {
if s, exists := statuses[v.Metric.Fingerprint()]; exists {
s.Availability.Errors = float64(v.Value)
s.Availability.Percentage = 1 - (s.Availability.Errors / s.Availability.Total)
} else {
objectiveLabels := make(map[string]string)
for k, v := range v.Metric {
objectiveLabels[string(k)] = string(v)
}
statuses[v.Metric.Fingerprint()] = &objectivesv1alpha1.ObjectiveStatus{
Labels: objectiveLabels,
Availability: &objectivesv1alpha1.Availability{
Percentage: 1 - (s.Availability.Errors / s.Availability.Total),
Total: float64(v.Value),
},
}
}
}
statusSlice := make([]*objectivesv1alpha1.ObjectiveStatus, 0, len(statuses))
for _, s := range statuses {
s.Budget = &objectivesv1alpha1.Budget{}
s.Budget.Total = 1 - objective.Target
s.Budget.Remaining = (s.Budget.Total - (s.Availability.Errors / s.Availability.Total)) / s.Budget.Total
s.Budget.Max = s.Budget.Total * s.Availability.Total
// If this objective has no requests, we'll skip showing it too
if s.Availability.Total == 0 {
continue
}
if math.IsNaN(s.Availability.Percentage) {
s.Availability.Percentage = 1
}
if math.IsNaN(s.Budget.Remaining) {
s.Budget.Remaining = 1
}
statusSlice = append(statusSlice, s)
}
return connect.NewResponse(&objectivesv1alpha1.GetStatusResponse{
Status: statusSlice,
}), nil
}
func (s *objectiveServer) GraphErrorBudget(ctx context.Context, req *connect.Request[objectivesv1alpha1.GraphErrorBudgetRequest]) (*connect.Response[objectivesv1alpha1.GraphErrorBudgetResponse], error) {
objective, err := s.getObjective(ctx, req.Msg.Expr)
if err != nil {
return nil, err
}
if req.Msg.Grouping != "" && req.Msg.Grouping != "{}" {
groupingMatchers, err := parser.ParseMetricSelector(req.Msg.Grouping)
if err != nil {
return nil, connect.NewError(connect.CodeFailedPrecondition, fmt.Errorf("failed parsing alerts metric: %w", err))
}
if ratio := objective.Indicator.Ratio; ratio != nil {
groupings := map[string]struct{}{}
for _, g := range ratio.Grouping {
groupings[g] = struct{}{}
}
for _, m := range groupingMatchers {
objective.Indicator.Ratio.Errors.LabelMatchers = append(objective.Indicator.Ratio.Errors.LabelMatchers, m)
objective.Indicator.Ratio.Total.LabelMatchers = append(objective.Indicator.Ratio.Total.LabelMatchers, m)
delete(groupings, m.Name)
}
objective.Indicator.Ratio.Grouping = []string{}
for g := range groupings {
objective.Indicator.Ratio.Grouping = append(objective.Indicator.Ratio.Grouping, g)
}
}
if objective.Indicator.Latency != nil {
groupings := map[string]struct{}{}
for _, g := range objective.Indicator.Ratio.Grouping {
groupings[g] = struct{}{}
}
for _, m := range groupingMatchers {
objective.Indicator.Latency.Success.LabelMatchers = append(objective.Indicator.Latency.Success.LabelMatchers, m)
objective.Indicator.Latency.Total.LabelMatchers = append(objective.Indicator.Latency.Total.LabelMatchers, m)
delete(groupings, m.Name)
}
objective.Indicator.Latency.Grouping = []string{}
for g := range groupings {
objective.Indicator.Latency.Grouping = append(objective.Indicator.Latency.Grouping, g)
}
}
if objective.Indicator.BoolGauge != nil {
groupings := map[string]struct{}{}
for _, g := range objective.Indicator.BoolGauge.Grouping {
groupings[g] = struct{}{}
}
for _, m := range groupingMatchers {
objective.Indicator.BoolGauge.LabelMatchers = append(objective.Indicator.BoolGauge.LabelMatchers, m)
delete(groupings, m.Name)
}
objective.Indicator.BoolGauge.Grouping = []string{}
for g := range groupings {
objective.Indicator.BoolGauge.Grouping = append(objective.Indicator.BoolGauge.Grouping, g)
}
}
}
if objective.Indicator.LatencyNative != nil && objective.Indicator.Ratio.Total.Name != "" {
return nil, connect.NewError(connect.CodeInternal, fmt.Errorf("unimplemented"))
}
end := time.Now()
start := end.Add(-1 * time.Hour)
if !req.Msg.Start.AsTime().IsZero() && !req.Msg.End.AsTime().IsZero() {
start = req.Msg.Start.AsTime()
end = req.Msg.End.AsTime()
}
step := end.Sub(start) / 1000
query := objective.QueryErrorBudget()
value, _, err := s.promAPI.QueryRange(contextSetPromCache(ctx, 15*time.Second), query, prometheusapiv1.Range{
Start: start,
End: end,
Step: step,
})
if err != nil {
level.Warn(s.logger).Log("msg", "failed to query error budget", "query", query, "err", err)
return nil, connect.NewError(connect.CodeInternal, err)
}
matrix, ok := value.(model.Matrix)
if !ok {
err := fmt.Errorf("no matrix returned")
level.Debug(s.logger).Log("msg", "returned data wasn't of type matrix", "query", query, "err", err)
return nil, connect.NewError(connect.CodeInternal, err)
}
if len(matrix) == 0 {
level.Debug(s.logger).Log("msg", "returned no data", "query", query)
return nil, connect.NewError(connect.CodeNotFound, nil)
}
valueLength := 0
for _, m := range matrix {
if len(m.Values) > valueLength {
valueLength = len(m.Values)
}
}
values := matrixToValues(matrix)
// TODO: Return Samples from above function
series := make([]*objectivesv1alpha1.Series, 0, len(values))
for _, float64s := range values {
series = append(series, &objectivesv1alpha1.Series{Values: float64s})
}
return connect.NewResponse(&objectivesv1alpha1.GraphErrorBudgetResponse{
Timeseries: &objectivesv1alpha1.Timeseries{
Query: query,
Series: series,
},
}), nil
}
func (s *objectiveServer) GetAlerts(ctx context.Context, req *connect.Request[objectivesv1alpha1.GetAlertsRequest]) (*connect.Response[objectivesv1alpha1.GetAlertsResponse], error) {
resp, err := s.client.List(ctx, connect.NewRequest(&objectivesv1alpha1.ListRequest{
Expr: req.Msg.Expr,
}))
if err != nil {
return nil, err
}
objectives := make([]slo.Objective, 0, len(resp.Msg.Objectives))
for _, o := range resp.Msg.Objectives {
objectives = append(objectives, objectivesv1alpha1.ToInternal(o))
}
// Match alerts that at least have one character for the slo name.
queryAlerts := `ALERTS{slo=~".+"}`
var groupingMatchers []*labels.Matcher
if req.Msg.Grouping != "" && req.Msg.Grouping != "{}" {
expr, err := parser.ParseExpr(queryAlerts)
if err != nil {
return nil, connect.NewError(connect.CodeFailedPrecondition, fmt.Errorf("failed parsing alerts metric: %w", err))
}
// If grouping exists we merge those matchers directly into the queryAlerts query.
groupingMatchers, err = parser.ParseMetricSelector(req.Msg.Grouping)
if err != nil {