-
Notifications
You must be signed in to change notification settings - Fork 12
/
client.go
234 lines (200 loc) · 7.47 KB
/
client.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
/*
* Copyright (c) 2015, Salesforce.com, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
* following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of conditions and the following
* disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided with the distribution.
*
* * Neither the name of Salesforce.com nor the names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package rmux
import (
"bytes"
"errors"
"github.com/salesforce/rmux/connection"
. "github.com/salesforce/rmux/log"
"github.com/salesforce/rmux/protocol"
. "github.com/salesforce/rmux/writer"
"io"
"net"
"time"
"github.com/salesforce/rmux/graphite"
)
type readItem struct {
command protocol.Command
err error
}
//Represents a redis client that is connected to our rmux server
type Client struct {
//The underlying ReadWriter for this connection
Writer *FlexibleWriter
//Whether or not this client needs to consider multiplexing
Multiplexing bool
Connection net.Conn
//The Database that our client thinks we're connected to
DatabaseId int
//Whether or not this client connection is active or not
//Upon QUIT command, this gets toggled off
Active bool
ReadChannel chan readItem
HashRing *connection.HashRing
queued []protocol.Command
Scanner *protocol.RespScanner
}
var (
ERR_QUIT = errors.New("Client asked to quit")
ERR_CONNECTION_DOWN = errors.New(string(CONNECTION_DOWN_RESPONSE))
ERR_TIMEOUT = errors.New("Proxy timeout")
)
//Initializes a new client, for the given established net connection, with the specified read/write timeouts
func NewClient(connection net.Conn, readTimeout, writeTimeout time.Duration, isMuliplexing bool, hashRing *connection.HashRing) (newClient *Client) {
newClient = &Client{}
newClient.Connection = connection
newClient.Writer = NewFlexibleWriter(connection)
newClient.Active = true
newClient.Multiplexing = isMuliplexing
newClient.ReadChannel = make(chan readItem, 10000)
newClient.queued = make([]protocol.Command, 0, 4)
newClient.HashRing = hashRing
newClient.DatabaseId = 0
newClient.Scanner = protocol.NewRespScanner(connection)
return
}
//Parses the given command
func (this *Client) ParseCommand(command protocol.Command) ([]byte, error) {
//block all unsafe commands
if !protocol.IsSupportedFunction(command.GetCommand(), this.Multiplexing, command.GetArgCount() > 2) {
return nil, protocol.ERR_COMMAND_UNSUPPORTED
}
if bytes.Equal(command.GetCommand(), protocol.PING_COMMAND) {
return protocol.PONG_RESPONSE, nil
}
if bytes.Equal(command.GetCommand(), protocol.QUIT_COMMAND) {
return nil, ERR_QUIT
}
if bytes.Equal(command.GetCommand(), protocol.SELECT_COMMAND) {
databaseId, err := protocol.ParseInt(command.GetFirstArg())
if err != nil {
return nil, protocol.ERR_BAD_ARGUMENTS
}
this.DatabaseId = databaseId
return protocol.OK_RESPONSE, nil
}
return nil, nil
}
func (this *Client) WriteError(err error, flush bool) error {
return protocol.WriteError([]byte(err.Error()), this.Writer, flush)
}
func (this *Client) FlushError(err error) error {
return this.WriteError(err, true)
}
func (this *Client) WriteLine(line []byte) (err error) {
return protocol.WriteLine(line, this.Writer, false)
}
func (this *Client) FlushLine(line []byte) (err error) {
return protocol.WriteLine(line, this.Writer, true)
}
// Performs the query against the redis server and responds to the connected client with the response from redis.
func (this *Client) FlushRedisAndRespond() error {
var err error
if !this.HasQueued() {
return this.Writer.Flush()
}
var connectionPool *connection.ConnectionPool
if !this.Multiplexing {
connectionPool = this.HashRing.DefaultConnectionPool
} else {
if len(this.queued) != 1 {
panic("Should not have multiple commands to flush when multiplexing")
}
connectionPool, err = this.HashRing.GetConnectionPool(this.queued[0])
if err != nil {
Error("Failed to retrieve a connection pool from the hashring")
this.ReadChannel <- readItem{nil, err}
return err
}
}
redisConn, err := connectionPool.GetConnection()
if err != nil {
Error("Failed to retrieve an active connection from the provided connection pool")
this.ReadChannel <- readItem{nil, ERR_CONNECTION_DOWN}
return ERR_CONNECTION_DOWN
}
defer connectionPool.RecycleRemoteConnection(redisConn)
if redisConn.DatabaseId != this.DatabaseId {
if err := redisConn.SelectDatabase(this.DatabaseId); err != nil {
// Disconnect the current connection if selecting failed, will auto-reconnect this connection holder when queried later
redisConn.Disconnect()
return err
}
}
numCommands := len(this.queued)
startWrite := time.Now()
for _, command := range this.queued {
_, err := redisConn.Writer.Write(command.GetBuffer())
if err != nil {
Error("Error when writing to server: %s. Disconnecting the connection.", err)
redisConn.Disconnect()
return err
}
}
this.resetQueued()
for redisConn.Writer.Buffered() > 0 {
err := redisConn.Writer.Flush()
if err != nil {
Error("Error when flushing to server: %s. Disconnecting the connection.", err)
redisConn.Disconnect()
return err
}
}
graphite.Timing("redis_write", time.Now().Sub(startWrite))
if err := protocol.CopyServerResponses(redisConn.Reader, this.Writer, numCommands); err != nil {
Error("Error when copying redis responses to client: %s. Disconnecting the connection.", err)
redisConn.Disconnect()
this.ReadChannel <- readItem{nil, err}
return err
}
this.Writer.Flush()
return nil
}
func (this *Client) HasBufferedOutput() bool {
return this.Writer.Buffered() > 0
}
// Read loop for this client - moves commands and channels to the worker loop
func (this *Client) ReadLoop(rmux *RedisMultiplexer) {
for rmux.active && this.Active && this.Scanner.Scan() {
bytes := this.Scanner.Bytes()
command, err := protocol.ParseCommand(bytes)
this.ReadChannel <- readItem{command, err}
}
if err := this.Scanner.Err(); err != nil {
this.ReadChannel <- readItem{nil, err}
} else {
this.ReadChannel <- readItem{nil, io.EOF}
}
}
func (this *Client) resetQueued() {
// We make a new one instead of using this.queued=this.queued[:0] so that the command arrays are eligible for GC
this.queued = make([]protocol.Command, 0, 4)
}
func (this *Client) HasQueued() bool {
return len(this.queued) > 0
}
func (this *Client) Queue(command protocol.Command) {
this.queued = append(this.queued, command)
}