This repository has been archived by the owner on Aug 23, 2023. It is now read-only.
/
cluster.go
665 lines (555 loc) · 19.3 KB
/
cluster.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
package api
import (
"context"
"errors"
"fmt"
"net/http"
"regexp"
"strconv"
"strings"
"sync"
"time"
opentracing "github.com/opentracing/opentracing-go"
traceLog "github.com/opentracing/opentracing-go/log"
"github.com/grafana/metrictank/api/middleware"
"github.com/grafana/metrictank/api/models"
"github.com/grafana/metrictank/api/response"
"github.com/grafana/metrictank/cluster"
"github.com/grafana/metrictank/expr/tagquery"
"github.com/grafana/metrictank/stats"
"github.com/grafana/metrictank/tracing"
log "github.com/sirupsen/logrus"
"github.com/tinylib/msgp/msgp"
)
var NotFoundErr = errors.New("not found")
var (
// metric api.cluster.speculative.attempts is how many peer queries resulted in speculation
speculativeAttempts = stats.NewCounter32("api.cluster.speculative.attempts")
// metric api.cluster.speculative.wins is how many peer queries were improved due to speculation
speculativeWins = stats.NewCounter32("api.cluster.speculative.wins")
// metric api.cluster.speculative.requests is how many speculative http requests made to peers
speculativeRequests = stats.NewCounter32("api.cluster.speculative.requests")
)
func (s *Server) explainPriority(ctx *middleware.Context) {
var data []interface{}
for _, p := range s.prioritySetters {
data = append(data, p.ExplainPriority())
}
response.Write(ctx, response.NewJson(200, data, ""))
}
func (s *Server) getNodeStatus(ctx *middleware.Context) {
response.Write(ctx, response.NewJson(200, cluster.Manager.ThisNode(), ""))
}
func (s *Server) setNodeStatus(ctx *middleware.Context, status models.NodeStatus) {
primary, err := strconv.ParseBool(status.Primary)
if err != nil {
response.Write(ctx, response.NewError(http.StatusBadRequest, fmt.Sprintf(
"could not parse status to bool. %s",
err.Error())),
)
return
}
cluster.Manager.SetPrimary(primary)
ctx.PlainText(200, []byte("OK"))
}
func (s *Server) appStatus(ctx *middleware.Context) {
if cluster.Manager.IsReady() {
ctx.PlainText(200, []byte("OK"))
return
}
response.Write(ctx, response.NewError(http.StatusServiceUnavailable, "node not ready"))
}
func (s *Server) getClusterStatus(ctx *middleware.Context) {
status := models.ClusterStatus{
ClusterName: cluster.ClusterName,
NodeName: cluster.Manager.ThisNode().GetName(),
Members: cluster.Manager.MemberList(false, false),
}
response.Write(ctx, response.NewJson(200, status, ""))
}
func (s *Server) postClusterMembers(ctx *middleware.Context, req models.ClusterMembers) {
memberNames := make(map[string]struct{})
var toJoin []string
for _, memberNode := range cluster.Manager.MemberList(false, false) {
memberNames[memberNode.GetName()] = struct{}{}
}
for _, peerName := range req.Members {
if _, ok := memberNames[peerName]; !ok {
toJoin = append(toJoin, peerName)
}
}
resp := models.ClusterMembersResp{
Status: "ok",
MembersAdded: 0,
}
if len(toJoin) == 0 {
response.Write(ctx, response.NewJson(200, resp, ""))
return
}
n, err := cluster.Manager.Join(toJoin)
if err != nil {
response.Write(ctx, response.NewError(http.StatusBadRequest, fmt.Sprintf(
"error when joining cluster members: %s", err.Error())),
)
return
}
resp.MembersAdded = n
response.Write(ctx, response.NewJson(200, resp, ""))
}
// IndexFind returns a sequence of msgp encoded idx.Node's
func (s *Server) indexFind(ctx *middleware.Context, req models.IndexFind) {
resp := models.NewIndexFindResp()
// query nodes don't own any data
if s.MetricIndex == nil {
response.Write(ctx, response.NewMsgp(200, resp))
return
}
for _, pattern := range req.Patterns {
nodes, err := s.MetricIndex.Find(req.OrgId, pattern, req.From)
if err != nil {
response.Write(ctx, response.WrapError(err))
return
}
resp.Nodes[pattern] = nodes
}
response.Write(ctx, response.NewMsgp(200, resp))
}
func (s *Server) indexTagDetails(ctx *middleware.Context, req models.IndexTagDetails) {
// query nodes don't own any data
if s.MetricIndex == nil {
response.Write(ctx, response.NewMsgp(200, &models.IndexTagDetailsResp{}))
return
}
re, err := compileRegexAnchored(req.Filter)
if err != nil {
response.Write(ctx, response.NewError(http.StatusBadRequest, err.Error()))
return
}
values := s.MetricIndex.TagDetails(req.OrgId, req.Tag, re)
response.Write(ctx, response.NewMsgp(200, &models.IndexTagDetailsResp{Values: values}))
}
func (s *Server) indexTags(ctx *middleware.Context, req models.IndexTags) {
// query nodes don't own any data
if s.MetricIndex == nil {
response.Write(ctx, response.NewMsgp(200, &models.IndexTagsResp{}))
return
}
re, err := compileRegexAnchored(req.Filter)
if err != nil {
response.Write(ctx, response.NewError(http.StatusBadRequest, err.Error()))
return
}
tags := s.MetricIndex.Tags(req.OrgId, re)
response.Write(ctx, response.NewMsgp(200, &models.IndexTagsResp{Tags: tags}))
}
func compileRegexAnchored(pattern string) (*regexp.Regexp, error) {
if len(pattern) == 0 {
return nil, nil
}
if pattern == "^.+" {
return nil, nil
}
if pattern[0] != '^' {
pattern = "^(?:" + pattern + ")"
}
return regexp.Compile(pattern)
}
func (s *Server) indexAutoCompleteTags(ctx *middleware.Context, req models.IndexAutoCompleteTags) {
// query nodes don't own any data
if s.MetricIndex == nil {
response.Write(ctx, response.NewMsgp(200, models.StringList(nil)))
return
}
// if there are no expressions given, we can shortcut the evaluation by not using a query
if len(req.Expr) == 0 {
tags := s.MetricIndex.FindTags(req.OrgId, req.Prefix, req.Limit)
response.Write(ctx, response.NewMsgp(200, models.StringList(tags)))
return
}
expressions := req.Expr
if len(req.Prefix) > 0 {
expressions = append(expressions, "__tag^="+req.Prefix)
}
query, err := tagquery.NewQueryFromStrings(expressions, 0)
if err != nil {
response.Write(ctx, response.NewError(http.StatusBadRequest, err.Error()))
return
}
tags := s.MetricIndex.FindTagsWithQuery(req.OrgId, req.Prefix, query, req.Limit)
response.Write(ctx, response.NewMsgp(200, models.StringList(tags)))
return
}
func (s *Server) indexAutoCompleteTagValues(ctx *middleware.Context, req models.IndexAutoCompleteTagValues) {
// query nodes don't own any data
if s.MetricIndex == nil {
response.Write(ctx, response.NewMsgp(200, models.StringList(nil)))
return
}
// if there are no expressions given, we can shortcut the evaluation by not using a query
if len(req.Expr) == 0 {
values := s.MetricIndex.FindTagValues(req.OrgId, req.Tag, req.Prefix, req.Limit)
response.Write(ctx, response.NewMsgp(200, models.StringList(values)))
return
}
expressions := req.Expr
if len(req.Prefix) > 0 {
expressions = append(expressions, req.Tag+"^="+req.Prefix)
}
query, err := tagquery.NewQueryFromStrings(expressions, 0)
if err != nil {
response.Write(ctx, response.NewError(http.StatusBadRequest, err.Error()))
return
}
tags := s.MetricIndex.FindTagValuesWithQuery(req.OrgId, req.Tag, req.Prefix, query, req.Limit)
response.Write(ctx, response.NewMsgp(200, models.StringList(tags)))
}
func (s *Server) indexTagDelSeries(ctx *middleware.Context, request models.IndexTagDelSeries) {
res := models.IndexTagDelSeriesResp{}
// nothing to do on query nodes.
if s.MetricIndex == nil {
response.Write(ctx, response.NewMsgp(200, res))
return
}
for _, path := range request.Paths {
tags, err := tagquery.ParseTagsFromMetricName(path)
if err != nil {
response.Write(ctx, response.WrapErrorForTagDB(err))
return
}
expressions := make(tagquery.Expressions, len(tags))
builder := strings.Builder{}
for i := range tags {
tags[i].StringIntoWriter(&builder)
expressions[i], err = tagquery.ParseExpression(builder.String())
if err != nil {
response.Write(ctx, response.WrapErrorForTagDB(err))
return
}
builder.Reset()
}
query, err := tagquery.NewQuery(expressions, 0)
if err != nil {
response.Write(ctx, response.WrapErrorForTagDB(err))
return
}
deleted, err := s.MetricIndex.DeleteTagged(request.OrgId, query)
if err != nil {
response.Write(ctx, response.WrapErrorForTagDB(err))
return
}
res.Count += len(deleted)
}
response.Write(ctx, response.NewMsgp(200, res))
}
func (s *Server) IndexTagTerms(ctx *middleware.Context, req models.IndexTagTerms) {
// query nodes don't own any data.
if s.MetricIndex == nil {
response.Write(ctx, response.NewMsgp(200, &models.GraphiteTagTermsResp{}))
return
}
query, err := tagquery.NewQueryFromStrings(req.Expr, 0)
if err != nil {
response.Write(ctx, response.NewError(http.StatusBadRequest, err.Error()))
return
}
total, terms := s.MetricIndex.FindTerms(req.OrgId, req.Tags, query)
response.Write(ctx, response.NewMsgp(200, &models.GraphiteTagTermsResp{TotalSeries: total, Terms: terms}))
}
func (s *Server) indexFindByTag(ctx *middleware.Context, req models.IndexFindByTag) {
// query nodes don't own any data.
if s.MetricIndex == nil {
response.Write(ctx, response.NewMsgp(200, &models.IndexFindByTagResp{}))
return
}
query, err := tagquery.NewQueryFromStrings(req.Expr, req.From)
if err != nil {
response.Write(ctx, response.NewError(http.StatusBadRequest, err.Error()))
return
}
metrics := s.MetricIndex.FindByTag(req.OrgId, query)
response.Write(ctx, response.NewMsgp(200, &models.IndexFindByTagResp{Metrics: metrics}))
}
// IndexGet returns a msgp encoded schema.MetricDefinition
func (s *Server) indexGet(ctx *middleware.Context, req models.IndexGet) {
// query nodes don't own any data.
if s.MetricIndex == nil {
response.Write(ctx, response.NewMsgp(404, nil))
return
}
def, ok := s.MetricIndex.Get(req.MKey)
if !ok {
response.Write(ctx, response.NewError(http.StatusNotFound, "Not Found"))
return
}
response.Write(ctx, response.NewMsgp(200, &def))
}
// IndexList returns msgp encoded schema.MetricDefinition's
func (s *Server) indexList(ctx *middleware.Context, req models.IndexList) {
// query nodes don't own any data.
if s.MetricIndex == nil {
response.Write(ctx, response.NewMsgpArray(200, nil))
return
}
defs := s.MetricIndex.List(req.OrgId)
resp := make([]msgp.Marshaler, len(defs))
for i := range defs {
d := defs[i]
resp[i] = &d
}
response.Write(ctx, response.NewMsgpArray(200, resp))
}
func (s *Server) getData(ctx *middleware.Context, request models.GetData) {
var ss models.StorageStats
series, err := s.getTargetsLocal(ctx.Req.Context(), &ss, request.Requests)
if err != nil {
// the only errors returned are from us catching panics, so we should treat them
// all as internalServerErrors
log.Errorf("HTTP getData() %s", err.Error())
response.Write(ctx, response.WrapError(err))
return
}
response.Write(ctx, response.NewMsgp(200, &models.GetDataRespV1{Stats: ss, Series: series}))
}
func (s *Server) indexDelete(ctx *middleware.Context, req models.IndexDelete) {
// nothing to do on query nodes.
if s.MetricIndex == nil {
return
}
defs, err := s.MetricIndex.Delete(req.OrgId, req.Query)
if err != nil {
// errors can only be caused by bad request.
response.Write(ctx, response.NewError(http.StatusBadRequest, err.Error()))
return
}
resp := models.MetricsDeleteResp{
DeletedDefs: len(defs),
}
response.Write(ctx, response.NewMsgp(200, &resp))
}
type PeerResponse struct {
peer cluster.Node
buf []byte
}
type GenericPeerResponse struct {
peer cluster.Node
resp interface{}
}
// queryAllPeers takes a request and the path to request it on, then fans it out
// across the cluster, except to the local peer or peers without data.
// Note: unlike the other queryAllPeers methods, we include peers that are not ready
// If any peer request fails, requests to other peers are aborted.
// ctx: request context
// data: request to be submitted
// name: name to be used in logging & tracing
// path: path to request on
func (s *Server) queryAllPeers(ctx context.Context, data cluster.Traceable, name, path string) (map[string]PeerResponse, map[string]error) {
peers := cluster.Manager.MemberList(false, true)
log.Debugf("HTTP %s across %d instances", name, len(peers)-1)
reqCtx, cancel := context.WithCancel(ctx)
defer cancel()
responses := make(chan struct {
data PeerResponse
err error
}, 1)
var wg sync.WaitGroup
for _, peer := range peers {
if peer.IsLocal() {
continue
}
wg.Add(1)
go func(peer cluster.Node) {
defer wg.Done()
log.Debugf("HTTP Render querying %s%s", peer.GetName(), path)
buf, err := peer.Post(reqCtx, name, path, data)
if err != nil {
cancel()
log.Errorf("HTTP Render error querying %s%s: %q", peer.GetName(), path, err.Error())
}
responses <- struct {
data PeerResponse
err error
}{PeerResponse{peer, buf}, err}
}(peer)
}
// wait for all list goroutines to end, then close our responses channel
go func() {
wg.Wait()
close(responses)
}()
result := make(map[string]PeerResponse)
errors := make(map[string]error)
for resp := range responses {
if resp.err != nil {
errors[resp.data.peer.GetName()] = resp.err
} else {
result[resp.data.peer.GetName()] = resp.data
}
}
return result, errors
}
// queryAllShards takes a request and the path to request it on, then fans it out
// across the cluster. If any peer fails, we try another replica. If enough
// peers have been heard from (based on speculation-threshold configuration), and we
// are missing the others, try to speculatively query other members of the shard group.
// ctx: request context
// data: request to be submitted
// name: name to be used in logging & tracing
// path: path to request on
func (s *Server) queryAllShards(ctx context.Context, data cluster.Traceable, name, path string) (map[string]PeerResponse, error) {
result := make(map[string]PeerResponse)
responseChan, errorChan := s.queryAllShardsGeneric(ctx, name, func(reqCtx context.Context, peer cluster.Node) (interface{}, error) {
return peer.Post(reqCtx, name, path, data)
})
for resp := range responseChan {
result[resp.peer.GetName()] = PeerResponse{
peer: resp.peer,
buf: resp.resp.([]byte),
}
}
err := <-errorChan
return result, err
}
// queryAllShardsGeneric takes a function and calls it for one peer in each shard
// across the cluster. If any peer fails, we try another replica. If enough
// peers have been heard from (based on speculation-threshold configuration), and we
// are missing the others, try to speculatively query other members of the shard group.
// ctx: request context
// fetchFunc: function to call to fetch the data from a peer
func (s *Server) queryAllShardsGeneric(ctx context.Context, name string, fetchFunc func(context.Context, cluster.Node) (interface{}, error)) (<-chan GenericPeerResponse, <-chan error) {
peerGroups, err := cluster.MembersForSpeculativeQuery()
if err != nil {
log.Errorf("HTTP peerQuery unable to get peers, %s", err.Error())
resultChan := make(chan GenericPeerResponse)
errorChan := make(chan error, 1)
errorChan <- err
return resultChan, errorChan
}
return queryPeers(ctx, peerGroups, name, fetchFunc)
}
// queryPeers takes a function and peers grouped by shard. The function
// is called it for one peer of each shard. If any peer fails, we try another replica.
// If enough peers have been heard from (based on speculation-threshold configuration),
// and we are missing the others, try to speculatively query other members of the shard group.
// ctx: request context
// peerGroups: peers grouped by shard
// fetchFunc: function to call to fetch the data from a peer
func queryPeers(ctx context.Context, peerGroups map[int32][]cluster.Node, name string, fetchFunc func(context.Context, cluster.Node) (interface{}, error)) (<-chan GenericPeerResponse, <-chan error) {
resultChan := make(chan GenericPeerResponse)
errorChan := make(chan error, 1)
go func() {
defer close(errorChan)
defer close(resultChan)
span := opentracing.SpanFromContext(ctx)
OpCtx, opSpan := tracing.NewSpan(ctx, span.Tracer(), name)
reqCtx, cancel := context.WithCancel(OpCtx)
defer cancel()
defer opSpan.Finish()
type response struct {
shardGroup int32
data GenericPeerResponse
err error
}
responses := make(chan response)
originalPeers := make(map[string]struct{}, len(peerGroups))
receivedResponses := make(map[int32]struct{}, len(peerGroups))
askPeer := func(shardGroup int32, peer cluster.Node, specCtx context.Context) {
//log.Debugf("HTTP Render querying %s%s", peer.GetName(), path)
resp, err := fetchFunc(specCtx, peer)
select {
case <-specCtx.Done():
return
case responses <- response{shardGroup, GenericPeerResponse{peer, resp}, err}:
}
// Only print if the context isn't done
if err != nil {
log.Errorf("Peer %s responded with error = %q", peer.GetName(), err.Error())
}
}
for group, peers := range peerGroups {
if len(peers) == 0 {
log.Warningf("HTTP Peer group %d has no peers", group)
delete(peerGroups, group)
continue
}
nextPeer := peers[0]
// shift nextPeer from the group
peerGroups[group] = peers[1:]
originalPeers[nextPeer.GetName()] = struct{}{}
go askPeer(group, nextPeer, reqCtx)
}
var specSpan opentracing.Span
var ticker *time.Ticker
var tickChan <-chan time.Time
if speculationThreshold != 1 {
ticker = time.NewTicker(5 * time.Millisecond)
tickChan = ticker.C
defer ticker.Stop()
}
for len(receivedResponses) < len(peerGroups) {
select {
case <-reqCtx.Done():
//request canceled
return
case resp := <-responses:
if _, ok := receivedResponses[resp.shardGroup]; ok {
// already received this response (possibly speculatively)
continue
}
if resp.err != nil {
// check if there is another peer for this shardGroup. If so try it.
if len(peerGroups[resp.shardGroup]) > 0 {
speculativeRequests.Inc()
nextPeer := peerGroups[resp.shardGroup][0]
// shift nextPeer from the group
peerGroups[resp.shardGroup] = peerGroups[resp.shardGroup][1:]
go askPeer(resp.shardGroup, nextPeer, reqCtx)
continue
}
// No more peers to try. Cancel the reqCtx, which will cancel all in-flight
// requests.
cancel()
errorChan <- resp.err
return
}
resultChan <- resp.data
receivedResponses[resp.shardGroup] = struct{}{}
delete(originalPeers, resp.data.peer.GetName())
case <-tickChan:
// Check if it's time to speculate!
percentReceived := float64(len(receivedResponses)) / float64(len(peerGroups))
if percentReceived >= speculationThreshold {
// kick off speculative queries to other members now
ticker.Stop()
speculativeAttempts.Inc()
var specCtx context.Context
specCtx, specSpan = tracing.NewSpan(OpCtx, span.Tracer(), "speculative-queries")
defer specSpan.Finish()
for shardGroup, peers := range peerGroups {
if _, ok := receivedResponses[shardGroup]; ok {
continue
}
if len(peers) == 0 {
// no more peers to try
continue
}
nextPeer := peers[0]
// shift nextPeer from the group
peerGroups[shardGroup] = peers[1:]
// send the request to the next peer for the group.
speculativeRequests.Inc()
go askPeer(shardGroup, nextPeer, specCtx)
}
}
}
}
if len(originalPeers) > 0 {
speculativeWins.Inc()
if specSpan != nil {
specSpan.LogFields(traceLog.Int32("spec-wins", int32(len(originalPeers))))
} else {
log.Warnf("Something weird: %v", originalPeers)
}
}
}()
return resultChan, errorChan
}