d6129b850f909862c8d8a24529f7c11fd4f60cae
[awesomized/libmemcached] / libmemcached / io.c
1 /* LibMemcached
2 * Copyright (C) 2006-2009 Brian Aker
3 * All rights reserved.
4 *
5 * Use and distribution licensed under the BSD license. See
6 * the COPYING file in the parent directory for full text.
7 *
8 * Summary: Server IO, Not public!
9 *
10 */
11
12
13 #include "common.h"
14 #include <sys/select.h>
15 #include <poll.h>
16
17 typedef enum {
18 MEM_READ,
19 MEM_WRITE
20 } memc_read_or_write;
21
22 static ssize_t io_flush(memcached_server_write_instance_st ptr,
23 memcached_return_t *error);
24 static void increment_udp_message_id(memcached_server_write_instance_st ptr);
25
26 static memcached_return_t io_wait(memcached_server_write_instance_st ptr,
27 memc_read_or_write read_or_write)
28 {
29 struct pollfd fds= {
30 .fd= ptr->fd,
31 .events = POLLIN
32 };
33 int error;
34
35 if (read_or_write == MEM_WRITE) /* write */
36 {
37 fds.events= POLLOUT;
38 WATCHPOINT_SET(ptr->io_wait_count.write++);
39 }
40 else
41 {
42 WATCHPOINT_SET(ptr->io_wait_count.read++);
43 }
44
45 /*
46 ** We are going to block on write, but at least on Solaris we might block
47 ** on write if we haven't read anything from our input buffer..
48 ** Try to purge the input buffer if we don't do any flow control in the
49 ** application layer (just sending a lot of data etc)
50 ** The test is moved down in the purge function to avoid duplication of
51 ** the test.
52 */
53 if (read_or_write == MEM_WRITE)
54 {
55 memcached_return_t rc= memcached_purge(ptr);
56 if (rc != MEMCACHED_SUCCESS && rc != MEMCACHED_STORED)
57 return MEMCACHED_FAILURE;
58 }
59
60 int timeout= ptr->root->poll_timeout;
61 if (ptr->root->flags.no_block == false)
62 timeout= -1;
63
64 size_t loop_max= 5;
65 while (--loop_max)
66 {
67 error= poll(&fds, 1, timeout);
68
69 switch (error)
70 {
71 case 1:
72 WATCHPOINT_IF_LABELED_NUMBER(read_or_write && loop_max < 4, "read() times we had to loop, decremented down from 5", loop_max);
73 WATCHPOINT_IF_LABELED_NUMBER(!read_or_write && loop_max < 4, "write() times we had to loop, decremented down from 5", loop_max);
74
75 return MEMCACHED_SUCCESS;
76 case 0:
77 return MEMCACHED_TIMEOUT;
78 default:
79 WATCHPOINT_ERRNO(errno);
80 {
81 switch (errno)
82 {
83 #ifdef TARGET_OS_LINUX
84 case ERESTART:
85 #endif
86 case EINTR:
87 continue;
88 default:
89 ptr->cached_errno= error;
90 memcached_quit_server(ptr, true);
91
92 return MEMCACHED_FAILURE;
93 }
94 }
95 }
96 }
97
98 if (loop_max == 0 && error == 0)
99 return MEMCACHED_TIMEOUT;
100
101 /* Imposssible for anything other then -1 */
102 WATCHPOINT_ASSERT(error == -1);
103 ptr->cached_errno= error;
104 memcached_quit_server(ptr, true);
105
106 return MEMCACHED_FAILURE;
107 }
108
109 /**
110 * Try to fill the input buffer for a server with as much
111 * data as possible.
112 *
113 * @param ptr the server to pack
114 */
115 static bool repack_input_buffer(memcached_server_write_instance_st ptr)
116 {
117 if (ptr->read_ptr != ptr->read_buffer)
118 {
119 /* Move all of the data to the beginning of the buffer so
120 ** that we can fit more data into the buffer...
121 */
122 memmove(ptr->read_buffer, ptr->read_ptr, ptr->read_buffer_length);
123 ptr->read_ptr= ptr->read_buffer;
124 ptr->read_data_length= ptr->read_buffer_length;
125 }
126
127 /* There is room in the buffer, try to fill it! */
128 if (ptr->read_buffer_length != MEMCACHED_MAX_BUFFER)
129 {
130 /* Just try a single read to grab what's available */
131 ssize_t nr= read(ptr->fd,
132 ptr->read_ptr + ptr->read_data_length,
133 MEMCACHED_MAX_BUFFER - ptr->read_data_length);
134
135 if (nr > 0)
136 {
137 ptr->read_data_length+= (size_t)nr;
138 ptr->read_buffer_length+= (size_t)nr;
139 return true;
140 }
141 }
142 return false;
143 }
144
145 /**
146 * If the we have callbacks connected to this server structure
147 * we may start process the input queue and fire the callbacks
148 * for the incomming messages. This function is _only_ called
149 * when the input buffer is full, so that we _know_ that we have
150 * at least _one_ message to process.
151 *
152 * @param ptr the server to star processing iput messages for
153 * @return true if we processed anything, false otherwise
154 */
155 static bool process_input_buffer(memcached_server_write_instance_st ptr)
156 {
157 /*
158 ** We might be able to process some of the response messages if we
159 ** have a callback set up
160 */
161 if (ptr->root->callbacks != NULL && ptr->root->flags.use_udp == false)
162 {
163 /*
164 * We might have responses... try to read them out and fire
165 * callbacks
166 */
167 memcached_callback_st cb= *ptr->root->callbacks;
168
169 memcached_set_processing_input((memcached_st *)ptr->root, true);
170
171 char buffer[MEMCACHED_DEFAULT_COMMAND_SIZE];
172 memcached_return_t error;
173 memcached_st *root= (memcached_st *)ptr->root;
174 error= memcached_response(ptr, buffer, sizeof(buffer),
175 &root->result);
176
177 memcached_set_processing_input(root, false);
178
179 if (error == MEMCACHED_SUCCESS)
180 {
181 for (unsigned int x= 0; x < cb.number_of_callback; x++)
182 {
183 error= (*cb.callback[x])(ptr->root, &root->result, cb.context);
184 if (error != MEMCACHED_SUCCESS)
185 break;
186 }
187
188 /* @todo what should I do with the error message??? */
189 }
190 /* @todo what should I do with other error messages?? */
191 return true;
192 }
193
194 return false;
195 }
196
197 static inline void memcached_io_cork_push(memcached_server_st *ptr)
198 {
199 (void)ptr;
200 #ifdef CORK
201 if (ptr->root->flags.cork == false || ptr->state.is_corked)
202 return;
203
204 int enable= 1;
205 int err= setsockopt(ptr->fd, IPPROTO_TCP, CORK,
206 &enable, (socklen_t)sizeof(int));
207 if (! err)
208 ptr->state.is_corked= true;
209
210 WATCHPOINT_ASSERT(ptr->state.is_corked == true);
211 #endif
212 }
213
214 static inline void memcached_io_cork_pop(memcached_server_st *ptr)
215 {
216 (void)ptr;
217 #ifdef CORK
218 if (ptr->root->flags.cork == false || ptr->state.is_corked == false)
219 return;
220
221 int enable= 0;
222 int err= setsockopt(ptr->fd, IPPROTO_TCP, CORK,
223 &enable, (socklen_t)sizeof(int));
224 if (! err)
225 ptr->state.is_corked= false;
226
227 WATCHPOINT_ASSERT(ptr->state.is_corked == false);
228 #endif
229 }
230
231 #if 0 // Dead code, this should be removed.
232 void memcached_io_preread(memcached_st *ptr)
233 {
234 unsigned int x;
235
236 return;
237
238 for (x= 0; x < memcached_server_count(ptr); x++)
239 {
240 if (memcached_server_response_count(ptr, x) &&
241 ptr->hosts[x].read_data_length < MEMCACHED_MAX_BUFFER )
242 {
243 size_t data_read;
244
245 data_read= read(ptr->hosts[x].fd,
246 ptr->hosts[x].read_ptr + ptr->hosts[x].read_data_length,
247 MEMCACHED_MAX_BUFFER - ptr->hosts[x].read_data_length);
248 if (data_read == -1)
249 continue;
250
251 ptr->hosts[x].read_buffer_length+= data_read;
252 ptr->hosts[x].read_data_length+= data_read;
253 }
254 }
255 }
256 #endif
257
258 memcached_return_t memcached_io_read(memcached_server_write_instance_st ptr,
259 void *buffer, size_t length, ssize_t *nread)
260 {
261 char *buffer_ptr;
262
263 buffer_ptr= buffer;
264
265 while (length)
266 {
267 if (!ptr->read_buffer_length)
268 {
269 ssize_t data_read;
270
271 while (1)
272 {
273 data_read= read(ptr->fd, ptr->read_buffer, MEMCACHED_MAX_BUFFER);
274 if (data_read > 0)
275 {
276 break;
277 }
278 else if (data_read == -1)
279 {
280 ptr->cached_errno= errno;
281 memcached_return_t rc= MEMCACHED_ERRNO;
282 switch (errno)
283 {
284 case EAGAIN:
285 case EINTR:
286 #ifdef TARGET_OS_LINUX
287 case ERESTART:
288 #endif
289 if ((rc= io_wait(ptr, MEM_READ)) == MEMCACHED_SUCCESS)
290 continue;
291 /* fall through */
292
293 default:
294 {
295 memcached_quit_server(ptr, true);
296 *nread= -1;
297 return rc;
298 }
299 }
300 }
301 else
302 {
303 /*
304 EOF. Any data received so far is incomplete
305 so discard it. This always reads by byte in case of TCP
306 and protocol enforcement happens at memcached_response()
307 looking for '\n'. We do not care for UDB which requests 8 bytes
308 at once. Generally, this means that connection went away. Since
309 for blocking I/O we do not return 0 and for non-blocking case
310 it will return EGAIN if data is not immediatly available.
311 */
312 WATCHPOINT_STRING("We had a zero length read()");
313 memcached_quit_server(ptr, true);
314 *nread= -1;
315 return MEMCACHED_UNKNOWN_READ_FAILURE;
316 }
317 }
318
319 ptr->io_bytes_sent = 0;
320 ptr->read_data_length= (size_t) data_read;
321 ptr->read_buffer_length= (size_t) data_read;
322 ptr->read_ptr= ptr->read_buffer;
323 }
324
325 if (length > 1)
326 {
327 size_t difference;
328
329 difference= (length > ptr->read_buffer_length) ? ptr->read_buffer_length : length;
330
331 memcpy(buffer_ptr, ptr->read_ptr, difference);
332 length -= difference;
333 ptr->read_ptr+= difference;
334 ptr->read_buffer_length-= difference;
335 buffer_ptr+= difference;
336 }
337 else
338 {
339 *buffer_ptr= *ptr->read_ptr;
340 ptr->read_ptr++;
341 ptr->read_buffer_length--;
342 buffer_ptr++;
343 break;
344 }
345 }
346
347 ptr->server_failure_counter= 0;
348 *nread = (ssize_t)(buffer_ptr - (char*)buffer);
349 return MEMCACHED_SUCCESS;
350 }
351
352 static ssize_t _io_write(memcached_server_write_instance_st ptr,
353 const void *buffer, size_t length, bool with_flush)
354 {
355 size_t original_length;
356 const char* buffer_ptr;
357
358 WATCHPOINT_ASSERT(ptr->fd != -1);
359
360 original_length= length;
361 buffer_ptr= buffer;
362
363 /* more writable data is coming if a flush isn't required, so delay send */
364 if (! with_flush)
365 {
366 memcached_io_cork_push(ptr);
367 }
368
369 while (length)
370 {
371 char *write_ptr;
372 size_t should_write;
373 size_t buffer_end;
374
375 if (ptr->type == MEMCACHED_CONNECTION_UDP)
376 {
377 //UDP does not support partial writes
378 buffer_end= MAX_UDP_DATAGRAM_LENGTH;
379 should_write= length;
380 if (ptr->write_buffer_offset + should_write > buffer_end)
381 return -1;
382 }
383 else
384 {
385 buffer_end= MEMCACHED_MAX_BUFFER;
386 should_write= buffer_end - ptr->write_buffer_offset;
387 should_write= (should_write < length) ? should_write : length;
388 }
389
390 write_ptr= ptr->write_buffer + ptr->write_buffer_offset;
391 memcpy(write_ptr, buffer_ptr, should_write);
392 ptr->write_buffer_offset+= should_write;
393 buffer_ptr+= should_write;
394 length-= should_write;
395
396 if (ptr->write_buffer_offset == buffer_end && ptr->type != MEMCACHED_CONNECTION_UDP)
397 {
398 memcached_return_t rc;
399 ssize_t sent_length;
400
401 WATCHPOINT_ASSERT(ptr->fd != -1);
402 sent_length= io_flush(ptr, &rc);
403 if (sent_length == -1)
404 return -1;
405
406 /* If io_flush calls memcached_purge, sent_length may be 0 */
407 unlikely (sent_length != 0)
408 {
409 WATCHPOINT_ASSERT(sent_length == (ssize_t)buffer_end);
410 }
411 }
412 }
413
414 if (with_flush)
415 {
416 memcached_return_t rc;
417 WATCHPOINT_ASSERT(ptr->fd != -1);
418 if (io_flush(ptr, &rc) == -1)
419 {
420 return -1;
421 }
422
423 memcached_io_cork_pop(ptr);
424 }
425
426 return (ssize_t) original_length;
427 }
428
429 ssize_t memcached_io_write(memcached_server_write_instance_st ptr,
430 const void *buffer, size_t length, bool with_flush)
431 {
432 return _io_write(ptr, buffer, length, with_flush);
433 }
434
435 ssize_t memcached_io_writev(memcached_server_write_instance_st ptr,
436 const struct __write_vector_st *vector,
437 size_t number_of, bool with_flush)
438 {
439 ssize_t total= 0;
440
441 for (size_t x= 0; x < number_of; x++, vector++)
442 {
443 ssize_t returnable;
444
445 if ((returnable= _io_write(ptr, vector->buffer, vector->length, false)) == -1)
446 {
447 return -1;
448 }
449 total+= returnable;
450 }
451
452 if (with_flush)
453 {
454 if (memcached_io_write(ptr, NULL, 0, true) == -1)
455 {
456 return -1;
457 }
458 }
459
460 return total;
461 }
462
463
464 memcached_return_t memcached_io_close(memcached_server_write_instance_st ptr)
465 {
466 if (ptr->fd == -1)
467 {
468 return MEMCACHED_SUCCESS;
469 }
470
471 /* in case of death shutdown to avoid blocking at close() */
472 if (shutdown(ptr->fd, SHUT_RDWR) == -1 && errno != ENOTCONN)
473 {
474 WATCHPOINT_NUMBER(ptr->fd);
475 WATCHPOINT_ERRNO(errno);
476 WATCHPOINT_ASSERT(errno);
477 }
478
479 if (close(ptr->fd) == -1)
480 {
481 WATCHPOINT_ERRNO(errno);
482 }
483
484 return MEMCACHED_SUCCESS;
485 }
486
487 memcached_server_write_instance_st memcached_io_get_readable_server(memcached_st *memc)
488 {
489 #define MAX_SERVERS_TO_POLL 100
490 struct pollfd fds[MAX_SERVERS_TO_POLL];
491 unsigned int host_index= 0;
492
493 for (uint32_t x= 0;
494 x< memcached_server_count(memc) && host_index < MAX_SERVERS_TO_POLL;
495 ++x)
496 {
497 memcached_server_write_instance_st instance=
498 memcached_server_instance_fetch(memc, x);
499
500 if (instance->read_buffer_length > 0) /* I have data in the buffer */
501 return instance;
502
503 if (memcached_server_response_count(instance) > 0)
504 {
505 fds[host_index].events = POLLIN;
506 fds[host_index].revents = 0;
507 fds[host_index].fd = instance->fd;
508 ++host_index;
509 }
510 }
511
512 if (host_index < 2)
513 {
514 /* We have 0 or 1 server with pending events.. */
515 for (uint32_t x= 0; x< memcached_server_count(memc); ++x)
516 {
517 memcached_server_write_instance_st instance=
518 memcached_server_instance_fetch(memc, x);
519
520 if (memcached_server_response_count(instance) > 0)
521 {
522 return instance;
523 }
524 }
525
526 return NULL;
527 }
528
529 int err= poll(fds, host_index, memc->poll_timeout);
530 switch (err) {
531 case -1:
532 memc->cached_errno = errno;
533 /* FALLTHROUGH */
534 case 0:
535 break;
536 default:
537 for (size_t x= 0; x < host_index; ++x)
538 {
539 if (fds[x].revents & POLLIN)
540 {
541 for (uint32_t y= 0; y < memcached_server_count(memc); ++y)
542 {
543 memcached_server_write_instance_st instance=
544 memcached_server_instance_fetch(memc, y);
545
546 if (instance->fd == fds[x].fd)
547 return instance;
548 }
549 }
550 }
551 }
552
553 return NULL;
554 }
555
556 static ssize_t io_flush(memcached_server_write_instance_st ptr,
557 memcached_return_t *error)
558 {
559 /*
560 ** We might want to purge the input buffer if we haven't consumed
561 ** any output yet... The test for the limits is the purge is inline
562 ** in the purge function to avoid duplicating the logic..
563 */
564 {
565 memcached_return_t rc;
566 WATCHPOINT_ASSERT(ptr->fd != -1);
567 rc= memcached_purge(ptr);
568
569 if (rc != MEMCACHED_SUCCESS && rc != MEMCACHED_STORED)
570 return -1;
571 }
572 ssize_t sent_length;
573 size_t return_length;
574 char *local_write_ptr= ptr->write_buffer;
575 size_t write_length= ptr->write_buffer_offset;
576
577 *error= MEMCACHED_SUCCESS;
578
579 WATCHPOINT_ASSERT(ptr->fd != -1);
580
581 // UDP Sanity check, make sure that we are not sending somthing too big
582 if (ptr->type == MEMCACHED_CONNECTION_UDP && write_length > MAX_UDP_DATAGRAM_LENGTH)
583 return -1;
584
585 if (ptr->write_buffer_offset == 0 || (ptr->type == MEMCACHED_CONNECTION_UDP
586 && ptr->write_buffer_offset == UDP_DATAGRAM_HEADER_LENGTH))
587 return 0;
588
589 /* Looking for memory overflows */
590 #if defined(DEBUG)
591 if (write_length == MEMCACHED_MAX_BUFFER)
592 WATCHPOINT_ASSERT(ptr->write_buffer == local_write_ptr);
593 WATCHPOINT_ASSERT((ptr->write_buffer + MEMCACHED_MAX_BUFFER) >= (local_write_ptr + write_length));
594 #endif
595
596 return_length= 0;
597 while (write_length)
598 {
599 WATCHPOINT_ASSERT(ptr->fd != -1);
600 WATCHPOINT_ASSERT(write_length > 0);
601 sent_length= 0;
602 if (ptr->type == MEMCACHED_CONNECTION_UDP)
603 increment_udp_message_id(ptr);
604 sent_length= write(ptr->fd, local_write_ptr, write_length);
605
606 if (sent_length == -1)
607 {
608 ptr->cached_errno= errno;
609 WATCHPOINT_ERRNO(errno);
610 WATCHPOINT_NUMBER(errno);
611 switch (errno)
612 {
613 case ENOBUFS:
614 continue;
615 case EAGAIN:
616 {
617 /*
618 * We may be blocked on write because the input buffer
619 * is full. Let's check if we have room in our input
620 * buffer for more data and retry the write before
621 * waiting..
622 */
623 if (repack_input_buffer(ptr) ||
624 process_input_buffer(ptr))
625 continue;
626
627 memcached_return_t rc;
628 rc= io_wait(ptr, MEM_WRITE);
629
630 if (rc == MEMCACHED_SUCCESS || rc == MEMCACHED_TIMEOUT)
631 continue;
632
633 memcached_quit_server(ptr, true);
634 return -1;
635 }
636 default:
637 memcached_quit_server(ptr, true);
638 *error= MEMCACHED_ERRNO;
639 return -1;
640 }
641 }
642
643 if (ptr->type == MEMCACHED_CONNECTION_UDP &&
644 (size_t)sent_length != write_length)
645 {
646 memcached_quit_server(ptr, true);
647 return -1;
648 }
649
650 ptr->io_bytes_sent += (uint32_t) sent_length;
651
652 local_write_ptr+= sent_length;
653 write_length-= (uint32_t) sent_length;
654 return_length+= (uint32_t) sent_length;
655 }
656
657 WATCHPOINT_ASSERT(write_length == 0);
658 // Need to study this assert() WATCHPOINT_ASSERT(return_length ==
659 // ptr->write_buffer_offset);
660
661 // if we are a udp server, the begining of the buffer is reserverd for
662 // the upd frame header
663 if (ptr->type == MEMCACHED_CONNECTION_UDP)
664 ptr->write_buffer_offset= UDP_DATAGRAM_HEADER_LENGTH;
665 else
666 ptr->write_buffer_offset= 0;
667
668 return (ssize_t) return_length;
669 }
670
671 /*
672 Eventually we will just kill off the server with the problem.
673 */
674 void memcached_io_reset(memcached_server_write_instance_st ptr)
675 {
676 memcached_quit_server(ptr, true);
677 }
678
679 /**
680 * Read a given number of bytes from the server and place it into a specific
681 * buffer. Reset the IO channel on this server if an error occurs.
682 */
683 memcached_return_t memcached_safe_read(memcached_server_write_instance_st ptr,
684 void *dta,
685 size_t size)
686 {
687 size_t offset= 0;
688 char *data= dta;
689
690 while (offset < size)
691 {
692 ssize_t nread;
693 memcached_return_t rc= memcached_io_read(ptr, data + offset, size - offset,
694 &nread);
695 if (rc != MEMCACHED_SUCCESS)
696 return rc;
697
698 offset+= (size_t) nread;
699 }
700
701 return MEMCACHED_SUCCESS;
702 }
703
704 memcached_return_t memcached_io_readline(memcached_server_write_instance_st ptr,
705 char *buffer_ptr,
706 size_t size)
707 {
708 bool line_complete= false;
709 size_t total_nr= 0;
710
711 while (!line_complete)
712 {
713 if (ptr->read_buffer_length == 0)
714 {
715 /*
716 * We don't have any data in the buffer, so let's fill the read
717 * buffer. Call the standard read function to avoid duplicating
718 * the logic.
719 */
720 ssize_t nread;
721 memcached_return_t rc= memcached_io_read(ptr, buffer_ptr, 1, &nread);
722 if (rc != MEMCACHED_SUCCESS)
723 return rc;
724
725 if (*buffer_ptr == '\n')
726 line_complete= true;
727
728 ++buffer_ptr;
729 ++total_nr;
730 }
731
732 /* Now let's look in the buffer and copy as we go! */
733 while (ptr->read_buffer_length && total_nr < size && !line_complete)
734 {
735 *buffer_ptr = *ptr->read_ptr;
736 if (*buffer_ptr == '\n')
737 line_complete = true;
738 --ptr->read_buffer_length;
739 ++ptr->read_ptr;
740 ++total_nr;
741 ++buffer_ptr;
742 }
743
744 if (total_nr == size)
745 return MEMCACHED_PROTOCOL_ERROR;
746 }
747
748 return MEMCACHED_SUCCESS;
749 }
750
751 /*
752 * The udp request id consists of two seperate sections
753 * 1) The thread id
754 * 2) The message number
755 * The thread id should only be set when the memcached_st struct is created
756 * and should not be changed.
757 *
758 * The message num is incremented for each new message we send, this function
759 * extracts the message number from message_id, increments it and then
760 * writes the new value back into the header
761 */
762 static void increment_udp_message_id(memcached_server_write_instance_st ptr)
763 {
764 struct udp_datagram_header_st *header= (struct udp_datagram_header_st *)ptr->write_buffer;
765 uint16_t cur_req= get_udp_datagram_request_id(header);
766 int msg_num= get_msg_num_from_request_id(cur_req);
767 int thread_id= get_thread_id_from_request_id(cur_req);
768
769 if (((++msg_num) & UDP_REQUEST_ID_THREAD_MASK) != 0)
770 msg_num= 0;
771
772 header->request_id= htons((uint16_t) (thread_id | msg_num));
773 }
774
775 memcached_return_t memcached_io_init_udp_header(memcached_server_write_instance_st ptr, uint16_t thread_id)
776 {
777 if (thread_id > UDP_REQUEST_ID_MAX_THREAD_ID)
778 return MEMCACHED_FAILURE;
779
780 struct udp_datagram_header_st *header= (struct udp_datagram_header_st *)ptr->write_buffer;
781 header->request_id= htons((uint16_t) (generate_udp_request_thread_id(thread_id)));
782 header->num_datagrams= htons(1);
783 header->sequence_number= htons(0);
784
785 return MEMCACHED_SUCCESS;
786 }