-
Notifications
You must be signed in to change notification settings - Fork 5
/
control.go
474 lines (432 loc) · 10.9 KB
/
control.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
// Copyright 2014 The Sporting Exchange Limited. All rights reserved.
// Use of this source code is governed by a free license that can be
// found in the LICENSE file.
// Package control handles config requests from collect-jmx.
//
// The lookup requests use the simple key host, or the composite (host,
// process).
//
// The host-specific settings are always served. These setting may be
// extended using the process-specific settings, if found.
package control
import (
"encoding/json"
"encoding/xml"
"fmt"
"log"
"net/http"
"net/url"
"reflect"
"strings"
"opentsp.org/cmd/tsp-controller/config"
"opentsp.org/cmd/tsp-controller/control"
)
const (
defaultInterval = 10000 // default mbean poll interval
)
func init() {
control.Register(Update, Handle)
}
// Update decodes the collect-jmx parts of the config.
func Update(config *config.Config) error {
if err := updateHost(config); err != nil {
return err
}
if err := updateGlobal(config); err != nil {
return err
}
return nil
}
// updateGlobal extends the provided common config with global QueryGroup elements.
func updateGlobal(config_ *config.Config) error {
ns := make(config.Namespace)
for _, elem := range config_.Extra {
if elem.Value != nil {
continue
}
g := new(QueryGroup)
if err := xml.Unmarshal(elem.Raw, g); err != nil {
continue
}
if err := g.validate(config_); err != nil {
return err
}
if err := ns.Add(g.ID); err != nil {
return fmt.Errorf("querygroup %s: %v", g.ID, err)
}
elem.Value = g
}
return nil
}
// updateHost extends the provided common config with host-level Process elements.
func updateHost(config_ *config.Config) error {
global := make(config.Namespace)
before := make(config.Namespace)
for id := range config_.Hosts.NS {
before[id] = true
}
// Decode <process> elements.
err := config_.UpdateHost(func(hostID string, elem *config.Element) error {
p := new(Process)
if err := xml.Unmarshal(elem.Raw, p); err != nil {
return nil
}
if err := p.validate(); err != nil {
return fmt.Errorf("host %s: %v", hostID, err)
}
config_.Hosts.NS[p.ID] = true
global[p.ID] = true
elem.Value = p
return nil
})
if err != nil {
return err
}
// Ensure no naming ambiguity exists.
count := make(map[string]int)
for id := range global {
count[id]++
}
for id := range before {
count[id]++
}
for id := range count {
if count[id] > 1 {
return fmt.Errorf("identifier redeclared: %v", id)
}
}
return nil
}
// A QueryGroup corresponds to a <querygroup> configuration element.
type QueryGroup struct {
ID string
Targets []string
Query []*Query
}
var _ xml.Unmarshaler = &QueryGroup{}
func (g *QueryGroup) UnmarshalXML(dec *xml.Decoder, start xml.StartElement) error {
var v struct {
XMLName xml.Name `xml:"querygroup"`
ID string `xml:"id,attr"`
Targets *string `xml:"targets,attr"`
Query []*Query `xml:"query"`
Any *xml.Name `xml:",any"`
}
if err := dec.DecodeElement(&v, &start); err != nil {
return err
}
if any := v.Any; any != nil {
return fmt.Errorf("querygroup %s: invalid element: %s", g.ID, any.Local)
}
var targets []string
switch p := v.Targets; {
case p != nil && *p != "":
targets = strings.Split(*p, ",")
case p != nil:
targets = []string{}
}
*g = QueryGroup{
ID: v.ID,
Targets: targets,
Query: v.Query,
}
return nil
}
func (g *QueryGroup) Match(ids ...string) bool {
for _, want := range g.Targets {
for _, got := range ids {
if got == want {
return true
}
}
}
return false
}
func (g *QueryGroup) validate(config *config.Config) error {
if g.ID == "" {
return fmt.Errorf("missing querygroup attribute: id")
}
if g.Targets == nil {
return fmt.Errorf("querygroup %s: missing attribute: targets", g.ID)
}
seen := make(map[interface{}]bool)
for _, targetID := range g.Targets {
if !config.Hosts.NS[targetID] {
return fmt.Errorf("undefined: %s", targetID)
}
for _, host := range config.Hosts.All {
for _, id := range host.Tags {
if id == targetID {
if seen[host] {
return fmt.Errorf("host %s: query redeclared", host.ID)
}
seen[host] = true
}
}
for _, elem := range host.Extra {
process, ok := elem.Value.(*Process)
if !ok {
continue
}
if process.ID == targetID {
if seen[process] {
return fmt.Errorf("process %s: query redeclared", host.ID)
}
seen[process] = true
}
}
}
}
for _, query := range g.Query {
if err := query.validate(); err != nil {
return fmt.Errorf("querygroup %s: %v", g.ID, err)
}
}
return nil
}
// A Process corresponds to a <process> configuration element.
type Process struct {
ID string
}
var _ = xml.Unmarshaler(&Process{})
func (p *Process) UnmarshalXML(dec *xml.Decoder, start xml.StartElement) error {
var v struct {
XMLName xml.Name `xml:"process"`
ID string `xml:"id,attr"`
Any *xml.Name `xml:",any"`
}
if err := dec.DecodeElement(&v, &start); err != nil {
return err
}
if any := v.Any; any != nil {
return fmt.Errorf("process %s: invalid element: %s", p.ID, any.Local)
}
*p = Process{ID: v.ID}
return nil
}
func (p *Process) validate() error {
if p.ID == "" {
return fmt.Errorf("missing process attribute: id")
}
// XXX: check namespace conflict
return nil
}
// Handle registers the HTTP handlers.
func Handle(config *config.Config) error {
handler := &handler{config}
http.Handle("/control/v1/collect-jmx", handler)
http.Handle("/config/betex", handler) // legacy
http.Handle("/config/jmx", handler) // legacy
return nil
}
// Key represents the configuration lookup request.
type Key struct {
Program, Host, Process string
}
func parseKey(url *url.URL) (*Key, error) {
query := url.Query()
host := query.Get("host")
if host == "" {
return nil, fmt.Errorf("missing query parameter: host")
}
query.Del("host")
process := query.Get("process")
query.Del("process")
for _, key := range []string{"version", "wibble"} {
query.Del(key)
}
for key := range query {
return nil, fmt.Errorf("unexpected query parameter: %s", key)
}
return &Key{"collect-jmx", host, process}, nil
}
// View corresponds to collect-jmx configuration file.
type View struct {
Period int `json:"period"`
Objects []*Query `json:"objects"`
}
func (v *View) appendObject(nq *Query) {
for _, item := range v.Objects {
if reflect.DeepEqual(nq, item) {
return
}
}
v.Objects = append(v.Objects, nq)
}
// An Object is the JSON structure describing a Query.
type Object struct {
// Attributes corresponds to Query's Attributes field.
Attributes []*Attribute `json:"attributes,omitempty"`
// KPIs corresponds to Query's KPI field.
KPIs []*KPI `json:"kpis"`
// MetricName corresponds to Query's ID field.
MetricName string `json:"metricName"`
// ObjectName corresponds to Query's On field.
ObjectName string `json:"objectName"`
}
// Attribute represent a single mbean attribute.
type Attribute struct {
Name string `json:"attributeName"`
}
// A KPI is the JSON structure of a KPIQuery.
type KPI struct {
Name string `xml:"name,attr" json:"name"`
ID string `xml:"id,attr" json:"id"`
CollectRanges bool `xml:"collectRanges,attr" json:"collectRanges"`
}
func (kpi *KPI) validate() error {
if kpi.ID == "" {
return fmt.Errorf("missing kpi attribute: id")
}
if kpi.Name == "" {
return fmt.Errorf("kpi %s: missing attribute: name", kpi.ID)
}
return nil
}
type handler struct {
config *config.Config
}
func (h *handler) View(key *Key) (*View, error) {
// Lookup the host.
host, err := h.config.Host(key.Host)
if err != nil {
return nil, err
}
view := new(View)
// Add host-level queries.
view.Objects = hostQueries(host, h.config)
// Add process-level queries.
for _, query := range processQueries(host, h.config, key.Process) {
view.appendObject(query)
}
// Set poll interval.
view.Period = defaultInterval
return view, nil
}
func hostQueries(host *config.Host, config *config.Config) []*Query {
var found []*Query
for _, elem := range config.Extra {
group := elem.Value.(*QueryGroup)
if group.Match(host.Tags...) {
found = append(found, group.Query...)
}
}
return found
}
func processQueries(host *config.Host, config *config.Config, processID string) []*Query {
if !hasProcess(host, processID) {
return nil
}
var found []*Query
for _, elem := range config.Extra {
group := elem.Value.(*QueryGroup)
if group.Match(processID) {
found = append(found, group.Query...)
}
}
return found
}
// hasProcess reports if the given host contains a process subelement
// with the given id.
func hasProcess(host *config.Host, id string) bool {
for _, extra := range host.Extra {
if p, ok := extra.Value.(*Process); ok && p.ID == id {
return true
}
}
return false
}
type internalError struct{ error }
func (h *handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
key, err := parseKey(req.URL)
if err != nil {
log.Printf("%v", err)
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
view, err := h.View(key)
if err != nil {
log.Printf("%s: %v", key.Program, err)
if _, ok := err.(*internalError); ok {
http.Error(w, err.Error(), http.StatusInternalServerError)
} else {
http.Error(w, err.Error(), http.StatusBadRequest)
}
return
}
control.Marshal(w, view)
}
// Query represents a <query> element in the config file.
type Query struct {
ID string
On string
Attributes []string
KPI []*KPI
}
func (q *Query) UnmarshalXML(dec *xml.Decoder, start xml.StartElement) error {
var e struct {
ID string `xml:"id,attr"`
On string `xml:"on,attr"`
Attributes string `xml:"attributes,attr"`
KPI []*KPI `xml:"kpi"`
}
if err := dec.DecodeElement(&e, &start); err != nil {
return err
}
var attributes []string
if e.Attributes != "" {
attributes = strings.Split(e.Attributes, ",")
}
*q = Query{e.ID, e.On, attributes, e.KPI}
return nil
}
func (q *Query) validate() error {
if q.ID == "" {
return fmt.Errorf("missing query attribute: id")
}
if q.On == "" {
return fmt.Errorf("query %s: missing attribute: on", q.ID)
}
seen := make(map[string]bool)
for _, attr := range q.Attributes {
if seen[attr] {
return fmt.Errorf("query %s: attribute redeclared: %s", q.ID, attr)
}
seen[attr] = true
}
for _, kpi := range q.KPI {
if err := kpi.validate(); err != nil {
return fmt.Errorf("query %s: %v", q.ID, err)
}
}
return nil
}
func (q *Query) MarshalJSON() ([]byte, error) {
object := &Object{
Attributes: q.attributes(),
KPIs: q.kpis(),
ObjectName: q.On,
MetricName: q.ID,
}
return json.Marshal(object)
}
func (q *Query) attributes() []*Attribute {
var attrs []*Attribute
for _, name := range q.Attributes {
attrs = append(attrs, &Attribute{
Name: name,
})
}
return attrs
}
func (q *Query) kpis() []*KPI {
kpis := make([]*KPI, 0, len(q.KPI))
for _, k := range q.KPI {
kpis = append(kpis, &KPI{
Name: k.Name,
ID: k.ID,
CollectRanges: k.CollectRanges,
})
}
return kpis
}