Small updates/wins around non-block IO
[m6w6/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_UNKNOWN_READ_FAILURE;
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 memcached_quit_server(ptr, true);
313 *nread= -1;
314 return MEMCACHED_UNKNOWN_READ_FAILURE;
315 }
316 }
317
318 ptr->io_bytes_sent = 0;
319 ptr->read_data_length= (size_t) data_read;
320 ptr->read_buffer_length= (size_t) data_read;
321 ptr->read_ptr= ptr->read_buffer;
322 }
323
324 if (length > 1)
325 {
326 size_t difference;
327
328 difference= (length > ptr->read_buffer_length) ? ptr->read_buffer_length : length;
329
330 memcpy(buffer_ptr, ptr->read_ptr, difference);
331 length -= difference;
332 ptr->read_ptr+= difference;
333 ptr->read_buffer_length-= difference;
334 buffer_ptr+= difference;
335 }
336 else
337 {
338 *buffer_ptr= *ptr->read_ptr;
339 ptr->read_ptr++;
340 ptr->read_buffer_length--;
341 buffer_ptr++;
342 break;
343 }
344 }
345
346 ptr->server_failure_counter= 0;
347 *nread = (ssize_t)(buffer_ptr - (char*)buffer);
348 return MEMCACHED_SUCCESS;
349 }
350
351 static ssize_t _io_write(memcached_server_write_instance_st ptr,
352 const void *buffer, size_t length, bool with_flush)
353 {
354 size_t original_length;
355 const char* buffer_ptr;
356
357 WATCHPOINT_ASSERT(ptr->fd != -1);
358
359 original_length= length;
360 buffer_ptr= buffer;
361
362 /* more writable data is coming if a flush isn't required, so delay send */
363 if (! with_flush)
364 {
365 memcached_io_cork_push(ptr);
366 }
367
368 while (length)
369 {
370 char *write_ptr;
371 size_t should_write;
372 size_t buffer_end;
373
374 if (ptr->type == MEMCACHED_CONNECTION_UDP)
375 {
376 //UDP does not support partial writes
377 buffer_end= MAX_UDP_DATAGRAM_LENGTH;
378 should_write= length;
379 if (ptr->write_buffer_offset + should_write > buffer_end)
380 return -1;
381 }
382 else
383 {
384 buffer_end= MEMCACHED_MAX_BUFFER;
385 should_write= buffer_end - ptr->write_buffer_offset;
386 should_write= (should_write < length) ? should_write : length;
387 }
388
389 write_ptr= ptr->write_buffer + ptr->write_buffer_offset;
390 memcpy(write_ptr, buffer_ptr, should_write);
391 ptr->write_buffer_offset+= should_write;
392 buffer_ptr+= should_write;
393 length-= should_write;
394
395 if (ptr->write_buffer_offset == buffer_end && ptr->type != MEMCACHED_CONNECTION_UDP)
396 {
397 memcached_return_t rc;
398 ssize_t sent_length;
399
400 WATCHPOINT_ASSERT(ptr->fd != -1);
401 sent_length= io_flush(ptr, &rc);
402 if (sent_length == -1)
403 return -1;
404
405 /* If io_flush calls memcached_purge, sent_length may be 0 */
406 unlikely (sent_length != 0)
407 {
408 WATCHPOINT_ASSERT(sent_length == (ssize_t)buffer_end);
409 }
410 }
411 }
412
413 if (with_flush)
414 {
415 memcached_return_t rc;
416 WATCHPOINT_ASSERT(ptr->fd != -1);
417 if (io_flush(ptr, &rc) == -1)
418 {
419 return -1;
420 }
421
422 memcached_io_cork_pop(ptr);
423 }
424
425 return (ssize_t) original_length;
426 }
427
428 ssize_t memcached_io_write(memcached_server_write_instance_st ptr,
429 const void *buffer, size_t length, bool with_flush)
430 {
431 return _io_write(ptr, buffer, length, with_flush);
432 }
433
434 ssize_t memcached_io_writev(memcached_server_write_instance_st ptr,
435 const struct __write_vector_st *vector,
436 size_t number_of, bool with_flush)
437 {
438 ssize_t total= 0;
439
440 for (size_t x= 0; x < number_of; x++, vector++)
441 {
442 ssize_t returnable;
443
444 if ((returnable= _io_write(ptr, vector->buffer, vector->length, false)) == -1)
445 {
446 return -1;
447 }
448 total+= returnable;
449 }
450
451 if (with_flush)
452 {
453 if (memcached_io_write(ptr, NULL, 0, true) == -1)
454 {
455 return -1;
456 }
457 }
458
459 return total;
460 }
461
462
463 memcached_return_t memcached_io_close(memcached_server_write_instance_st ptr)
464 {
465 if (ptr->fd == -1)
466 {
467 return MEMCACHED_SUCCESS;
468 }
469
470 /* in case of death shutdown to avoid blocking at close() */
471 if (shutdown(ptr->fd, SHUT_RDWR) == -1 && errno != ENOTCONN)
472 {
473 WATCHPOINT_NUMBER(ptr->fd);
474 WATCHPOINT_ERRNO(errno);
475 WATCHPOINT_ASSERT(errno);
476 }
477
478 if (close(ptr->fd) == -1)
479 {
480 WATCHPOINT_ERRNO(errno);
481 }
482
483 return MEMCACHED_SUCCESS;
484 }
485
486 memcached_server_write_instance_st memcached_io_get_readable_server(memcached_st *memc)
487 {
488 #define MAX_SERVERS_TO_POLL 100
489 struct pollfd fds[MAX_SERVERS_TO_POLL];
490 unsigned int host_index= 0;
491
492 for (uint32_t x= 0;
493 x< memcached_server_count(memc) && host_index < MAX_SERVERS_TO_POLL;
494 ++x)
495 {
496 memcached_server_write_instance_st instance=
497 memcached_server_instance_fetch(memc, x);
498
499 if (instance->read_buffer_length > 0) /* I have data in the buffer */
500 return instance;
501
502 if (memcached_server_response_count(instance) > 0)
503 {
504 fds[host_index].events = POLLIN;
505 fds[host_index].revents = 0;
506 fds[host_index].fd = instance->fd;
507 ++host_index;
508 }
509 }
510
511 if (host_index < 2)
512 {
513 /* We have 0 or 1 server with pending events.. */
514 for (uint32_t x= 0; x< memcached_server_count(memc); ++x)
515 {
516 memcached_server_write_instance_st instance=
517 memcached_server_instance_fetch(memc, x);
518
519 if (memcached_server_response_count(instance) > 0)
520 {
521 return instance;
522 }
523 }
524
525 return NULL;
526 }
527
528 int err= poll(fds, host_index, memc->poll_timeout);
529 switch (err) {
530 case -1:
531 memc->cached_errno = errno;
532 /* FALLTHROUGH */
533 case 0:
534 break;
535 default:
536 for (size_t x= 0; x < host_index; ++x)
537 {
538 if (fds[x].revents & POLLIN)
539 {
540 for (uint32_t y= 0; y < memcached_server_count(memc); ++y)
541 {
542 memcached_server_write_instance_st instance=
543 memcached_server_instance_fetch(memc, y);
544
545 if (instance->fd == fds[x].fd)
546 return instance;
547 }
548 }
549 }
550 }
551
552 return NULL;
553 }
554
555 static ssize_t io_flush(memcached_server_write_instance_st ptr,
556 memcached_return_t *error)
557 {
558 /*
559 ** We might want to purge the input buffer if we haven't consumed
560 ** any output yet... The test for the limits is the purge is inline
561 ** in the purge function to avoid duplicating the logic..
562 */
563 {
564 memcached_return_t rc;
565 WATCHPOINT_ASSERT(ptr->fd != -1);
566 rc= memcached_purge(ptr);
567
568 if (rc != MEMCACHED_SUCCESS && rc != MEMCACHED_STORED)
569 return -1;
570 }
571 ssize_t sent_length;
572 size_t return_length;
573 char *local_write_ptr= ptr->write_buffer;
574 size_t write_length= ptr->write_buffer_offset;
575
576 *error= MEMCACHED_SUCCESS;
577
578 WATCHPOINT_ASSERT(ptr->fd != -1);
579
580 // UDP Sanity check, make sure that we are not sending somthing too big
581 if (ptr->type == MEMCACHED_CONNECTION_UDP && write_length > MAX_UDP_DATAGRAM_LENGTH)
582 return -1;
583
584 if (ptr->write_buffer_offset == 0 || (ptr->type == MEMCACHED_CONNECTION_UDP
585 && ptr->write_buffer_offset == UDP_DATAGRAM_HEADER_LENGTH))
586 return 0;
587
588 /* Looking for memory overflows */
589 #if defined(DEBUG)
590 if (write_length == MEMCACHED_MAX_BUFFER)
591 WATCHPOINT_ASSERT(ptr->write_buffer == local_write_ptr);
592 WATCHPOINT_ASSERT((ptr->write_buffer + MEMCACHED_MAX_BUFFER) >= (local_write_ptr + write_length));
593 #endif
594
595 return_length= 0;
596 while (write_length)
597 {
598 WATCHPOINT_ASSERT(ptr->fd != -1);
599 WATCHPOINT_ASSERT(write_length > 0);
600 sent_length= 0;
601 if (ptr->type == MEMCACHED_CONNECTION_UDP)
602 increment_udp_message_id(ptr);
603 sent_length= write(ptr->fd, local_write_ptr, write_length);
604
605 if (sent_length == -1)
606 {
607 ptr->cached_errno= errno;
608 WATCHPOINT_ERRNO(errno);
609 WATCHPOINT_NUMBER(errno);
610 switch (errno)
611 {
612 case ENOBUFS:
613 continue;
614 case EAGAIN:
615 {
616 /*
617 * We may be blocked on write because the input buffer
618 * is full. Let's check if we have room in our input
619 * buffer for more data and retry the write before
620 * waiting..
621 */
622 if (repack_input_buffer(ptr) ||
623 process_input_buffer(ptr))
624 continue;
625
626 memcached_return_t rc;
627 rc= io_wait(ptr, MEM_WRITE);
628
629 if (rc == MEMCACHED_SUCCESS || rc == MEMCACHED_TIMEOUT)
630 continue;
631
632 memcached_quit_server(ptr, true);
633 return -1;
634 }
635 default:
636 memcached_quit_server(ptr, true);
637 *error= MEMCACHED_ERRNO;
638 return -1;
639 }
640 }
641
642 if (ptr->type == MEMCACHED_CONNECTION_UDP &&
643 (size_t)sent_length != write_length)
644 {
645 memcached_quit_server(ptr, true);
646 return -1;
647 }
648
649 ptr->io_bytes_sent += (uint32_t) sent_length;
650
651 local_write_ptr+= sent_length;
652 write_length-= (uint32_t) sent_length;
653 return_length+= (uint32_t) sent_length;
654 }
655
656 WATCHPOINT_ASSERT(write_length == 0);
657 // Need to study this assert() WATCHPOINT_ASSERT(return_length ==
658 // ptr->write_buffer_offset);
659
660 // if we are a udp server, the begining of the buffer is reserverd for
661 // the upd frame header
662 if (ptr->type == MEMCACHED_CONNECTION_UDP)
663 ptr->write_buffer_offset= UDP_DATAGRAM_HEADER_LENGTH;
664 else
665 ptr->write_buffer_offset= 0;
666
667 return (ssize_t) return_length;
668 }
669
670 /*
671 Eventually we will just kill off the server with the problem.
672 */
673 void memcached_io_reset(memcached_server_write_instance_st ptr)
674 {
675 memcached_quit_server(ptr, true);
676 }
677
678 /**
679 * Read a given number of bytes from the server and place it into a specific
680 * buffer. Reset the IO channel on this server if an error occurs.
681 */
682 memcached_return_t memcached_safe_read(memcached_server_write_instance_st ptr,
683 void *dta,
684 size_t size)
685 {
686 size_t offset= 0;
687 char *data= dta;
688
689 while (offset < size)
690 {
691 ssize_t nread;
692 memcached_return_t rc= memcached_io_read(ptr, data + offset, size - offset,
693 &nread);
694 if (rc != MEMCACHED_SUCCESS)
695 return rc;
696
697 offset+= (size_t) nread;
698 }
699
700 return MEMCACHED_SUCCESS;
701 }
702
703 memcached_return_t memcached_io_readline(memcached_server_write_instance_st ptr,
704 char *buffer_ptr,
705 size_t size)
706 {
707 bool line_complete= false;
708 size_t total_nr= 0;
709
710 while (!line_complete)
711 {
712 if (ptr->read_buffer_length == 0)
713 {
714 /*
715 * We don't have any data in the buffer, so let's fill the read
716 * buffer. Call the standard read function to avoid duplicating
717 * the logic.
718 */
719 ssize_t nread;
720 memcached_return_t rc= memcached_io_read(ptr, buffer_ptr, 1, &nread);
721 if (rc != MEMCACHED_SUCCESS)
722 return rc;
723
724 if (*buffer_ptr == '\n')
725 line_complete= true;
726
727 ++buffer_ptr;
728 ++total_nr;
729 }
730
731 /* Now let's look in the buffer and copy as we go! */
732 while (ptr->read_buffer_length && total_nr < size && !line_complete)
733 {
734 *buffer_ptr = *ptr->read_ptr;
735 if (*buffer_ptr == '\n')
736 line_complete = true;
737 --ptr->read_buffer_length;
738 ++ptr->read_ptr;
739 ++total_nr;
740 ++buffer_ptr;
741 }
742
743 if (total_nr == size)
744 return MEMCACHED_PROTOCOL_ERROR;
745 }
746
747 return MEMCACHED_SUCCESS;
748 }
749
750 /*
751 * The udp request id consists of two seperate sections
752 * 1) The thread id
753 * 2) The message number
754 * The thread id should only be set when the memcached_st struct is created
755 * and should not be changed.
756 *
757 * The message num is incremented for each new message we send, this function
758 * extracts the message number from message_id, increments it and then
759 * writes the new value back into the header
760 */
761 static void increment_udp_message_id(memcached_server_write_instance_st ptr)
762 {
763 struct udp_datagram_header_st *header= (struct udp_datagram_header_st *)ptr->write_buffer;
764 uint16_t cur_req= get_udp_datagram_request_id(header);
765 int msg_num= get_msg_num_from_request_id(cur_req);
766 int thread_id= get_thread_id_from_request_id(cur_req);
767
768 if (((++msg_num) & UDP_REQUEST_ID_THREAD_MASK) != 0)
769 msg_num= 0;
770
771 header->request_id= htons((uint16_t) (thread_id | msg_num));
772 }
773
774 memcached_return_t memcached_io_init_udp_header(memcached_server_write_instance_st ptr, uint16_t thread_id)
775 {
776 if (thread_id > UDP_REQUEST_ID_MAX_THREAD_ID)
777 return MEMCACHED_FAILURE;
778
779 struct udp_datagram_header_st *header= (struct udp_datagram_header_st *)ptr->write_buffer;
780 header->request_id= htons((uint16_t) (generate_udp_request_thread_id(thread_id)));
781 header->num_datagrams= htons(1);
782 header->sequence_number= htons(0);
783
784 return MEMCACHED_SUCCESS;
785 }