-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsystemstats.go
462 lines (436 loc) · 12.4 KB
/
systemstats.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
// Beacon Pi, a edge node system for iBeacons and Edge nodes made of Pi
// Copyright (C) 2017 Maeve Kennedy
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
// metricsserv builds cause problems with other binaries due to inclusion
// of packages that require python3
// +build metrics
package beaconpi
import (
"database/sql"
"encoding/json"
"fmt"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
"net/http"
)
// jsonResponse helper for sending simple JSON objects
func jsonResponse(w http.ResponseWriter, results map[string]interface{}) {
encoder := json.NewEncoder(w)
err := encoder.Encode(results)
if err != nil {
log.Error("Failed to write jsonResponse", err)
http.Error(w, "Server error", 500)
}
return
}
// quickStats returns a few simple statistics useful for system administration
func quickStats() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
dbconfig := dbHandler{mp.DriverName, mp.DataSourceName}
db, err := dbconfig.openDB()
if err != nil {
log.Errorf("Error opening DB", err)
http.Error(w, "Server failure", 500)
return
}
defer db.Close()
// Active edges in last 10 minutes
var (
countedges int
countbeacons int
)
type edges struct {
Id int
Title string
Room string
Location string
Description string
}
var inactEdges []edges
rowsedge, err := db.Query(`
select * from inactive_edges()
`)
if err != nil {
log.Errorf("Failed while getting inactive edges %s", err)
http.Error(w, "Server failure", 500)
return
}
defer rowsedge.Close()
for rowsedge.Next() {
var t edges
var desc sql.NullString
if err := rowsedge.Scan(&t.Id, &t.Title, &t.Room, &t.Location,
&desc); err != nil {
log.Errorf("Failed while scanning edges %s", err)
http.Error(w, "Server failure", 500)
return
}
t.Description = desc.String
inactEdges = append(inactEdges, t)
}
if err = db.QueryRow(`select count(*)
from edge_node
`).Scan(&countedges); err != nil {
log.Printf("Failed while getting total count %s", err)
http.Error(w, "Server failure", 500)
return
}
if err = db.QueryRow(`select count(*)
from ibeacons
`).Scan(&countbeacons); err != nil {
log.Printf("Failed while getting total beacon count %s", err)
http.Error(w, "Server failure", 500)
return
}
type ibeacons struct {
Label string
Uuid string
Major int
Minor int
}
var inactivebeacons []ibeacons
rows, err := db.Query(`
select * from inactive_beacons()
`)
defer rows.Close()
if err != nil {
log.Printf("Failed to get inactive beacons %s", err)
http.Error(w, "Server failure", 500)
return
}
for rows.Next() {
var t ibeacons
if err = rows.Scan(&t.Label, &t.Uuid, &t.Major, &t.Minor); err != nil {
log.Errorf("Failed while scanning beacons %s", err)
http.Error(w, "Server failure", 500)
return
}
inactivebeacons = append(inactivebeacons, t)
}
jsonResponse(w, map[string]interface{}{
"InactiveBeacons": inactivebeacons,
"InactiveEdges": inactEdges,
"EdgeCount": countedges,
"InaEdgeCount": len(inactEdges),
"BeaconCount": countbeacons,
"InaBeaconCount": len(inactivebeacons),
})
return
})
}
// getBeacons returns all beacons to the requestor
func getBeacons() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
dbconfig := dbHandler{mp.DriverName, mp.DataSourceName}
db, err := dbconfig.openDB()
if err != nil {
log.Infof("Error opening DB", err)
http.Error(w, "Server failure", 500)
return
}
defer db.Close()
rows, err := db.Query(`
select id, label, uuid, major, minor
from ibeacons
order by label`)
if err != nil {
log.Infof("Failed while quering beacons %s", err)
http.Error(w, "Server failure", 500)
return
}
type ibeacon struct {
Id int
Label string
Uuid string
Major int
Minor int
}
var outdata []ibeacon
for rows.Next() {
var b ibeacon
if err = rows.Scan(&b.Id, &b.Label, &b.Uuid, &b.Major,
&b.Minor); err != nil {
log.Errorf("Failed to scan beacons in GetBeacons %s", err)
http.Error(w, "Server failure", 500)
return
}
outdata = append(outdata, b)
}
jsonResponse(w, map[string]interface{}{
"Beacons": outdata,
})
return
})
}
// getEdges returns all the edges to the caller
func getEdges() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
dbconfig := dbHandler{mp.DriverName, mp.DataSourceName}
db, err := dbconfig.openDB()
if err != nil {
log.Infof("Error opening DB", err)
http.Error(w, "Server failure", 500)
return
}
defer db.Close()
rows, err := db.Query(`
select id, uuid, title, room, location, description, bias, gamma
from edge_node
order by title`)
if err != nil {
log.Errorf("Failed while quering edges %s", err)
http.Error(w, "Server failure", 500)
return
}
type edge struct {
Id int
Uuid string
Title string
Room string
Location string
Description string
Bias float64
Gamma float64
}
var outdata []edge
for rows.Next() {
var edge edge
var description sql.NullString
if err = rows.Scan(&edge.Id, &edge.Uuid, &edge.Title,
&edge.Room, &edge.Location, &description,
&edge.Bias, &edge.Gamma); err != nil {
log.Errorf("Failed to scan edges in GetEdges %s", err)
http.Error(w, "Server failure", 500)
return
}
edge.Description = description.String
outdata = append(outdata, edge)
}
jsonResponse(w, map[string]interface{}{
"Edges": outdata,
})
return
})
}
// Function that checks if the field is greater than the minlen
// if not it will return an error. This is chainable however,
// the first error is the only one that is returned
func validateLen(pass error, field interface{}, fieldn string, minlen int) error {
if pass != nil {
return pass
}
switch v := field.(type) {
case string:
if len(v) < minlen {
return errors.New(
fmt.Sprintf("Field %s was too short %d < %d, (value %v)",
fieldn, len(v), minlen, field))
}
return nil
case []interface{}:
if len(v) < minlen {
return errors.New(
fmt.Sprintf("Field %s was too short %d < %d, (value %v)",
fieldn, len(v), minlen, field))
}
return nil
}
return errors.New(fmt.Sprintf("Field %s is unknown type, (value %v)", fieldn, field))
}
// modEdge allows the caller to modify edges through the administrative panel
func modEdge() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
input := struct {
Id int
Uuid string
Title string
Room string
Location string
Description string
Bias float64
Gamma float64
Option string
}{}
dec := json.NewDecoder(req.Body)
err := dec.Decode(&input)
if err != nil {
log.Infof("Failed to decode json request in ModEdge %s", err)
http.Error(w, "Invalid Request", 400)
return
}
if input.Option != "rem" {
err = validateLen(nil, input.Uuid, "Uuid", 16)
err = validateLen(err, input.Title, "Title", 1)
err = validateLen(err, input.Room, "Room", 1)
err = validateLen(err, input.Location, "Location", 1)
err = validateLen(err, input.Option, "Option", 3)
if err != nil {
log.Infof("Failed validation %s", err)
http.Error(w, "Invalid Request", 400)
return
}
}
dbconfig := dbHandler{mp.DriverName, mp.DataSourceName}
db, err := dbconfig.openDB()
if err != nil {
log.Errorf("Error opening DB %s", err)
http.Error(w, "Server failure", 500)
return
}
defer db.Close()
switch input.Option {
case "new":
_, err = db.Exec(`insert into edge_node (uuid, title, room, location,
description, bias, gamma) values ($1, $2, $3, $4, $5, $6, $7)`,
input.Uuid, input.Title, input.Room, input.Location,
input.Description, input.Bias, input.Gamma)
case "mod":
_, err = db.Exec(`update edge_node set
(uuid, title, room, location, description, bias, gamma) =
($1, $2, $3, $4, $5, $6, $7) where id = $8`, input.Uuid, input.Title,
input.Room, input.Location, input.Description, input.Bias,
input.Gamma, input.Id)
case "rem":
_, err = db.Exec(`delete from edge_node
where id = $1`, input.Id)
default:
log.Infof("Option invalid given \"%s\"", input.Option)
http.Error(w, "Invalid Request", 400)
return
// Mod
}
if err != nil {
log.Infof("Failed operation on DB %s", err)
http.Error(w, "Invalid Request", 400)
return
}
jsonResponse(w, map[string]interface{}{
"Success": true,
})
return
})
}
// modBeacon allows users to modify beacons through the admin interface
func modBeacon() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
input := struct {
Id int
Label string
Uuid string
Major int
Minor int
Option string
}{}
dec := json.NewDecoder(req.Body)
err := dec.Decode(&input)
if err != nil {
log.Infof("Failed to decode json request in ModBeacon %s", err)
http.Error(w, "Invalid Request", 400)
return
}
if len(input.Option) != 3 {
log.Infof("Option invalid in ModBeacon given \"%s\"", input.Option)
http.Error(w, "Invalid Request", 400)
return
}
if input.Option != "rem" {
err = validateLen(nil, input.Label, "Label", 1)
err = validateLen(err, input.Option, "Option", 3)
if err != nil {
log.Infof("Failed validation %s", err)
http.Error(w, "Invalid Request", 400)
return
}
}
dbconfig := dbHandler{mp.DriverName, mp.DataSourceName}
db, err := dbconfig.openDB()
if err != nil {
log.Errorf("Error opening DB %s", err)
http.Error(w, "Server failure", 500)
return
}
defer db.Close()
switch input.Option {
case "new":
_, err = db.Exec(`insert into ibeacons
(label, uuid, major, minor) values
($1, $2, $3, $4)`, input.Label, input.Uuid,
input.Major, input.Minor)
case "mod":
_, err = db.Exec(`update ibeacons
set (label, uuid, major, minor) =
($1, $2, $3, $4) where id = $5`, input.Label, input.Uuid,
input.Major, input.Minor, input.Id)
case "rem":
_, err = db.Exec(`delete from ibeacons
where id = $1`, input.Id)
default:
log.Infof("Option invalid given \"%s\"", input.Option)
http.Error(w, "Invalid Request", 400)
return
// Mod
}
if err != nil {
log.Infof("Failed operation on DB %s", err)
http.Error(w, "Invalid Request", 400)
return
}
jsonResponse(w, map[string]interface{}{
"Success": true,
})
return
})
}
// syncCheck returns the maximum time difference between the last 10 beacon_logs
// entered and the current time, this is used to see if any edges are misbehaving
func syncCheck() (timedeltaseconds float64, edgenodeid int, err error) {
dbconfig := dbHandler{mp.DriverName, mp.DataSourceName}
db, err := dbconfig.openDB()
if err != nil {
return 0.0, 0, errors.Wrap(err, "Error opening DB")
}
defer db.Close()
query := `select a.edgenodeid as edge,
abs(extract(epoch from a.td)) as diff
from (select edgenodeid, datetime - current_timestamp as td
from beacon_log order by id desc limit 10) as a
order by diff desc limit 1`
err = db.QueryRow(query).Scan(&edgenodeid, &timedeltaseconds)
return
}
func changedActiveEdges() (inactEdges []int, err error) {
dbconfig := dbHandler{mp.DriverName, mp.DataSourceName}
db, err := dbconfig.openDB()
if err != nil {
log.Println("Failed to open db")
return nil, err
}
defer db.Close()
rowsedge, err := db.Query(`
select id from inactive_edges() order by id
`)
if err != nil {
return nil, errors.Wrap(err, "Failed while getting inactive edges")
}
defer rowsedge.Close()
for rowsedge.Next() {
var t int
if err := rowsedge.Scan(&t); err != nil {
return nil, errors.Wrap(err, "Failed while scanning edges")
}
inactEdges = append(inactEdges, t)
}
return
}