This repository has been archived by the owner on Feb 12, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 10
/
http.go
206 lines (169 loc) · 5.12 KB
/
http.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
package main
import (
"fmt"
"log"
"net/http"
"sync"
"time"
auth "github.com/heroku/lumbermill/Godeps/_workspace/src/github.com/heroku/authenticater"
influx "github.com/heroku/lumbermill/Godeps/_workspace/src/github.com/influxdb/influxdb-go"
)
var influxDbStaleTimeout = 24 * time.Minute // Would be nice to make this smaller, but it lags due to continuous queries.
var influxDbSeriesCheckQueries = []string{
"select * from dyno.load.%s limit 1",
"select * from dyno.mem.%s limit 1",
}
var healthCheckClientsLock = new(sync.Mutex)
var healthCheckClients = make(map[string]*influx.Client)
type server struct {
sync.WaitGroup
connectionCloser chan struct{}
hashRing *hashRing
http *http.Server
shutdownChan shutdownChan
isShuttingDown bool
credStore map[string]string
// scheduler based sampling lock for writing to recentTokens
tokenLock *int32
recentTokensLock *sync.RWMutex
recentTokens map[string]string
}
func newServer(httpServer *http.Server, ath auth.Authenticater, hashRing *hashRing) *server {
s := &server{
connectionCloser: make(chan struct{}),
shutdownChan: make(chan struct{}),
http: httpServer,
hashRing: hashRing,
credStore: make(map[string]string),
tokenLock: new(int32),
recentTokensLock: new(sync.RWMutex),
recentTokens: make(map[string]string),
}
mux := http.NewServeMux()
mux.HandleFunc("/drain", auth.WrapAuth(ath,
func(w http.ResponseWriter, r *http.Request) {
s.serveDrain(w, r)
s.recycleConnection(w)
}))
mux.HandleFunc("/health", s.serveHealth)
mux.HandleFunc("/health/influxdb", auth.WrapAuth(ath, s.serveInfluxDBHealth))
mux.HandleFunc("/target/", auth.WrapAuth(ath, s.serveTarget))
s.http.Handler = mux
return s
}
func (s *server) Close() error {
s.shutdownChan <- struct{}{}
return nil
}
func (s *server) scheduleConnectionRecycling(after time.Duration) {
for !s.isShuttingDown {
time.Sleep(after)
s.connectionCloser <- struct{}{}
}
}
func (s *server) recycleConnection(w http.ResponseWriter) {
select {
case <-s.connectionCloser:
w.Header().Set("Connection", "close")
default:
if s.isShuttingDown {
w.Header().Set("Connection", "close")
}
}
}
func (s *server) Run(connRecycle time.Duration) {
go s.awaitShutdown()
go s.scheduleConnectionRecycling(connRecycle)
if err := s.http.ListenAndServe(); err != nil {
log.Fatalln("Unable to start HTTP server: ", err)
}
}
// Serves a 200 OK, unless shutdown has been requested.
// Shutting down serves a 503 since that's how ELBs implement connection draining.
func (s *server) serveHealth(w http.ResponseWriter, r *http.Request) {
if s.isShuttingDown {
http.Error(w, "Shutting Down", 503)
}
w.WriteHeader(http.StatusOK)
}
func getHealthCheckClient(host string, f clientFunc) (*influx.Client, error) {
healthCheckClientsLock.Lock()
defer healthCheckClientsLock.Unlock()
client, exists := healthCheckClients[host]
if !exists {
var err error
clientConfig := createInfluxDBClient(host, f)
client, err = influx.NewClient(&clientConfig)
if err != nil {
log.Printf("err=%q at=getHealthCheckClient host=%q", err, host)
return nil, err
}
healthCheckClients[host] = client
}
return client, nil
}
func checkRecentToken(client *influx.Client, token, host string, errors chan error) {
for _, qfmt := range influxDbSeriesCheckQueries {
query := fmt.Sprintf(qfmt, token)
results, err := client.Query(query, influx.Second)
if err != nil || len(results) == 0 {
errors <- fmt.Errorf("at=influxdb-health err=%q result_length=%d host=%q query=%q", err, len(results), host, query)
continue
}
t, ok := results[0].Points[0][0].(float64)
if !ok {
errors <- fmt.Errorf("at=influxdb-health err=\"time column was not a number\" host=%q query=%q", host, query)
continue
}
ts := time.Unix(int64(t), int64(0)).UTC()
now := time.Now().UTC()
if now.Sub(ts) > influxDbStaleTimeout {
errors <- fmt.Errorf("at=influxdb-health err=\"stale data\" host=%q ts=%q now=%q query=%q", host, ts, now, query)
}
}
}
func (s *server) checkRecentTokens() []error {
var errSlice []error
wg := new(sync.WaitGroup)
s.recentTokensLock.RLock()
tokenMap := make(map[string]string)
for host, token := range s.recentTokens {
tokenMap[host] = token
}
s.recentTokensLock.RUnlock()
errors := make(chan error, len(tokenMap)*len(influxDbSeriesCheckQueries))
for host, token := range tokenMap {
wg.Add(1)
go func(token, host string) {
client, err := getHealthCheckClient(host, newClientFunc)
if err != nil {
return
}
checkRecentToken(client, token, host, errors)
wg.Done()
}(token, host)
}
wg.Wait()
close(errors)
for err := range errors {
errSlice = append(errSlice, err)
}
return errSlice
}
func (s *server) serveInfluxDBHealth(w http.ResponseWriter, r *http.Request) {
errors := s.checkRecentTokens()
if len(errors) > 0 {
w.WriteHeader(http.StatusServiceUnavailable)
for _, err := range errors {
w.Write([]byte(err.Error() + "\n"))
log.Println(err)
}
return
}
w.WriteHeader(http.StatusOK)
}
func (s *server) awaitShutdown() {
<-s.shutdownChan
log.Printf("Shutting down.")
s.isShuttingDown = true
}