root/branches/binary/server/memcached.h @ 732

Revision 732, 15.6 kB (checked in by dsallings, 21 months ago)

Auto-discover the protocol being spoken on a per-connection basis.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1/* -*- Mode: C; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
2/* $Id$ */
3
4#ifdef HAVE_CONFIG_H
5#include "config.h"
6#endif
7
8#include <sys/types.h>
9#include <sys/socket.h>
10#include <sys/time.h>
11#include <netinet/in.h>
12#include <event.h>
13#include <netdb.h>
14
15#define DATA_BUFFER_SIZE 2048
16#define UDP_READ_BUFFER_SIZE 65536
17#define UDP_MAX_PAYLOAD_SIZE 1400
18#define UDP_HEADER_SIZE 8
19#define MAX_SENDBUF_SIZE (256 * 1024 * 1024)
20/* I'm told the max legnth of a 64-bit num converted to string is 20 bytes.
21 * Plus a few for spaces, \r\n, \0 */
22#define SUFFIX_SIZE 24
23
24/** Initial size of list of items being returned by "get". */
25#define ITEM_LIST_INITIAL 200
26
27/** Initial size of list of CAS suffixes appended to "gets" lines. */
28#define SUFFIX_LIST_INITIAL 20
29
30/** Initial size of the sendmsg() scatter/gather array. */
31#define IOV_LIST_INITIAL 400
32
33/** Initial number of sendmsg() argument structures to allocate. */
34#define MSG_LIST_INITIAL 10
35
36/** High water marks for buffer shrinking */
37#define READ_BUFFER_HIGHWAT 8192
38#define ITEM_LIST_HIGHWAT 400
39#define IOV_LIST_HIGHWAT 600
40#define MSG_LIST_HIGHWAT 100
41
42/* Binary protocol stuff */
43#define MIN_BIN_PKT_LENGTH 16
44/* flags:32, expiration:32, cas:64 */
45#define BIN_SET_HDR_LEN 16
46/* incr:64, initial:64, expiration:32 */
47#define BIN_INCR_HDR_LEN 20
48/* flags:32, cas:64 */
49#define GET_RES_HDR_LEN (4+8)
50/* timeout:32 */
51#define BIN_DEL_HDR_LEN 4
52#define BIN_PKT_HDR_WORDS (MIN_BIN_PKT_LENGTH/sizeof(uint32_t))
53
54/* Body is a single 64-bit int */
55#define INCR_RES_LEN 8
56/* len(18446744073709551616) + 2 (or so) */
57#define INCR_MAX_STORAGE_LEN 24
58
59#define BIN_REQ_MAGIC 0x80
60#define BIN_RES_MAGIC 0x80
61
62#define CMD_GET 0
63#define CMD_SET 1
64#define CMD_ADD 2
65#define CMD_REPLACE 3
66#define CMD_DELETE 4
67#define CMD_INCR 5
68#define CMD_DECR 6
69#define CMD_QUIT 7
70#define CMD_FLUSH 8
71#define CMD_GETQ 9
72#define CMD_NOOP 10
73#define CMD_VERSION 11
74
75#define ERR_UNKNOWN_CMD 0x81
76#define ERR_OUT_OF_MEMORY 0x82
77
78#define ERR_NOT_FOUND 0x1
79#define ERR_EXISTS 0x2
80#define ERR_TOO_LARGE 0x3
81#define ERR_INVALID_ARGUMENTS 0x4
82#define ERR_NOT_STORED 0x5
83
84/* Get a consistent bool type */
85#if HAVE_STDBOOL_H
86# include <stdbool.h>
87#else
88  typedef enum {false = 0, true = 1} bool;
89#endif
90
91#if HAVE_STDINT_H
92# include <stdint.h>
93#else
94 typedef unsigned char             uint8_t;
95#endif
96
97/* unistd.h is here */
98#if HAVE_UNISTD_H
99# include <unistd.h>
100#endif
101
102/** Time relative to server start. Smaller than time_t on 64-bit systems. */
103typedef unsigned int rel_time_t;
104
105struct stats {
106    unsigned int  curr_items;
107    unsigned int  total_items;
108    uint64_t      curr_bytes;
109    unsigned int  curr_conns;
110    unsigned int  total_conns;
111    unsigned int  conn_structs;
112    uint64_t      get_cmds;
113    uint64_t      set_cmds;
114    uint64_t      get_hits;
115    uint64_t      get_misses;
116    uint64_t      evictions;
117    time_t        started;          /* when the process was started */
118    uint64_t      bytes_read;
119    uint64_t      bytes_written;
120};
121
122#define MAX_VERBOSITY_LEVEL 2
123
124struct settings {
125    size_t maxbytes;
126    int maxconns;
127    int port;
128    int udpport;
129    int binport;           /* Port for binary protocol. */
130    char *inter;
131    int verbose;
132    rel_time_t oldest_live; /* ignore existing items older than this */
133    bool managed;          /* if 1, a tracker manages virtual buckets */
134    int evict_to_free;
135    char *socketpath;   /* path to unix socket if using local socket */
136    int access;  /* access mask (a la chmod) for unix domain socket */
137    double factor;          /* chunk size growth factor */
138    int chunk_size;
139    int num_threads;        /* number of libevent threads to run */
140    char prefix_delimiter;  /* character that marks a key prefix (for stats) */
141    int detail_enabled;     /* nonzero if we're collecting detailed stats */
142};
143
144extern struct stats stats;
145extern struct settings settings;
146
147#define ITEM_LINKED 1
148#define ITEM_DELETED 2
149
150/* temp */
151#define ITEM_SLABBED 4
152
153typedef struct _stritem {
154    struct _stritem *next;
155    struct _stritem *prev;
156    struct _stritem *h_next;    /* hash chain next */
157    rel_time_t      time;       /* least recent access */
158    rel_time_t      exptime;    /* expire time */
159    int             nbytes;     /* size of data */
160    unsigned short  refcount;
161    uint8_t         nsuffix;    /* length of flags-and-length string */
162    uint8_t         it_flags;   /* ITEM_* above */
163    uint8_t         slabs_clsid;/* which slab class we're in */
164    uint8_t         nkey;       /* key length, w/terminating null and padding */
165    uint64_t        cas_id;     /* the CAS identifier */
166    void * end[];
167    /* then null-terminated key */
168    /* then " flags length\r\n" (no terminating null) */
169    /* then data with terminating \r\n (no terminating null; it's binary!) */
170} item;
171
172#define ITEM_key(item) ((char*)&((item)->end[0]))
173
174/* warning: don't use these macros with a function, as it evals its arg twice */
175#define ITEM_suffix(item) ((char*) &((item)->end[0]) + (item)->nkey + 1)
176#define ITEM_data(item) ((char*) &((item)->end[0]) + (item)->nkey + 1 + (item)->nsuffix)
177#define ITEM_ntotal(item) (sizeof(struct _stritem) + (item)->nkey + 1 + (item)->nsuffix + (item)->nbytes)
178
179enum conn_states {
180    conn_listening,  /** the socket which listens for connections */
181    conn_read,       /** reading in a command line */
182    conn_write,      /** writing out a simple response */
183    conn_nread,      /** reading in a fixed number of bytes */
184    conn_swallow,    /** swallowing unnecessary bytes w/o storing */
185    conn_closing,    /** closing this connection */
186    conn_mwrite,     /** writing out many items sequentially */
187    conn_bin_init,   /** Reinitializing a binary protocol connection */
188    conn_negotiate,  /** Negotiating a protocol */
189};
190
191enum bin_substates {
192    bin_no_state,
193    bin_reading_set_header,
194    bin_reading_cas_header,
195    bin_read_set_value,
196    bin_reading_get_key,
197    bin_reading_del_header,
198    bin_reading_incr_header,
199};
200
201enum protocols {
202    ascii_prot = 3, /* arbitrary value. */
203    ascii_udp_prot,
204    binary_prot,
205    negotiating_prot, /* Discovering the protocol */
206};
207
208#define IS_UDP(x) (x == ascii_udp_prot)
209
210#define NREAD_ADD 1
211#define NREAD_SET 2
212#define NREAD_REPLACE 3
213#define NREAD_APPEND 4
214#define NREAD_PREPEND 5
215#define NREAD_CAS 6
216
217typedef struct conn conn;
218struct conn {
219    int    sfd;
220    int    state;
221    int    substate;
222    struct event event;
223    short  ev_flags;
224    short  which;   /** which events were just triggered */
225
226    char   *rbuf;   /** buffer to read commands into */
227    char   *rcurr;  /** but if we parsed some already, this is where we stopped */
228    int    rsize;   /** total allocated size of rbuf */
229    int    rbytes;  /** how much data, starting from rcur, do we have unparsed */
230
231    char   *wbuf;
232    char   *wcurr;
233    int    wsize;
234    int    wbytes;
235    int    write_and_go; /** which state to go into after finishing current write */
236    void   *write_and_free; /** free this memory after finishing writing */
237
238    char   *ritem;  /** when we read in an item's value, it goes here */
239    int    rlbytes;
240
241    /* data for the nread state */
242
243    /**
244     * item is used to hold an item structure created after reading the command
245     * line of set/add/replace commands, but before we finished reading the actual
246     * data. The data is read into ITEM_data(item) to avoid extra copying.
247     */
248
249    void   *item;     /* for commands set/add/replace  */
250    int    item_comm; /* which one is it: set/add/replace */
251
252    /* data for the swallow state */
253    int    sbytes;    /* how many bytes to swallow */
254
255    /* data for the mwrite state */
256    struct iovec *iov;
257    int    iovsize;   /* number of elements allocated in iov[] */
258    int    iovused;   /* number of elements used in iov[] */
259
260    struct msghdr *msglist;
261    int    msgsize;   /* number of elements allocated in msglist[] */
262    int    msgused;   /* number of elements used in msglist[] */
263    int    msgcurr;   /* element in msglist[] being transmitted now */
264    int    msgbytes;  /* number of bytes in current msg */
265
266    item   **ilist;   /* list of items to write out */
267    int    isize;
268    item   **icurr;
269    int    ileft;
270
271    char   **suffixlist;
272    int    suffixsize;
273    char   **suffixcurr;
274    int    suffixleft;
275
276    int protocol;   /* which protocol this connection speaks */
277
278    /* data for UDP clients */
279    int    request_id; /* Incoming UDP request ID, if this is a UDP "connection" */
280    struct sockaddr request_addr; /* Who sent the most recent request */
281    socklen_t request_addr_size;
282    unsigned char *hdrbuf; /* udp packet headers */
283    int    hdrsize;   /* number of headers' worth of space is allocated */
284
285    int    binary;    /* are we in binary mode */
286    int    bucket;    /* bucket number for the next command, if running as
287                         a managed instance. -1 (_not_ 0) means invalid. */
288    int    gen;       /* generation requested for the bucket */
289    bool   noreply;   /* True if the reply should not be sent. */
290    /* Binary protocol stuff */
291    /* This is where the binary header goes */
292    uint32_t bin_header[MIN_BIN_PKT_LENGTH/sizeof(uint32_t)];
293    short cmd;
294    int opaque;
295    int keylen;
296    conn   *next;     /* Used for generating a list of conn structures */
297};
298
299
300/* number of virtual buckets for a managed instance */
301#define MAX_BUCKETS 32768
302
303/* current time of day (updated periodically) */
304extern volatile rel_time_t current_time;
305
306/*
307 * Functions
308 */
309
310conn *do_conn_from_freelist();
311bool do_conn_add_to_freelist(conn *c);
312char *do_suffix_from_freelist();
313bool do_suffix_add_to_freelist(char *s);
314char *do_defer_delete(item *item, time_t exptime);
315void do_run_deferred_deletes(void);
316char *do_add_delta(item *item, const bool incr, const int64_t delta, char *buf);
317int do_store_item(item *item, int comm);
318conn *conn_new(const int sfd, const int init_state, const int event_flags, const int read_buffer_size, const int prot, struct event_base *base);
319
320
321#include "stats.h"
322#include "slabs.h"
323#include "assoc.h"
324#include "items.h"
325
326
327/*
328 * In multithreaded mode, we wrap certain functions with lock management and
329 * replace the logic of some other functions. All wrapped functions have
330 * "mt_" and "do_" variants. In multithreaded mode, the plain version of a
331 * function is #define-d to the "mt_" variant, which often just grabs a
332 * lock and calls the "do_" function. In singlethreaded mode, the "do_"
333 * function is called directly.
334 *
335 * Functions such as the libevent-related calls that need to do cross-thread
336 * communication in multithreaded mode (rather than actually doing the work
337 * in the current thread) are called via "dispatch_" frontends, which are
338 * also #define-d to directly call the underlying code in singlethreaded mode.
339 */
340#ifdef USE_THREADS
341
342void thread_init(int nthreads, struct event_base *main_base);
343int  dispatch_event_add(int thread, conn *c);
344void dispatch_conn_new(int sfd, int init_state, int event_flags, int read_buffer_size, int prot);
345
346/* Lock wrappers for cache functions that are called from main loop. */
347char *mt_add_delta(item *item, const int incr, const int64_t delta, char *buf);
348void mt_assoc_move_next_bucket(void);
349conn *mt_conn_from_freelist(void);
350bool  mt_conn_add_to_freelist(conn *c);
351char *mt_suffix_from_freelist(void);
352bool  mt_suffix_add_to_freelist(char *s);
353char *mt_defer_delete(item *it, time_t exptime);
354int   mt_is_listen_thread(void);
355item *mt_item_alloc(char *key, size_t nkey, int flags, rel_time_t exptime, int nbytes);
356char *mt_item_cachedump(const unsigned int slabs_clsid, const unsigned int limit, unsigned int *bytes);
357void  mt_item_flush_expired(void);
358item *mt_item_get_notedeleted(const char *key, const size_t nkey, bool *delete_locked);
359int   mt_item_link(item *it);
360void  mt_item_remove(item *it);
361int   mt_item_replace(item *it, item *new_it);
362char *mt_item_stats(int *bytes);
363char *mt_item_stats_sizes(int *bytes);
364void  mt_item_unlink(item *it);
365void  mt_item_update(item *it);
366void  mt_run_deferred_deletes(void);
367void *mt_slabs_alloc(size_t size);
368void  mt_slabs_free(void *ptr, size_t size);
369int   mt_slabs_reassign(unsigned char srcid, unsigned char dstid);
370char *mt_slabs_stats(int *buflen);
371void  mt_stats_lock(void);
372void  mt_stats_unlock(void);
373int   mt_store_item(item *item, int comm);
374
375
376# define add_delta(x,y,z,a)          mt_add_delta(x,y,z,a)
377# define assoc_move_next_bucket()    mt_assoc_move_next_bucket()
378# define conn_from_freelist()        mt_conn_from_freelist()
379# define conn_add_to_freelist(x)     mt_conn_add_to_freelist(x)
380# define suffix_from_freelist()      mt_suffix_from_freelist()
381# define suffix_add_to_freelist(x)   mt_suffix_add_to_freelist(x)
382# define defer_delete(x,y)           mt_defer_delete(x,y)
383# define is_listen_thread()          mt_is_listen_thread()
384# define item_alloc(x,y,z,a,b)       mt_item_alloc(x,y,z,a,b)
385# define item_cachedump(x,y,z)       mt_item_cachedump(x,y,z)
386# define item_flush_expired()        mt_item_flush_expired()
387# define item_get_notedeleted(x,y,z) mt_item_get_notedeleted(x,y,z)
388# define item_link(x)                mt_item_link(x)
389# define item_remove(x)              mt_item_remove(x)
390# define item_replace(x,y)           mt_item_replace(x,y)
391# define item_stats(x)               mt_item_stats(x)
392# define item_stats_sizes(x)         mt_item_stats_sizes(x)
393# define item_update(x)              mt_item_update(x)
394# define item_unlink(x)              mt_item_unlink(x)
395# define run_deferred_deletes()      mt_run_deferred_deletes()
396# define slabs_alloc(x)              mt_slabs_alloc(x)
397# define slabs_free(x,y)             mt_slabs_free(x,y)
398# define slabs_reassign(x,y)         mt_slabs_reassign(x,y)
399# define slabs_stats(x)              mt_slabs_stats(x)
400# define store_item(x,y)             mt_store_item(x,y)
401
402# define STATS_LOCK()                mt_stats_lock()
403# define STATS_UNLOCK()              mt_stats_unlock()
404
405#else /* !USE_THREADS */
406
407# define add_delta(x,y,z,a)          do_add_delta(x,y,z,a)
408# define assoc_move_next_bucket()    do_assoc_move_next_bucket()
409# define conn_from_freelist()        do_conn_from_freelist()
410# define conn_add_to_freelist(x)     do_conn_add_to_freelist(x)
411# define suffix_from_freelist()      do_suffix_from_freelist()
412# define suffix_add_to_freelist(x)   do_suffix_add_to_freelist(x)
413# define defer_delete(x,y)           do_defer_delete(x,y)
414# define dispatch_conn_new(x,y,z,a,b) conn_new(x,y,z,a,b,main_base)
415# define dispatch_event_add(t,c)     event_add(&(c)->event, 0)
416# define is_listen_thread()          1
417# define item_alloc(x,y,z,a,b)       do_item_alloc(x,y,z,a,b)
418# define item_cachedump(x,y,z)       do_item_cachedump(x,y,z)
419# define item_flush_expired()        do_item_flush_expired()
420# define item_get_notedeleted(x,y,z) do_item_get_notedeleted(x,y,z)
421# define item_link(x)                do_item_link(x)
422# define item_remove(x)              do_item_remove(x)
423# define item_replace(x,y)           do_item_replace(x,y)
424# define item_stats(x)               do_item_stats(x)
425# define item_stats_sizes(x)         do_item_stats_sizes(x)
426# define item_unlink(x)              do_item_unlink(x)
427# define item_update(x)              do_item_update(x)
428# define run_deferred_deletes()      do_run_deferred_deletes()
429# define slabs_alloc(x)              do_slabs_alloc(x)
430# define slabs_free(x,y)             do_slabs_free(x,y)
431# define slabs_reassign(x,y)         do_slabs_reassign(x,y)
432# define slabs_stats(x)              do_slabs_stats(x)
433# define store_item(x,y)             do_store_item(x,y)
434# define thread_init(x,y)            0
435
436# define STATS_LOCK()                /**/
437# define STATS_UNLOCK()              /**/
438
439#endif /* !USE_THREADS */
440
441/* If supported, give compiler hints for branch prediction. */
442#if !defined(__GNUC__) || (__GNUC__ == 2 && __GNUC_MINOR__ < 96)
443#define __builtin_expect(x, expected_value) (x)
444#endif
445
446#define likely(x)       __builtin_expect((x),1)
447#define unlikely(x)     __builtin_expect((x),0)
Note: See TracBrowser for help on using the browser.