-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.go
111 lines (92 loc) · 2.6 KB
/
server.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
package gerty
import (
"encoding/json"
"io/ioutil"
"log"
"net/http"
"os"
)
var logger = log.New(os.Stdout, "", log.Ldate|log.Ltime|log.Lshortfile)
type GertyServer struct {
Groups []Group
Alarms []Alarm
}
func (server GertyServer) GetGroups() []Group {
return server.Groups
}
func (server GertyServer) Failed(monitor Monitor) {
if len(server.Alarms) == 0 {
return
}
logger.Printf("monitor %s has failed, notifying errors", monitor.Name())
for i, _ := range server.Alarms {
server.Alarms[i].NotifyError(monitor)
}
}
func (server GertyServer) Restored(monitor Monitor) {
if len(server.Alarms) == 0 {
return
}
logger.Printf("monitor %s is back to normal", monitor.Name())
for i, _ := range server.Alarms {
server.Alarms[i].NotifyRestore(monitor)
}
}
type GroupJson struct {
Name string `json:"name"`
Tiles []TileJson `json:"tiles"`
}
type TileJson struct {
Title string `json:"title"`
Description string `json:"description"`
Values []TileValue `json:"values"`
}
type TileValue struct {
Value Result `json:"value"`
Timestamp int64 `json:"timestamp"`
}
var appPath = os.Getenv("GOPATH") + "/src/github.com/gerty-monit/core"
func HomePage(w http.ResponseWriter, r *http.Request) {
bytes, err := ioutil.ReadFile(appPath + "/views/index.html")
if err != nil {
logger.Panicf("error reading index.html: %v", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
w.WriteHeader(200)
w.Write(bytes)
}
func createTileValues(checks []ValueWithTimestamp) []TileValue {
values := []TileValue{}
for i := range checks {
values = append(values, TileValue{checks[i].Value, checks[i].Timestamp})
}
return values
}
func MonitorApi(s *GertyServer) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
data := []GroupJson{}
for _, group := range s.Groups {
ms := []TileJson{}
for _, monitor := range group.Monitors {
tileValues := createTileValues(monitor.Values())
ms = append(ms, TileJson{monitor.Name(), monitor.Description(), tileValues})
}
data = append(data, GroupJson{group.Name, ms})
}
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(200)
bytes, _ := json.Marshal(data)
w.Write(bytes)
}
}
func (server *GertyServer) ListenAndServe(address string) {
Ping(server)
mux := http.NewServeMux()
statics := os.Getenv("GOPATH") + "/src/github.com/gerty-monit/core/public"
fs := http.FileServer(http.Dir(statics))
mux.Handle("/assets/", http.StripPrefix("/assets/", fs))
mux.HandleFunc("/api/v1/monitors", MonitorApi(server))
mux.HandleFunc("/", HomePage)
http.ListenAndServe(address, mux)
}