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