forked from go-graphite/carbonapi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
1398 lines (1180 loc) · 38.9 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 (
"bytes"
"encoding/json"
"expvar"
"flag"
"fmt"
"log"
"net/http"
_ "net/http/pprof"
"os"
"runtime"
"strconv"
"strings"
"time"
"unicode"
"io/ioutil"
"github.com/facebookgo/grace/gracehttp"
"github.com/facebookgo/pidfile"
"github.com/go-graphite/carbonapi/date"
"github.com/go-graphite/carbonapi/expr"
"github.com/go-graphite/carbonapi/util"
"github.com/go-graphite/carbonzipper/cache"
pb "github.com/go-graphite/carbonzipper/carbonzipperpb3"
"github.com/go-graphite/carbonzipper/intervalset"
"github.com/go-graphite/carbonzipper/mstats"
"github.com/go-graphite/carbonzipper/pathcache"
realZipper "github.com/go-graphite/carbonzipper/zipper"
"github.com/gorilla/handlers"
pickle "github.com/lomik/og-rek"
"github.com/lomik/zapwriter"
"github.com/peterbourgon/g2g"
"github.com/satori/go.uuid"
"github.com/spf13/viper"
"go.uber.org/zap"
)
const (
jsonFormat = "json"
treejsonFormat = "treejson"
pngFormat = "png"
csvFormat = "csv"
rawFormat = "raw"
svgFormat = "svg"
protobufFormat = "protobuf"
protobuf3Format = "protobuf3"
pickleFormat = "pickle"
)
// apiMetrics contains exported counters and values for graphite
var apiMetrics = struct {
Requests *expvar.Int
RenderRequests *expvar.Int
RequestCacheHits *expvar.Int
RequestCacheMisses *expvar.Int
RenderCacheOverheadNS *expvar.Int
FindRequests *expvar.Int
FindCacheHits *expvar.Int
FindCacheMisses *expvar.Int
FindCacheOverheadNS *expvar.Int
MemcacheTimeouts expvar.Func
CacheSize expvar.Func
CacheItems expvar.Func
}{
Requests: expvar.NewInt("requests"),
// TODO: request_cache -> render_cache
RenderRequests: expvar.NewInt("render_requests"),
RequestCacheHits: expvar.NewInt("request_cache_hits"),
RequestCacheMisses: expvar.NewInt("request_cache_misses"),
RenderCacheOverheadNS: expvar.NewInt("render_cache_overhead_ns"),
FindRequests: expvar.NewInt("find_requests"),
FindCacheHits: expvar.NewInt("find_cache_hits"),
FindCacheMisses: expvar.NewInt("find_cache_misses"),
FindCacheOverheadNS: expvar.NewInt("find_cache_overhead_ns"),
}
var zipperMetrics = struct {
FindRequests *expvar.Int
FindErrors *expvar.Int
SearchRequests *expvar.Int
RenderRequests *expvar.Int
RenderErrors *expvar.Int
InfoRequests *expvar.Int
InfoErrors *expvar.Int
Timeouts *expvar.Int
CacheSize expvar.Func
CacheItems expvar.Func
SearchCacheSize expvar.Func
SearchCacheItems expvar.Func
CacheMisses *expvar.Int
CacheHits *expvar.Int
SearchCacheMisses *expvar.Int
SearchCacheHits *expvar.Int
}{
FindRequests: expvar.NewInt("zipper_find_requests"),
FindErrors: expvar.NewInt("zipper_find_errors"),
SearchRequests: expvar.NewInt("zipper_search_requests"),
RenderRequests: expvar.NewInt("zipper_render_requests"),
RenderErrors: expvar.NewInt("zipper_render_errors"),
InfoRequests: expvar.NewInt("zipper_info_requests"),
InfoErrors: expvar.NewInt("zipper_info_errors"),
Timeouts: expvar.NewInt("zipper_timeouts"),
CacheHits: expvar.NewInt("zipper_cache_hits"),
CacheMisses: expvar.NewInt("zipper_cache_misses"),
SearchCacheHits: expvar.NewInt("zipper_search_cache_hits"),
SearchCacheMisses: expvar.NewInt("zipper_search_cache_misses"),
}
// BuildVersion is provided to be overridden at build time. Eg. go build -ldflags -X 'main.BuildVersion=...'
var BuildVersion = "(development build)"
// for testing
var timeNow = time.Now
func splitRemoteAddr(addr string) (string, string) {
tmp := strings.Split(addr, ":")
if len(tmp) < 1 {
return "unknown", "unknown"
}
if len(tmp) == 1 {
return tmp[0], ""
}
return tmp[0], tmp[1]
}
func writeResponse(w http.ResponseWriter, b []byte, format string, jsonp string) {
switch format {
case jsonFormat:
if jsonp != "" {
w.Header().Set("Content-Type", contentTypeJavaScript)
w.Write([]byte(jsonp))
w.Write([]byte{'('})
w.Write(b)
w.Write([]byte{')'})
} else {
w.Header().Set("Content-Type", contentTypeJSON)
w.Write(b)
}
case protobufFormat, protobuf3Format:
w.Header().Set("Content-Type", contentTypeProtobuf)
w.Write(b)
case rawFormat:
w.Header().Set("Content-Type", contentTypeRaw)
w.Write(b)
case pickleFormat:
w.Header().Set("Content-Type", contentTypePickle)
w.Write(b)
case csvFormat:
w.Header().Set("Content-Type", contentTypeCSV)
w.Write(b)
case pngFormat:
w.Header().Set("Content-Type", contentTypePNG)
w.Write(b)
case svgFormat:
w.Header().Set("Content-Type", contentTypeSVG)
w.Write(b)
}
}
const (
contentTypeJSON = "application/json"
contentTypeProtobuf = "application/x-protobuf"
contentTypeJavaScript = "text/javascript"
contentTypeRaw = "text/plain"
contentTypePickle = "application/pickle"
contentTypePNG = "image/png"
contentTypeCSV = "text/csv"
contentTypeSVG = "image/svg+xml"
)
func buildParseErrorString(target, e string, err error) string {
msg := fmt.Sprintf("%s\n\n%-20s: %s\n", http.StatusText(http.StatusBadRequest), "Target", target)
if err != nil {
msg += fmt.Sprintf("%-20s: %s\n", "Error", err.Error())
}
if e != "" {
msg += fmt.Sprintf("%-20s: %s\n%-20s: %s\n",
"Parsed so far", target[0:len(target)-len(e)],
"Could not parse", e)
}
return msg
}
func renderHandler(w http.ResponseWriter, r *http.Request) {
t0 := time.Now()
uuid := uuid.NewV4()
// TODO: Migrate to context.WithTimeout
// ctx, _ := context.WithTimeout(context.TODO(), config.ZipperTimeout)
ctx := util.SetUUID(r.Context(), uuid.String())
username, _, _ := r.BasicAuth()
logger := zapwriter.Logger("render").With(
zap.String("carbonapi_uuid", uuid.String()),
zap.String("username", username),
)
srcIP, srcPort := splitRemoteAddr(r.RemoteAddr)
accessLogger := zapwriter.Logger("access").With(
zap.String("handler", "render"),
zap.String("carbonapi_uuid", uuid.String()),
zap.String("username", username),
zap.String("url", r.URL.RequestURI()),
zap.String("peer_ip", srcIP),
zap.String("peer_port", srcPort),
zap.String("host", r.Host),
zap.String("referer", r.Referer()),
)
size := 0
zipperRequests := 0
apiMetrics.Requests.Add(1)
err := r.ParseForm()
if err != nil {
http.Error(w, http.StatusText(http.StatusBadRequest)+": "+err.Error(), http.StatusBadRequest)
accessLogger.Error("request failed",
zap.Duration("runtime", time.Since(t0)),
zap.Int("http_code", http.StatusBadRequest),
)
return
}
targets := r.Form["target"]
from := r.FormValue("from")
until := r.FormValue("until")
format := r.FormValue("format")
useCache := !expr.TruthyBool(r.FormValue("noCache"))
var jsonp string
if format == jsonFormat {
// TODO(dgryski): check jsonp only has valid characters
jsonp = r.FormValue("jsonp")
}
if format == "" && (expr.TruthyBool(r.FormValue("rawData")) || expr.TruthyBool(r.FormValue("rawdata"))) {
format = rawFormat
}
if format == "" {
format = pngFormat
}
cacheTimeout := config.Cache.DefaultTimeoutSec
if tstr := r.FormValue("cacheTimeout"); tstr != "" {
t, err := strconv.Atoi(tstr)
if err != nil {
logger.Error("failed to parse cacheTimeout",
zap.String("cache_string", tstr),
zap.Error(err),
)
} else {
cacheTimeout = int32(t)
}
}
// make sure the cache key doesn't say noCache, because it will never hit
r.Form.Del("noCache")
// jsonp callback names are frequently autogenerated and hurt our cache
r.Form.Del("jsonp")
// Strip some cache-busters. If you don't want to cache, use noCache=1
r.Form.Del("_salt")
r.Form.Del("_ts")
r.Form.Del("_t") // Used by jquery.graphite.js
cacheKey := r.Form.Encode()
// normalize from and until values
qtz := r.FormValue("tz")
from32 := date.DateParamToEpoch(from, qtz, timeNow().Add(-24*time.Hour).Unix(), config.defaultTimeZone)
until32 := date.DateParamToEpoch(until, qtz, timeNow().Unix(), config.defaultTimeZone)
accessLogger = accessLogger.With(
zap.String("format", format),
zap.Bool("use_cache", useCache),
zap.Strings("targets", targets),
zap.String("from_raw", from),
zap.String("until_raw", until),
zap.Int32("from", from32),
zap.Int32("until", until32),
zap.String("tz", qtz),
zap.Int32("cache_timeout", cacheTimeout),
)
if useCache {
tc := time.Now()
response, err := config.queryCache.Get(cacheKey)
td := time.Since(tc).Nanoseconds()
apiMetrics.RenderCacheOverheadNS.Add(td)
if err == nil {
apiMetrics.RequestCacheHits.Add(1)
writeResponse(w, response, format, jsonp)
accessLogger.Info("request served",
zap.Bool("from_cache", true),
zap.Duration("runtime", time.Since(t0)),
zap.Int("http_code", http.StatusOK),
zap.Int("carbonzipper_response_size_bytes", 0),
zap.Int("carbonapi_response_size_bytes", len(response)),
)
return
}
apiMetrics.RequestCacheMisses.Add(1)
}
if from32 == until32 {
http.Error(w, "Invalid empty time range", http.StatusBadRequest)
accessLogger.Error("request failed",
zap.String("reason", "Invalid empty time range"),
zap.Duration("runtime", time.Since(t0)),
zap.Int("http_code", http.StatusBadRequest),
)
return
}
var results []*expr.MetricData
errors := make(map[string]string)
metricMap := make(map[expr.MetricRequest][]*expr.MetricData)
fatalError := false
var metrics []string
var targetIdx = 0
for targetIdx < len(targets) {
var target = targets[targetIdx]
targetIdx++
exp, e, err := expr.ParseExpr(target)
if err != nil || e != "" {
msg := buildParseErrorString(target, e, err)
http.Error(w, msg, http.StatusBadRequest)
accessLogger.Error("request failed",
zap.String("reason", msg),
zap.Duration("runtime", time.Since(t0)),
zap.Int("http_code", http.StatusBadRequest),
)
return
}
for _, m := range exp.Metrics() {
metrics = append(metrics, m.Metric)
mfetch := m
mfetch.From += from32
mfetch.Until += until32
if _, ok := metricMap[mfetch]; ok {
// already fetched this metric for this request
continue
}
var glob pb.GlobResponse
var haveCacheData bool
if useCache {
tc := time.Now()
response, err := config.findCache.Get(m.Metric)
td := time.Since(tc).Nanoseconds()
apiMetrics.FindCacheOverheadNS.Add(td)
if err == nil {
err := glob.Unmarshal(response)
haveCacheData = err == nil
}
}
if haveCacheData {
apiMetrics.FindCacheHits.Add(1)
} else {
apiMetrics.FindCacheMisses.Add(1)
var err error
apiMetrics.FindRequests.Add(1)
zipperRequests++
glob, err = config.zipper.Find(ctx, m.Metric)
if err != nil {
logger.Error("find error",
zap.String("metric", m.Metric),
zap.Error(err),
)
continue
}
b, err := glob.Marshal()
if err == nil {
tc := time.Now()
config.findCache.Set(m.Metric, b, 5*60)
td := time.Since(tc).Nanoseconds()
apiMetrics.FindCacheOverheadNS.Add(td)
}
}
var sendGlobs = config.SendGlobsAsIs && len(glob.Matches) < config.MaxBatchSize
accessLogger = accessLogger.With(zap.Bool("send_globs", sendGlobs))
if sendGlobs {
// Request is "small enough" -- send the entire thing as a render request
apiMetrics.RenderRequests.Add(1)
config.limiter.enter()
zipperRequests++
r, err := config.zipper.Render(ctx, m.Metric, mfetch.From, mfetch.Until)
if err != nil {
errors[target] = err.Error()
config.limiter.leave()
continue
}
config.limiter.leave()
metricMap[mfetch] = r
for i := range r {
size += r[i].Size()
}
} else {
// Request is "too large"; send render requests individually
// TODO(dgryski): group the render requests into batches
rch := make(chan *expr.MetricData, len(glob.Matches))
var leaves int
for _, m := range glob.Matches {
if !m.IsLeaf {
continue
}
leaves++
apiMetrics.RenderRequests.Add(1)
config.limiter.enter()
zipperRequests++
go func(path string, from, until int32) {
if r, err := config.zipper.Render(ctx, path, from, until); err == nil {
rch <- r[0]
} else {
logger.Error("render error",
zap.String("target", path),
zap.Error(err),
)
rch <- nil
}
config.limiter.leave()
}(m.Path, mfetch.From, mfetch.Until)
}
for i := 0; i < leaves; i++ {
if r := <-rch; r != nil {
size += r.Size()
metricMap[mfetch] = append(metricMap[mfetch], r)
}
}
}
expr.SortMetrics(metricMap[mfetch], mfetch)
}
var rewritten bool
var newTargets []string
rewritten, newTargets, err = expr.RewriteExpr(exp, from32, until32, metricMap)
if err != nil && err != expr.ErrSeriesDoesNotExist {
errors[target] = err.Error()
fatalError = true
return
} else if rewritten {
targets = append(targets, newTargets...)
} else {
func() {
defer func() {
if r := recover(); r != nil {
logger.Error("panic during eval:",
zap.String("cache_key", cacheKey),
zap.Stack("stack"),
)
}
}()
exprs, err := expr.EvalExpr(exp, from32, until32, metricMap)
if err != nil && err != expr.ErrSeriesDoesNotExist {
errors[target] = err.Error()
fatalError = true
return
}
results = append(results, exprs...)
}()
}
}
accessLogger = accessLogger.With(zap.Strings("metrics", metrics))
if len(errors) > 0 && fatalError {
httpErrors := make([]string, 0, len(errors))
httpErrors = append(httpErrors, "Following errors have occured:")
for _, e := range errors {
httpErrors = append(httpErrors, e)
}
http.Error(w, strings.Join(httpErrors, "\n"), http.StatusBadRequest)
accessLogger.Error("request failed",
zap.String("reason", "encoundered multiple errors"),
zap.Any("errors", errors),
zap.Duration("runtime", time.Since(t0)),
zap.Int("http_code", http.StatusBadRequest),
)
return
}
var body []byte
switch format {
case jsonFormat:
if maxDataPoints, _ := strconv.Atoi(r.FormValue("maxDataPoints")); maxDataPoints != 0 {
expr.ConsolidateJSON(maxDataPoints, results)
}
body = expr.MarshalJSON(results)
case protobufFormat, protobuf3Format:
body, err = expr.MarshalProtobuf(results)
if err != nil {
logger.Info("request failed",
zap.Int("http_code", http.StatusInternalServerError),
zap.String("reason", err.Error()),
zap.Duration("runtime", time.Since(t0)),
)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
case rawFormat:
body = expr.MarshalRaw(results)
case csvFormat:
body = expr.MarshalCSV(results)
case pickleFormat:
body = expr.MarshalPickle(results)
case pngFormat:
body = expr.MarshalPNG(r, results)
case svgFormat:
body = expr.MarshalSVG(r, results)
}
writeResponse(w, body, format, jsonp)
if len(results) != 0 {
tc := time.Now()
config.queryCache.Set(cacheKey, body, cacheTimeout)
td := time.Since(tc).Nanoseconds()
apiMetrics.RenderCacheOverheadNS.Add(td)
}
gotErrors := false
if len(errors) > 0 {
gotErrors = true
}
accessLogger.Info("request served",
zap.String("uri", r.RequestURI),
zap.Duration("runtime", time.Since(t0)),
zap.Int("http_code", http.StatusOK),
zap.Bool("have_non_fatal_errors", gotErrors),
zap.Any("errors", errors),
zap.Int("zipper_requests", zipperRequests),
zap.Int("zipper_response_size_bytes", size),
zap.Int("carbonapi_response_size_bytes", len(body)),
)
}
func findHandler(w http.ResponseWriter, r *http.Request) {
t0 := time.Now()
uuid := uuid.NewV4()
// TODO: Migrate to context.WithTimeout
// ctx, _ := context.WithTimeout(context.TODO(), config.ZipperTimeout)
ctx := util.SetUUID(r.Context(), uuid.String())
username, _, _ := r.BasicAuth()
format := r.FormValue("format")
jsonp := r.FormValue("jsonp")
query := r.FormValue("query")
srcIP, srcPort := splitRemoteAddr(r.RemoteAddr)
accessLogger := zapwriter.Logger("access").With(
zap.String("handler", "find"),
zap.String("carbonapi_uuid", uuid.String()),
zap.String("username", username),
zap.String("url", r.URL.RequestURI()),
zap.String("peer_ip", srcIP),
zap.String("peer_port", srcPort),
zap.String("host", r.Host),
zap.String("referer", r.Referer()),
)
if query == "" {
http.Error(w, "missing parameter `query`", http.StatusBadRequest)
accessLogger.Info("request failed",
zap.Int("http_code", http.StatusBadRequest),
zap.String("reason", "missing parameter `query`"),
zap.Duration("runtime", time.Since(t0)),
)
return
}
if format == "" {
format = treejsonFormat
}
globs, err := config.zipper.Find(ctx, query)
if err != nil {
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
accessLogger.Info("request failed",
zap.String("uri", r.RequestURI),
zap.Int("http_code", http.StatusInternalServerError),
zap.String("reason", err.Error()),
zap.Duration("runtime", time.Since(t0)),
)
return
}
var b []byte
switch format {
case treejsonFormat, jsonFormat:
b, err = findTreejson(globs)
format = jsonFormat
case "completer":
b, err = findCompleter(globs)
format = jsonFormat
case rawFormat:
b, err = findList(globs)
format = rawFormat
case protobufFormat, protobuf3Format:
b, err = globs.Marshal()
format = protobufFormat
case "", pickleFormat:
var result []map[string]interface{}
now := int32(time.Now().Unix() + 60)
for _, metric := range globs.Matches {
// Tell graphite-web that we have everything
var mm map[string]interface{}
if config.GraphiteWeb09Compatibility {
// graphite-web 0.9.x
mm = map[string]interface{}{
// graphite-web 0.9.x
"metric_path": metric.Path,
"isLeaf": metric.IsLeaf,
}
} else {
// graphite-web 1.0
interval := &intervalset.IntervalSet{Start: 0, End: now}
mm = map[string]interface{}{
"is_leaf": metric.IsLeaf,
"path": metric.Path,
"intervals": interval,
}
}
result = append(result, mm)
}
p := bytes.NewBuffer(b)
pEnc := pickle.NewEncoder(p)
err = pEnc.Encode(result)
}
if err != nil {
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
accessLogger.Info("request failed",
zap.String("uri", r.RequestURI),
zap.Int("http_code", http.StatusInternalServerError),
zap.String("reason", err.Error()),
zap.Duration("runtime", time.Since(t0)),
)
return
}
writeResponse(w, b, format, jsonp)
accessLogger.Info("request served",
zap.String("uri", r.RequestURI),
zap.Int("http_code", http.StatusOK),
zap.Duration("runtime", time.Since(t0)),
)
}
type completer struct {
Path string `json:"path"`
Name string `json:"name"`
IsLeaf string `json:"is_leaf"`
}
func findCompleter(globs pb.GlobResponse) ([]byte, error) {
var b bytes.Buffer
var complete = make([]completer, 0)
for _, g := range globs.Matches {
c := completer{
Path: g.Path,
}
if g.IsLeaf {
c.IsLeaf = "1"
} else {
c.IsLeaf = "0"
}
i := strings.LastIndex(c.Path, ".")
if i != -1 {
c.Name = c.Path[i+1:]
} else {
c.Name = g.Path
}
complete = append(complete, c)
}
err := json.NewEncoder(&b).Encode(struct {
Metrics []completer `json:"metrics"`
}{
Metrics: complete},
)
return b.Bytes(), err
}
func findList(globs pb.GlobResponse) ([]byte, error) {
var b bytes.Buffer
for _, g := range globs.Matches {
var dot string
// make sure non-leaves end in one dot
if !g.IsLeaf && !strings.HasSuffix(g.Path, ".") {
dot = "."
}
fmt.Fprintln(&b, g.Path+dot)
}
return b.Bytes(), nil
}
type treejson struct {
AllowChildren int `json:"allowChildren"`
Expandable int `json:"expandable"`
Leaf int `json:"leaf"`
ID string `json:"id"`
Text string `json:"text"`
Context map[string]int `json:"context"` // unused
}
var treejsonContext = make(map[string]int)
func findTreejson(globs pb.GlobResponse) ([]byte, error) {
var b bytes.Buffer
var tree = make([]treejson, 0)
seen := make(map[string]struct{})
basepath := globs.Name
if i := strings.LastIndex(basepath, "."); i != -1 {
basepath = basepath[:i+1]
}
for _, g := range globs.Matches {
name := g.Path
if i := strings.LastIndex(name, "."); i != -1 {
name = name[i+1:]
}
if _, ok := seen[name]; ok {
continue
}
seen[name] = struct{}{}
t := treejson{
ID: basepath + name,
Context: treejsonContext,
Text: name,
}
if g.IsLeaf {
t.Leaf = 1
} else {
t.AllowChildren = 1
t.Expandable = 1
}
tree = append(tree, t)
}
err := json.NewEncoder(&b).Encode(tree)
return b.Bytes(), err
}
func infoHandler(w http.ResponseWriter, r *http.Request) {
t0 := time.Now()
uuid := uuid.NewV4()
// TODO: Migrate to context.WithTimeout
// ctx, _ := context.WithTimeout(context.TODO(), config.ZipperTimeout)
ctx := util.SetUUID(r.Context(), uuid.String())
username, _, _ := r.BasicAuth()
srcIP, srcPort := splitRemoteAddr(r.RemoteAddr)
format := r.FormValue("format")
accessLogger := zapwriter.Logger("access").With(
zap.String("username", username),
zap.String("handler", "info"),
zap.String("carbonapi_uuid", uuid.String()),
zap.String("peer_ip", srcIP),
zap.String("peer_port", srcPort),
zap.String("host", r.Host),
zap.String("format", format),
zap.String("referer", r.Referer()),
)
var data map[string]pb.InfoResponse
var err error
query := r.FormValue("target")
if query == "" {
accessLogger.Info("request failed",
zap.String("uri", r.RequestURI),
zap.Duration("runtime", time.Since(t0)),
zap.Int("http_code", http.StatusBadRequest),
zap.String("reason", "no target specified"),
)
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
return
}
if data, err = config.zipper.Info(ctx, query); err != nil {
accessLogger.Info("request failed",
zap.String("uri", r.RequestURI),
zap.Duration("runtime", time.Since(t0)),
zap.String("reason", err.Error()),
zap.Int("http_code", http.StatusInternalServerError),
)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
var b []byte
switch format {
case jsonFormat:
b, err = json.Marshal(data)
case protobufFormat, protobuf3Format:
err = fmt.Errorf("Not implemented yet")
}
if err != nil {
accessLogger.Info("request failed",
zap.String("uri", r.RequestURI),
zap.Duration("runtime", time.Since(t0)),
zap.String("reason", err.Error()),
zap.Int("http_code", http.StatusInternalServerError),
)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
w.Write(b)
accessLogger.Info("request served",
zap.String("uri", r.RequestURI),
zap.Duration("runtime", time.Since(t0)),
zap.Int("http_code", http.StatusOK),
)
}
func lbcheckHandler(w http.ResponseWriter, r *http.Request) {
t0 := time.Now()
accessLogger := zapwriter.Logger("access")
w.Write([]byte("Ok\n"))
srcIP, srcPort := splitRemoteAddr(r.RemoteAddr)
accessLogger.Info("request served",
zap.String("handler", "lbcheck"),
zap.String("uri", r.RequestURI),
zap.String("peer_ip", srcIP),
zap.String("peer_port", srcPort),
zap.String("host", r.Host),
zap.Duration("runtime", time.Since(t0)),
zap.Int("http_code", http.StatusOK),
zap.String("referer", r.Referer()),
)
}
func versionHandler(w http.ResponseWriter, r *http.Request) {
t0 := time.Now()
accessLogger := zapwriter.Logger("access")
if config.GraphiteWeb09Compatibility {
w.Write([]byte("0.9.15\n"))
} else {
w.Write([]byte("1.0.0\n"))
}
srcIP, srcPort := splitRemoteAddr(r.RemoteAddr)
accessLogger.Info("request served",
zap.String("handler", "version"),
zap.String("uri", r.RequestURI),
zap.String("peer_ip", srcIP),
zap.String("peer_port", srcPort),
zap.String("host", r.Host),
zap.Duration("runtime", time.Since(t0)),
zap.Int("http_code", http.StatusOK),
zap.String("referer", r.Referer()),
)
}
var usageMsg = []byte(`
supported requests:
/render/?target=
/metrics/find/?query=
/info/?target=
`)
func usageHandler(w http.ResponseWriter, r *http.Request) {
w.Write(usageMsg)
}
var defaultLoggerConfig = zapwriter.Config{
Logger: "",
File: "stdout",
Level: "info",
Encoding: "console",
EncodingTime: "iso8601",
EncodingDuration: "seconds",
}
type cacheConfig struct {
Type string `yaml:"type"`
Size int `yaml:"size_mb"`
MemcachedServers []string `yaml:"memcachedServers"`
DefaultTimeoutSec int32 `yaml:"defaultTimeoutSec"`
}
type graphiteConfig struct {
Pattern string
Host string
Interval time.Duration
Prefix string
}
var config = struct {
Logger []zapwriter.Config `yaml:"logger"`
Listen string `yaml:"listen"`
Concurency int `yaml:"concurency"`
Cache cacheConfig `yaml:"cache"`
Cpus int `yaml:"cpus"`
TimezoneString string `yaml:"tz"`
UnicodeRangeTables []string `yaml:"unicodeRangeTables"`
Graphite graphiteConfig `yaml:"graphite"`
IdleConnections int `yaml:"idleConnections"`
PidFile string `yaml:"pidFile"`
SendGlobsAsIs bool `yaml:"sendGlobsAsIs"`
MaxBatchSize int `yaml:"maxBatchSize"`
Zipper string `yaml:"zipper"`
Upstreams realZipper.Config `yaml:"upstreams"`
ExpireDelaySec int32 `yaml:"expireDelaySec"`
GraphiteWeb09Compatibility bool `yaml:"graphite09compat"`
queryCache cache.BytesCache
findCache cache.BytesCache
defaultTimeZone *time.Location
// Zipper is API entry to carbonzipper
zipper *zipper
// Limiter limits concurrent zipper requests
limiter limiter
}{
Listen: "[::]:8081",
Concurency: 20,
SendGlobsAsIs: false,
MaxBatchSize: 100,
Cache: cacheConfig{
Type: "mem",
DefaultTimeoutSec: 60,
},
TimezoneString: "",
Graphite: graphiteConfig{
Pattern: "{prefix}.{fqdn}",