-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
270 lines (228 loc) · 6.62 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
package main
import (
"crypto/tls"
"fmt"
"os"
"net/http"
"strings"
"html/template"
"github.com/kicombs/componentMetrics/Godeps/_workspace/src/github.com/cloudfoundry/noaa"
"github.com/kicombs/componentMetrics/Godeps/_workspace/src/github.com/cloudfoundry/sonde-go/events"
)
// FUTURE if time, removing metrics after TTL?
var dopplerAddress = os.Getenv("DOPPLER_ADDR") // should look like ws://host:port
var authToken = os.Getenv("CF_ACCESS_TOKEN") // use $(cf oauth-token | grep bearer)
const firehoseSubscriptionId = "firehose-a"
type metricCategory interface {
GetCategory() string
}
// IMPORTANT!!!!
// In order for Json to marshal the members must be public (aka capitalized)
type metricCategoryOnly struct {
Category string
}
func (m metricCategoryOnly) GetCategory() string {
return m.Category
}
// IMPORTANT!!!!
// In order for Json to marshal the members must be public (aka capitalized)
type metricCategoryWithSubCategory struct {
Category string
SubCategory []string
}
func (m metricCategoryWithSubCategory) GetCategory() string {
return m.Category
}
func main() {
var messages map[string][]metricCategory // [origin]{metricCategory To []names}]
messages = make(map[string][]metricCategory)
connection := noaa.NewConsumer(dopplerAddress, &tls.Config{InsecureSkipVerify: true}, nil)
connection.SetDebugPrinter(ConsoleDebugPrinter{})
fmt.Println("===== Streaming Firehose (will only succeed if you have admin credentials)")
msgChan := make(chan *events.Envelope)
go func() {
defer close(msgChan)
errorChan := make(chan error)
go connection.Firehose(firehoseSubscriptionId, authToken, msgChan, errorChan)
for err := range errorChan {
fmt.Fprintf(os.Stderr, "%v\n", err.Error())
}
}()
go startHttp(messages)
for msg := range msgChan {
vm := msg.GetValueMetric()
if vm == nil {
continue
}
origin := msg.GetOrigin()
category, subCategory := parseMetric(*vm.Name)
index := indexOf(messages[origin], category)
if index >= 0 {
metricCategoryGroup := messages[origin][index]
switch f := metricCategoryGroup.(type) {
case *metricCategoryWithSubCategory:
if len(subCategory) > 0 {
if contains(f.SubCategory, subCategory) == false {
f.SubCategory = append(f.SubCategory, subCategory)
}
}
default:
}
} else {
if len(subCategory) > 0 {
messages[origin] = append(messages[origin], &metricCategoryWithSubCategory{
Category: category,
SubCategory: []string{subCategory},
})
} else {
messages[origin] = append(messages[origin], &metricCategoryOnly{
Category: category,
})
}
}
}
}
func parseMetric(metric string) (category, subCategory string) {
//TODO logSenderTotalMessagesRead.{appId} ignore
separatedMetric := strings.SplitN(metric, ".", 2)
if len(separatedMetric) < 2 {
return metric, ""
}
return separatedMetric[0], separatedMetric[1]
}
func indexOf(metricsCollected []metricCategory, key string) int {
for index, entry := range metricsCollected {
metricCategoryVar := entry
if metricCategoryVar.GetCategory() == key {
return index
}
}
return -1
}
func contains(slice []string, value string) bool {
for _, entry := range slice {
if entry == value {
return true
}
}
return false
}
type ConsoleDebugPrinter struct{}
func (c ConsoleDebugPrinter) Print(title, dump string) {
println(title)
println(dump)
}
func startHttp(messages map[string][]metricCategory) {
http.Handle("/messages", NewMetricsListingHandler(messages))
port := os.Getenv("PORT")
err := http.ListenAndServe(fmt.Sprintf(":%v", port), nil)
if err != nil {
println("Proxy Server Error", err)
panic("We could not start the HTTP listener")
}
}
func NewMetricsListingHandler(instanceToMetrics map[string][]metricCategory) http.Handler {
return metricsListingHandler{instancesToMetrics: instanceToMetrics}
}
type metricsListingHandler struct {
instancesToMetrics map[string][]metricCategory
}
func (m metricsListingHandler) ServeHTTP(res http.ResponseWriter, req *http.Request) {
res.Header().Set("Content-Type", "html")
m.render(res)
}
func (m metricsListingHandler) render(res http.ResponseWriter) {
printCategory := func(typeInterface metricCategory) template.HTML {
td := ""
switch f := typeInterface.(type) {
case *metricCategoryWithSubCategory:
td = fmt.Sprintf("<td>%s</td>", f.Category)
break
case *metricCategoryOnly:
td = fmt.Sprintf("<td style=\"border-right:none\">%s</td>", f.Category)
break
default:
}
return template.HTML(td)
}
printSubCategory := func(typeInterface metricCategory) template.HTML {
td := ""
switch f := typeInterface.(type) {
case *metricCategoryWithSubCategory:
t := "<td><table border=0>"
for _, subCat := range f.SubCategory {
base, sub := parseMetric(subCat)
t += fmt.Sprintf("<tr><td>%s", base)
for len(sub) > 0 {
t += fmt.Sprintf("<table border =0><tr><td>%s</td></tr>", sub)
base, sub = parseMetric(subCat)
}
t += fmt.Sprintf("</td></tr>")
}
td = t + "</table></td>"
break
case *metricCategoryOnly:
td = "<td style=\"border-left:none\"></td>"
break
default:
}
return template.HTML(td)
}
buildOriginRowSpan := func(indexOfSlice int, origin string, categories []metricCategory) template.HTML {
td := ""
if indexOfSlice == 0 {
if len(categories) > 1 {
td = fmt.Sprintf("<td rowspan=%d>%s</td>", len(categories), origin)
} else {
td = fmt.Sprintf("<td>%s</td>", origin)
}
}
return template.HTML(td)
}
totalMetrics := func(metrics map[string][]metricCategory) int {
total := 0
for _, origin := range metrics {
for _, categoryGroup := range origin {
switch f := categoryGroup.(type) {
case *metricCategoryWithSubCategory:
total += len(f.SubCategory)
break
case *metricCategoryOnly:
total++
break
default:
}
}
}
return total
}
htmlTemplate := `<!DOCTYPE html>
<html>
<head></head>
<body>
<h1>Loggregator Metrics</h1>
<p>Total Number of Metrics: {{ totalMetrics . }}</p>
<table border=1><tr><th>Origin</th><th>Category</th><th>Sub Category</th></tr>
{{range $index, $item := .}}
{{range $counter, $element := $item}}
<tr>
{{ buildOriginRowSpan $counter $index $item }}
{{printCategory $element}}
{{printSubCategory $element}}</tr>
{{end}}
{{end}}</table></body>
</html>`
t := template.New("t").Funcs(template.FuncMap{"printCategory": printCategory,
"printSubCategory": printSubCategory,
"buildOriginRowSpan": buildOriginRowSpan,
"totalMetrics": totalMetrics})
t, err := t.Parse(htmlTemplate)
if err != nil {
fmt.Println("ERROR: could not parse template: ", err.Error())
return
}
err = t.Execute(res, m.instancesToMetrics)
if err != nil {
panic(err)
}
}