Skip to content

Commit

Permalink
implemented the memcache protocol
Browse files Browse the repository at this point in the history
  • Loading branch information
tarekziade committed Nov 13, 2012
1 parent 8231d4c commit 572386b
Showing 1 changed file with 68 additions and 1 deletion.
69 changes: 68 additions & 1 deletion vaurien/handlers/dummy.py
Expand Up @@ -6,6 +6,8 @@

RE_LEN = re.compile('Content-Length: (\d+)', re.M | re.I)
RE_KEEPALIVE = re.compile('Connection: Keep-Alive')
RE_MEMCACHE_COMMAND = re.compile('(.*)\r\n')

EOH = '\r\n\r\n'


Expand Down Expand Up @@ -36,6 +38,70 @@ class Dummy(BaseHandler):
'buffer': ("Buffer size", int, 2048),
'protocol': ("Protocol used", str, 'unknown')}

def _memcache(self, client_sock, backend_sock, to_backend):
buffer_size = self.option('buffer')

# Sending the query
buffer = self._get_data(client_sock, backend_sock, to_backend)
if not buffer:
if not to_backend:
# We want to close the socket if the backend sock is empty
if not self.option('reuse_socket'):
backend_sock.close()
backend_sock._closed = True
return

# sending the first packet
dest = to_backend and backend_sock or client_sock
source = to_backend and client_sock or backend_sock
dest.sendall(buffer)

# finding the command sent.
cmd = RE_MEMCACHE_COMMAND.search(buffer)

if cmd is None:
# wat ?
if not to_backend:
# We want to close the socket if the backend sock is empty
if not self.option('reuse_socket'):
backend_sock.close()
backend_sock._closed = True
return

# looking at the command
cmd = cmd.groups()[0]

if cmd in ('set', 'add', 'replace', 'append'):
cmd_size = len(cmd) + len('\r\n')
data_size = int(cmd.split()[-1])
total_size = cmd_size + data_size

# grabbing more data if needed
left_to_read = total_size - len(buffer)
if left_to_read > 0:
for chunk in chunked(left_to_read, buffer_size):
data = source.recv(chunk)
buffer += data
dest.sendall(data)

# Receiving the response now
buffer = dest.recv(buffer_size)
source.sendall(buffer)

if buffer.startswith('VALUE'):
# we're getting back a value.
EOW = 'END\r\n'
else:
EOW = '\r\n'

while not buffer.endswith(EOW):
data = dest.recv(buffer_size)
buffer += data
source.sendall(data)

# we're done
return True # keeping connected

def _http(self, client_sock, backend_sock, to_backend):
buffer_size = self.option('buffer')

Expand Down Expand Up @@ -100,7 +166,8 @@ def _http(self, client_sock, backend_sock, to_backend):
def __call__(self, client_sock, backend_sock, to_backend):
if self.option('protocol') == 'http':
return self._http(client_sock, backend_sock, to_backend)

elif self.option('protocol') == 'memcache':
return self._memcache(client_sock, backend_sock, to_backend)

data = self._get_data(client_sock, backend_sock, to_backend)
if data:
Expand Down

0 comments on commit 572386b

Please sign in to comment.