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