/
graph_options.go
255 lines (232 loc) · 6.6 KB
/
graph_options.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
package main
import (
"encoding/json"
"errors"
"fmt"
"github.com/bitly/go-simplejson"
"github.com/bitly/nsq/util"
"html/template"
"log"
"net"
"net/http"
"net/url"
"time"
)
type GraphTarget interface {
Target(key string) (string, string)
}
type Topic struct {
TopicName string
}
type Topics []*Topic
func TopicsFromStrings(s []string) Topics {
t := make(Topics, 0, len(s))
for _, ss := range s {
tt := &Topic{ss}
t = append(t, tt)
}
return t
}
func (t *Topic) Target(key string) (string, string) {
color := "blue"
if key == "depth" || key == "deferred_count" {
color = "red"
}
target := fmt.Sprintf("nsq.*.topic.%s.%s", t.TopicName, key)
return target, color
}
type GraphInterval struct {
Selected bool
Timeframe string // the UI string
GraphFrom string // ?from=.
GraphUntil string // ?until=.
Duration time.Duration // for sort order
}
type GraphIntervals []*GraphInterval
func (g *GraphInterval) UrlOption() template.URL {
return template.URL(fmt.Sprintf("t=%s", g.Timeframe))
}
func DefaultGraphTimeframes(selected string) GraphIntervals {
var d GraphIntervals
for _, t := range []string{"1h", "2h", "12h", "24h", "48h", "168h", "off"} {
g, err := GraphIntervalForTimeframe(t, t == selected)
if err != nil {
log.Fatalf("error parsing duration %s", err.Error())
}
d = append(d, g)
}
return d
}
func GraphIntervalForTimeframe(t string, selected bool) (*GraphInterval, error) {
if t == "off" {
return &GraphInterval{
Selected: selected,
Timeframe: t,
GraphFrom: "",
GraphUntil: "",
Duration: 0,
}, nil
}
duration, err := time.ParseDuration(t)
if err != nil {
return nil, err
}
start, end := startEndForTimeframe(duration)
return &GraphInterval{
Selected: selected,
Timeframe: t,
GraphFrom: start,
GraphUntil: end,
Duration: duration,
}, nil
}
type GraphOptions struct {
Configured bool
Enabled bool
GraphiteUrl string
UseStatsdPrefix bool
TimeframeString template.URL
AllGraphIntervals []*GraphInterval
GraphInterval *GraphInterval
}
func NewGraphOptions(rw http.ResponseWriter, req *http.Request, r *util.ReqParams) *GraphOptions {
selectedTimeString, err := r.Get("t")
if err != nil && selectedTimeString == "" {
// get from cookie
cookie, err := req.Cookie("t")
if err != nil {
selectedTimeString = "2h"
} else {
selectedTimeString = cookie.Value
}
} else {
// set cookie
host, _, _ := net.SplitHostPort(req.Host)
cookie := &http.Cookie{
Name: "t",
Value: selectedTimeString,
Path: "/",
Domain: host,
Expires: time.Now().Add(time.Duration(720) * time.Hour),
HttpOnly: true,
}
http.SetCookie(rw, cookie)
}
g, err := GraphIntervalForTimeframe(selectedTimeString, true)
if err != nil {
g, _ = GraphIntervalForTimeframe("2h", true)
}
base := *graphiteUrl
configured := base != ""
enabled := configured
if *proxyGraphite {
base = ""
}
if g.Timeframe == "off" {
enabled = false
}
o := &GraphOptions{
Configured: configured,
Enabled: enabled,
UseStatsdPrefix: *useStatsdPrefixes,
GraphiteUrl: base,
AllGraphIntervals: DefaultGraphTimeframes(selectedTimeString),
GraphInterval: g,
}
return o
}
func (g *GraphOptions) Prefix(metricType string) string {
if g.UseStatsdPrefix && metricType == "counter" {
return "stats_counts."
} else if g.UseStatsdPrefix && metricType == "gauge" {
return "stats.gauges."
}
return ""
}
func (g *GraphOptions) Sparkline(gr GraphTarget, key string) template.URL {
target, color := gr.Target(key)
target = g.Prefix(metricType(key)) + target
params := url.Values{}
params.Set("height", "20")
params.Set("width", "120")
params.Set("hideGrid", "true")
params.Set("hideLegend", "true")
params.Set("hideAxes", "true")
params.Set("bgcolor", "ff000000") // transparent
params.Set("fgcolor", "black")
params.Set("margin", "0")
params.Set("colorList", color)
params.Set("yMin", "0")
interval := fmt.Sprintf("%dsec", *statsdInterval/time.Second)
params.Set("target", fmt.Sprintf(`summarize(sumSeries(%s),"%s","avg")`, target, interval))
params.Set("from", g.GraphInterval.GraphFrom)
params.Set("until", g.GraphInterval.GraphUntil)
return template.URL(fmt.Sprintf("%s/render?%s", g.GraphiteUrl, params.Encode()))
}
func (g *GraphOptions) LargeGraph(gr GraphTarget, key string) template.URL {
target, color := gr.Target(key)
target = g.Prefix(metricType(key)) + target
params := url.Values{}
params.Set("height", "450")
params.Set("width", "800")
params.Set("bgcolor", "ff000000") // transparent
params.Set("fgcolor", "999999")
params.Set("colorList", color)
params.Set("yMin", "0")
interval := fmt.Sprintf("%dsec", *statsdInterval/time.Second)
target = fmt.Sprintf(`summarize(sumSeries(%s),"%s","avg")`, target, interval)
if metricType(key) != "gauge" {
scale := fmt.Sprintf("%.04f", 1/float64(*statsdInterval/time.Second))
target = fmt.Sprintf(`scale(%s,%s)`, target, scale)
}
params.Set("target", target)
params.Set("from", g.GraphInterval.GraphFrom)
params.Set("until", g.GraphInterval.GraphUntil)
return template.URL(fmt.Sprintf("%s/render?%s", g.GraphiteUrl, params.Encode()))
}
func (g *GraphOptions) Rate(gr GraphTarget) string {
target, _ := gr.Target("message_count")
return g.Prefix(metricType("message_count")) + target
}
func metricType(key string) string {
metricType := "counter"
switch key {
case "backend_depth", "depth", "clients", "in_flight_count", "deferred_count":
metricType = "gauge"
}
return metricType
}
func rateQuery(target string) string {
params := url.Values{}
fromInterval := fmt.Sprintf("-%dsec", *statsdInterval*2/time.Second)
params.Set("from", fromInterval)
untilInterval := fmt.Sprintf("-%dsec", *statsdInterval/time.Second)
params.Set("until", untilInterval)
params.Set("format", "json")
params.Set("target", fmt.Sprintf("sumSeries(%s)", target))
return fmt.Sprintf("/render?%s", params.Encode())
}
func parseRateResponse(body []byte) ([]byte, error) {
js, err := simplejson.NewJson([]byte(body))
if err != nil {
log.Printf("ERROR: failed to parse metadata - %s", err.Error())
return nil, err
}
js, ok := js.GetIndex(0).CheckGet("datapoints")
if !ok {
return nil, errors.New("datapoints not found")
}
var rateStr string
rate, _ := js.GetIndex(0).GetIndex(0).Float64()
if rate < 0 {
rateStr = "N/A"
} else {
rateDivisor := *statsdInterval / time.Second
rateStr = fmt.Sprintf("%.2f", rate/float64(rateDivisor))
}
return json.Marshal(map[string]string{"datapoint": rateStr})
}
func startEndForTimeframe(t time.Duration) (string, string) {
start := fmt.Sprintf("-%dmin", int(t.Minutes()))
return start, "-1min"
}