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);
333 int flags
= with_flush
? MSG_NOSIGNAL
|MSG_DONTWAIT
: MSG_NOSIGNAL
|MSG_DONTWAIT
|MSG_MORE
;
334 ssize_t sent_length
= ::send(ptr
->fd
, local_write_ptr
, write_length
, flags
);
336 if (sent_length
== SOCKET_ERROR
)
338 #if 0 // @todo I should look at why we hit this bit of code hard frequently
339 WATCHPOINT_ERRNO(get_socket_errno());
340 WATCHPOINT_NUMBER(get_socket_errno());
342 switch (get_socket_errno())
347 #if EWOULDBLOCK != EAGAIN
353 * We may be blocked on write because the input buffer
354 * is full. Let's check if we have room in our input
355 * buffer for more data and retry the write before
358 if (repack_input_buffer(ptr
) or process_input_buffer(ptr
))
363 memcached_return_t rc
= io_wait(ptr
, MEM_WRITE
);
364 if (memcached_success(rc
))
368 else if (rc
== MEMCACHED_TIMEOUT
)
373 memcached_quit_server(ptr
, true);
374 error
= memcached_set_errno(*ptr
, get_socket_errno(), MEMCACHED_AT
);
380 memcached_quit_server(ptr
, true);
381 error
= memcached_set_errno(*ptr
, get_socket_errno(), MEMCACHED_AT
);
382 WATCHPOINT_ASSERT(ptr
->fd
== INVALID_SOCKET
);
387 ptr
->io_bytes_sent
+= uint32_t(sent_length
);
389 local_write_ptr
+= sent_length
;
390 write_length
-= uint32_t(sent_length
);
393 WATCHPOINT_ASSERT(write_length
== 0);
394 ptr
->write_buffer_offset
= 0;
399 memcached_return_t
memcached_io_wait_for_write(org::libmemcached::Instance
* ptr
)
401 return io_wait(ptr
, MEM_WRITE
);
404 static memcached_return_t
_io_fill(org::libmemcached::Instance
* ptr
)
409 data_read
= ::recv(ptr
->fd
, ptr
->read_buffer
, MEMCACHED_MAX_BUFFER
, MSG_DONTWAIT
);
410 if (data_read
== SOCKET_ERROR
)
412 switch (get_socket_errno())
414 case EINTR
: // We just retry
417 case ETIMEDOUT
: // OSX
418 #if EWOULDBLOCK != EAGAIN
422 #ifdef TARGET_OS_LINUX
426 memcached_return_t io_wait_ret
;
427 if (memcached_success(io_wait_ret
= io_wait(ptr
, MEM_READ
)))
437 case ENOTCONN
: // Programmer Error
438 WATCHPOINT_ASSERT(0);
440 WATCHPOINT_ASSERT(0);
442 assert_msg(ptr
->fd
!= INVALID_SOCKET
, "Programmer error, invalid socket");
447 memcached_quit_server(ptr
, true);
448 memcached_set_errno(*ptr
, get_socket_errno(), MEMCACHED_AT
);
452 return memcached_instance_error_return(ptr
);
454 else if (data_read
== 0)
457 EOF. Any data received so far is incomplete
458 so discard it. This always reads by byte in case of TCP
459 and protocol enforcement happens at memcached_response()
460 looking for '\n'. We do not care for UDB which requests 8 bytes
461 at once. Generally, this means that connection went away. Since
462 for blocking I/O we do not return 0 and for non-blocking case
463 it will return EGAIN if data is not immediatly available.
465 memcached_quit_server(ptr
, true);
466 return memcached_set_error(*ptr
, MEMCACHED_CONNECTION_FAILURE
, MEMCACHED_AT
,
467 memcached_literal_param("::rec() returned zero, server has disconnected"));
469 ptr
->io_wait_count
._bytes_read
+= data_read
;
470 } while (data_read
<= 0);
472 ptr
->io_bytes_sent
= 0;
473 ptr
->read_data_length
= (size_t) data_read
;
474 ptr
->read_buffer_length
= (size_t) data_read
;
475 ptr
->read_ptr
= ptr
->read_buffer
;
477 return MEMCACHED_SUCCESS
;
480 memcached_return_t
memcached_io_read(org::libmemcached::Instance
* ptr
,
481 void *buffer
, size_t length
, ssize_t
& nread
)
483 assert(memcached_is_udp(ptr
->root
) == false);
484 assert_msg(ptr
, "Programmer error, memcached_io_read() recieved an invalid Instance"); // Programmer error
485 char *buffer_ptr
= static_cast<char *>(buffer
);
487 if (ptr
->fd
== INVALID_SOCKET
)
490 assert_msg(int(ptr
->state
) <= int(MEMCACHED_SERVER_STATE_ADDRINFO
), "Programmer error, invalid socket state");
492 return MEMCACHED_CONNECTION_FAILURE
;
497 if (ptr
->read_buffer_length
== 0)
499 memcached_return_t io_fill_ret
;
500 if (memcached_fatal(io_fill_ret
= _io_fill(ptr
)))
509 size_t difference
= (length
> ptr
->read_buffer_length
) ? ptr
->read_buffer_length
: length
;
511 memcpy(buffer_ptr
, ptr
->read_ptr
, difference
);
512 length
-= difference
;
513 ptr
->read_ptr
+= difference
;
514 ptr
->read_buffer_length
-= difference
;
515 buffer_ptr
+= difference
;
519 *buffer_ptr
= *ptr
->read_ptr
;
521 ptr
->read_buffer_length
--;
527 nread
= ssize_t(buffer_ptr
- (char*)buffer
);
529 return MEMCACHED_SUCCESS
;
532 memcached_return_t
memcached_io_slurp(org::libmemcached::Instance
* ptr
)
534 assert_msg(ptr
, "Programmer error, invalid Instance");
535 assert(memcached_is_udp(ptr
->root
) == false);
537 if (ptr
->fd
== INVALID_SOCKET
)
539 assert_msg(int(ptr
->state
) <= int(MEMCACHED_SERVER_STATE_ADDRINFO
), "Invalid socket state");
540 return MEMCACHED_CONNECTION_FAILURE
;
544 char buffer
[MEMCACHED_MAX_BUFFER
];
547 data_read
= recv(ptr
->fd
, ptr
->read_buffer
, sizeof(buffer
), MSG_DONTWAIT
);
548 if (data_read
== SOCKET_ERROR
)
550 switch (get_socket_errno())
552 case EINTR
: // We just retry
555 case ETIMEDOUT
: // OSX
556 #if EWOULDBLOCK != EAGAIN
560 #ifdef TARGET_OS_LINUX
563 if (memcached_success(io_wait(ptr
, MEM_READ
)))
567 return MEMCACHED_IN_PROGRESS
;
571 case ENOTCONN
: // Programmer Error
576 assert_msg(ptr
->fd
!= INVALID_SOCKET
, "Invalid socket state");
581 return MEMCACHED_CONNECTION_FAILURE
; // We want this!
584 } while (data_read
> 0);
586 return MEMCACHED_CONNECTION_FAILURE
;
589 static bool _io_write(org::libmemcached::Instance
* ptr
,
590 const void *buffer
, size_t length
, bool with_flush
,
593 assert(ptr
->fd
!= INVALID_SOCKET
);
594 assert(memcached_is_udp(ptr
->root
) == false);
596 const char *buffer_ptr
= static_cast<const char *>(buffer
);
598 const size_t original_length
= length
;
603 size_t buffer_end
= MEMCACHED_MAX_BUFFER
;
604 size_t should_write
= buffer_end
-ptr
->write_buffer_offset
;
605 should_write
= (should_write
< length
) ? should_write
: length
;
607 write_ptr
= ptr
->write_buffer
+ ptr
->write_buffer_offset
;
608 memcpy(write_ptr
, buffer_ptr
, should_write
);
609 ptr
->write_buffer_offset
+= should_write
;
610 buffer_ptr
+= should_write
;
611 length
-= should_write
;
613 if (ptr
->write_buffer_offset
== buffer_end
)
615 WATCHPOINT_ASSERT(ptr
->fd
!= INVALID_SOCKET
);
617 memcached_return_t rc
;
618 if (io_flush(ptr
, with_flush
, rc
) == false)
620 written
= original_length
-length
;
628 memcached_return_t rc
;
629 WATCHPOINT_ASSERT(ptr
->fd
!= INVALID_SOCKET
);
630 if (io_flush(ptr
, with_flush
, rc
) == false)
632 written
= original_length
-length
;
637 written
= original_length
-length
;
642 bool memcached_io_write(org::libmemcached::Instance
* ptr
)
645 return _io_write(ptr
, NULL
, 0, true, written
);
648 ssize_t
memcached_io_write(org::libmemcached::Instance
* ptr
,
649 const void *buffer
, const size_t length
, const bool with_flush
)
653 if (_io_write(ptr
, buffer
, length
, with_flush
, written
) == false)
658 return ssize_t(written
);
661 bool memcached_io_writev(org::libmemcached::Instance
* ptr
,
662 libmemcached_io_vector_st vector
[],
663 const size_t number_of
, const bool with_flush
)
665 ssize_t complete_total
= 0;
668 for (size_t x
= 0; x
< number_of
; x
++, vector
++)
670 complete_total
+= vector
->length
;
674 if ((_io_write(ptr
, vector
->buffer
, vector
->length
, false, written
)) == false)
684 if (memcached_io_write(ptr
) == false)
690 return (complete_total
== total
);
694 void memcached_io_close(org::libmemcached::Instance
* ptr
)
696 if (ptr
->fd
== INVALID_SOCKET
)
701 /* in case of death shutdown to avoid blocking at close() */
702 if (shutdown(ptr
->fd
, SHUT_RDWR
) == SOCKET_ERROR
&& get_socket_errno() != ENOTCONN
)
704 WATCHPOINT_NUMBER(ptr
->fd
);
705 WATCHPOINT_ERRNO(get_socket_errno());
706 WATCHPOINT_ASSERT(get_socket_errno());
709 if (closesocket(ptr
->fd
) == SOCKET_ERROR
)
711 WATCHPOINT_ERRNO(get_socket_errno());
713 ptr
->state
= MEMCACHED_SERVER_STATE_NEW
;
714 ptr
->fd
= INVALID_SOCKET
;
717 org::libmemcached::Instance
* memcached_io_get_readable_server(memcached_st
*memc
)
719 #define MAX_SERVERS_TO_POLL 100
720 struct pollfd fds
[MAX_SERVERS_TO_POLL
];
721 nfds_t host_index
= 0;
723 for (uint32_t x
= 0; x
< memcached_server_count(memc
) and host_index
< MAX_SERVERS_TO_POLL
; ++x
)
725 org::libmemcached::Instance
* instance
= memcached_instance_fetch(memc
, x
);
727 if (instance
->read_buffer_length
> 0) /* I have data in the buffer */
732 if (memcached_instance_response_count(instance
) > 0)
734 fds
[host_index
].events
= POLLIN
;
735 fds
[host_index
].revents
= 0;
736 fds
[host_index
].fd
= instance
->fd
;
743 /* We have 0 or 1 server with pending events.. */
744 for (uint32_t x
= 0; x
< memcached_server_count(memc
); ++x
)
746 org::libmemcached::Instance
* instance
= memcached_instance_fetch(memc
, x
);
748 if (memcached_instance_response_count(instance
) > 0)
757 int error
= poll(fds
, host_index
, memc
->poll_timeout
);
761 memcached_set_errno(*memc
, get_socket_errno(), MEMCACHED_AT
);
767 for (nfds_t x
= 0; x
< host_index
; ++x
)
769 if (fds
[x
].revents
& POLLIN
)
771 for (uint32_t y
= 0; y
< memcached_server_count(memc
); ++y
)
773 org::libmemcached::Instance
* instance
= memcached_instance_fetch(memc
, y
);
775 if (instance
->fd
== fds
[x
].fd
)
788 Eventually we will just kill off the server with the problem.
790 void memcached_io_reset(org::libmemcached::Instance
* ptr
)
792 memcached_quit_server(ptr
, true);
796 * Read a given number of bytes from the server and place it into a specific
797 * buffer. Reset the IO channel on this server if an error occurs.
799 memcached_return_t
memcached_safe_read(org::libmemcached::Instance
* ptr
,
804 char *data
= static_cast<char *>(dta
);
806 while (offset
< size
)
809 memcached_return_t rc
;
811 while (memcached_continue(rc
= memcached_io_read(ptr
, data
+ offset
, size
- offset
, nread
))) { };
813 if (memcached_failed(rc
))
818 offset
+= size_t(nread
);
821 return MEMCACHED_SUCCESS
;
824 memcached_return_t
memcached_io_readline(org::libmemcached::Instance
* ptr
,
830 bool line_complete
= false;
832 while (line_complete
== false)
834 if (ptr
->read_buffer_length
== 0)
837 * We don't have any data in the buffer, so let's fill the read
838 * buffer. Call the standard read function to avoid duplicating
842 memcached_return_t rc
= memcached_io_read(ptr
, buffer_ptr
, 1, nread
);
843 if (memcached_failed(rc
) and rc
== MEMCACHED_IN_PROGRESS
)
845 memcached_quit_server(ptr
, true);
846 return memcached_set_error(*ptr
, rc
, MEMCACHED_AT
);
848 else if (memcached_failed(rc
))
853 if (*buffer_ptr
== '\n')
862 /* Now let's look in the buffer and copy as we go! */
863 while (ptr
->read_buffer_length
and total_nr
< size
and line_complete
== false)
865 *buffer_ptr
= *ptr
->read_ptr
;
866 if (*buffer_ptr
== '\n')
868 line_complete
= true;
870 --ptr
->read_buffer_length
;
876 if (total_nr
== size
)
878 return MEMCACHED_PROTOCOL_ERROR
;
882 return MEMCACHED_SUCCESS
;