-
Notifications
You must be signed in to change notification settings - Fork 3
/
tsadmin.go
103 lines (79 loc) · 2.29 KB
/
tsadmin.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
// tsadmin
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"time"
"github.com/jamesrwhite/tsadmin/config"
"github.com/jamesrwhite/tsadmin/database"
"github.com/codegangsta/negroni"
"github.com/julienschmidt/httprouter"
)
var ticker = time.NewTicker(time.Second * 1)
var statuses map[string]*database.DatabaseStatus
func main() {
// Check the required env vars are set
if os.Getenv("PORT") == "" {
fmt.Println("You must set the PORT environment variable")
os.Exit(1)
}
if os.Getenv("CONFIG_FILE") == "" {
fmt.Println("You must set the CONFIG_FILE environment variable")
os.Exit(1)
}
// Create an instance of our app
app := negroni.Classic()
// Create a new router
router := httprouter.New()
// Fetch the initial statuses of the databases with 2 seconds of data
statuses, _ = monitor()
time.Sleep(time.Second * 1)
statuses, _ = monitor()
// Then refresh the statuses once a second
go func() {
for range ticker.C {
statuses, _ = monitor()
}
}()
// Add our routes
router.GET("/status.json", func(w http.ResponseWriter, _ *http.Request, _ httprouter.Params) {
// JSON please
w.Header().Set("Content-Type", "application/json")
// Define our response array
response := []*database.DatabaseStatus{}
// Reformat the statuses map as a simple array for JSON
for _, status := range statuses {
response = append(response, status)
}
// Encode the response
jsonResponse, _ := json.Marshal(response)
fmt.Fprint(w, string(jsonResponse))
})
// Set the router to use
app.UseHandler(router)
// Start our app on $PORT
app.Run(":" + os.Getenv("PORT"))
}
func monitor() (map[string]*database.DatabaseStatus, error) {
// Load the config on each request in case it gets updated
tsConfig, err := config.Load(os.Getenv("CONFIG_FILE"))
if err != nil {
log.Fatal(err)
}
// Define our response map
updatedStatuses := make(map[string]*database.DatabaseStatus)
// Loop each database and fetch the status
for _, dbConfig := range tsConfig.Databases {
// Get the database status, here we pass the last known status
// so we can determine metrics like queries per second
status, err := database.Status(dbConfig, statuses[dbConfig.Name])
if err != nil {
log.Fatal(err)
}
updatedStatuses[dbConfig.Name] = status
}
return updatedStatuses, nil
}