forked from rainycape/memcache
-
Notifications
You must be signed in to change notification settings - Fork 0
/
memcache.go
409 lines (366 loc) · 10.4 KB
/
memcache.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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
// Package memcache provides a client for the memcached cache server.
package memcache
import (
"bytes"
"errors"
"net"
"sync"
)
func legalKey(key string) bool {
if len(key) > 250 {
return false
}
for i := 0; i < len(key); i++ {
if key[i] <= ' ' || key[i] > 0x7e {
return false
}
}
return true
}
// New returns a memcache client using the provided server(s)
// with equal weight. If a server is listed multiple times,
// it gets a proportional amount of weight.
func New(config []Config) (*Client, error) {
servers, err := NewServerList(config)
if err != nil {
return nil, err
}
return NewFromServers(servers), nil
}
// NewFromServers returns a new Client using the provided Servers.
func NewFromServers(servers *ServerList) *Client {
return &Client{
servers: servers,
}
}
// Client is a memcache client.
// It is safe for unlocked use by multiple concurrent goroutines.
type Client struct {
mu sync.Mutex
servers *ServerList
}
// Close closes all currently open connections.
func (c *Client) Close() {
c.mu.Lock()
c.servers.Release()
c.mu.Unlock()
}
func (c *Client) getConnection(index uint32) (net.Conn, error) {
c.mu.Lock()
defer c.mu.Unlock()
return c.servers.GetConnection(index)
}
func (c *Client) putConnection(index uint32, conn net.Conn) error {
c.mu.Lock()
defer c.mu.Unlock()
return c.servers.PutConnection(index, conn)
}
func (c *Client) closeConnection(index uint32, conn net.Conn) error {
c.mu.Lock()
defer c.mu.Unlock()
return c.servers.CloseConnection(index, conn)
}
// Item is an item to be got or stored in a memcached server.
type Item struct {
// Key is the Item's key (250 bytes maximum).
Key string
// Value is the Item's value.
Value []byte
// Flags are server-opaque flags whose semantics are entirely
// up to the app.
Flags uint32
// Expiration is the cache expiration time, in seconds: either a relative
// time from now (up to 1 month), or an absolute Unix epoch time.
// Zero means the Item has no expiration time.
Expiration int32
// Compare and swap ID.
casid uint64
}
// Get gets the item for the given key. ErrCacheMiss is returned for a
// memcache cache miss. The key must be at most 250 bytes in length.
func (c *Client) Get(key string) (*Item, error) {
serverIndex, err := c.servers.PickServerIndex(key)
if err != nil {
return nil, err
}
cn, err := c.getConnection(serverIndex)
if err != nil {
return nil, err
}
err = sendConnCommand(cn, key, cmdGet, nil, 0, nil)
if err != nil {
_ = c.closeConnection(serverIndex, cn)
return nil, err
}
hdr, k, extras, value, err := parseResponse(key, cn)
switch err {
case nil, ErrCacheMiss, ErrCASConflict, ErrNotStored, ErrBadIncrDec:
_ = c.putConnection(serverIndex, cn)
default:
_ = c.closeConnection(serverIndex, cn)
}
if err != nil {
return nil, err
}
var flags uint32
if len(extras) > 0 {
flags = bUint32(extras)
}
if key == "" && len(k) > 0 {
key = string(k)
}
return &Item{
Key: key,
Value: value,
Flags: flags,
casid: bUint64(hdr[16:24]),
}, nil
}
// GetMulti is a batch version of Get. The returned map from keys to
// items may have fewer elements than the input slice, due to memcache
// cache misses. Each key must be at most 250 bytes in length.
// If no error is returned, the returned map will also be non-nil.
func (c *Client) GetMulti(keys []string) (map[string]*Item, error) {
keyMap := make(map[uint32][]string)
for _, key := range keys {
serverIndex, err := c.servers.PickServerIndex(key)
if err != nil {
return nil, err
}
keyMap[serverIndex] = append(keyMap[serverIndex], key)
}
mu := sync.Mutex{}
items := make(map[string]*Item)
wg := sync.WaitGroup{}
wg.Add(len(keyMap))
for addr, keys := range keyMap {
go func(serverIndex uint32, keys []string) {
defer wg.Done()
cn, err := c.servers.GetConnection(serverIndex)
if err != nil {
return
}
for _, k := range keys {
if err = sendConnCommand(cn, k, cmdGetKQ, nil, 0, nil); err != nil {
switch err {
case nil, ErrCacheMiss, ErrCASConflict, ErrNotStored, ErrBadIncrDec:
_ = c.putConnection(serverIndex, cn)
default:
_ = c.closeConnection(serverIndex, cn)
}
return
}
}
if err = sendConnCommand(cn, "", cmdNoop, nil, 0, nil); err != nil {
switch err {
case nil, ErrCacheMiss, ErrCASConflict, ErrNotStored, ErrBadIncrDec:
_ = c.putConnection(serverIndex, cn)
default:
_ = c.closeConnection(serverIndex, cn)
}
return
}
for {
hdr, k, extras, value, err := parseResponse("", cn)
if err != nil {
break
}
if len(k) == 0 {
break
}
var flags uint32
if len(extras) > 0 {
flags = bUint32(extras)
}
mu.Lock()
items[string(k)] = &Item{
Key: string(k),
Value: value,
Flags: flags,
casid: bUint64(hdr[16:24]),
}
mu.Unlock()
}
switch err {
case nil, ErrCacheMiss, ErrCASConflict, ErrNotStored, ErrBadIncrDec:
_ = c.putConnection(serverIndex, cn)
default:
_ = c.closeConnection(serverIndex, cn)
}
}(addr, keys)
}
wg.Wait()
return items, nil
}
// Set writes the given item, unconditionally.
func (c *Client) Set(item *Item) error {
return c.populateOne(cmdSet, item, 0)
}
// Add writes the given item, if no value already exists for its
// key. ErrNotStored is returned if that condition is not met.
func (c *Client) Add(item *Item) error {
return c.populateOne(cmdAdd, item, 0)
}
// CompareAndSwap writes the given item that was previously returned
// by Get, if the value was neither modified or evicted between the
// Get and the CompareAndSwap calls. The item's Key should not change
// between calls but all other item fields may differ. ErrCASConflict
// is returned if the value was modified in between the
// calls. ErrNotStored is returned if the value was evicted in between
// the calls.
func (c *Client) CompareAndSwap(item *Item) error {
return c.populateOne(cmdSet, item, item.casid)
}
func (c *Client) populateOne(cmd command, item *Item, casid uint64) error {
extras := make([]byte, 8)
putUint32(extras, item.Flags)
putUint32(extras[4:8], uint32(item.Expiration))
serverIndex, err := c.servers.PickServerIndex(item.Key)
if err != nil {
return err
}
cn, err := c.getConnection(serverIndex)
if err != nil {
return err
}
err = sendConnCommand(cn, item.Key, cmd, item.Value, casid, extras)
if err != nil {
_ = c.closeConnection(serverIndex, cn)
return err
}
hdr, _, _, _, err := parseResponse(item.Key, cn)
switch err {
case nil, ErrCacheMiss, ErrCASConflict, ErrNotStored, ErrBadIncrDec:
_ = c.putConnection(serverIndex, cn)
default:
_ = c.closeConnection(serverIndex, cn)
return err
}
item.casid = bUint64(hdr[16:24])
return nil
}
// Delete deletes the item with the provided key. The error ErrCacheMiss is
// returned if the item didn't already exist in the cache.
func (c *Client) Delete(key string) error {
serverIndex, err := c.servers.PickServerIndex(key)
if err != nil {
return err
}
cn, err := c.getConnection(serverIndex)
if err != nil {
return err
}
err = sendConnCommand(cn, key, cmdDelete, nil, 0, nil)
if err != nil {
_ = c.closeConnection(serverIndex, cn)
return err
}
if err != nil {
return err
}
_, _, _, _, err = parseResponse(key, cn)
switch err {
case nil, ErrCacheMiss, ErrCASConflict, ErrNotStored, ErrBadIncrDec:
_ = c.putConnection(serverIndex, cn)
default:
_ = c.closeConnection(serverIndex, cn)
}
return err
}
// Increment atomically increments key by delta. The return value is
// the new value after being incremented or an error. If the value
// didn't exist in memcached the error is ErrCacheMiss. The value in
// memcached must be an decimal number, or an error will be returned.
// On 64-bit overflow, the new value wraps around.
func (c *Client) Increment(key string, delta uint64) (newValue uint64, err error) {
return c.incrDecr(cmdIncr, key, delta)
}
// Decrement atomically decrements key by delta. The return value is
// the new value after being decremented or an error. If the value
// didn't exist in memcached the error is ErrCacheMiss. The value in
// memcached must be an decimal number, or an error will be returned.
// On underflow, the new value is capped at zero and does not wrap
// around.
func (c *Client) Decrement(key string, delta uint64) (newValue uint64, err error) {
return c.incrDecr(cmdDecr, key, delta)
}
func (c *Client) incrDecr(cmd command, key string, delta uint64) (uint64, error) {
extras := make([]byte, 20)
putUint64(extras, delta)
// Set expiration to 0xfffffff, so the command fails if the key
// does not exist.
for ii := 16; ii < 20; ii++ {
extras[ii] = 0xff
}
serverIndex, err := c.servers.PickServerIndex(key)
if err != nil {
return 0, err
}
cn, err := c.getConnection(serverIndex)
if err != nil {
return 0, err
}
err = sendConnCommand(cn, key, cmd, nil, 0, extras)
if err != nil {
_ = c.closeConnection(serverIndex, cn)
return 0, err
}
_, _, _, value, err := parseResponse(key, cn)
switch err {
case nil, ErrCacheMiss, ErrCASConflict, ErrNotStored, ErrBadIncrDec:
_ = c.putConnection(serverIndex, cn)
default:
_ = c.closeConnection(serverIndex, cn)
}
if err != nil {
return 0, err
}
return bUint64(value), nil
}
// Flush removes all the items in the cache after expiration seconds. If
// expiration is <= 0, it removes all the items right now.
func (c *Client) Flush(expiration int) error {
var failed []string
var errs []error
var extras []byte
if expiration > 0 {
extras = make([]byte, 4)
putUint32(extras, uint32(expiration))
}
for serverIndex := uint32(0); serverIndex < c.servers.PoolLen(); serverIndex++ {
connection, err := c.getConnection(serverIndex)
if err != nil {
failed = append(failed, c.servers.Name(serverIndex))
errs = append(errs, err)
continue
}
cn := connection.(net.Conn)
if err = sendConnCommand(cn, "", cmdFlush, nil, 0, extras); err == nil {
_, _, _, _, err = parseResponse("", cn)
}
if err != nil {
failed = append(failed, c.servers.Name(serverIndex))
errs = append(errs, err)
}
switch err {
case nil, ErrCacheMiss, ErrCASConflict, ErrNotStored, ErrBadIncrDec:
_ = c.putConnection(serverIndex, cn)
default:
_ = c.closeConnection(serverIndex, cn)
}
}
if len(failed) > 0 {
var buf bytes.Buffer
buf.WriteString("failed to flush some servers: ")
for ii, addr := range failed {
if ii > 0 {
buf.WriteString(", ")
}
buf.WriteString(addr)
buf.WriteString(": ")
buf.WriteString(errs[ii].Error())
}
return errors.New(buf.String())
}
return nil
}