forked from elastic/beats
-
Notifications
You must be signed in to change notification settings - Fork 0
/
check.go
102 lines (89 loc) · 1.88 KB
/
check.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
package tcp
import (
"bytes"
"errors"
"net"
)
type ConnCheck func(net.Conn) error
var (
errNoDataReceived = errors.New("no data")
errRecvMismatch = errors.New("received string mismatch")
)
func (c ConnCheck) Validate(conn net.Conn) error {
return c(conn)
}
func makeValidateConn(config *Config) ConnCheck {
send := config.SendString
recv := config.ReceiveString
switch {
case send == "" && recv == "":
return nil
case send != "" && recv == "":
return checkAll(checkSend([]byte(send)), checkRecvAny)
case send == "" && recv != "":
return checkRecv([]byte(recv))
default: // send != "" && recv != "":
return checkAll(checkSend([]byte(send)), checkRecv([]byte(recv)))
}
}
func checkOk(_ net.Conn) error { return nil }
func checkAll(checks ...ConnCheck) ConnCheck {
return func(conn net.Conn) error {
for _, check := range checks {
if err := check(conn); err != nil {
return err
}
}
return nil
}
}
func checkSend(buf []byte) ConnCheck {
return func(conn net.Conn) error {
return sendBuffer(conn, buf)
}
}
func checkRecv(expected []byte) ConnCheck {
return func(conn net.Conn) error {
buf := make([]byte, len(expected))
if err := recvBuffer(conn, buf); err != nil {
return err
}
if !bytes.Equal(expected, buf) {
// TODO: report received value and expected value in event
return errRecvMismatch
}
return nil
}
}
func checkRecvAny(conn net.Conn) error {
// receive 'anything'
var buf [1024]byte
n, err := conn.Read(buf[:])
if err != nil {
return err
}
if n == 0 {
return errNoDataReceived
}
return nil
}
func sendBuffer(conn net.Conn, buf []byte) error {
for len(buf) > 0 {
n, err := conn.Write(buf)
if err != nil {
return err
}
buf = buf[n:]
}
return nil
}
func recvBuffer(conn net.Conn, buf []byte) error {
for len(buf) > 0 {
n, err := conn.Read(buf)
if err != nil {
return err
}
buf = buf[n:]
}
return nil
}