/
minmonitor.go
661 lines (598 loc) · 16.5 KB
/
minmonitor.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
package monitor
import (
"bytes"
"encoding/json"
"fmt"
"net"
"net/http"
"net/url"
"strings"
"time"
"github.com/proidiot/gone/errors"
"github.com/proidiot/gone/log"
"github.com/stuphlabs/pullcord/config"
"github.com/stuphlabs/pullcord/proxy"
"github.com/stuphlabs/pullcord/trigger"
)
// DuplicateServiceRegistrationError indicates that a service with that name
// has already been registered to this monitor.
const DuplicateServiceRegistrationError = errors.New(
"A service with this name has already been registered",
)
// UnknownServiceError indicates that no service with the given name has been
// registered.
const UnknownServiceError = errors.New(
"No service has been registered with the requested name",
)
// MinMonitorredService holds the information for a single service definition.
type MinMonitorredService struct {
URL *url.URL
GracePeriod time.Duration
OnDown trigger.Triggerrer
OnUp trigger.Triggerrer
Always trigger.Triggerrer
lastChecked time.Time
up bool
passthru http.Handler
}
func init() {
config.MustRegisterResourceType(
"minmonitorredservice",
func() json.Unmarshaler {
return new(MinMonitorredService)
},
)
}
// UnmarshalJSON implements encoding/json.Unmarshaler.
func (s *MinMonitorredService) UnmarshalJSON(data []byte) error {
var t struct {
URL string
GracePeriod string
OnDown *config.Resource
OnUp *config.Resource
Always *config.Resource
}
dec := json.NewDecoder(bytes.NewReader(data))
if e := dec.Decode(&t); e != nil {
return e
}
g, e := time.ParseDuration(t.GracePeriod)
if e != nil {
return e
}
s.GracePeriod = g
if t.OnDown != nil {
d := t.OnDown.Unmarshalled
switch d := d.(type) {
case trigger.Triggerrer:
s.OnDown = d
default:
return config.UnexpectedResourceType
}
} else {
// TODO test null values for these as well
s.OnDown = nil
}
if t.OnUp != nil {
u := t.OnUp.Unmarshalled
switch u := u.(type) {
case trigger.Triggerrer:
s.OnUp = u
default:
return config.UnexpectedResourceType
}
} else {
s.OnUp = nil
}
if t.Always != nil {
a := t.Always.Unmarshalled
switch a := a.(type) {
case trigger.Triggerrer:
s.Always = a
default:
return config.UnexpectedResourceType
}
} else {
s.Always = nil
}
u, e := url.Parse(t.URL)
if e != nil {
return e
}
s.URL = u
return nil
}
// NewMinMonitorredService creates an initialized MinMonitorredService.
func NewMinMonitorredService(
u *url.URL,
gracePeriod time.Duration,
onDown trigger.Triggerrer,
onUp trigger.Triggerrer,
always trigger.Triggerrer,
) (service *MinMonitorredService, err error) {
result := MinMonitorredService{
URL: u,
GracePeriod: gracePeriod,
OnDown: onDown,
OnUp: onUp,
Always: always,
lastChecked: time.Time{},
up: false,
passthru: nil,
}
return &result, nil
}
// MinMonitor is a minimal service monitor not intended to be used in
// production. Named services will have an up status cached for a time, while a
// down status will never be cached. It is possible to explicitly set a service
// as being up (which will be cached as with a normal probe). It is also
// possible to explicitly re-probe a service regardless of the status of the
// cache.
type MinMonitor struct {
table map[string]*MinMonitorredService
}
// Add adds a named service to the monitor. The named service is associated
// with a specific protocol (i.e. TCP, UDP) on a specific port at a specific
// address. A grace period can be used to keep this monitor from unnecessarily
// overwhelming the service by allowing an up status to be cached for a time.
// This function also allows the initial probe to either begin immediately or
// to be deferred until the first status request.
//
// At this time, it is suggested that only TCP services be probed as the
// current version of MinMonitor only checks to see that net.Dial() does not
// fail, which would not be enough information to make a determination of the
// status of a service that communicates over UDP. As the inability to interact
// beyond an attempt to open a connection is a handicap in determining even the
// status of some TCP-based services, future monitor implementations (including
// any intended to be used in a production environment) should allow service
// status to be determined by some amount of specified interaction (perhaps
// involving regular expressions or callback functions).
func (monitor *MinMonitor) Add(
name string,
service *MinMonitorredService,
) (err error) {
osvc, previousEntryExists := monitor.table[name]
if previousEntryExists {
_ = log.Err(
fmt.Sprintf(
"minmonitor cannot add service: name \"%s\""+
" previously used for service at"+
" \"%s\", new service at \"%s\"",
name,
osvc.URL.String(),
service.URL.String(),
),
)
return DuplicateServiceRegistrationError
}
if monitor.table == nil {
monitor.table = make(map[string]*MinMonitorredService)
}
monitor.table[name] = service
_ = log.Info(
fmt.Sprintf(
"minmonitor has successfully added service: \"%s\"",
name,
),
)
return err
}
// Reprobe forces the status of the named service to be checked immediately
// without regard to a possible previously cached up status. The result of this
// probe will automatically be cached by the monitor.
func (monitor *MinMonitor) Reprobe(name string) (up bool, err error) {
s, entryExists := monitor.table[name]
if !entryExists {
_ = log.Err(
fmt.Sprintf(
"minmonitor cannot probe unknown service:"+
" \"%s\"",
name,
),
)
return false, UnknownServiceError
}
return s.Reprobe()
}
// Reprobe forces the status of the service to be checked immediately without
// regard to a possible previously cached up status. The result of this probe
// will automatically be cached by the monitor.
func (s *MinMonitorredService) Reprobe() (up bool, err error) {
hostname := s.URL.Hostname()
socktypefam := "tcp"
if strings.Index(hostname, ":") > 0 {
hostname = fmt.Sprintf("//[%s]", hostname)
socktypefam = "tcp6"
}
port := s.URL.Port()
if port == "" {
port = s.URL.Scheme
}
addr := fmt.Sprintf("%s:%s", hostname, port)
conn, err := net.Dial(socktypefam, addr)
s.lastChecked = time.Now()
if err != nil {
s.up = false
// TODO check what the error was
switch castErr := err.(type) {
case *net.OpError:
if castErr.Addr != nil {
_ = log.Info(
fmt.Sprintf(
"minmonitor received a"+
" connection refused"+
" (interpereted as a"+
" down status) from"+
" \"%s\"",
s.URL.String(),
),
)
return false, nil
}
_ = log.Warning(
fmt.Sprintf(
"minmonitor encountered an error while"+
" probing \"%s\": %v",
s.URL.String(),
err,
),
)
return false, err
default:
_ = log.Warning(
fmt.Sprintf(
"minmonitor encountered an unknown"+
" error while probing"+
" \"%s\": %v",
s.URL.String(),
err,
),
)
return false, err
}
} else {
defer func() {
_ = conn.Close()
}()
s.up = true
_ = log.Info(
fmt.Sprintf(
"minmonitor successfully probed: \"%s\"",
s.URL.String(),
),
)
return true, nil
}
}
// Status returns true if the status of the named service is currently believed
// to be up. The service could have its status reported as being up if a brand
// new probe of the service indicates that the service is indeed up, or if a
// recent probe indicated that the service was up (specifically if the most
// recent probe indicated that the service was up and that probe was within a
// grace period that was specified when the service was registered), or if the
// status of the service was explicitly set as being up within that same grace
// period (and no other forced re-probe has occurred since this forced status
// up assignment). However, if the status of the service is reported as being
// down, then it necessarily means that a probe has just occurred and the
// service was unable to be reached.
func (monitor *MinMonitor) Status(name string) (up bool, err error) {
s, entryExists := monitor.table[name]
if !entryExists {
_ = log.Err(
fmt.Sprintf(
"minmonitor cannot probe unknown service:"+
" \"%s\"",
name,
),
)
return false, UnknownServiceError
}
return s.Status()
}
// Status returns true if the status of the service is currently believed to be
// up. The service could have its status reported as being up if a brand new
// probe of the service indicates that the service is indeed up, or if a recent
// probe indicated that the service was up (specifically if the most recent
// probe indicated that the service was up and that probe was within a grace
// period that was specified when the service was registered), or if the status
// of the service was explicitly set as being up within that same grace period
// (and no other forced re-probe has occurred since this forced status up
// assignment). However, if the status of the service is reported as being down,
// then it necessarily means that a probe has just occurred and the service was
// unable to be reached.
func (s *MinMonitorredService) Status() (up bool, err error) {
if (!s.up) || time.Now().After(
s.lastChecked.Add(s.GracePeriod),
) {
_ = log.Info(
fmt.Sprintf(
"minmonitor must reprobe as either the grace"+
" period has lapsed or the previous"+
" probe indicated a down status for:"+
" \"%s\"",
s.URL.String(),
),
)
return s.Reprobe()
}
_ = log.Info(
fmt.Sprintf(
"minmonitor is skipping the reprobe as the current"+
" time is still within the grace period of the"+
" last successful probe of: \"%s\"",
s.URL.String(),
),
)
return true, nil
}
// SetStatusUp explicitly sets the status of a named service as being up. This
// up status will be cached just as if it were the result of a normal probe.
func (monitor *MinMonitor) SetStatusUp(name string) (err error) {
s, entryExists := monitor.table[name]
if !entryExists {
_ = log.Err(
fmt.Sprintf(
"minmonitor cannot set the status of unknown"+
" service: \"%s\"",
name,
),
)
return UnknownServiceError
}
return s.SetStatusUp()
}
// SetStatusUp explicitly sets the status of the service as being up. This up
// status will be cached just as if it were the result of a normal probe.
func (s *MinMonitorredService) SetStatusUp() error {
_ = log.Info(
fmt.Sprintf(
"minmonitor has been explicitly informed of the up"+
" status of: \"%s\"",
s.URL.String(),
),
)
s.lastChecked = time.Now()
s.up = true
return nil
}
// NewMinMonitorFilter produces an http.Handler for a given named service. This
// handler will forward to the service if it is up, otherwise it will display an
// error page to the requester. There are also optional triggers which would be
// run if the service is down (presumably to bring it up), or if the service is
// already up, or in either case, respectively.
func (monitor *MinMonitor) NewMinMonitorFilter(
name string,
) (http.Handler, error) {
s, serviceExists := monitor.table[name]
if !serviceExists {
_ = log.Err(
fmt.Sprintf(
"minmonitor cannot create a request filter"+
" for unknown service: \"%s\"",
name,
),
)
return nil, UnknownServiceError
}
return s, nil
}
func (s *MinMonitorredService) ServeHTTP(
w http.ResponseWriter,
req *http.Request,
) {
_ = log.Debug("running minmonitor filter")
up, err := s.Status()
if err != nil {
_ = log.Warning(
fmt.Sprintf(
"minmonitor filter received an error"+
" while requesting the status for"+
" \"%s\": %v",
s.URL.String(),
err,
),
)
w.WriteHeader(500)
_, err = fmt.Fprint(
w,
"<html><head><title>Pullcord - Internal"+
" Server Error</title></head><body><h1>"+
"Pullcord - Internal Server Error</h1><p>An"+
" internal server error has occurred, but it"+
" might not be serious. However, If the"+
" problem persists, the site administrator"+
" should be contacted.</p></body></html>",
)
if err != nil {
_ = log.Error(
fmt.Sprintf(
"error writing page after error with"+
" monitor status: %s",
err.Error(),
),
)
}
return
}
if s.Always != nil {
_ = log.Debug("minmonitor running always trigger")
err = s.Always.Trigger()
if err != nil {
_ = log.Warning(
fmt.Sprintf(
"minmonitor filter received"+
" an error while running the"+
" always trigger on \"%s\":"+
" %v",
s.URL.String(),
err,
),
)
w.WriteHeader(500)
_, err = fmt.Fprint(
w,
"<html><head><title>Pullcord -"+
" Internal Server Error</title>"+
"</head><body><h1>Pullcord -"+
" Internal Server Error</h1><p>"+
"An internal server error has"+
" occurred, but it might not be"+
" serious. However, if the problem"+
" persists, the site administrator"+
" should be contacted.</p></body>"+
"</html>",
)
if err != nil {
_ = log.Error(
fmt.Sprintf(
"error writing page after"+
" error with always"+
" trigger: %s",
err.Error(),
),
)
}
return
}
_ = log.Debug("minmonitor completed always trigger")
}
if up {
_ = log.Debug("minmonitor determined service is up")
if s.OnUp != nil {
_ = log.Debug("minmonitor running up trigger")
err = s.OnUp.Trigger()
if err != nil {
_ = log.Warning(
fmt.Sprintf(
"minmonitor filter"+
" received an error"+
" while running the"+
" onDown trigger on"+
" \"%s\": %v",
s.URL.String(),
err,
),
)
w.WriteHeader(500)
_, err = fmt.Fprint(
w,
"<html><head><title>Pullcord"+
" - Internal Server Error"+
"</title></head><body><h1>"+
"Pullcord - Internal Server"+
" Error</h1><p>An internal"+
" server error has occurred,"+
" but it might not be"+
" serious. However, if the"+
" problem persists, the site"+
" administrator should be"+
" contacted.</p></body></html>",
)
if err != nil {
_ = log.Error(
fmt.Sprintf(
"error writing page"+
" after error"+
" with onup"+
" trigger: %s",
err.Error(),
),
)
}
return
}
_ = log.Debug("minmonitor completed up trigger")
}
if s.passthru == nil {
_ = log.Debug(
"minmonitor filter passthru creation started",
)
s.passthru = proxy.NewPassthruFilter(s.URL)
_ = log.Debug(
"minmonitor filter passthru creation completed",
)
}
_ = log.Debug("minmonitor filter passthru starting")
s.passthru.ServeHTTP(w, req)
_ = log.Debug("minmonitor filter passthru completed")
return
}
_ = log.Debug("minmonitor determined service is down")
if s.OnDown != nil {
_ = log.Debug("minmonitor running down trigger")
err = s.OnDown.Trigger()
if err != nil {
_ = log.Warning(
fmt.Sprintf(
"minmonitor filter received"+
" an error while running the"+
" onDown trigger on \"%s\": %v",
s.URL.String(),
err,
),
)
w.WriteHeader(500)
_, err = fmt.Fprint(
w,
"<html><head><title>Pullcord -"+
" Internal Server Error</title>"+
"</head><body><h1>Pullcord -"+
" Internal Server Error</h1><p>"+
"An internal server error has"+
" occurred, but it might not be"+
" serious. However, If the problem"+
" persists, the site administrator"+
" should be contacted.</p></body>"+
"</html>",
)
if err != nil {
_ = log.Error(
fmt.Sprintf(
"error writing page after"+
" error with ondown"+
" trigger: %s",
err.Error(),
),
)
}
return
}
_ = log.Debug("minmonitor completed down trigger")
}
_ = log.Info(
fmt.Sprintf(
"minmonitor filter has reached a down"+
" service (\"%s\"), but any triggers have"+
" fired successfully",
s.URL.String(),
),
)
w.WriteHeader(503)
_, err = fmt.Fprint(
w,
"<html><head><title>Pullcord - Service Not Ready"+
"</title></head><body><h1>Pullcord - Service Not"+
" Ready</h1><p>The requested service is not yet"+
" ready, but any trigger to start the service has"+
" been started successfully, so hopefully the"+
" service will be up in a few minutes.</p><p>If you"+
" would like further information, please contact the"+
" site administrator.</p></body></html>",
)
if err != nil {
_ = log.Error(
fmt.Sprintf(
"error writing page after status down: %s",
err.Error(),
),
)
}
return
}
// NewMinMonitor constructs a new MinMonitor.
func NewMinMonitor() *MinMonitor {
_ = log.Info("initializing minimal service monitor")
var result MinMonitor
result.table = make(map[string]*MinMonitorredService)
return &result
}