-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathclient.go
296 lines (260 loc) · 7.36 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
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
package redis
import (
"fmt"
"os"
"strconv"
"strings"
"time"
"github.com/garyburd/redigo/redis"
"github.com/kelseyhightower/confd/log"
)
type watchResponse struct {
waitIndex uint64
err error
}
// Client is a wrapper around the redis client
type Client struct {
client redis.Conn
machines []string
password string
separator string
psc redis.PubSubConn
pscChan chan watchResponse
}
// Iterate through `machines`, trying to connect to each in turn.
// Returns the first successful connection or the last error encountered.
// Assumes that `machines` is non-empty.
func tryConnect(machines []string, password string, timeout bool) (redis.Conn, int, error) {
var err error
for _, address := range machines {
var conn redis.Conn
var db int
idx := strings.Index(address, "/")
if idx != -1 {
// a database is provided
db, err = strconv.Atoi(address[idx+1:])
if err == nil {
address = address[:idx]
}
}
network := "tcp"
if _, err = os.Stat(address); err == nil {
network = "unix"
}
log.Debug(fmt.Sprintf("Trying to connect to redis node %s", address))
var dialops []redis.DialOption
if timeout {
dialops = []redis.DialOption{
redis.DialConnectTimeout(time.Second),
redis.DialReadTimeout(time.Second),
redis.DialWriteTimeout(time.Second),
redis.DialDatabase(db),
}
} else {
dialops = []redis.DialOption{
redis.DialConnectTimeout(time.Second),
redis.DialWriteTimeout(time.Second),
redis.DialDatabase(db),
}
}
if password != "" {
dialops = append(dialops, redis.DialPassword(password))
}
conn, err = redis.Dial(network, address, dialops...)
if err != nil {
continue
}
return conn, db, nil
}
return nil, 0, err
}
// Retrieves a connected redis client from the client wrapper.
// Existing connections will be tested with a PING command before being returned. Tries to reconnect once if necessary.
// Returns the established redis connection or the error encountered.
func (c *Client) connectedClient() (redis.Conn, error) {
if c.client != nil {
log.Debug("Testing existing redis connection.")
resp, err := c.client.Do("PING")
if (err != nil && err == redis.ErrNil) || resp != "PONG" {
log.Error(fmt.Sprintf("Existing redis connection no longer usable. "+
"Will try to re-establish. Error: %s", err.Error()))
c.client = nil
}
}
// Existing client could have been deleted by previous block
if c.client == nil {
var err error
c.client, _, err = tryConnect(c.machines, c.password, true)
if err != nil {
return nil, err
}
}
return c.client, nil
}
// NewRedisClient returns an *redis.Client with a connection to named machines.
// It returns an error if a connection to the cluster cannot be made.
func NewRedisClient(machines []string, password string, separator string) (*Client, error) {
if separator == "" {
separator = "/"
}
log.Debug(fmt.Sprintf("Redis Separator: %#v", separator))
var err error
clientWrapper := &Client{machines: machines, password: password, separator: separator, client: nil, pscChan: make(chan watchResponse), psc: redis.PubSubConn{Conn: nil} }
clientWrapper.client, _, err = tryConnect(machines, password, true)
return clientWrapper, err
}
func (c *Client) transform(key string) string {
if c.separator == "/" {
return key;
}
k := strings.TrimPrefix(key, "/")
return strings.Replace(k, "/", c.separator, -1);
}
func (c *Client) clean(key string) string {
k := key
if !strings.HasPrefix(k, "/") {
k = "/" + k
}
return strings.Replace(k, c.separator, "/", -1);
}
// GetValues queries redis for keys prefixed by prefix.
func (c *Client) GetValues(keys []string) (map[string]string, error) {
// Ensure we have a connected redis client
rClient, err := c.connectedClient()
if err != nil && err != redis.ErrNil {
return nil, err
}
vars := make(map[string]string)
for _, key := range keys {
key = strings.Replace(key, "/*", "", -1)
k := c.transform(key)
t, err := redis.String(rClient.Do("TYPE", k))
if err == nil && err != redis.ErrNil {
if t == "string" {
value, err := redis.String(rClient.Do("GET", k))
if err == nil {
vars[key] = value
continue
}
if err != redis.ErrNil {
return vars, err
}
} else if t == "hash" {
idx := 0
for {
values, err := redis.Values(rClient.Do("HSCAN", k, idx, "MATCH", "*", "COUNT", "1000"))
if err != nil && err != redis.ErrNil {
return vars, err
}
idx, _ = redis.Int(values[0], nil)
items, _ := redis.Strings(values[1], nil)
for i := 0; i < len(items); i+=2 {
var newKey, value string
if newKey, err = redis.String(items[i], nil); err != nil {
return vars, err
}
if value, err = redis.String(items[i+1], nil); err != nil {
return vars, err
}
vars[c.clean(k + "/" + newKey)] = value
}
if idx == 0 {
break
}
}
} else {
if key == "/" {
k = "*"
} else {
k = fmt.Sprintf(c.transform("%s/*"), k)
}
idx := 0
for {
values, err := redis.Values(rClient.Do("SCAN", idx, "MATCH", k, "COUNT", "1000"))
if err != nil && err != redis.ErrNil {
return vars, err
}
idx, _ = redis.Int(values[0], nil)
items, _ := redis.Strings(values[1], nil)
for _, item := range items {
var newKey string
if newKey, err = redis.String(item, nil); err != nil {
return vars, err
}
if value, err := redis.String(rClient.Do("GET", newKey)); err == nil {
vars[c.clean(newKey)] = value
}
}
if idx == 0 {
break
}
}
}
} else {
return vars, err
}
}
log.Debug(fmt.Sprintf("Key Map: %#v", vars))
return vars, nil
}
func (c *Client) WatchPrefix(prefix string, keys []string, waitIndex uint64, stopChan chan bool) (uint64, error) {
if waitIndex == 0 {
return 1, nil
}
if len(c.pscChan) > 0 {
var respChan watchResponse
for len(c.pscChan) > 0 {
respChan = <-c.pscChan
}
return respChan.waitIndex, respChan.err
}
go func() {
if c.psc.Conn == nil {
rClient, db, err := tryConnect(c.machines, c.password, false);
if err != nil {
c.psc = redis.PubSubConn{Conn: nil}
c.pscChan <- watchResponse{0, err}
return
}
c.psc = redis.PubSubConn{Conn: rClient}
go func() {
defer func() {
c.psc.Close()
c.psc = redis.PubSubConn{Conn: nil}
}()
for {
switch n := c.psc.Receive().(type) {
case redis.PMessage:
log.Debug(fmt.Sprintf("Redis Message: %s %s\n", n.Channel, n.Data))
data := string(n.Data)
commands := [12]string{"del", "append", "rename_from", "rename_to", "expire", "set", "incrby", "incrbyfloat", "hset", "hincrby", "hincrbyfloat", "hdel"}
for _, command := range commands {
if command == data {
c.pscChan <- watchResponse{1, nil}
break
}
}
case redis.Subscription:
log.Debug(fmt.Sprintf("Redis Subscription: %s %s %d\n", n.Kind, n.Channel, n.Count))
if n.Count == 0 {
c.pscChan <- watchResponse{0, nil}
return
}
case error:
log.Debug(fmt.Sprintf("Redis error: %v\n", n))
c.pscChan <- watchResponse{0, n}
return
}
}
}()
c.psc.PSubscribe("__keyspace@" + strconv.Itoa(db) + "__:" + c.transform(prefix) + "*")
}
}()
select {
case <-stopChan:
c.psc.PUnsubscribe()
return waitIndex, nil
case r := <- c.pscChan:
return r.waitIndex, r.err
}
}