-
Notifications
You must be signed in to change notification settings - Fork 2k
/
Copy pathMemcached.lua
executable file
·567 lines (457 loc) · 13.5 KB
/
Memcached.lua
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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
--Copyright (c) 2006-2008 Neil Richardson (nrich@iinet.net.au)
--
--Permission is hereby granted, free of charge, to any person obtaining a copy
--of this software and associated documentation files (the "Software"), to deal
--in the Software without restriction, including without limitation the rights
--to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
--copies of the Software, and to permit persons to whom the Software is
--furnished to do so, subject to the following conditions:
--
--The above copyright notice and this permission notice shall be included in all
--copies or substantial portions of the Software.
--
--THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
--IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
--FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
--AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
--LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
--OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
--IN THE SOFTWARE.
module('Memcached', package.seeall)
require('socket')
require('CRC32')
local SERVER_RETRIES = 10
local STATS_KEYS = {
malloc = true,
sizes = true,
slabs = true,
items = true,
}
local FLAGS = {
'STORABLE',
'COMPRESSED',
'SERIALISED',
}
local function warn(str)
io.stderr:write(string.format('Warning: %s\n', tostring(str)))
end
local function _select_server(cache, key)
local server_count = #cache.servers
local hashfunc = cache.hash or CRC32.Hash
if server_count == 1 then
return cache.servers[1].socket
else
local serverhash = hashfunc(key)
for i = 0, SERVER_RETRIES do
local index = (serverhash % server_count) + 1
local server = cache.servers[index].socket
if not server then
serverhash = hashfunc(serverhash .. i)
else
return server
end
end
end
error('No servers found')
return nil
end
local function _retrieve(cache, key, str)
local server = _select_server(cache, key)
server:send(str .. '\r\n')
local function toboolean(value)
if type(value) == 'string' then
if value == 'true' then
return true
elseif value == 'false' then
return false
end
end
return nil
end
local function extract_flags(str)
local num = tonumber(str)
local flags = {}
for i = table.maxn(FLAGS), 1, -1 do
local bf = 2 ^ (i - 1)
if num >= bf then
flags[FLAGS[i]] = true
num = num - bf
end
end
return flags
end
local returndata = {}
while true do
local line, err = server:receive()
if line == 'END' then
break
elseif string.sub(line, 1, 5) == 'VALUE' then
local key,flagstr,size,cas = string.match(line, 'VALUE (%S+) (%d+) (%d+)')
flags = extract_flags(flagstr)
local data = server:receive(size)
if flags.COMPRESSED and cache.compress_enabled then
data = cache.decompress(data)
end
if flags.SERIALISED then
returndata[key] = cache.decode(data)
else
local ldata = tonumber(data) or toboolean(data)
if ldata == nil then
if data == 'nil' then
returndata[key] = nil
else
returndata[key] = data
end
else
returndata[key] = ldata
end
end
end
end
return returndata
end
local function _send(cache, key, str)
local server = _select_server(cache, key)
server:send(str .. "\r\n")
local line, err = server:receive()
if not err then return line end
end
local function _store(cache, op, key, value, expiry)
local str
local flags = 0
if type(value) == 'table' then
str = cache.encode(value)
-- TODO lookup rather than hard code
flags = flags + 4
else
str = tostring(value)
end
if cache.compress_enabled and string.len(str) > cache.compress_threshold then
local cstr = cache.compress(str)
if string.len(cstr) < (string.len(str) * 0.8) then
str = cstr
-- TODO lookup rather than hard code
flags = flags + 2
end
end
local len = string.len(str)
expiry = expiry or 0
local cmd = op .. ' ' .. key .. ' ' .. flags .. ' ' .. expiry .. ' ' .. len .. '\r\n' .. str
local res = _send(cache, key, cmd)
if res ~= 'STORED' then
return false, res
end
return true
end
local function set(cache, key, value, expiry)
return _store(cache, 'set', key, value, expiry)
end
local function add(cache, key, value, expiry)
return _store(cache, 'add', key, value, expiry)
end
local function replace(cache, key, value, expiry)
return _store(cache, 'replace', key, value, expiry)
end
local function get(cache, key)
local dataset = _retrieve(cache, key, 'get ' .. key)
return dataset[key]
end
local function delete(cache, key)
local res = _send(cache, key, 'delete ' .. key)
if res == 'NOT_FOUND' then
return false
end
if res ~= 'DELETED' then
return false, res
end
return true
end
local function incr(cache, key, val)
val = val or 1
local res = _send(cache, key, 'incr ' .. key .. ' ' .. val)
if res == 'ERROR' or res == 'CLIENT_ERROR' then
return false, res
end
return res
end
local function decr(cache, key, val)
val = val or 1
local res = _send(cache, key, 'decr ' .. key .. ' ' .. val)
if res == 'ERROR' or res == 'CLIENT_ERROR' then
return false, res
end
return res
end
local function stats(cache, key)
local servers = {}
key = key or ''
if string.len(key) > 0 and not STATS_KEYS[key] then
error(string.format("Unknown stats key '%s'", key))
end
for i,server in pairs(cache.servers) do
server.socket:send('stats ' .. key .. '\r\n')
local stats = {}
while true do
local line, err = server.socket:receive()
if line == 'END' or line == 'ERROR' then
break
end
local k,v = string.match(line, 'STAT (%S+) (%S+)')
if k then
stats[k] = v
end
end
servers[server.name] = stats
end
return servers
end
local function get_multi(cache, ...)
local dataset = nil
if table.maxn(cache.servers) > 1 then
dataset = {}
for i,k in ipairs(arg) do
local data = _retrieve(cache, k, 'get ' .. k)
dataset[k] = data[k]
end
else
local keys = table.concat(arg, ' ')
dataset = _retrieve(cache, keys, 'get ' .. keys)
end
return dataset
end
local function flush_all(cache)
local success = true
for i,server in ipairs(cache.servers) do
server.socket:send('flush_all\r\n')
local res = assert(server.socket:receive())
if res ~= 'OK' then
success = false
end
end
return success
end
local function disconnect_all(cache)
while true do
local server = table.remove(cache.servers)
if not server then
break
end
server.socket:close()
end
end
local function set_hash(cache, hashfunc)
cache.hash = hashfunc
end
local function set_encode(cache, func)
cache.encode = func
end
local function set_decode(cache, func)
cache.decode = func
end
local function set_compress(cache, func)
cache.compress = func
end
local function set_decompress(cache, func)
cache.decompress = func
end
function Connect(hostlist, port)
local servers = {}
if type(hostlist) == 'table' then
for i,host in pairs(hostlist) do
local h, p
if type(host) == 'table' then
h = host[1]
p = host[2]
elseif type(host) == 'string' then
h = host
elseif type(host) == 'number' then
p = host
h = nil
end
if not h then
h = '127.0.0.1'
end
if not p then
p = 11211
end
local server = socket.connect(h, p)
if not server then
warn('Could not connect to ' .. h .. ':' .. p)
else
table.insert(servers, {socket = server, name = string.format('%s:%d', h, p)})
end
end
else
local address = hostlist
if type(address) == 'number' then
port = address
address = nil
end
if address == nil then
address = '127.0.0.1'
end
if port == nil then
port = 11211
end
local server = socket.connect(address, port)
if not server then
warn('Could not connect to ' .. address .. ':' .. port)
else
servers = {{socket = server, name = string.format('%s:%d', address, port)}}
end
end
if table.maxn(servers) < 1 then
error('No servers available')
end
local cache = {
servers = servers,
set_hash = set_hash,
set_encode = set_encode,
set_decode = set_decode,
set_decompress = set_decompress,
set_compress = set_compress,
compress_enabled = false,
enable_compression = function(self, on)
self.compress_enabled = on
end,
hash = nil,
encode = function()
error('No encode function set')
end,
decode = function()
error('No decode function set')
end,
compress = function()
error('No compress function set')
end,
decompress = function()
error('No decompress function set')
end,
-- 10K default
compress_threshold = 10240,
set_compress_threshold = function(self, threshold)
if threshold == nil then
self:enable_compression(false)
else
self.compress_threshold = threshold
end
end,
set = set,
add = add,
replace = replace,
get = get,
delete = delete,
incr = incr,
decr = decr,
get_multi = get_multi,
stats = stats,
flush_all = flush_all,
disconnect_all = disconnect_all,
}
return cache
end
function New(hostlist, port)
return Connect(hostlist, port)
end
--
-- Memcached.lua
--
-- A pure Lua implementation of a simple memcached client. 1 or more memcached server(s) are currently supported. Requires the luasocket library.
-- See http://www.danga.com/memcached/ for more information about memcached.
--
--
--
-- Synopsis
--
-- require('Memcached')
--
-- memcache = Memcached.Connect('some.host.com', 11000)
-- OR
-- memcache = Memcached.New('some.host.com', 11000)
--
-- memcache:set('some_key', 1234)
-- memcache:add('new_key', 'add new value')
-- memcache:replace('existing_key', 'replace old value')
--
-- cached_data = memcache:get('some_key')
--
-- memcache:delete('old_key')
--
--
--
-- Methods:
--
-- memcache = Memcached.Connect()
-- Connect to memcached server at localhost on port number 11211.
--
-- memcache = Memcached.Connect(host[, port])
-- Connect to memcached server at 'host' on port number 'port'. If port is not provided, port 11211 is used.
--
---memcache = Memcached.Connect(port)
-- Connect to memcached server at localhost on port number 'port'.
--
-- memcache = Memcached.Connect({{'host', port}, 'host', port})
-- Connect to multiple memcached servers.
--
-- memcache:set(key, value[, expiry])
-- Unconditionally sets a key to a given value in the memcache. The value for 'expiry' is the expiration
-- time (default is 0, never expire).
--
-- memcache:add(key, value[, expiry])
-- Like set, but only stores in memcache if the key doesn't already exist.
--
-- memcache:replace(key, value[, expiry])
-- Like set, but only stores in memcache if the key already exists. The opposite of add.
--
-- value = memcache:get(key)
-- Retrieves a key from the memcache. Returns the value or nil
--
-- values = memcache:get_multi(...)
-- Retrieves multiple keys from the memcache doing just one query. Returns a table of key/value pairs that were available.
--
-- memcache:delete(key)
-- Deletes a key. Returns true on deletion, false if the key was not found.
--
-- value = memcache:incr(key[, value])
-- Sends a command to the server to atomically increment the value for key by value, or by 1 if value is nil.
-- Returns nil if key doesn't exist on server, otherwise it returns the new value after incrementing. Value should be zero or greater.
--
-- value = memcache:decr(key[, value])
-- Like incr, but decrements. Unlike incr, underflow is checked and new values are capped at 0. If server value is 1, a decrement of 2 returns 0, not -1.
--
-- servers = memcache:stats([key])
-- Returns a table of statistical data regarding the memcache server(s). Allowed keys are:
-- '', 'malloc', 'sizes', 'slabs', 'items'
--
-- success = memcache:flush_all()
-- Runs the memcached "flush_all" command on all configured hosts, emptying all their caches.
--
-- memcache:disconnect_all()
-- Closes all cached sockets to all memcached servers.
--
-- memcache:set_hash(hashfunc)
-- Sets a custom hash function for key values. The default is a CRC32 hashing function.
-- 'hashfunc' should be defined receiving a single string parameter and returning a single integer value.
--
-- memcache:set_encode(func)
-- Sets a custom encode function for serialising table values. 'func' should be defined receiving a single
-- table value and returning a single string value.
--
-- memcache:set_decode(func)
-- Sets a custom decode function for deserialising table values. 'func' should be defined receiving a
-- single single and returning a single table value
--
-- memcache:enable_compression(onflag)
-- Turns data compression support on or off.
--
-- memcache:set_compress_threshold(size)
-- Set the compression threshold. If the value to be stored is larger than `size' bytes (and compression
-- is enabled), compress before storing.
--
-- memcache:set_compress(func)
-- Sets a custom data compression function. 'func' should be defined receiving a single string value and
-- returning a single string value.
--
-- memcache:set_decompress(func)
-- Sets a custom data decompression function. 'func' should be defined receiving a single string value and
-- returning a single string value.