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