forked from stith/gorelp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrelp.go
334 lines (276 loc) · 6.98 KB
/
relp.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
package relp
import (
"bufio"
"fmt"
"io"
"log"
"math"
"math/rand"
"net"
"strconv"
"strings"
"sync"
"time"
"github.com/pkg/errors"
)
const relpVersion = 0
const relpSoftware = "gorelp,0.2.0,https://github.com/stith/gorelp"
// Message - A single RELP message
type Message struct {
// The transaction ID that the message was sent in
Txn int
// The command that was run. Will be "syslog" pretty much always under normal
// operation
Command string
// The actual message data
Data string
// true if the message has been acked
Acked bool
// Used internally for acking.
sourceConnection io.ReadWriteCloser
}
type ClientEvent interface {
Event() string
Message() string
Error() error
}
type Stats struct {
sent int64
received int64
errors int
acked int64
}
// Client - A client to a RELP server
type Client struct {
Id string
// connection net.Conn
connection io.ReadWriteCloser
reader *bufio.Reader
writer *bufio.Writer
windowSize int
window Window
nextTxn int
eventChan chan ClientEvent
mutex *sync.Mutex
Error error
Closed bool
stats Stats
}
func readMessage(reader *bufio.Reader) (message Message, err error) {
txn, err := reader.ReadString(' ')
if err == io.EOF {
// A graceful EOF means the client closed the connection. Hooray!
fmt.Println("Done!")
return
} else if err != nil && strings.HasSuffix(err.Error(), "connection reset by peer") {
fmt.Println("Client rudely disconnected, but that's fine.")
return
} else if err != nil {
log.Println("Error reading txn:", err, txn)
return
}
message.Txn, _ = strconv.Atoi(strings.TrimSpace(txn))
cmd, err := reader.ReadString(' ')
if err != nil {
log.Println("Error reading cmd:", err)
return
}
message.Command = strings.TrimSpace(cmd)
// Check for dataLen == 0
peekLen, err := reader.Peek(1)
message.Data = ""
if string(peekLen[:]) != "0" {
dataLenS, err := reader.ReadString(' ')
if err != nil {
log.Println("Error reading dataLen:", err)
return message, err
}
dataLen, err := strconv.Atoi(strings.TrimSpace(dataLenS))
if err != nil {
log.Println("Error converting dataLenS to int:", err)
return message, err
}
dataBytes := make([]byte, dataLen)
_, err = io.ReadFull(reader, dataBytes)
if err != nil {
log.Println("Error reading message:", err)
return message, err
}
message.Data = string(dataBytes[:dataLen])
}
return message, err
}
// NewClient - Starts a new RELP client
func NewClient(host string, port int, windowSize int, eventChan chan ClientEvent) (Client, error) {
connection, err := net.Dial("tcp", fmt.Sprintf("%s:%d", host, port))
if err != nil {
return Client{}, err
}
return NewClientFrom(connection, windowSize, eventChan)
}
// NewClientFrom creates a RelpClient from a ReadWriteCloser (i.e. TCP or TLS connection)
func NewClientFrom(rwc io.ReadWriteCloser, windowSize int, eventChan chan ClientEvent) (client Client, err error) {
client.Id = fmt.Sprintf("%v", uint64(math.Abs(float64(rand.Int63()))))
client.connection = rwc
client.eventChan = eventChan
client.mutex = &sync.Mutex{}
client.reader = bufio.NewReaderSize(rwc, 512*1024)
client.writer = bufio.NewWriterSize(rwc, 2*1024*1024)
offer := Message{
Txn: 1,
Command: "open",
Data: fmt.Sprintf("relp_version=%d\nrelp_software=%s\ncommands=syslog", relpVersion, relpSoftware),
}
offer.send(client.writer)
client.writer.Flush()
offerResponse, err := readMessage(client.reader)
if err != nil {
return client, err
}
responseParts := strings.Split(offerResponse.Data, "\n")
if !strings.HasPrefix(responseParts[0], "200 OK") {
err = fmt.Errorf("server responded to offer with: %s", responseParts[0])
} else {
err = nil
}
client.nextTxn = 2
// TODO: Parse the server's info/commands into the Client object
client.windowSize = windowSize
client.window = NewArrayWindow(windowSize)
go client.Reader()
return client, err
}
// Send - Sends a message
func (m Message) send(out io.Writer) (nn int, err error) {
outLength := len([]byte(m.Data))
outString := fmt.Sprintf("%d %s %d %s\n", m.Txn, m.Command, outLength, m.Data)
return out.Write([]byte(outString))
}
// SendString - Convenience method which constructs a Message and sends it
func (c *Client) SendString(msg string) (err error) {
message := Message{
Txn: c.nextTxn,
Command: "syslog",
Data: msg,
}
err = c.SendMessage(message)
return err
}
func (c *Client) Flush() error {
c.mutex.Lock()
defer c.mutex.Unlock()
return c.writer.Flush()
}
// SendMessage - Sends a message using the client's connection
func (c *Client) SendMessage(msg Message) (err error) {
c.mutex.Lock()
defer c.mutex.Unlock()
// return last error from reader thread
if c.Error != nil {
return c.Error
}
c.stats.sent++
c.nextTxn = c.nextTxn + 1
c.window.Add(Txn(msg.Txn))
_, err = msg.send(c.writer)
if err != nil {
c.notifyError(err)
c.Error = err
}
// TODO - magic number of messages remaining before we flush
if c.window.Remaining() < 10 {
c.writer.Flush()
}
return c.Error
}
// Outstanding returns the number of messages outstanding
func (c *Client) Outstanding() int {
return c.window.Outstanding()
}
// Drain waits for all outstanding messages to be acked
func (c *Client) Drain(timeout time.Duration) (err error) {
deadline := time.Now().Add(timeout)
for {
c.Flush()
if c.window.Outstanding() == 0 {
return nil
}
if timeout != 0 && time.Now().After(deadline) {
err = errors.New("drain() timed out")
c.notifyError(err)
}
time.Sleep(100 * time.Millisecond)
}
}
// Reader reader responses on the client connection and updates the protocol window
// Any errors encountered are sent on the eventChan
func (c *Client) Reader() {
for {
var err error
if c.Closed {
return
}
ack, err := readMessage(c.reader)
doClose := false
if err != nil {
log.Fatal("Failed to read response: ", err)
doClose = true
} else {
switch ack.Command {
case "rsp":
c.stats.acked++
c.window.Remove(Txn(ack.Txn))
case "serverclose":
log.Print("Received serverclose hint")
c.notifyClose()
doClose = true
default:
c.stats.errors++
err = errors.Errorf("Received non-rsp response from server (%v, %v, %v)\n", ack.Txn, ack.Command, ack.Data)
doClose = true
}
}
if err != nil {
c.Error = err
log.Fatal("Error in Reader event loop: ", err.Error())
c.notifyError(err)
}
if doClose {
c.Close()
return
}
}
}
func (c *Client) forceClose() {
c.mutex.Lock()
defer c.mutex.Unlock()
if c.Closed {
return
}
c.connection.Close()
c.Closed = true
c.notifyClose()
}
// Close - Closes the connection gracefully
func (c *Client) Close() (err error) {
c.mutex.Lock()
defer c.mutex.Unlock()
closeMessage := Message{
Txn: c.nextTxn,
Command: "close",
}
_, err = closeMessage.send(c.writer)
if err != nil {
c.notifyError(err)
}
c.writer.Flush()
if err != nil {
c.notifyError(err)
}
// force close in 5 seconds if the server doesn't handle it
go func() {
time.Sleep(5 * time.Second)
c.forceClose()
}()
return
}