forked from valleyelectronics/cachet-monitor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tcp.go
76 lines (60 loc) · 1.59 KB
/
tcp.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
// Thanks go to https://github.com/Soontao/cachet-monitor/blob/master/tcp.go
package cachet
import (
"fmt"
"net"
"time"
)
// Investigating template
var defaultTCPInvestigatingTpl = MessageTemplate{
Subject: `{{ .Monitor.Name }} - {{ .SystemName }}`,
Message: `{{ .Monitor.Name }} check **failed** (server time: {{ .now }})
{{ .FailReason }}`,
}
// Fixed template
var defaultTCPFixedTpl = MessageTemplate{
Subject: `{{ .Monitor.Name }} - {{ .SystemName }}`,
Message: `**Resolved** - {{ .now }}
Down seconds: {{ .downSeconds }}s`,
}
// TCPMonitor struct
type TCPMonitor struct {
AbstractMonitor `mapstructure:",squash"`
Port string
}
// CheckTCPPortAlive func
func CheckTCPPortAlive(ip, port string, timeout int64) (bool, error) {
conn, err := net.DialTimeout("tcp", net.JoinHostPort(ip, port), time.Duration(timeout)*time.Second)
if conn != nil {
defer conn.Close()
}
if err != nil {
return false, err
} else {
return true, nil
}
}
// test if it available
func (m *TCPMonitor) test() bool {
if alive, e := CheckTCPPortAlive(m.Target, m.Port, int64(m.Timeout)); alive {
return true
} else {
m.lastFailReason = fmt.Sprintf("TCP check failed: %v", e)
return false
}
}
// Validate configuration
func (m *TCPMonitor) Validate() []string {
// set incident temp
m.Template.Investigating.SetDefault(defaultTCPInvestigatingTpl)
m.Template.Fixed.SetDefault(defaultTCPFixedTpl)
// super.Validate()
errs := m.AbstractMonitor.Validate()
if m.Target == "" {
errs = append(errs, "Target is required")
}
if m.Port == "" {
errs = append(errs, "Port is required")
}
return errs
}