forked from skx/puppet-summary
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cmd_serve.go
1237 lines (1067 loc) · 23.4 KB
/
cmd_serve.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
//
// Launch our HTTP-server for both consuming reports, and viewing them.
//
package main
import (
"bytes"
"context"
"encoding/json"
"encoding/xml"
"errors"
"flag"
"fmt"
"html/template"
"io/ioutil"
"net/http"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"time"
"github.com/google/subcommands"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
"github.com/robfig/cron"
_ "github.com/skx/golang-metrics"
)
//
// ReportPrefix is the path beneath which reports are stored.
//
var ReportPrefix = "reports"
//
// Exists is a utility method to determine whether a file/directory exists.
//
func Exists(name string) bool {
_, err := os.Stat(name)
return !os.IsNotExist(err)
}
//
// APIState is the handler for the HTTP end-point
//
// GET /api/state/$state
//
// This only will return plain-text by default, but JSON and XML are both
// possible via the `Accept:` header or `?accept=XX` parameter.
//
func APIState(res http.ResponseWriter, req *http.Request) {
var (
status int
err error
)
defer func() {
if nil != err {
http.Error(res, err.Error(), status)
}
}()
//
// Get the state the user is interested in.
//
vars := mux.Vars(req)
state := vars["state"]
//
// Ensure we received a parameter.
//
if len(state) < 1 {
status = http.StatusNotFound
err = errors.New("missing 'state' parameter")
return
}
//
// Test the supplied state is valid.
//
switch state {
case "changed":
case "unchanged":
case "failed":
case "orphaned":
default:
err = errors.New("invalid state supplied")
status = http.StatusInternalServerError
return
}
//
// Get the nodes.
//
NodeList, err := getIndexNodes("")
if err != nil {
status = http.StatusInternalServerError
return
}
//
// The result
//
var result []string
//
// Add the hosts in the correct users' preferred state.
//
for _, o := range NodeList {
if o.State == state {
result = append(result, o.Fqdn)
}
}
//
// What kind of reply should we send?
//
// Accept either a "?accept=XXX" URL-parameter, or
// the Accept HEADER in the HTTP request
//
accept := req.FormValue("accept")
if len(accept) < 1 {
accept = req.Header.Get("Accept")
}
switch accept {
case "text/plain":
res.Header().Set("Content-Type", "text/plain")
for _, o := range result {
fmt.Fprintf(res, "%s\n", o)
}
case "application/xml":
x, err := xml.MarshalIndent(result, "", " ")
if err != nil {
status = http.StatusInternalServerError
return
}
res.Header().Set("Content-Type", "application/xml")
res.Write(x)
default:
//
// Convert the string-array to JSON, and return it.
//
res.Header().Set("Content-Type", "application/json")
if len(result) > 0 {
out, _ := json.Marshal(result)
fmt.Fprintf(res, "%s", out)
} else {
fmt.Fprintf(res, "[]")
}
}
}
//
// RadiatorView is the handler for the HTTP end-point
//
// GET /radiator/
//
// It will respond in either HTML, JSON, or XML depending on the
// Accepts-header which is received.
//
func RadiatorView(res http.ResponseWriter, req *http.Request) {
var (
status int
err error
)
defer func() {
if nil != err {
http.Error(res, err.Error(), status)
}
}()
// anonymous struct
type Pagedata struct {
States []PuppetState
Urlprefix string
}
//
// Get the state of the nodes.
//
data, err := getStates("")
if err != nil {
status = http.StatusInternalServerError
return
}
//
// Sum up our known-nodes.
//
total := 0
for i := range data {
total += data[i].Count
}
//
// Add in the total count of nodes.
//
var tmp PuppetState
tmp.State = "Total"
tmp.Count = total
tmp.Percentage = 0
data = append(data, tmp)
// genereic template args
var x Pagedata
x.States = data
x.Urlprefix = templateArgs.urlprefix
//
// What kind of reply should we send?
//
// Accept either a "?accept=XXX" URL-parameter, or
// the Accept HEADER in the HTTP request
//
accept := req.FormValue("accept")
if len(accept) < 1 {
accept = req.Header.Get("Accept")
}
switch accept {
case "application/json":
js, err := json.Marshal(data)
if err != nil {
status = http.StatusInternalServerError
return
}
res.Header().Set("Content-Type", "application/json")
res.Write(js)
case "application/xml":
x, err := xml.MarshalIndent(data, "", " ")
if err != nil {
status = http.StatusInternalServerError
return
}
res.Header().Set("Content-Type", "application/xml")
res.Write(x)
default:
//
// Load our template resource.
//
tmpl, err := getResource("data/radiator.template")
if err != nil {
fmt.Fprint(res, err.Error())
return
}
//
// Load our template, from the resource.
//
src := string(tmpl)
t := template.Must(template.New("tmpl").Parse(src))
//
// Execute the template into our buffer.
//
buf := &bytes.Buffer{}
err = t.Execute(buf, x)
//
// If there were errors, then show them.
if err != nil {
fmt.Fprint(res, err.Error())
return
}
//
// Otherwise write the result.
//
buf.WriteTo(res)
}
}
//
// ReportSubmissionHandler is the handler for the HTTP end-point:
//
// POST /upload
//
// The input is read, and parsed as Yaml, and assuming that succeeds
// then the data is written beneath ./reports/$hostname/$timestamp
// and a summary-record is inserted into our SQLite database.
//
//
func ReportSubmissionHandler(res http.ResponseWriter, req *http.Request) {
var (
status int
err error
)
defer func() {
if nil != err {
http.Error(res, err.Error(), status)
// Don't spam stdout when running test-cases.
if flag.Lookup("test.v") == nil {
fmt.Printf("Error: %s\n", err.Error())
}
}
}()
//
// Ensure this was a POST-request
//
if req.Method != "POST" {
err = errors.New("must be called via HTTP-POST")
status = http.StatusInternalServerError
return
}
//
// Read the body of the request.
//
content, err := ioutil.ReadAll(req.Body)
if err != nil {
status = http.StatusInternalServerError
return
}
//
// Parse the YAML into something we can work with.
//
report, err := ParsePuppetReport(content)
if err != nil {
status = http.StatusInternalServerError
return
}
//
// Create a report directory for this host, unless it already exists.
//
dir := filepath.Join(ReportPrefix, report.Fqdn)
if !Exists(dir) {
err = os.MkdirAll(dir, 0755)
if err != nil {
status = http.StatusInternalServerError
return
}
}
//
// Does this report already exist? This shouldn't happen
// in a usual setup, but will happen if you're repeatedly
// importing reports manually from a puppet-server.
//
// (Which is something you might do when testing the dashboard.)
//
path := filepath.Join(dir, report.Hash)
if Exists(path) {
fmt.Fprintf(res, "Ignoring duplicate submission")
return
}
//
// Create the new report-file, on-disk.
//
err = ioutil.WriteFile(path, content, 0644)
if err != nil {
status = http.StatusInternalServerError
return
}
//
// Record that report in our SQLite database
//
relativePath := filepath.Join(report.Fqdn, report.Hash)
addDB(report, relativePath)
//
// Show something to the caller.
//
out := fmt.Sprintf("{\"host\":\"%s\"}", report.Fqdn)
fmt.Fprint(res, string(out))
}
//
// SearchHandler is the handler for the HTTP end-point:
//
// POST /search
//
// We perform a search for nodes matching a given pattern. The comparison
// is a regular substring-match, rather than a regular expression.
//
func SearchHandler(res http.ResponseWriter, req *http.Request) {
var (
status int
err error
)
defer func() {
if nil != err {
http.Error(res, err.Error(), status)
// Don't spam stdout when running test-cases.
if flag.Lookup("test.v") == nil {
fmt.Printf("Error: %s\n", err.Error())
}
}
}()
//
// Ensure this was a POST-request
//
if req.Method != "POST" {
err = errors.New("must be called via HTTP-POST")
status = http.StatusInternalServerError
return
}
//
// Get the term from the form.
//
req.ParseForm()
term := req.FormValue("term")
//
// Ensure we have a term.
//
if len(term) < 1 {
err = errors.New("missing search term")
status = http.StatusInternalServerError
return
}
//
// Annoying struct to allow us to populate our template
// with both the matching nodes, and the term used for the search
//
type Pagedata struct {
Nodes []PuppetRuns
Term string
Urlprefix string
}
//
// Get all known nodes.
//
NodeList, err := getIndexNodes("")
if err != nil {
status = http.StatusInternalServerError
return
}
//
// Populate this structure with the search-term
//
var x Pagedata
x.Term = term
x.Urlprefix = templateArgs.urlprefix
//
// Add in any nodes which match our term.
//
for _, o := range NodeList {
if strings.Contains(o.Fqdn, term) {
x.Nodes = append(x.Nodes, o)
}
}
//
// Load our template source.
//
tmpl, err := getResource("data/results.template")
if err != nil {
fmt.Fprint(res, err.Error())
return
}
//
// Load our template, from the resource.
//
src := string(tmpl)
t := template.Must(template.New("tmpl").Parse(src))
//
// Execute the template into our buffer.
//
buf := &bytes.Buffer{}
err = t.Execute(buf, x)
//
// If there were errors, then show them.
if err != nil {
fmt.Fprint(res, err.Error())
return
}
//
// Otherwise write the result.
//
buf.WriteTo(res)
}
//
// ReportHandler is the handler for the HTTP end-point
//
// GET /report/NN
//
// It will respond in either HTML, JSON, or XML depending on the
// Accepts-header which is received.
//
func ReportHandler(res http.ResponseWriter, req *http.Request) {
var (
status int
err error
)
defer func() {
if nil != err {
http.Error(res, err.Error(), status)
// Don't spam stdout when running test-cases.
if flag.Lookup("test.v") == nil {
fmt.Printf("Error: %s\n", err.Error())
}
}
}()
//
// Get the node name we're going to show.
//
vars := mux.Vars(req)
id := vars["id"]
//
// Ensure we received a parameter.
//
if len(id) < 1 {
status = http.StatusNotFound
err = errors.New("missing 'id' parameter")
return
}
//
// If the ID is non-numeric we're in trouble.
//
reg, _ := regexp.Compile("^([0-9]+)$")
if !reg.MatchString(id) {
status = http.StatusInternalServerError
err = errors.New("the report ID must be numeric")
return
}
//
// Get the content.
//
content, err := getYAML(ReportPrefix, id)
if err != nil {
status = http.StatusInternalServerError
return
}
// need generic struct
type Pagedata struct {
Report PuppetReport
Urlprefix string
}
//
// Parse it
//
report, err := ParsePuppetReport(content)
if err != nil {
status = http.StatusInternalServerError
return
}
var x Pagedata
x.Report = report
x.Urlprefix = templateArgs.urlprefix
//
// Accept either a "?accept=XXX" URL-parameter, or
// the Accept HEADER in the HTTP request
//
accept := req.FormValue("accept")
if len(accept) < 1 {
accept = req.Header.Get("Accept")
}
switch accept {
case "application/json":
js, err := json.Marshal(report)
if err != nil {
status = http.StatusInternalServerError
return
}
res.Header().Set("Content-Type", "application/json")
res.Write(js)
case "application/xml":
x, err := xml.MarshalIndent(report, "", " ")
if err != nil {
status = http.StatusInternalServerError
return
}
res.Header().Set("Content-Type", "application/xml")
res.Write(x)
default:
//
// Load our template resource.
//
tmpl, err := getResource("data/report.template")
if err != nil {
fmt.Fprint(res, err.Error())
return
}
//
// Helper to allow a float to be truncated
// to two/three digits.
//
funcMap := template.FuncMap{
"truncate": func(s string) string {
//
// Parse as a float.
//
f, _ := strconv.ParseFloat(s, 64)
//
// Output to a truncated string
//
s = fmt.Sprintf("%.2f", f)
return s
},
}
//
// Load our template, from the resource.
//
src := string(tmpl)
t := template.Must(template.New("tmpl").Funcs(funcMap).Parse(src))
//
// Execute the template into our buffer.
//
buf := &bytes.Buffer{}
err = t.Execute(buf, x)
//
// If there were errors, then show them.
if err != nil {
fmt.Fprint(res, err.Error())
return
}
//
// Otherwise write the result.
//
buf.WriteTo(res)
}
}
//
// NodeHandler is the handler for the HTTP end-point
//
// GET /node/$FQDN
//
// It will respond in either HTML, JSON, or XML depending on the
// Accepts-header which is received.
//
func NodeHandler(res http.ResponseWriter, req *http.Request) {
var (
status int
err error
)
defer func() {
if nil != err {
http.Error(res, err.Error(), status)
// Don't spam stdout when running test-cases.
if flag.Lookup("test.v") == nil {
fmt.Printf("Error: %s\n", err.Error())
}
}
}()
//
// Get the node name we're going to show.
//
vars := mux.Vars(req)
fqdn := vars["fqdn"]
//
// Ensure we received a parameter.
//
if len(fqdn) < 1 {
status = http.StatusNotFound
err = errors.New("missing 'fqdn' parameter")
return
}
//
// Get the reports
//
reports, err := getReports(fqdn)
//
// Ensure that something was present.
//
if (reports == nil) || (len(reports) < 1) {
status = http.StatusNotFound
return
}
//
// Handle error(s)
//
if err != nil {
status = http.StatusInternalServerError
return
}
//
// Annoying struct to allow us to populate our template
// with both the reports and the fqdn of the host.
//
type Pagedata struct {
Fqdn string
Nodes []PuppetReportSummary
Urlprefix string
}
//
// Populate this structure.
//
var x Pagedata
x.Nodes = reports
x.Fqdn = fqdn
x.Urlprefix = templateArgs.urlprefix
//
// Accept either a "?accept=XXX" URL-parameter, or
// the Accept HEADER in the HTTP request
//
accept := req.FormValue("accept")
if len(accept) < 1 {
accept = req.Header.Get("Accept")
}
switch accept {
case "application/json":
js, err := json.Marshal(reports)
if err != nil {
status = http.StatusInternalServerError
return
}
res.Header().Set("Content-Type", "application/json")
res.Write(js)
case "application/xml":
x, err := xml.MarshalIndent(reports, "", " ")
if err != nil {
status = http.StatusInternalServerError
return
}
res.Header().Set("Content-Type", "application/xml")
res.Write(x)
default:
//
// Load our template resource.
//
tmpl, err := getResource("data/node.template")
if err != nil {
fmt.Fprint(res, err.Error())
return
}
funcMap := template.FuncMap{
"incr": func(d int) string {
//
// Return the incremented string.
//
s := fmt.Sprintf("%d", (d + 1))
return s
},
}
//
// Load our template, from the resource.
//
src := string(tmpl)
t := template.Must(template.New("tmpl").Funcs(funcMap).Parse(src))
//
// Execute the template into our buffer.
//
buf := &bytes.Buffer{}
err = t.Execute(buf, x)
//
// If there were errors, then show them.
if err != nil {
fmt.Fprint(res, err.Error())
return
}
//
// Otherwise write the result.
//
buf.WriteTo(res)
}
}
//
// IconHandler is the handler for the HTTP end-point
//
// GET /favicon.ico
//
// It will server an embedded binary resource.
//
func IconHandler(res http.ResponseWriter, req *http.Request) {
serveStatic(res, req, "data/favicon.ico", "image/vnd.microsoft.icon")
}
// CSSPath is the handler for all the CSS files beneath /css.
func CSSPath(res http.ResponseWriter, req *http.Request) {
//
// Get the path we're going to serve.
//
vars := mux.Vars(req)
path := vars["path"]
//
// Ensure we received a path.
//
if len(path) < 1 {
res.WriteHeader(http.StatusNotFound)
fmt.Fprint(res, "The request you made pointed to a missing resource")
return
}
//
// Serve it
//
serveStatic(res, req, "data/css/"+path, "text/css")
}
// serveStatic serves a static path, with the given MIME type.
func serveStatic(res http.ResponseWriter, req *http.Request, path string, mime string) {
// Load the asset.
data, err := getResource(path)
if err != nil {
res.WriteHeader(http.StatusNotFound)
fmt.Fprintf(res, "Error loading the resource you requested: %s", err.Error())
return
}
res.Header().Set("Content-Type", mime)
res.Write(data)
}
//
// JavascriptPath is the handler for all the javascript files beneath /js.
// It will serve an embedded javascript resource.
//
func JavascriptPath(res http.ResponseWriter, req *http.Request) {
//
// Get the path we're going to serve.
//
vars := mux.Vars(req)
path := vars["path"]
//
// Ensure we received a path.
//
if len(path) < 1 {
res.WriteHeader(http.StatusNotFound)
fmt.Fprint(res, "The request you made pointed to a missing resource")
return
}
//
// Serve it
//
serveStatic(res, req, "data/js/"+path, "application/javascript")
}
//
// IndexHandler is the handler for the HTTP end-point
//
// GET /
//
// It will respond in either HTML, JSON, or XML depending on the
// Accepts-header which is received.
//
func IndexHandler(res http.ResponseWriter, req *http.Request) {
var (
status int
err error
)
defer func() {
if nil != err {
http.Error(res, err.Error(), status)
// Don't spam stdout when running test-cases.
if flag.Lookup("test.v") == nil {
fmt.Printf("Error: %s\n", err.Error())
}
}
}()
//
// Check if we are filtering by environment
//
vars := mux.Vars(req)
environment := vars["environment"]
//
// Annoying struct to allow us to populate our template
// with both the nodes in the list, and the graph-data
//
type Pagedata struct {
Graph []PuppetHistory
Nodes []PuppetRuns
Environment string
Environments []string
Urlprefix string
}
//
// Get the nodes to show on our front-page
//
NodeList, err := getIndexNodes(environment)
if err != nil {
status = http.StatusInternalServerError
return
}
//
// Get the graph-data
//
graphs, err := getHistory(environment)
if err != nil {
status = http.StatusInternalServerError
return
}
//
// Get all environments
environments, err := getEnvironments()
//
// Populate this structure.
//
var x Pagedata
x.Graph = graphs
x.Nodes = NodeList
x.Environment = environment
x.Environments = environments
x.Urlprefix = templateArgs.urlprefix
//
// Accept either a "?accept=XXX" URL-parameter, or
// the Accept HEADER in the HTTP request
//
accept := req.FormValue("accept")
if len(accept) < 1 {
accept = req.Header.Get("Accept")
}
switch accept {
case "application/json":
js, err := json.Marshal(NodeList)
if err != nil {
status = http.StatusInternalServerError
return
}
res.Header().Set("Content-Type", "application/json")
res.Write(js)
case "application/xml":
x, err := xml.MarshalIndent(NodeList, "", " ")
if err != nil {