/
common.go
283 lines (242 loc) · 5.61 KB
/
common.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
package proxy
import (
"bytes"
"errors"
"fmt"
"github.com/sirupsen/logrus"
"io"
"net"
"sync"
"time"
)
type DeadlineReadWriteCloser interface {
io.ReadWriteCloser
SetWriteDeadline(t time.Time) error
SetReadDeadline(t time.Time) error
SetDeadline(t time.Time) error
}
type DeadlineWriter interface {
io.Writer
SetWriteDeadline(t time.Time) error
}
type DeadlineReader interface {
io.Reader
SetReadDeadline(t time.Time) error
}
type DeadlineReaderWriter interface {
DeadlineReader
DeadlineWriter
SetDeadline(t time.Time) error
}
// myCopy is similar to io.Copy, but reports whether the returned error was due
// to a bad read or write. The returned error will never be nil
func myCopy(dst io.Writer, src io.Reader) (readErr bool, err error) {
buf := make([]byte, 4096)
for {
n, err := src.Read(buf)
if n > 0 {
if _, werr := dst.Write(buf[:n]); werr != nil {
if err == nil {
return false, werr
}
// Read and write error; just report read error (it happened first).
return true, err
}
}
if err != nil {
return true, err
}
}
}
// myCopyN is similar to io.CopyN, but reports whether the returned error was due
// to a bad read or write. The returned error will never be nil
func myCopyN(dst io.Writer, src io.Reader, size int64, buf []byte) (readErr bool, err error) {
// limit reader - EOF when finished
src = io.LimitReader(src, size)
var written int64
var n int
for {
n, err = src.Read(buf)
if n > 0 {
nw, werr := dst.Write(buf[0:n])
if nw > 0 {
written += int64(nw)
}
if err != nil {
// Read and write error; just report read error (it happened first).
readErr = true
break
}
if werr != nil {
err = werr
break
}
if n != nw {
err = io.ErrShortWrite
break
}
}
if err != nil {
readErr = true
break
}
}
if written == size {
return false, nil
}
if written < size && err == nil {
// src stopped early; must have been EOF.
readErr = true
err = io.EOF
}
return
}
func copyError(readDesc, writeDesc string, readErr bool, err error) {
var desc string
if readErr {
desc = "Reading data from " + readDesc
} else {
desc = "Writing data to " + writeDesc
}
logrus.Infof("%v had error: %s", desc, err.Error())
}
func copyThenClose(cfg ProcessorConfig, remote, local DeadlineReadWriteCloser, brokerAddress string, remoteDesc, localDesc string) {
processor := newProcessor(cfg, brokerAddress)
firstErr := make(chan error, 1)
go withRecover(func() {
readErr, err := processor.RequestsLoop(remote, local)
select {
case firstErr <- err:
if readErr && err == io.EOF {
logrus.Infof("Client closed %v", localDesc)
} else {
copyError(localDesc, remoteDesc, readErr, err)
}
remote.Close()
local.Close()
default:
}
})
readErr, err := processor.ResponsesLoop(local, remote)
select {
case firstErr <- err:
if readErr && err == io.EOF {
logrus.Infof("Server %v closed connection", remoteDesc)
} else {
copyError(remoteDesc, localDesc, readErr, err)
}
remote.Close()
local.Close()
default:
// In this case, the other goroutine exited first and already printed its
// error (and closed the things).
}
}
// NewConnSet initializes a new ConnSet and returns it.
func NewConnSet() *ConnSet {
return &ConnSet{m: make(map[string][]net.Conn)}
}
// A ConnSet tracks net.Conns associated with a provided ID.
type ConnSet struct {
sync.RWMutex
m map[string][]net.Conn
}
// String returns a debug string for the ConnSet.
func (c *ConnSet) String() string {
var b bytes.Buffer
c.RLock()
for id, conns := range c.m {
fmt.Fprintf(&b, "ID %s:", id)
for i, c := range conns {
fmt.Fprintf(&b, "\n\t%d: %v", i, c)
}
}
c.RUnlock()
return b.String()
}
// Add saves the provided conn and associates it with the given string
// identifier.
func (c *ConnSet) Add(id string, conn net.Conn) {
c.Lock()
c.m[id] = append(c.m[id], conn)
c.Unlock()
}
// IDs returns a slice of all identifiers which still have active connections.
func (c *ConnSet) IDs() []string {
ret := make([]string, 0, len(c.m))
c.RLock()
for k := range c.m {
ret = append(ret, k)
}
c.RUnlock()
return ret
}
// Conns returns all active connections associated with the provided ids.
func (c *ConnSet) Conns(ids ...string) []net.Conn {
var ret []net.Conn
c.RLock()
for _, id := range ids {
ret = append(ret, c.m[id]...)
}
c.RUnlock()
return ret
}
// Count returns number of connection pro identifier
func (c *ConnSet) Count() map[string]int {
ret := make(map[string]int)
c.RLock()
for k, v := range c.m {
ret[k] = len(v)
}
c.RUnlock()
return ret
}
// brokerToCount := make(map[string]int)
// Remove undoes an Add operation to have the set forget about a conn. Do not
// Remove an id/conn pair more than it has been Added.
func (c *ConnSet) Remove(id string, conn net.Conn) error {
c.Lock()
defer c.Unlock()
pos := -1
conns := c.m[id]
for i, cc := range conns {
if cc == conn {
pos = i
break
}
}
if pos == -1 {
return fmt.Errorf("couldn't find connection %v for id %s", conn, id)
}
if len(conns) == 1 {
delete(c.m, id)
} else {
c.m[id] = append(conns[:pos], conns[pos+1:]...)
}
return nil
}
// Close closes every net.Conn contained in the set.
func (c *ConnSet) Close() error {
var errs bytes.Buffer
c.Lock()
for id, conns := range c.m {
for _, c := range conns {
if err := c.Close(); err != nil {
fmt.Fprintf(&errs, "%s close error: %v\n", id, err)
}
}
}
c.Unlock()
if errs.Len() == 0 {
return nil
}
return errors.New(errs.String())
}
func withRecover(fn func()) {
defer func() {
if err := recover(); err != nil {
logrus.Errorf("Recovered from %v", err)
}
}()
fn()
}