aboutsummaryrefslogtreecommitdiffstats
path: root/src/memcached.c
blob: 22dd9fbb323d262209363938cb44630839179ce0 (plain)
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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
#ifdef _THREAD_SAFE
#include <pthread.h>
#endif

#include <stdarg.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <sys/param.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sysexits.h>
#include <unistd.h>
#include <syslog.h>

#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/poll.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/uio.h>
#include <event.h>
#include <glib.h>

#include "memcached.h"

#define CRLF "\r\n"
#define END_TRAILER "END" CRLF
#define STORED_TRAILER "STORED" CRLF
#define NOT_STORED_TRAILER "NOT STORED" CRLF
#define EXISTS_TRAILER "EXISTS" CRLF
#define DELETED_TRAILER "DELETED" CRLF
#define NOT_FOUND_TRAILER "NOT_FOUND" CRLF
#define CLIENT_ERROR_TRAILER "CLIENT_ERROR"
#define SERVER_ERROR_TRAILER "SERVER_ERROR"

#define READ_BUFSIZ 1500
#define MAX_RETRIES 3

/* Header for udp protocol */
struct memc_udp_header
{
	uint16_t req_id;
	uint16_t seq_num;
	uint16_t dg_sent;
	uint16_t unused;
};

static void socket_callback (int fd, short what, void *arg);
static int memc_parse_header (char *buf, size_t *len, char **end);

/*
 * Write to syslog if OPT_DEBUG is specified
 */
static void
memc_log (const memcached_ctx_t *ctx, int line, const char *fmt, ...) 
{
	va_list args;
	if (ctx->options & MEMC_OPT_DEBUG) {
		va_start (args, fmt);
		g_log (G_LOG_DOMAIN, G_LOG_LEVEL_DEBUG, "memc_debug(%d): host: %s, port: %d", line, inet_ntoa (ctx->addr), ntohs (ctx->port));
		g_logv (G_LOG_DOMAIN, G_LOG_LEVEL_DEBUG, fmt, args);
		va_end (args);
	}
}

/*
 * Callback for write command
 */
static void
write_handler (int fd, short what, memcached_ctx_t *ctx)
{
	char read_buf[READ_BUFSIZ];
	int retries;
	ssize_t r;
	struct memc_udp_header header;
	struct iovec iov[4];

	/* Write something to memcached */
	if (what == EV_WRITE) {
		if (ctx->protocol == UDP_TEXT) {
			/* Send udp header */
			bzero (&header, sizeof (header));
			header.dg_sent = htons (1);
			header.req_id = ctx->count;
		}

		r = snprintf (read_buf, READ_BUFSIZ, "%s %s 0 %d %zu" CRLF, ctx->cmd, ctx->param->key, ctx->param->expire, ctx->param->bufsize);
		memc_log (ctx, __LINE__, "memc_write: send write request to memcached: %s", read_buf);

		if (ctx->protocol == UDP_TEXT) {
			iov[0].iov_base = &header;
			iov[0].iov_len = sizeof (struct memc_udp_header);
			if (ctx->param->bufpos == 0) {
				iov[1].iov_base = read_buf;
				iov[1].iov_len = r;
			}
			else {
				iov[1].iov_base = NULL;
				iov[1].iov_len = 0;
			}
			iov[2].iov_base = ctx->param->buf + ctx->param->bufpos;
			iov[2].iov_len = ctx->param->bufsize - ctx->param->bufpos;
			iov[3].iov_base = CRLF;
			iov[3].iov_len = sizeof (CRLF) - 1;
			if (writev (ctx->sock, iov, 4) == -1) {
				memc_log (ctx, __LINE__, "memc_write: writev failed: %m");
			}
		}
		else {
			iov[0].iov_base = read_buf;
			iov[0].iov_len = r;
			iov[1].iov_base = ctx->param->buf + ctx->param->bufpos;
			iov[1].iov_len = ctx->param->bufsize - ctx->param->bufpos;
			iov[2].iov_base = CRLF;
			iov[2].iov_len = sizeof (CRLF) - 1;
			writev (ctx->sock, iov, 3);
		}
		event_del (&ctx->mem_ev);
		event_set (&ctx->mem_ev, ctx->sock, EV_READ | EV_PERSIST | EV_TIMEOUT, socket_callback, (void *)ctx);
		event_add (&ctx->mem_ev, &ctx->timeout);
	}
	else if (what == EV_READ) {
		/* Read header */
		retries = 0;
		while (ctx->protocol == UDP_TEXT) {
			iov[0].iov_base = &header;
			iov[0].iov_len = sizeof (struct memc_udp_header);
			iov[1].iov_base = read_buf;
			iov[1].iov_len = READ_BUFSIZ;
			if ((r = readv (ctx->sock, iov, 2)) == -1) {
				event_del (&ctx->mem_ev);
				ctx->callback (ctx, SERVER_ERROR, ctx->callback_data);
			}
			if (header.req_id != ctx->count && retries < MAX_RETRIES) {
				retries ++;
				/* Not our reply packet */
				continue;
			}
			break;
		}
		if (ctx->protocol != UDP_TEXT) {
			r = read (ctx->sock, read_buf, READ_BUFSIZ - 1);
		}
		memc_log (ctx, __LINE__, "memc_write: read reply from memcached: %s", read_buf);
		/* Increment count */
		ctx->count++;
		event_del (&ctx->mem_ev);
		if (strncmp (read_buf, STORED_TRAILER, sizeof (STORED_TRAILER) - 1) == 0) {
			ctx->callback (ctx, OK, ctx->callback_data);
		}
		else if (strncmp (read_buf, NOT_STORED_TRAILER, sizeof (NOT_STORED_TRAILER) - 1) == 0) {
			ctx->callback (ctx, CLIENT_ERROR, ctx->callback_data);
		}
		else if (strncmp (read_buf, EXISTS_TRAILER, sizeof (EXISTS_TRAILER) - 1) == 0) {
			ctx->callback (ctx, EXISTS, ctx->callback_data);
		}
		else {
			ctx->callback (ctx, SERVER_ERROR, ctx->callback_data);
		}
	}
	else if (what == EV_TIMEOUT) {
		event_del (&ctx->mem_ev);
		ctx->callback (ctx, SERVER_TIMEOUT, ctx->callback_data);
	}
}

/*
 * Callback for read command
 */
static void
read_handler (int fd, short what, memcached_ctx_t *ctx)
{
	char read_buf[READ_BUFSIZ];
	char *p;
	ssize_t r;
	size_t datalen;
	struct memc_udp_header header;
	struct iovec iov[2];
	int retries = 0, t;
	
	if (what == EV_WRITE) {
		/* Send command to memcached */
		if (ctx->protocol == UDP_TEXT) {
			/* Send udp header */
			bzero (&header, sizeof (header));
			header.dg_sent = htons (1);
			header.req_id = ctx->count;
		}

		r = snprintf (read_buf, READ_BUFSIZ, "%s %s" CRLF, ctx->cmd, ctx->param->key);
		memc_log (ctx, __LINE__, "memc_read: send read request to memcached: %s", read_buf);
		if (ctx->protocol == UDP_TEXT) {
			iov[0].iov_base = &header;
			iov[0].iov_len = sizeof (struct memc_udp_header);
			iov[1].iov_base = read_buf;
			iov[1].iov_len = r;
			if (writev (ctx->sock, iov, 2) == -1) {
				memc_log (ctx, __LINE__, "memc_write: writev failed: %m");
			}
		}
		else {
			if (write (ctx->sock, read_buf, r) == -1) {
				memc_log (ctx, __LINE__, "memc_write: write failed: %m");
			}
		}
		event_del (&ctx->mem_ev);
		event_set (&ctx->mem_ev, ctx->sock, EV_READ | EV_PERSIST | EV_TIMEOUT, socket_callback, (void *)ctx);
		event_add (&ctx->mem_ev, &ctx->timeout);
	}
	else if (what == EV_READ) {
		while (ctx->protocol == UDP_TEXT) {
			iov[0].iov_base = &header;
			iov[0].iov_len = sizeof (struct memc_udp_header);
			iov[1].iov_base = read_buf;
			iov[1].iov_len = READ_BUFSIZ;
			if ((r = readv (ctx->sock, iov, 2)) == -1) {
				event_del (&ctx->mem_ev);
				ctx->callback (ctx, SERVER_ERROR, ctx->callback_data);
				return;
			}
			memc_log (ctx, __LINE__, "memc_read: got read_buf: %s", read_buf);
			if (header.req_id != ctx->count && retries < MAX_RETRIES) {
				memc_log (ctx, __LINE__, "memc_read: got wrong packet id: %d, %d was awaited", header.req_id, ctx->count);
				retries++;
				/* Not our reply packet */
				continue;
			}
			break;
		}
		if (ctx->protocol != UDP_TEXT) {
			r = read (ctx->sock, read_buf, READ_BUFSIZ - 1);
		}

		if (r > 0) {
			read_buf[r] = 0;
			if (ctx->param->bufpos == 0) {
				t = memc_parse_header (read_buf, &datalen, &p);
				if (t < 0) {
					event_del (&ctx->mem_ev);
					memc_log (ctx, __LINE__, "memc_read: cannot parse memcached reply");
					ctx->callback (ctx, SERVER_ERROR, ctx->callback_data);
					return;
				}
				else if (t == 0) {
					memc_log (ctx, __LINE__, "memc_read: record does not exists");
					event_del (&ctx->mem_ev);
					ctx->callback (ctx, NOT_EXISTS, ctx->callback_data);
					return;
				}

				if (datalen > ctx->param->bufsize) {
					memc_log (ctx, __LINE__, "memc_read: user's buffer is too small: %zd, %zd required", ctx->param->bufsize, datalen);
					event_del (&ctx->mem_ev);
					ctx->callback (ctx, WRONG_LENGTH, ctx->callback_data);
					return;
				}
				/* Check if we already have all data in buffer */
				if (r >= datalen + sizeof (END_TRAILER) + sizeof (CRLF) - 2) {
					/* Store all data in param's buffer */
					memcpy (ctx->param->buf + ctx->param->bufpos, p, datalen);
					/* Increment count */
					ctx->count++;
					event_del (&ctx->mem_ev);
					ctx->callback (ctx, OK, ctx->callback_data);
					return;
				}
				/* Subtract from sum parsed header's length */
				r -= p - read_buf;
			}
			else {
				p = read_buf;
			}
			
			if (strncmp (ctx->param->buf + ctx->param->bufpos + r - sizeof (END_TRAILER) - sizeof (CRLF) + 2, 
						END_TRAILER, sizeof (END_TRAILER) - 1) == 0) {
				r -= sizeof (END_TRAILER) - sizeof (CRLF) - 2;
				memcpy (ctx->param->buf + ctx->param->bufpos, p, r);
				event_del (&ctx->mem_ev);
				ctx->callback (ctx, OK, ctx->callback_data);
				return;
			}
			/* Store this part of data in param's buffer */
			memcpy (ctx->param->buf + ctx->param->bufpos, p, r);
			ctx->param->bufpos += r;
		}
		else {
			memc_log (ctx, __LINE__, "memc_read: read(v) failed: %d, %m", r);
			event_del (&ctx->mem_ev);
			ctx->callback (ctx, SERVER_ERROR, ctx->callback_data);
			return;
		}

		ctx->count++;
	}
	else if (what == EV_TIMEOUT) {
		event_del (&ctx->mem_ev);
		ctx->callback (ctx, SERVER_TIMEOUT, ctx->callback_data);
	}
	
}

/*
 * Callback for delete command
 */
static void
delete_handler (int fd, short what, memcached_ctx_t *ctx)
{
	char read_buf[READ_BUFSIZ];
	int retries;
	ssize_t r;
	struct memc_udp_header header;
	struct iovec iov[2];

	/* Write something to memcached */
	if (what == EV_WRITE) {
		if (ctx->protocol == UDP_TEXT) {
			/* Send udp header */
			bzero (&header, sizeof (header));
			header.dg_sent = htons (1);
			header.req_id = ctx->count;
		}
		r = snprintf (read_buf, READ_BUFSIZ, "delete %s" CRLF, ctx->param->key);
		memc_log (ctx, __LINE__, "memc_delete: send delete request to memcached: %s", read_buf);

		if (ctx->protocol == UDP_TEXT) {
			iov[0].iov_base = &header;
			iov[0].iov_len = sizeof (struct memc_udp_header);
			iov[1].iov_base = read_buf;
			iov[1].iov_len = r;
			ctx->param->bufpos = writev (ctx->sock, iov, 2);
			if (ctx->param->bufpos == -1) {
				memc_log (ctx, __LINE__, "memc_write: writev failed: %m");
			}
		}
		else {
			if (write (ctx->sock, read_buf, r) == -1) {
				memc_log (ctx, __LINE__, "memc_write: write failed: %m");
			}
		}
		event_del (&ctx->mem_ev);
		event_set (&ctx->mem_ev, ctx->sock, EV_READ | EV_PERSIST | EV_TIMEOUT, socket_callback, (void *)ctx);
		event_add (&ctx->mem_ev, &ctx->timeout);
	}
	else if (what == EV_READ) {
		/* Read header */
		retries = 0;
		while (ctx->protocol == UDP_TEXT) {
			iov[0].iov_base = &header;
			iov[0].iov_len = sizeof (struct memc_udp_header);
			iov[1].iov_base = read_buf;
			iov[1].iov_len = READ_BUFSIZ;
			if ((r = readv (ctx->sock, iov, 2)) == -1) {
				event_del (&ctx->mem_ev);
				ctx->callback (ctx, SERVER_ERROR, ctx->callback_data);
				return;
			}
			if (header.req_id != ctx->count && retries < MAX_RETRIES) {
				retries ++;
				/* Not our reply packet */
				continue;
			}
			break;
		}
		if (ctx->protocol != UDP_TEXT) {
			r = read (ctx->sock, read_buf, READ_BUFSIZ - 1);
		}
		/* Increment count */
		ctx->count++;
		event_del (&ctx->mem_ev);
		if (strncmp (read_buf, DELETED_TRAILER, sizeof (STORED_TRAILER) - 1) == 0) {
			ctx->callback (ctx, OK, ctx->callback_data);
		}
		else if (strncmp (read_buf, NOT_FOUND_TRAILER, sizeof (NOT_FOUND_TRAILER) - 1) == 0) {
			ctx->callback (ctx, NOT_EXISTS, ctx->callback_data);
		}
		else {
			ctx->callback (ctx, SERVER_ERROR, ctx->callback_data);
		}
	}
	else if (what == EV_TIMEOUT) {
		event_del (&ctx->mem_ev);
		ctx->callback (ctx, SERVER_TIMEOUT, ctx->callback_data);
	}
}

/*
 * Callback for our socket events
 */
static void
socket_callback (int fd, short what, void *arg)
{
	memcached_ctx_t *ctx = (memcached_ctx_t *)arg;

	switch (ctx->op) {
		case CMD_NULL:
			/* Do nothing here */
			break;
		case CMD_CONNECT:
			/* We have write readiness after connect call, so reinit event */
			ctx->cmd = "connect";
			if (what == EV_WRITE) {
				event_del (&ctx->mem_ev);
				event_set (&ctx->mem_ev, ctx->sock, EV_READ | EV_PERSIST | EV_TIMEOUT, socket_callback, (void *)ctx);
				event_add (&ctx->mem_ev, NULL);
				ctx->callback (ctx, OK, ctx->callback_data);
                ctx->alive = 1;
			}
			else {
				ctx->callback (ctx, SERVER_TIMEOUT, ctx->callback_data);
                ctx->alive = 0;
			}
			break;
		case CMD_WRITE:
			write_handler (fd, what, ctx);
			break;
		case CMD_READ:
			read_handler (fd, what, ctx);
			break;
		case CMD_DELETE:
			delete_handler (fd, what, ctx);
			break;
	}
}

/*
 * Common callback function for memcached operations if no user's callback is specified
 */
static void
common_memc_callback (memcached_ctx_t *ctx, memc_error_t error, void *data)
{
	memc_log (ctx, __LINE__, "common_memc_callback: result of memc command '%s' is '%s'", ctx->cmd, memc_strerror (error));
}

/*
 * Make socket for udp connection
 */
static int
memc_make_udp_sock (memcached_ctx_t *ctx)
{
	struct sockaddr_in sc;
	int ofl;

	bzero (&sc, sizeof (struct sockaddr_in *));
	sc.sin_family = AF_INET;
	sc.sin_port = ctx->port;
	memcpy (&sc.sin_addr, &ctx->addr, sizeof (struct in_addr));

	ctx->sock = socket (PF_INET, SOCK_DGRAM, 0);

	if (ctx->sock == -1) {
		memc_log (ctx, __LINE__, "memc_make_udp_sock: socket() failed: %m");
		return -1;
	}

	/* set nonblocking */
    ofl = fcntl(ctx->sock, F_GETFL, 0);
    fcntl(ctx->sock, F_SETFL, ofl | O_NONBLOCK);

	/* 
	 * Call connect to set default destination for datagrams 
	 * May not block
	 */
	ctx->op = CMD_CONNECT;
	event_set (&ctx->mem_ev, ctx->sock, EV_WRITE | EV_TIMEOUT, socket_callback, (void *)ctx);
	event_add (&ctx->mem_ev, NULL);
	return connect (ctx->sock, (struct sockaddr*)&sc, sizeof (struct sockaddr_in));
}

/*
 * Make socket for tcp connection
 */
static int
memc_make_tcp_sock (memcached_ctx_t *ctx)
{
	struct sockaddr_in sc;
	int ofl, r;

	bzero (&sc, sizeof (struct sockaddr_in *));
	sc.sin_family = AF_INET;
	sc.sin_port = ctx->port;
	memcpy (&sc.sin_addr, &ctx->addr, sizeof (struct in_addr));

	ctx->sock = socket (PF_INET, SOCK_STREAM, 0);

	if (ctx->sock == -1) {
		memc_log (ctx, __LINE__, "memc_make_tcp_sock: socket() failed: %m");
		return -1;
	}

	/* set nonblocking */
    ofl = fcntl(ctx->sock, F_GETFL, 0);
    fcntl(ctx->sock, F_SETFL, ofl | O_NONBLOCK);
	
	if ((r = connect (ctx->sock, (struct sockaddr*)&sc, sizeof (struct sockaddr_in))) == -1) {
		if (errno != EINPROGRESS) {
			close (ctx->sock);
			ctx->sock = -1;
			memc_log (ctx, __LINE__, "memc_make_tcp_sock: connect() failed: %m");
			return -1;
		}
	}
	ctx->op = CMD_CONNECT;
	event_set (&ctx->mem_ev, ctx->sock, EV_WRITE | EV_TIMEOUT, socket_callback, (void *)ctx);
	event_add (&ctx->mem_ev, &ctx->timeout);
	return 0;
}

/* 
 * Parse VALUE reply from server and set len argument to value returned by memcached 
 */
static int
memc_parse_header (char *buf, size_t *len, char **end)
{
	char *p, *c;
	int i;

	/* VALUE <key> <flags> <bytes> [<cas unique>]\r\n */
	c = strstr (buf, CRLF);
	if (c == NULL) {
		return -1;
	}
	*end = c + sizeof (CRLF) - 1;
	
	if (strncmp (buf, "VALUE ", sizeof ("VALUE ") - 1) == 0) {
		p = buf + sizeof ("VALUE ") - 1;
	
		/* Read bytes value and ignore all other fields, such as flags and key */
		for (i = 0; i < 2; i++) {
			while (p++ < c && *p != ' ');

			if (p > c) {
				return -1;
			}
		}
		*len = strtoul (p, &c, 10);
		return 1;
	}
	/* If value not found memcached return just END\r\n , in this case return 0 */
	else if (strncmp (buf, END_TRAILER, sizeof (END_TRAILER) - 1) == 0) {
		return 0;
	}

	return -1;
}


/*
 * Common read command handler for memcached
 */
memc_error_t
memc_read (memcached_ctx_t *ctx, const char *cmd, memcached_param_t *param)
{
	ctx->cmd = cmd;
	ctx->op = CMD_READ;
	ctx->param = param;
	event_set (&ctx->mem_ev, ctx->sock, EV_WRITE | EV_TIMEOUT, socket_callback, (void *)ctx);
	event_add (&ctx->mem_ev, &ctx->timeout);

	return OK;
}

/*
 * Common write command handler for memcached
 */
memc_error_t
memc_write (memcached_ctx_t *ctx, const char *cmd, memcached_param_t *param, int expire)
{
	ctx->cmd = cmd;
	ctx->op = CMD_WRITE;
	ctx->param = param;
	param->expire = expire;
	event_set (&ctx->mem_ev, ctx->sock, EV_WRITE | EV_TIMEOUT, socket_callback, (void *)ctx);
	event_add (&ctx->mem_ev, &ctx->timeout);

	return OK;
}
/*
 * Delete command handler
 */
memc_error_t
memc_delete (memcached_ctx_t *ctx, memcached_param_t *param)
{
	ctx->cmd = "delete";
	ctx->op = CMD_DELETE;
	ctx->param = param;
	event_set (&ctx->mem_ev, ctx->sock, EV_WRITE | EV_TIMEOUT, socket_callback, (void *)ctx);
	event_add (&ctx->mem_ev, &ctx->timeout);

	return OK;
}

/*
 * Write handler for memcached mirroring
 * writing is done to each memcached server
 */
memc_error_t
memc_write_mirror (memcached_ctx_t *ctx, size_t memcached_num, const char *cmd, memcached_param_t *param, int expire)
{
	memc_error_t r, result = OK;

	while (memcached_num --) {
		if (ctx[memcached_num].alive == 1) {
			r = memc_write (&ctx[memcached_num], cmd, param, expire);
			if (r != OK) {
				memc_log (&ctx[memcached_num], __LINE__, "memc_write_mirror: cannot write to mirror server: %s", memc_strerror (r));
				result = r;
				ctx[memcached_num].alive = 0;
			}
		}
	}

	return result;
}

/*
 * Read handler for memcached mirroring
 * reading is done from first active memcached server
 */
memc_error_t
memc_read_mirror (memcached_ctx_t *ctx, size_t memcached_num, const char *cmd, memcached_param_t *param)
{
	memc_error_t r, result = OK;

	while (memcached_num --) {
		if (ctx[memcached_num].alive == 1) {
			r = memc_read (&ctx[memcached_num], cmd, param);
			if (r != OK) {
				result = r;
				if (r != NOT_EXISTS) {
					ctx[memcached_num].alive = 0;
					memc_log (&ctx[memcached_num], __LINE__, "memc_read_mirror: cannot write read from mirror server: %s", memc_strerror (r));
				}
				else {
					memc_log (&ctx[memcached_num], __LINE__, "memc_read_mirror: record not exists", memc_strerror (r));
				}
			}
			else {
				break;
			}
		}
	}

	return result;
}

/*
 * Delete handler for memcached mirroring
 * deleting is done for each active memcached server
 */
memc_error_t
memc_delete_mirror (memcached_ctx_t *ctx, size_t memcached_num, const char *cmd, memcached_param_t *param)
{
	memc_error_t r, result = OK;

	while (memcached_num --) {
		if (ctx[memcached_num].alive == 1) {
			r = memc_delete (&ctx[memcached_num], param);
			if (r != OK) {
				result = r;
				if (r != NOT_EXISTS) {
					ctx[memcached_num].alive = 0;
					memc_log (&ctx[memcached_num], __LINE__, "memc_delete_mirror: cannot delete from mirror server: %s", memc_strerror (r));
				}
			}
		}
	}

	return result;
}


/* 
 * Initialize memcached context for specified protocol
 */
int 
memc_init_ctx (memcached_ctx_t *ctx)
{
	if (ctx == NULL) {
		return -1;
	}

	ctx->count = 0;
	ctx->alive = 0;
	ctx->op = CMD_NULL;
	/* Set default callback */
	if (ctx->callback == NULL) {
		ctx->callback = common_memc_callback;
	}

	switch (ctx->protocol) {
		case UDP_TEXT:
			return memc_make_udp_sock (ctx);
			break;
		case TCP_TEXT:
			return memc_make_tcp_sock (ctx);
			break;
		/* Not implemented */
		case UDP_BIN:
		case TCP_BIN:
		default:
			return -1;
	}
}
/*
 * Mirror init
 */
int 
memc_init_ctx_mirror (memcached_ctx_t *ctx, size_t memcached_num)
{
	int r, result = -1;
	while (memcached_num--) {
		if (ctx[memcached_num].alive == 1) {
			r = memc_init_ctx (&ctx[memcached_num]);
			if (r == -1) {
				ctx[memcached_num].alive = 0;
				memc_log (&ctx[memcached_num], __LINE__, "memc_init_ctx_mirror: cannot connect to server");
			}
			else {
				result = 1;
			}
		}
	}

	return result;
}

/*
 * Close context connection
 */
int
memc_close_ctx (memcached_ctx_t *ctx)
{
	if (ctx != NULL && ctx->sock != -1) {
		event_del (&ctx->mem_ev);
		return close (ctx->sock);
	}

	return -1;
}
/* 
 * Mirror close
 */
int 
memc_close_ctx_mirror (memcached_ctx_t *ctx, size_t memcached_num)
{
	int r = 0;
	while (memcached_num--) {
		if (ctx[memcached_num].alive == 1) {
			r = memc_close_ctx (&ctx[memcached_num]);
			if (r == -1) {
				memc_log (&ctx[memcached_num], __LINE__, "memc_close_ctx_mirror: cannot close connection to server properly");
				ctx[memcached_num].alive = 0;
			}
		}
	}

	return r;
}


const char * memc_strerror (memc_error_t err)
{
	const char *p;

	switch (err) {
		case OK:
			p = "Ok";
			break;
		case BAD_COMMAND:
			p = "Bad command";
			break;
		case CLIENT_ERROR:
			p = "Client error";
			break;
		case SERVER_ERROR:
			p = "Server error";
			break;
		case SERVER_TIMEOUT:
			p = "Server timeout";
			break;
		case NOT_EXISTS:
			p = "Key not found";
			break;
		case EXISTS:
			p = "Key already exists";
			break;
		case WRONG_LENGTH:
			p = "Wrong result length";
			break;
		default:
			p = "Unknown error";
			break;
	}

	return p;
}

/* 
 * vi:ts=4 
 */