1 /* vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
5 * Copyright (C) 2011 Data Differential, http://datadifferential.com/
6 * Copyright (C) 2006-2009 Brian Aker
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions are
13 * * Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
16 * * Redistributions in binary form must reproduce the above
17 * copyright notice, this list of conditions and the following disclaimer
18 * in the documentation and/or other materials provided with the
21 * * The names of its contributors may not be used to endorse or
22 * promote products derived from this software without specific prior
25 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
26 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
27 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
28 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
29 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
30 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
31 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
32 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
33 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
34 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
35 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40 #include <libmemcached/common.h>
42 void initialize_binary_request(org::libmemcached::Instance
* server
, protocol_binary_request_header
& header
)
45 header
.request
.magic
= PROTOCOL_BINARY_REQ
;
46 header
.request
.opaque
= htons(server
->request_id
);
49 enum memc_read_or_write
{
55 * Try to fill the input buffer for a server with as much
58 * @param ptr the server to pack
60 static bool repack_input_buffer(org::libmemcached::Instance
* ptr
)
62 if (ptr
->read_ptr
!= ptr
->read_buffer
)
64 /* Move all of the data to the beginning of the buffer so
65 ** that we can fit more data into the buffer...
67 memmove(ptr
->read_buffer
, ptr
->read_ptr
, ptr
->read_buffer_length
);
68 ptr
->read_ptr
= ptr
->read_buffer
;
69 ptr
->read_data_length
= ptr
->read_buffer_length
;
72 /* There is room in the buffer, try to fill it! */
73 if (ptr
->read_buffer_length
!= MEMCACHED_MAX_BUFFER
)
76 /* Just try a single read to grab what's available */
78 if ((nr
= recv(ptr
->fd
,
79 ptr
->read_ptr
+ ptr
->read_data_length
,
80 MEMCACHED_MAX_BUFFER
- ptr
->read_data_length
,
85 memcached_set_error(*ptr
, MEMCACHED_CONNECTION_FAILURE
, MEMCACHED_AT
);
89 switch (get_socket_errno())
94 #if EWOULDBLOCK != EAGAIN
98 #ifdef TARGET_OS_LINUX
101 break; // No IO is fine, we can just move on
104 memcached_set_errno(*ptr
, get_socket_errno(), MEMCACHED_AT
);
110 else // We read data, append to our read buffer
112 ptr
->read_data_length
+= size_t(nr
);
113 ptr
->read_buffer_length
+= size_t(nr
);
124 * If the we have callbacks connected to this server structure
125 * we may start process the input queue and fire the callbacks
126 * for the incomming messages. This function is _only_ called
127 * when the input buffer is full, so that we _know_ that we have
128 * at least _one_ message to process.
130 * @param ptr the server to star processing iput messages for
131 * @return true if we processed anything, false otherwise
133 static bool process_input_buffer(org::libmemcached::Instance
* ptr
)
136 ** We might be able to process some of the response messages if we
137 ** have a callback set up
139 if (ptr
->root
->callbacks
!= NULL
)
142 * We might have responses... try to read them out and fire
145 memcached_callback_st cb
= *ptr
->root
->callbacks
;
147 memcached_set_processing_input((memcached_st
*)ptr
->root
, true);
149 char buffer
[MEMCACHED_DEFAULT_COMMAND_SIZE
];
150 memcached_st
*root
= (memcached_st
*)ptr
->root
;
151 memcached_return_t error
= memcached_response(ptr
, buffer
, sizeof(buffer
), &root
->result
);
153 memcached_set_processing_input(root
, false);
155 if (error
== MEMCACHED_SUCCESS
)
157 for (unsigned int x
= 0; x
< cb
.number_of_callback
; x
++)
159 error
= (*cb
.callback
[x
])(ptr
->root
, &root
->result
, cb
.context
);
160 if (error
!= MEMCACHED_SUCCESS
)
166 /* @todo what should I do with the error message??? */
168 /* @todo what should I do with other error messages?? */
175 static memcached_return_t
io_wait(org::libmemcached::Instance
* ptr
,
176 const memc_read_or_write read_or_write
)
179 ** We are going to block on write, but at least on Solaris we might block
180 ** on write if we haven't read anything from our input buffer..
181 ** Try to purge the input buffer if we don't do any flow control in the
182 ** application layer (just sending a lot of data etc)
183 ** The test is moved down in the purge function to avoid duplication of
186 if (read_or_write
== MEM_WRITE
)
188 if (memcached_purge(ptr
) == false)
190 return MEMCACHED_FAILURE
;
199 if (read_or_write
== MEM_WRITE
) /* write */
202 ptr
->io_wait_count
.write
++;
206 ptr
->io_wait_count
.read
++;
209 if (ptr
->root
->poll_timeout
== 0) // Mimic 0 causes timeout behavior (not all platforms do this)
211 ptr
->io_wait_count
.timeouts
++;
212 return memcached_set_error(*ptr
, MEMCACHED_TIMEOUT
, MEMCACHED_AT
);
216 while (--loop_max
) // While loop is for ERESTART or EINTR
218 int active_fd
= poll(&fds
, 1, ptr
->root
->poll_timeout
);
222 assert_msg(active_fd
== 1 , "poll() returned an unexpected number of active file descriptors");
223 if (fds
.revents
& POLLIN
or fds
.revents
& POLLOUT
)
225 return MEMCACHED_SUCCESS
;
228 if (fds
.revents
& POLLHUP
)
230 return memcached_set_error(*ptr
, MEMCACHED_CONNECTION_FAILURE
, MEMCACHED_AT
,
231 memcached_literal_param("poll() detected hang up"));
234 if (fds
.revents
& POLLERR
)
236 int local_errno
= EINVAL
;
238 socklen_t len
= sizeof (err
);
239 if (getsockopt(ptr
->fd
, SOL_SOCKET
, SO_ERROR
, &err
, &len
) == 0)
241 if (err
== 0) // treat this as EINTR
247 memcached_quit_server(ptr
, true);
248 return memcached_set_errno(*ptr
, local_errno
, MEMCACHED_AT
,
249 memcached_literal_param("poll() returned POLLHUP"));
252 return memcached_set_error(*ptr
, MEMCACHED_FAILURE
, MEMCACHED_AT
, memcached_literal_param("poll() returned a value that was not dealt with"));
257 ptr
->io_wait_count
.timeouts
++;
258 return memcached_set_error(*ptr
, MEMCACHED_TIMEOUT
, MEMCACHED_AT
);
261 // Only an error should result in this code being called.
262 int local_errno
= get_socket_errno(); // We cache in case memcached_quit_server() modifies errno
263 assert_msg(active_fd
== -1 , "poll() returned an unexpected value");
266 #ifdef TARGET_OS_LINUX
274 memcached_set_error(*ptr
, MEMCACHED_MEMORY_ALLOCATION_FAILURE
, MEMCACHED_AT
);
277 memcached_set_error(*ptr
, MEMCACHED_MEMORY_ALLOCATION_FAILURE
, MEMCACHED_AT
, memcached_literal_param("RLIMIT_NOFILE exceeded, or if OSX the timeout value was invalid"));
280 memcached_set_errno(*ptr
, local_errno
, MEMCACHED_AT
, memcached_literal_param("poll"));
286 memcached_quit_server(ptr
, true);
288 if (memcached_has_error(ptr
))
290 return memcached_instance_error_return(ptr
);
293 return memcached_set_error(*ptr
, MEMCACHED_CONNECTION_FAILURE
, MEMCACHED_AT
,
294 memcached_literal_param("number of attempts to call io_wait() failed"));
297 static bool io_flush(org::libmemcached::Instance
* ptr
,
298 const bool with_flush
,
299 memcached_return_t
& error
)
302 ** We might want to purge the input buffer if we haven't consumed
303 ** any output yet... The test for the limits is the purge is inline
304 ** in the purge function to avoid duplicating the logic..
307 WATCHPOINT_ASSERT(ptr
->fd
!= INVALID_SOCKET
);
309 if (memcached_purge(ptr
) == false)
314 char *local_write_ptr
= ptr
->write_buffer
;
315 size_t write_length
= ptr
->write_buffer_offset
;
317 error
= MEMCACHED_SUCCESS
;
319 WATCHPOINT_ASSERT(ptr
->fd
!= INVALID_SOCKET
);
321 /* Looking for memory overflows */
323 if (write_length
== MEMCACHED_MAX_BUFFER
)
324 WATCHPOINT_ASSERT(ptr
->write_buffer
== local_write_ptr
);
325 WATCHPOINT_ASSERT((ptr
->write_buffer
+ MEMCACHED_MAX_BUFFER
) >= (local_write_ptr
+ write_length
));
330 WATCHPOINT_ASSERT(ptr
->fd
!= INVALID_SOCKET
);
331 WATCHPOINT_ASSERT(write_length
> 0);
336 flags
= MSG_NOSIGNAL
|MSG_DONTWAIT
;
340 flags
= MSG_NOSIGNAL
|MSG_DONTWAIT
|MSG_MORE
;
343 ssize_t sent_length
= ::send(ptr
->fd
, local_write_ptr
, write_length
, flags
);
345 if (sent_length
== SOCKET_ERROR
)
347 #if 0 // @todo I should look at why we hit this bit of code hard frequently
348 WATCHPOINT_ERRNO(get_socket_errno());
349 WATCHPOINT_NUMBER(get_socket_errno());
351 switch (get_socket_errno())
356 #if EWOULDBLOCK != EAGAIN
362 * We may be blocked on write because the input buffer
363 * is full. Let's check if we have room in our input
364 * buffer for more data and retry the write before
367 if (repack_input_buffer(ptr
) or process_input_buffer(ptr
))
372 memcached_return_t rc
= io_wait(ptr
, MEM_WRITE
);
373 if (memcached_success(rc
))
377 else if (rc
== MEMCACHED_TIMEOUT
)
382 memcached_quit_server(ptr
, true);
383 error
= memcached_set_errno(*ptr
, get_socket_errno(), MEMCACHED_AT
);
389 memcached_quit_server(ptr
, true);
390 error
= memcached_set_errno(*ptr
, get_socket_errno(), MEMCACHED_AT
);
391 WATCHPOINT_ASSERT(ptr
->fd
== INVALID_SOCKET
);
396 ptr
->io_bytes_sent
+= uint32_t(sent_length
);
398 local_write_ptr
+= sent_length
;
399 write_length
-= uint32_t(sent_length
);
402 WATCHPOINT_ASSERT(write_length
== 0);
403 ptr
->write_buffer_offset
= 0;
408 memcached_return_t
memcached_io_wait_for_write(org::libmemcached::Instance
* ptr
)
410 return io_wait(ptr
, MEM_WRITE
);
413 static memcached_return_t
_io_fill(org::libmemcached::Instance
* ptr
)
418 data_read
= ::recv(ptr
->fd
, ptr
->read_buffer
, MEMCACHED_MAX_BUFFER
, MSG_DONTWAIT
);
419 if (data_read
== SOCKET_ERROR
)
421 switch (get_socket_errno())
423 case EINTR
: // We just retry
426 case ETIMEDOUT
: // OSX
427 #if EWOULDBLOCK != EAGAIN
431 #ifdef TARGET_OS_LINUX
435 memcached_return_t io_wait_ret
;
436 if (memcached_success(io_wait_ret
= io_wait(ptr
, MEM_READ
)))
446 case ENOTCONN
: // Programmer Error
447 WATCHPOINT_ASSERT(0);
449 WATCHPOINT_ASSERT(0);
451 assert_msg(ptr
->fd
!= INVALID_SOCKET
, "Programmer error, invalid socket");
456 memcached_quit_server(ptr
, true);
457 memcached_set_errno(*ptr
, get_socket_errno(), MEMCACHED_AT
);
461 return memcached_instance_error_return(ptr
);
463 else if (data_read
== 0)
466 EOF. Any data received so far is incomplete
467 so discard it. This always reads by byte in case of TCP
468 and protocol enforcement happens at memcached_response()
469 looking for '\n'. We do not care for UDB which requests 8 bytes
470 at once. Generally, this means that connection went away. Since
471 for blocking I/O we do not return 0 and for non-blocking case
472 it will return EGAIN if data is not immediatly available.
474 memcached_quit_server(ptr
, true);
475 return memcached_set_error(*ptr
, MEMCACHED_CONNECTION_FAILURE
, MEMCACHED_AT
,
476 memcached_literal_param("::rec() returned zero, server has disconnected"));
478 ptr
->io_wait_count
._bytes_read
+= data_read
;
479 } while (data_read
<= 0);
481 ptr
->io_bytes_sent
= 0;
482 ptr
->read_data_length
= (size_t) data_read
;
483 ptr
->read_buffer_length
= (size_t) data_read
;
484 ptr
->read_ptr
= ptr
->read_buffer
;
486 return MEMCACHED_SUCCESS
;
489 memcached_return_t
memcached_io_read(org::libmemcached::Instance
* ptr
,
490 void *buffer
, size_t length
, ssize_t
& nread
)
492 assert(memcached_is_udp(ptr
->root
) == false);
493 assert_msg(ptr
, "Programmer error, memcached_io_read() recieved an invalid Instance"); // Programmer error
494 char *buffer_ptr
= static_cast<char *>(buffer
);
496 if (ptr
->fd
== INVALID_SOCKET
)
499 assert_msg(int(ptr
->state
) <= int(MEMCACHED_SERVER_STATE_ADDRINFO
), "Programmer error, invalid socket state");
501 return MEMCACHED_CONNECTION_FAILURE
;
506 if (ptr
->read_buffer_length
== 0)
508 memcached_return_t io_fill_ret
;
509 if (memcached_fatal(io_fill_ret
= _io_fill(ptr
)))
518 size_t difference
= (length
> ptr
->read_buffer_length
) ? ptr
->read_buffer_length
: length
;
520 memcpy(buffer_ptr
, ptr
->read_ptr
, difference
);
521 length
-= difference
;
522 ptr
->read_ptr
+= difference
;
523 ptr
->read_buffer_length
-= difference
;
524 buffer_ptr
+= difference
;
528 *buffer_ptr
= *ptr
->read_ptr
;
530 ptr
->read_buffer_length
--;
536 nread
= ssize_t(buffer_ptr
- (char*)buffer
);
538 return MEMCACHED_SUCCESS
;
541 memcached_return_t
memcached_io_slurp(org::libmemcached::Instance
* ptr
)
543 assert_msg(ptr
, "Programmer error, invalid Instance");
544 assert(memcached_is_udp(ptr
->root
) == false);
546 if (ptr
->fd
== INVALID_SOCKET
)
548 assert_msg(int(ptr
->state
) <= int(MEMCACHED_SERVER_STATE_ADDRINFO
), "Invalid socket state");
549 return MEMCACHED_CONNECTION_FAILURE
;
553 char buffer
[MEMCACHED_MAX_BUFFER
];
556 data_read
= recv(ptr
->fd
, ptr
->read_buffer
, sizeof(buffer
), MSG_DONTWAIT
);
557 if (data_read
== SOCKET_ERROR
)
559 switch (get_socket_errno())
561 case EINTR
: // We just retry
564 case ETIMEDOUT
: // OSX
565 #if EWOULDBLOCK != EAGAIN
569 #ifdef TARGET_OS_LINUX
572 if (memcached_success(io_wait(ptr
, MEM_READ
)))
576 return MEMCACHED_IN_PROGRESS
;
580 case ENOTCONN
: // Programmer Error
585 assert_msg(ptr
->fd
!= INVALID_SOCKET
, "Invalid socket state");
590 return MEMCACHED_CONNECTION_FAILURE
; // We want this!
593 } while (data_read
> 0);
595 return MEMCACHED_CONNECTION_FAILURE
;
598 static bool _io_write(org::libmemcached::Instance
* ptr
,
599 const void *buffer
, size_t length
, bool with_flush
,
602 assert(ptr
->fd
!= INVALID_SOCKET
);
603 assert(memcached_is_udp(ptr
->root
) == false);
605 const char *buffer_ptr
= static_cast<const char *>(buffer
);
607 const size_t original_length
= length
;
612 size_t buffer_end
= MEMCACHED_MAX_BUFFER
;
613 size_t should_write
= buffer_end
-ptr
->write_buffer_offset
;
614 should_write
= (should_write
< length
) ? should_write
: length
;
616 write_ptr
= ptr
->write_buffer
+ ptr
->write_buffer_offset
;
617 memcpy(write_ptr
, buffer_ptr
, should_write
);
618 ptr
->write_buffer_offset
+= should_write
;
619 buffer_ptr
+= should_write
;
620 length
-= should_write
;
622 if (ptr
->write_buffer_offset
== buffer_end
)
624 WATCHPOINT_ASSERT(ptr
->fd
!= INVALID_SOCKET
);
626 memcached_return_t rc
;
627 if (io_flush(ptr
, with_flush
, rc
) == false)
629 written
= original_length
-length
;
637 memcached_return_t rc
;
638 WATCHPOINT_ASSERT(ptr
->fd
!= INVALID_SOCKET
);
639 if (io_flush(ptr
, with_flush
, rc
) == false)
641 written
= original_length
-length
;
646 written
= original_length
-length
;
651 bool memcached_io_write(org::libmemcached::Instance
* ptr
)
654 return _io_write(ptr
, NULL
, 0, true, written
);
657 ssize_t
memcached_io_write(org::libmemcached::Instance
* ptr
,
658 const void *buffer
, const size_t length
, const bool with_flush
)
662 if (_io_write(ptr
, buffer
, length
, with_flush
, written
) == false)
667 return ssize_t(written
);
670 bool memcached_io_writev(org::libmemcached::Instance
* ptr
,
671 libmemcached_io_vector_st vector
[],
672 const size_t number_of
, const bool with_flush
)
674 ssize_t complete_total
= 0;
677 for (size_t x
= 0; x
< number_of
; x
++, vector
++)
679 complete_total
+= vector
->length
;
683 if ((_io_write(ptr
, vector
->buffer
, vector
->length
, false, written
)) == false)
693 if (memcached_io_write(ptr
) == false)
699 return (complete_total
== total
);
703 void memcached_io_close(org::libmemcached::Instance
* ptr
)
705 if (ptr
->fd
== INVALID_SOCKET
)
710 /* in case of death shutdown to avoid blocking at close() */
711 if (shutdown(ptr
->fd
, SHUT_RDWR
) == SOCKET_ERROR
&& get_socket_errno() != ENOTCONN
)
713 WATCHPOINT_NUMBER(ptr
->fd
);
714 WATCHPOINT_ERRNO(get_socket_errno());
715 WATCHPOINT_ASSERT(get_socket_errno());
718 if (closesocket(ptr
->fd
) == SOCKET_ERROR
)
720 WATCHPOINT_ERRNO(get_socket_errno());
722 ptr
->state
= MEMCACHED_SERVER_STATE_NEW
;
723 ptr
->fd
= INVALID_SOCKET
;
726 org::libmemcached::Instance
* memcached_io_get_readable_server(memcached_st
*memc
)
728 #define MAX_SERVERS_TO_POLL 100
729 struct pollfd fds
[MAX_SERVERS_TO_POLL
];
730 nfds_t host_index
= 0;
732 for (uint32_t x
= 0; x
< memcached_server_count(memc
) and host_index
< MAX_SERVERS_TO_POLL
; ++x
)
734 org::libmemcached::Instance
* instance
= memcached_instance_fetch(memc
, x
);
736 if (instance
->read_buffer_length
> 0) /* I have data in the buffer */
741 if (memcached_instance_response_count(instance
) > 0)
743 fds
[host_index
].events
= POLLIN
;
744 fds
[host_index
].revents
= 0;
745 fds
[host_index
].fd
= instance
->fd
;
752 /* We have 0 or 1 server with pending events.. */
753 for (uint32_t x
= 0; x
< memcached_server_count(memc
); ++x
)
755 org::libmemcached::Instance
* instance
= memcached_instance_fetch(memc
, x
);
757 if (memcached_instance_response_count(instance
) > 0)
766 int error
= poll(fds
, host_index
, memc
->poll_timeout
);
770 memcached_set_errno(*memc
, get_socket_errno(), MEMCACHED_AT
);
776 for (nfds_t x
= 0; x
< host_index
; ++x
)
778 if (fds
[x
].revents
& POLLIN
)
780 for (uint32_t y
= 0; y
< memcached_server_count(memc
); ++y
)
782 org::libmemcached::Instance
* instance
= memcached_instance_fetch(memc
, y
);
784 if (instance
->fd
== fds
[x
].fd
)
797 Eventually we will just kill off the server with the problem.
799 void memcached_io_reset(org::libmemcached::Instance
* ptr
)
801 memcached_quit_server(ptr
, true);
805 * Read a given number of bytes from the server and place it into a specific
806 * buffer. Reset the IO channel on this server if an error occurs.
808 memcached_return_t
memcached_safe_read(org::libmemcached::Instance
* ptr
,
813 char *data
= static_cast<char *>(dta
);
815 while (offset
< size
)
818 memcached_return_t rc
;
820 while (memcached_continue(rc
= memcached_io_read(ptr
, data
+ offset
, size
- offset
, nread
))) { };
822 if (memcached_failed(rc
))
827 offset
+= size_t(nread
);
830 return MEMCACHED_SUCCESS
;
833 memcached_return_t
memcached_io_readline(org::libmemcached::Instance
* ptr
,
839 bool line_complete
= false;
841 while (line_complete
== false)
843 if (ptr
->read_buffer_length
== 0)
846 * We don't have any data in the buffer, so let's fill the read
847 * buffer. Call the standard read function to avoid duplicating
851 memcached_return_t rc
= memcached_io_read(ptr
, buffer_ptr
, 1, nread
);
852 if (memcached_failed(rc
) and rc
== MEMCACHED_IN_PROGRESS
)
854 memcached_quit_server(ptr
, true);
855 return memcached_set_error(*ptr
, rc
, MEMCACHED_AT
);
857 else if (memcached_failed(rc
))
862 if (*buffer_ptr
== '\n')
871 /* Now let's look in the buffer and copy as we go! */
872 while (ptr
->read_buffer_length
and total_nr
< size
and line_complete
== false)
874 *buffer_ptr
= *ptr
->read_ptr
;
875 if (*buffer_ptr
== '\n')
877 line_complete
= true;
879 --ptr
->read_buffer_length
;
885 if (total_nr
== size
)
887 return MEMCACHED_PROTOCOL_ERROR
;
891 return MEMCACHED_SUCCESS
;