-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathpatrol.go
228 lines (196 loc) · 6.24 KB
/
patrol.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
package patrol
import (
"context"
"fmt"
"net/http"
"strings"
"time"
"github.com/NYTimes/gziphandler"
"github.com/karimsa/patrol/internal/checker"
"github.com/karimsa/patrol/internal/history"
"github.com/karimsa/patrol/internal/logger"
)
// Options used to setup patrol's HTTP server.
type PatrolHttpsOptions struct {
// Paths to SSL certificate and key files - cannot be zero value.
Cert, Key string
// This port is used to run the HTTPS server. Zero value is invalid
// for port.
Port uint32
}
// Patrol instance to manage a set of checkers, a history file, and run
// a web server to serve the web interface. Currently, instances cannot
// be created directly. You must use: 'New', 'FromConfig', or 'FromConfigFile'.
type Patrol struct {
History *history.File
name string
port int
https *PatrolHttpsOptions
checkers []*checker.Checker
server *http.Server
logger logger.Logger
logLevel logger.LogLevel
groupEventHandlers map[string]EventHandlers
globalEventHandlers EventHandlers
}
// Map that goes from item status values to a list of notification objects
type EventHandlers map[string][]*singleNotificationConfig
// Options for creating a new patrol instance.
type CreatePatrolOptions struct {
// Port at which to listen for HTTP requests. If HTTPS
// options are specified, this port simply acts as an
// HTTP to HTTPS redirect server.
Port uint32
// HTTPS options to listen on HTTPS as well as HTTP.
// Zero value indicates no HTTPS server.
HTTPS *PatrolHttpsOptions
// Name is used to render the web interface. It is used
// as the page's <title> and the heading at the top of
// the page.
Name string
// History options are used to open and create a new history
// file. If a history file is specified to the constructor, this
// struct is ignored.
History history.NewOptions
// Set of checkers that should be managed by the patrol instance.
// This slice cannot be nil, but it can be empty.
Checkers []*checker.Checker
// Minimum level of logs that should be printed. This value is forced
// onto the 'history.File' and 'checker.Checker' objects that are
// managed by this patrol instance.
LogLevel logger.LogLevel
// Event handlers by group
GroupEventHandlers map[string]EventHandlers
// Event handlers for all changes
GlobalEventHandlers EventHandlers
}
func New(options CreatePatrolOptions, historyFile *history.File) (*Patrol, error) {
if historyFile == nil {
groups := make(map[string]map[string]bool, len(options.Checkers))
for _, checker := range options.Checkers {
if _, ok := groups[checker.Group]; !ok {
groups[checker.Group] = make(map[string]bool, len(options.Checkers))
}
groups[checker.Group][checker.Name] = true
}
var err error
options.History.LogLevel = options.LogLevel
options.History.Groups = groups
historyFile, err = history.New(options.History)
if err != nil {
return nil, err
}
}
p := &Patrol{
name: options.Name,
port: int(options.Port),
https: options.HTTPS,
checkers: options.Checkers,
server: &http.Server{},
logLevel: options.LogLevel,
logger: logger.New(options.LogLevel, ""),
groupEventHandlers: options.GroupEventHandlers,
globalEventHandlers: options.GlobalEventHandlers,
History: historyFile,
}
p.server.Handler = gziphandler.GzipHandler(p)
if p.name == "" {
p.name = "Statuspage"
}
p.SetLogLevel(options.LogLevel)
return p, nil
}
func (p *Patrol) String() string {
hStr := strings.Split(p.History.String(), "\n")
for i := 1; i < len(hStr); i++ {
hStr[i] = "\t" + hStr[i]
}
return strings.Join([]string{
fmt.Sprintf("Patrol{"),
fmt.Sprintf("\tname: %s,", p.name),
fmt.Sprintf("\tport: %d,", p.port),
fmt.Sprintf("\thttps: %#v,", p.https),
fmt.Sprintf("\tcheckers: %d checkers,", len(p.checkers)),
fmt.Sprintf("\tlogLevel: %d,", p.logLevel),
fmt.Sprintf("\tHistory: %s,", strings.Join(hStr, "\n")),
fmt.Sprintf("}"),
}, "\n")
}
func (p *Patrol) SetLogLevel(level logger.LogLevel) {
p.logLevel = level
p.logger = logger.New(level, "")
p.History.SetLogLevel(level)
for _, checker := range p.checkers {
checker.SetLogLevel(level)
}
}
func (p *Patrol) OnCheckerStatus(status, group, checker string) {
p.logger.Debugf("status changed: %s, %s, %s", status, group, checker)
if p.globalEventHandlers != nil {
if handlers, ok := p.globalEventHandlers[status]; ok && len(handlers) > 0 {
p.logger.Debugf("Sending global notification for %s status of %s", status, group)
for idx, n := range handlers {
n.Run()
p.logger.Debugf("Sent global notifcation #%d", idx)
}
}
}
if groupHandlers, ok := p.groupEventHandlers[group]; ok {
if handlers, ok := groupHandlers[status]; ok && len(handlers) > 0 {
p.logger.Debugf("Sending group notification for %s status of %s", status, group)
for idx, n := range handlers {
n.Run()
p.logger.Debugf("Sent group notifcation #%d", idx)
}
}
}
}
func (p *Patrol) Start() {
if p.checkers == nil || len(p.checkers) == 0 {
panic(fmt.Errorf("Cannot start patrol with zero checkers"))
}
for _, checker := range p.checkers {
checker.Start(p)
}
go func() {
var err error
if p.https == nil {
p.server.Addr = fmt.Sprintf(":%d", p.port)
err = p.server.ListenAndServe()
} else {
go func() {
err := http.ListenAndServe(fmt.Sprintf(":%d", p.port), http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
http.Redirect(
res,
req,
fmt.Sprintf("https://%s:%d", strings.Split(req.Host, ":")[0], p.https.Port),
http.StatusTemporaryRedirect,
)
}))
if err != nil && err != http.ErrServerClosed {
panic(err)
}
}()
p.server.Addr = fmt.Sprintf(":%d", p.https.Port)
err = p.server.ListenAndServeTLS(p.https.Cert, p.https.Key)
}
if err != nil && err != http.ErrServerClosed {
panic(err)
}
}()
}
func (p *Patrol) Stop() {
for _, checker := range p.checkers {
checker.Close()
}
ctx, cancel := context.WithTimeout(context.TODO(), 5*time.Second)
defer cancel()
if err := p.server.Shutdown(ctx); err != nil {
panic(err)
}
}
func (p *Patrol) Close() {
p.logger.Infof("Waiting for graceful shutdown")
p.Stop()
p.History.Close()
}