forked from gallir/smart-relayer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
251 lines (218 loc) · 5.23 KB
/
main.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
package redis2
import (
"errors"
"log"
"net"
"sync"
"time"
"github.com/gallir/radix.improved/redis"
"github.com/gallir/smart-relayer/lib"
)
// Server is the thread that listen for clients' connections
type Server struct {
sync.Mutex
config lib.RelayerConfig
pool *Pool
mode int
done chan bool
exiting bool
listener net.Listener
}
const (
connectionRetries = 3
requestBufferSize = 1024
listenTimeout = 0 * time.Second // Don't timeout on local clients
connectTimeout = 5 * time.Second
maxIdle = 120 * time.Second
selectCommand = "SELECT"
)
var (
errBadCmd = errors.New("ERR bad command")
errKO = errors.New("fatal error")
errOverloaded = errors.New("Redis overloaded")
respOK = redis.NewRespSimple("OK")
respTrue = redis.NewResp(1)
respBadCommand = redis.NewResp(errBadCmd)
respKO = redis.NewResp(errKO)
commands map[string]*redis.Resp
)
func init() {
// These are the commands that can be sent in "background" when in smart mode
// The values are the immediate responses to the clients
commands = map[string]*redis.Resp{
"SET": respOK,
"SETEX": respOK,
"PSETEX": respOK,
"MSET": respOK,
"HMSET": respOK,
"SELECT": respOK,
"HSET": respTrue,
"SADD": respTrue,
"ZADD": respTrue,
"EXPIRE": respTrue,
"EXPIREAT": respTrue,
"PEXPIRE": respTrue,
"PEXPIREAT": respTrue,
}
}
// New creates a new Redis local server
func New(c lib.RelayerConfig, done chan bool) (*Server, error) {
srv := &Server{
done: done,
}
srv.Reload(&c)
return srv, nil
}
// Start accepts incoming connections on the Listener
func (srv *Server) Start() (e error) {
srv.Lock()
defer srv.Unlock()
srv.listener, e = lib.NewListener(srv.config)
if e != nil {
return e
}
// Serve clients
go func(l net.Listener) {
defer srv.listener.Close()
for {
netConn, e := l.Accept()
if e != nil {
if netErr, ok := e.(net.Error); ok && netErr.Timeout() {
// Paranoid, ignore timeout errors
log.Println("Timeout at local listener", srv.config.ListenHost(), e)
continue
}
if srv.exiting {
log.Println("Exiting local listener", srv.config.ListenHost())
return
}
log.Fatalln("Emergency error in local listener", srv.config.ListenHost(), e)
return
}
go srv.handleConnection(netConn)
}
}(srv.listener)
return nil
}
// Reload the configuration
func (srv *Server) Reload(c *lib.RelayerConfig) error {
srv.Lock()
defer srv.Unlock()
reset := false
if srv.config.URL != c.URL {
reset = true
}
srv.config = *c
srv.mode = c.Type()
if reset {
if srv.pool != nil {
log.Printf("Reset redis server at port %s for target %s", srv.config.Listen, srv.config.Host())
srv.pool.Reset()
}
srv.pool = NewPool(c)
} else {
log.Printf("Reload redis config at port %s for target %s", srv.config.Listen, srv.config.Host())
srv.pool.ReadConfig(c)
}
return nil
}
// Exit closes the listener and send done to main
func (srv *Server) Exit() {
srv.exiting = true
if srv.listener != nil {
srv.listener.Close()
}
srv.done <- true
}
func (srv *Server) handleConnection(netCon net.Conn) {
defer netCon.Close()
reader := redis.NewRespReader(netCon)
client := srv.pool.Get()
defer srv.pool.Put(client)
responseCh := make(chan *redis.Resp, 1)
defer close(responseCh)
currentDB := 0
for {
r := reader.Read()
if r.IsType(redis.IOErr) {
if redis.IsTimeout(r) {
// Paranoid, don't close it just log it
log.Println("Local client listen timeout at", srv.config.Listen)
continue
}
// Connection was closed
return
}
req := lib.NewRequest(r, &srv.config)
if req == nil {
respBadCommand.WriteTo(netCon)
continue
}
if req.Database != lib.UnknownDB && req.Database != currentDB {
currentDB = req.Database
}
req.Database = currentDB
// Smart mode, answer immediately and forget
if srv.mode == lib.ModeSmart {
fastResponse, ok := commands[req.Command]
if ok {
e := client.send(req)
if e != nil {
redis.NewResp(e).WriteTo(netCon)
continue
}
fastResponse.WriteTo(netCon)
continue
}
}
// Synchronized mode
req.ResponseChannel = responseCh
e := client.send(req)
if e != nil {
redis.NewResp(e).WriteTo(netCon)
continue
}
response, more := <-responseCh
if !more {
// The client has closed the channel
lib.Debugf("Redis client has closed channel, exiting")
return
}
response.WriteTo(netCon)
}
}
func sendRequest(c chan *lib.Request, r *lib.Request) (ok bool) {
defer func() {
e := recover() // To avoid panic due to closed channels
if e != nil {
log.Printf("sendRequest: Recovered from error %s, channel length %d", e, len(c))
ok = false
}
}()
if c == nil {
lib.Debugf("Nil channel in send request")
return false
}
c <- r
return true
}
func sendAsyncResponse(c chan *redis.Resp, r *redis.Resp) (ok bool) {
defer func() {
e := recover() // To avoid panic due to closed channels
if e != nil {
log.Printf("AsyncResponseyncRequest: Recovered from error %s, channel length %d", e, len(c))
ok = false
}
}()
if c == nil {
return
}
select {
case c <- r:
ok = true
default:
lib.Debugf("Error sending response to channel length %d", len(c))
ok = false
}
return
}