-
Notifications
You must be signed in to change notification settings - Fork 1
/
tcp_monitor.go
74 lines (60 loc) · 1.6 KB
/
tcp_monitor.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
package gerty
import (
"fmt"
"net"
"time"
)
type TcpMonitor struct {
*BaseMonitor
host string
port int
buffer CircularBuffer
opts *TcpMonitorOptions
}
type TcpMonitorOptions struct {
Checks int
Timeout time.Duration
}
// ensure we always implement Monitor
var _ Monitor = (*TcpMonitor)(nil)
var DefaultTcpMonitorOptions = TcpMonitorOptions{
Checks: 5,
Timeout: 10 * time.Second,
}
func mergeTcpOpts(given *TcpMonitorOptions) *TcpMonitorOptions {
if given == nil {
return &DefaultTcpMonitorOptions
}
if given.Checks <= 0 {
given.Checks = DefaultTcpMonitorOptions.Checks
}
if given.Timeout <= 0 {
given.Timeout = DefaultTcpMonitorOptions.Timeout
}
return given
}
func NewTcpMonitorWithOptions(title, description, host string, port int, _opts *TcpMonitorOptions) *TcpMonitor {
opts := mergeTcpOpts(_opts)
buffer := NewCircularBuffer(opts.Checks)
return &TcpMonitor{NewBaseMonitor(title, description), host, port, buffer, opts}
}
func NewTcpMonitor(title, description, host string, port int) *TcpMonitor {
return NewTcpMonitorWithOptions(title, description, host, port, nil)
}
func (monitor *TcpMonitor) Check() Result {
logger.Printf("checking monitor %s", monitor.Name())
address := fmt.Sprintf("%s:%d", monitor.host, monitor.port)
conn, err := net.DialTimeout("tcp", address, monitor.opts.Timeout)
if err == nil {
defer conn.Close()
monitor.buffer.Append(OK)
return OK
} else {
logger.Printf("tcp monitor check failed, error: %v", err)
monitor.buffer.Append(NOK)
return NOK
}
}
func (monitor *TcpMonitor) Values() []ValueWithTimestamp {
return monitor.buffer.GetValues()
}