forked from rancher/rancher
-
Notifications
You must be signed in to change notification settings - Fork 0
/
syslog.go
107 lines (89 loc) · 2.42 KB
/
syslog.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
package utils
import (
"crypto/tls"
"fmt"
"net"
"os"
"time"
"github.com/pkg/errors"
"github.com/rancher/types/apis/management.cattle.io/v3"
"github.com/rancher/types/config/dialer"
)
type syslogTestWrap struct {
*v3.SyslogConfig
}
func (w *syslogTestWrap) TestReachable(dial dialer.Dialer, includeSendTestLog bool) error {
//TODO: for udp we can't use cluster dialer now, how to handle in cluster deploy syslog
syslogTestData := newRFC5424Message(w.Severity, w.Program, w.Token, testMessage)
if w.Protocol == "udp" {
conn, err := net.Dial("udp", w.Endpoint)
if err != nil {
return errors.Wrapf(err, "couldn't dail udp endpoint %s", w.Endpoint)
}
defer conn.Close()
if includeSendTestLog {
return writeToUDPConn(syslogTestData, w.Endpoint)
}
return nil
}
var tlsConfig *tls.Config
if w.EnableTLS {
hostName, _, err := net.SplitHostPort(w.Endpoint)
if err != nil {
return errors.Wrapf(err, "couldn't parse url %s", w.Endpoint)
}
tlsConfig, err = buildTLSConfig(w.Certificate, w.ClientCert, w.ClientKey, "", "", hostName, w.SSLVerify)
if err != nil {
return err
}
}
conn, err := newTCPConn(dial, w.Endpoint, tlsConfig, true)
if err != nil {
return err
}
defer conn.Close()
if !includeSendTestLog {
return nil
}
if _, err = conn.Write(syslogTestData); err != nil {
return errors.Wrapf(err, "couldn't write data to syslog %s", w.Endpoint)
}
// try read to check whether the server close connect already
// because can't set read deadline for remote dialer, so if the error is timeout will treat as remote server not close the connection
if _, err := readDataWithTimeout(conn); err != nil && err != errReadDataTimeout {
return errors.Wrapf(err, "couldn't read data from syslog %s", w.Endpoint)
}
return nil
}
func newRFC5424Message(severityStr, app, token, msg string) []byte {
if app == "" {
app = "rancher"
}
severity := getSeverity(severityStr)
syslogVersion := 1
timestamp := time.Now().Format(time.RFC3339)
msgID := randHex(6)
hostname, _ := os.Hostname()
return []byte(fmt.Sprintf("<%d>%v %v %v %v %v %v [%v] %v\n",
severity,
syslogVersion,
timestamp,
hostname,
app,
os.Getpid(),
msgID,
token,
msg,
))
}
func getWrapSeverity(severity string) string {
// for adapt api and fluentd config
severityMap := map[string]string{
"warning": "warn",
}
wrapSeverity := severityMap[severity]
if wrapSeverity == "" {
return severity
}
return wrapSeverity
}