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