1 ;;; -*- Mode: Common-Lisp -*-
3 ;;; Copyright (c) 2006, Abhijit 'quasi' Rao. All rights reserved.
4 ;;; Copyright (c) 2006, Cleartrip Travel Services.
5 ;;; Copyright (c) 2011 Kevin Rosenberg
7 ;;; Redistribution and use in source and binary forms, with or without
8 ;;; modification, are permitted provided that the following conditions
11 ;;; * Redistributions of source code must retain the above copyright
12 ;;; notice, this list of conditions and the following disclaimer.
14 ;;; * Redistributions in binary form must reproduce the above
15 ;;; copyright notice, this list of conditions and the following
16 ;;; disclaimer in the documentation and/or other materials
17 ;;; provided with the distribution.
19 ;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
20 ;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
21 ;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 ;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
23 ;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 ;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
25 ;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26 ;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
27 ;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28 ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29 ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31 (in-package #:memcache)
33 (defmethod print-object ((mc memcache) stream)
34 (print-unreadable-object (mc stream :type t :identity t)
35 (format stream "~A on ~A:~A ~AMB"
36 (when (slot-boundp mc 'name) (name mc))
37 (when (slot-boundp mc 'ip) (ip mc))
38 (when (slot-boundp mc 'port) (port mc))
39 (when (and (slot-boundp mc 'memcached-server-storage-size)
40 (numberp (slot-value mc 'memcached-server-storage-size)))
41 (/ (memcached-server-storage-size mc) 1024 1024)))))
43 (defmethod initialize-instance :after ((memcache memcache) &rest initargs)
44 (declare (ignore initargs))
45 (setf (slot-value memcache 'pool) (make-instance 'memcache-connection-pool
46 :name (concatenate 'simple-string (name memcache) " - Connection Pool")
47 :max-capacity (pool-size memcache)))
48 (handler-case (mc-pool-init :memcache memcache)
50 (let ((stats (handler-case (mc-stats :memcache memcache)
53 (setf (slot-value memcache 'memcached-server-storage-size) (mc-stats-limit-maxbytes stats))
54 (setf (slot-value memcache 'memcached-server-storage-size) -1))))
56 (defun make-memcache-instance (&key (ip "127.0.0.1") (port 11211)
57 (name "Memcache") (pool-size 5))
58 "Creates an instance of class MEMCACHE which represents a memcached server."
59 (make-instance 'memcache :name name :ip ip :port port :pool-size pool-size))
62 (defmacro with-pool-maybe ((stream memcache use-pool) &body body)
63 "Macro to wrap the use-pool/dont-use-pool stuff and the cleanup
64 around a body of actual action statements"
65 (let ((mc (gensym "MEMCACHE-"))
66 (up (gensym "USE-POOL-"))
67 (us (gensym "USOCKET-")))
68 `(let* ((,mc ,memcache)
72 (mc-get-from-pool-with-try :memcache ,mc)
73 (mc-get-from-pool :memcache ,mc))
74 (mc-make-pool-item :memcache ,mc))))
77 (let ((,stream (usocket:socket-stream ,us)))
82 (mc-chuck-from-pool ,us ,mc))
85 (mc-put-in-pool ,us :memcache ,mc)
86 (ignore-errors (usocket:socket-close ,mc)))))))
88 (defun send-mc-command (s &rest args &aux started)
89 (flet ((write-string-bytes (str stream)
90 (loop for char across str
91 do (write-byte (char-code char) stream))))
95 (write-byte (char-code #\space) s)
98 (string (write-string-bytes arg s))
99 (character (write-byte (char-code arg) s))
100 (t (write-string-bytes (princ-to-string arg) s)))))
101 (write-string-bytes +crlf+ s)
107 ;;; Memcached API functionality
111 (defun mc-store (key data &key (memcache *memcache*) ((:command command) :set) ((:exptime exptime) 0)
112 ((:use-pool use-pool) *use-pool*) (cas-unique) (flags 0))
113 "Stores data in the memcached server using the :command command.
114 key => key by which the data is stored. this is of type SIMPLE-STRING
115 data => data to be stored into the cache. data is a sequence of type (UNSIGNED-BYTE 8)
116 length => size of data
117 memcache => The instance of class memcache which represnts the memcached we want to use.
118 command => The storage command we want to use. There are 3 available : set, add & replace.
119 exptime => The time in seconds when this data expires. 0 is never expire."
120 (declare (type fixnum exptime) (type simple-string key))
121 (when (and (eq command :cas) (not (integerp cas-unique)))
122 (error "CAS command, but CAS-UNIQUE not set."))
123 (let ((len (length data)))
124 (with-pool-maybe (s memcache use-pool)
134 key flags exptime len (when (eq command :cas) cas-unique))
135 (write-sequence data s)
137 (read-crlf-line s))))
139 (defun mc-get (key-or-keys &key (memcache *memcache*) (use-pool *use-pool*)
141 "Retrive value for key from memcached server.
142 keys-list => is a list of the keys, seperated by whitespace, by which data is stored in memcached
143 memcache => The instance of class memcache which represnts the memcached we want to use.
145 Returns a list of lists where each list has three elements key, flags, and value
146 key is of type SIMPLE-STRING
147 value is of type (UNSIGNED-BYTE 8)"
148 (let* ((multp (listp key-or-keys))
149 (keys-list (if multp key-or-keys (list key-or-keys)))
151 (with-pool-maybe (s memcache use-pool)
152 (apply 'send-mc-command s (ecase command
156 (loop for x = (read-crlf-line s)
157 until (string-equal x "END")
158 collect (let* ((status-line (delimited-string-to-list x))
159 (flags (parse-integer (third status-line)))
160 (len (parse-integer (fourth status-line)))
161 (cas-unique (when (eq command :gets)
162 (parse-integer (fifth status-line))))
163 (seq (make-sequence '(vector (unsigned-byte 8)) len)))
164 (read-sequence seq s)
166 (if (eq command :gets)
167 (list (second status-line) flags seq cas-unique)
168 (list (second status-line) flags seq)))))))
173 (defun mc-del (key &key (memcache *memcache*) ((:time time) 0) (use-pool *use-pool*))
174 "Deletes a particular 'key' and it's associated data from the memcached server"
175 (declare (type fixnum time))
176 (with-pool-maybe (s memcache use-pool)
177 (send-mc-command s "delete" key time)
180 (defun incr-or-decr (cmd key delta memcache use-pool)
181 (declare (type fixnum delta))
182 (let* ((res (with-pool-maybe (s memcache use-pool)
183 (send-mc-command s cmd key delta)
185 (int (ignore-errors (parse-integer res))))
188 (defun mc-incr (key &key (memcache *memcache*) (delta 1) (use-pool *use-pool*))
189 "Implements the INCR command. Increments the value of a key.
190 Please read memcached documentation for more information.
193 (incr-or-decr "incr" key delta memcache use-pool))
195 (defun mc-decr (key &key (memcache *memcache*) (delta 1) (use-pool *use-pool*))
196 "Implements the DECR command. Decrements the value of a key.
197 Please read memcached documentation for more information."
198 (incr-or-decr "decr" key delta memcache use-pool))
200 (defun mc-stats-raw (&key (memcache *memcache*) (use-pool *use-pool*) args
202 "Returns Raw stats data from memcached server to be used by the mc-stats function"
203 (with-pool-maybe (s memcache use-pool)
204 (send-mc-command s "stats" args)
205 (with-output-to-string (str)
206 (loop for line = (read-crlf-line s)
207 do (push line results)
208 until (or (string-equal "END" line)
209 (string-equal "ERROR" line)))))
212 (defun mc-get-stat (key stats)
213 (when (stringp key) (setq key (ensure-keyword key)))
214 (get-alist key (mc-stats-all-stats stats)))
216 ;;; Collects statistics from the memcached server
217 (defun mc-stats (&key (memcache *memcache*) (use-pool *use-pool*))
218 "Returns a struct of type memcache-stats which contains internal statistics from the
219 memcached server instance. Please refer to documentation of memcache-stats for detailed
220 information about each slot"
221 (let* ((result (mc-stats-raw :memcache memcache :use-pool use-pool))
222 (split (loop with xx = nil
224 do (setf xx (delimited-string-to-list x))
225 when (and (string= (first xx) "STAT") (second xx))
226 collect (cons (second xx) (third xx))))
227 (all-stats (sort split (lambda (a b) (string-greaterp (car a) (car b)))))
229 (dolist (r all-stats)
230 (push (cons (ensure-keyword (car r))
232 (int (ignore-errors (parse-integer val)))
233 (float (unless int (ignore-errors (parse-float val)))))
236 ((numberp float) float)
241 :pid (get-alist :pid results)
242 :uptime (get-alist :uptime results)
243 :time (get-alist :time results)
244 :version (get-alist :version results)
245 :rusage-user (get-alist :rusage_user results)
246 :rusage-system (get-alist :rusage_system results)
247 :curr-items (get-alist :curr_items results)
248 :curr-items-total (get-alist :curr_items_tot results)
249 :curr-connections (get-alist :curr_connections results)
250 :total-connections (get-alist :total_connections results)
251 :connection-structures (get-alist :connection_structures results)
252 :cmd-get (get-alist :cmd_get results)
253 :cmd-set (get-alist :cmd_set results)
254 :get-hits (get-alist :get_hits results)
255 :get-misses (get-alist :get_misses results)
256 :bytes-read (get-alist :bytes_read results)
257 :bytes-written (get-alist :bytes_written results)
258 :limit-maxbytes (get-alist :limit_maxbytes results)
264 (define-condition memcached-server-unreachable (error)
267 (define-condition memcache-pool-empty (error)
270 (define-condition cannot-make-pool-object (error)
273 (define-condition bad-pool-object (error)
278 ;;; Memcached Pooled Access
282 (defclass memcache-connection-pool ()
286 :initform "Connection Pool"
288 :documentation "Name of this pool")
290 :initform (make-queue)
294 :initform (make-lock "Memcache Connection Pool Lock"))
296 :initarg :max-capacity
300 :documentation "Total capacity of the pool to hold pool objects")
302 :accessor current-size
305 :accessor currently-in-use
308 :documentation "Pool objects currently in Use")
312 :documentation "Total uses of the pool")
314 :accessor total-created
317 :documentation "Total pool objects created")
320 :accessor pool-grow-requests
322 :documentation "Pool Grow Request pending Action")
324 :initform (make-lock "Pool Grow Lock")
325 :reader pool-grow-lock))
326 (:documentation "A memcached connection pool object"))
328 (defmethod print-object ((mcp memcache-connection-pool) stream)
329 (print-unreadable-object (mcp stream :type t :identity t)
330 (format stream "Capacity:~d, Currently in use:~d"
331 (when (slot-boundp mcp 'max-capacity) (max-capacity mcp))
332 (when (slot-boundp mcp 'currently-in-use) (currently-in-use mcp)))))
334 (defun mc-put-in-pool (conn &key (memcache *memcache*))
335 (with-lock-held ((pool-lock (pool memcache)))
336 (enqueue (pool (pool memcache)) conn)
337 (decf (currently-in-use (pool memcache)))))
339 (defun mc-get-from-pool (&key (memcache *memcache*))
340 "Returns a pool object from pool."
341 (let (pool-object (state t))
342 (with-lock-held ((pool-lock (pool memcache)))
343 (if (queue-empty-p (pool (pool memcache)))
345 (progn (incf (currently-in-use (pool memcache)))
346 (incf (total-uses (pool memcache)))
347 (setf pool-object (dequeue (pool (pool memcache)))))))
350 (error 'memcache-pool-empty))))
352 (defun mc-get-from-pool-with-try (&key (memcache *memcache*) (tries 5) (try-interval 1))
356 (progn (when (> tr tries)
358 (let ((conn (handler-case (mc-get-from-pool :memcache memcache)
359 (memcache-pool-empty () nil))))
362 (warn "memcache ~a : Connection Pool Empty! I will try again after ~d secs." (name memcache) try-interval)
363 (process-sleep try-interval))
366 (defun mc-pool-init (&key (memcache *memcache*))
367 "Cleans up the pool for this particular instance of memcache
368 & reinits it with POOL-SIZE number of objects required by this pool"
369 (mc-pool-cleanup memcache)
370 (dotimes (i (pool-size memcache))
371 (mc-pool-grow-request memcache))
372 (mc-pool-grow memcache))
374 (defun mc-make-pool-item (&key (memcache *memcache*))
375 (handler-case (usocket:socket-connect (ip memcache) (port memcache) :element-type '(unsigned-byte 8))
376 (usocket:socket-error () (error 'memcached-server-unreachable))
377 (error () (error 'cannot-make-pool-object))))
379 (defun mc-pool-grow (memcache)
380 (let (grow-count pool-item-list)
381 (with-lock-held ((pool-grow-lock (pool memcache)))
382 (setf grow-count (pool-grow-requests (pool memcache)))
383 (setf pool-item-list (remove nil (loop for x from 1 to grow-count
384 collect (mc-make-pool-item :memcache memcache))))
385 (loop for x from 1 to (length pool-item-list)
386 do (with-lock-held ((pool-lock (pool memcache)))
387 (enqueue (pool (pool memcache)) (pop pool-item-list))
388 (incf (total-created (pool memcache)))
389 (incf (current-size (pool memcache))))
390 do (decf (pool-grow-requests (pool memcache)))))))
392 (defun mc-destroy-pool-item (pool-item)
393 (ignore-errors (usocket:socket-close pool-item)))
395 (defun mc-pool-grow-request (memcache)
396 (with-lock-held ((pool-grow-lock (pool memcache)))
397 (if (> (max-capacity (pool memcache)) (+ (current-size (pool memcache))
398 (pool-grow-requests (pool memcache))))
399 (incf (pool-grow-requests (pool memcache)))
400 (warn "memcache: Pool is at capacity."))))
402 (defun mc-chuck-from-pool (object memcache)
403 (mc-destroy-pool-item object)
404 (with-lock-held ((pool-lock (pool memcache)))
405 (decf (current-size (pool memcache))))
406 #|(loop while (mc-pool-grow-request memcache))
407 (mc-pool-grow memcache)|#
408 (mc-pool-init :memcache memcache))
410 (defun mc-pool-cleanup (memcache)
411 (with-lock-held ((pool-lock (pool memcache)))
412 (with-lock-held ((pool-grow-lock (pool memcache)))
414 when (queue-empty-p (pool (pool memcache)))
416 else do (mc-destroy-pool-item (dequeue (pool (pool memcache)))))
417 (setf (current-size (pool memcache)) 0
418 (currently-in-use (pool memcache)) 0
419 (pool-grow-requests (pool memcache)) 0
420 (total-created (pool memcache)) 0
421 (total-uses (pool memcache)) 0))))