2012-03-19 13:45:34 -05:00
|
|
|
# Copyright (c) 2010-2012 OpenStack, LLC.
|
2010-07-12 17:03:45 -05:00
|
|
|
#
|
|
|
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
# you may not use this file except in compliance with the License.
|
|
|
|
# You may obtain a copy of the License at
|
|
|
|
#
|
|
|
|
# http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
#
|
|
|
|
# Unless required by applicable law or agreed to in writing, software
|
|
|
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
|
|
# implied.
|
|
|
|
# See the License for the specific language governing permissions and
|
|
|
|
# limitations under the License.
|
|
|
|
|
|
|
|
""" Tests for swift.common.utils """
|
|
|
|
|
|
|
|
from __future__ import with_statement
|
|
|
|
import hashlib
|
|
|
|
import logging
|
|
|
|
import socket
|
|
|
|
import time
|
|
|
|
import unittest
|
2012-01-12 22:30:32 +00:00
|
|
|
from uuid import uuid4
|
2010-07-12 17:03:45 -05:00
|
|
|
|
|
|
|
from swift.common import memcached
|
Adding StatsD logging to Swift.
Documentation, including a list of metrics reported and their semantics,
is in the Admin Guide in a new section, "Reporting Metrics to StatsD".
An optional "metric prefix" may be configured which will be prepended to
every metric name sent to StatsD.
Here is the rationale for doing a deep integration like this versus only
sending metrics to StatsD in middleware. It's the only way to report
some internal activities of Swift in a real-time manner. So to have one
way of reporting to StatsD and one place/style of configuration, even
some things (like, say, timing of PUT requests into the proxy-server)
which could be logged via middleware are consistently logged the same
way (deep integration via the logger delegate methods).
When log_statsd_host is configured, get_logger() injects a
swift.common.utils.StatsdClient object into the logger as
logger.statsd_client. Then a set of delegate methods on LogAdapter
either pass through to the StatsdClient object or become no-ops. This
allows StatsD logging to look like:
self.logger.increment('some.metric.here')
and do the right thing in all cases and with no messy conditional logic.
I wanted to use the pystatsd module for the StatsD client, but the
version on PyPi is lagging the git repo (and is missing both the prefix
functionality and timing_since() method). So I wrote my
swift.common.utils.StatsdClient. The interface is the same as
pystatsd.Client, but the code was written from scratch. It's pretty
simple, and the tests I added cover it. This also frees Swift from an
optional dependency on the pystatsd module, making this feature easier
to enable.
There's test coverage for the new code and all existing tests continue
to pass.
Refactored out _one_audit_pass() method in swift/account/auditor.py and
swift/container/auditor.py.
Fixed some misc. PEP8 violations.
Misc test cleanups and refactorings (particularly the way "fake logging"
is handled).
Change-Id: Ie968a9ae8771f59ee7591e2ae11999c44bfe33b2
2012-04-01 16:47:08 -07:00
|
|
|
from test.unit import NullLoggingHandler
|
2010-07-12 17:03:45 -05:00
|
|
|
|
|
|
|
|
|
|
|
class ExplodingMockMemcached(object):
|
|
|
|
exploded = False
|
|
|
|
def sendall(self, string):
|
|
|
|
self.exploded = True
|
|
|
|
raise socket.error()
|
|
|
|
def readline(self):
|
|
|
|
self.exploded = True
|
|
|
|
raise socket.error()
|
|
|
|
def read(self, size):
|
|
|
|
self.exploded = True
|
|
|
|
raise socket.error()
|
|
|
|
|
|
|
|
class MockMemcached(object):
|
|
|
|
def __init__(self):
|
|
|
|
self.inbuf = ''
|
|
|
|
self.outbuf = ''
|
|
|
|
self.cache = {}
|
|
|
|
self.down = False
|
|
|
|
self.exc_on_delete = False
|
2011-02-23 11:44:36 -08:00
|
|
|
self.read_return_none = False
|
2010-07-12 17:03:45 -05:00
|
|
|
|
|
|
|
def sendall(self, string):
|
|
|
|
if self.down:
|
|
|
|
raise Exception('mock is down')
|
|
|
|
self.inbuf += string
|
|
|
|
while '\n' in self.inbuf:
|
|
|
|
cmd, self.inbuf = self.inbuf.split('\n', 1)
|
|
|
|
parts = cmd.split()
|
|
|
|
if parts[0].lower() == 'set':
|
|
|
|
self.cache[parts[1]] = parts[2], parts[3], \
|
|
|
|
self.inbuf[:int(parts[4])]
|
|
|
|
self.inbuf = self.inbuf[int(parts[4])+2:]
|
|
|
|
if len(parts) < 6 or parts[5] != 'noreply':
|
|
|
|
self.outbuf += 'STORED\r\n'
|
|
|
|
elif parts[0].lower() == 'add':
|
|
|
|
value = self.inbuf[:int(parts[4])]
|
|
|
|
self.inbuf = self.inbuf[int(parts[4])+2:]
|
|
|
|
if parts[1] in self.cache:
|
|
|
|
if len(parts) < 6 or parts[5] != 'noreply':
|
|
|
|
self.outbuf += 'NOT_STORED\r\n'
|
|
|
|
else:
|
|
|
|
self.cache[parts[1]] = parts[2], parts[3], value
|
|
|
|
if len(parts) < 6 or parts[5] != 'noreply':
|
|
|
|
self.outbuf += 'STORED\r\n'
|
|
|
|
elif parts[0].lower() == 'delete':
|
|
|
|
if self.exc_on_delete:
|
|
|
|
raise Exception('mock is has exc_on_delete set')
|
|
|
|
if parts[1] in self.cache:
|
|
|
|
del self.cache[parts[1]]
|
|
|
|
if 'noreply' not in parts:
|
|
|
|
self.outbuf += 'DELETED\r\n'
|
|
|
|
elif 'noreply' not in parts:
|
|
|
|
self.outbuf += 'NOT_FOUND\r\n'
|
|
|
|
elif parts[0].lower() == 'get':
|
|
|
|
for key in parts[1:]:
|
|
|
|
if key in self.cache:
|
|
|
|
val = self.cache[key]
|
|
|
|
self.outbuf += 'VALUE %s %s %s\r\n' % (key, val[0], len(val[2]))
|
|
|
|
self.outbuf += val[2] + '\r\n'
|
|
|
|
self.outbuf += 'END\r\n'
|
|
|
|
elif parts[0].lower() == 'incr':
|
|
|
|
if parts[1] in self.cache:
|
|
|
|
val = list(self.cache[parts[1]])
|
|
|
|
val[2] = str(int(val[2]) + int(parts[2]))
|
|
|
|
self.cache[parts[1]] = val
|
|
|
|
self.outbuf += str(val[2]) + '\r\n'
|
|
|
|
else:
|
|
|
|
self.outbuf += 'NOT_FOUND\r\n'
|
2010-10-22 15:25:22 -07:00
|
|
|
elif parts[0].lower() == 'decr':
|
|
|
|
if parts[1] in self.cache:
|
|
|
|
val = list(self.cache[parts[1]])
|
|
|
|
if int(val[2]) - int(parts[2]) > 0:
|
|
|
|
val[2] = str(int(val[2]) - int(parts[2]))
|
|
|
|
else:
|
|
|
|
val[2] = '0'
|
|
|
|
self.cache[parts[1]] = val
|
|
|
|
self.outbuf += str(val[2]) + '\r\n'
|
|
|
|
else:
|
|
|
|
self.outbuf += 'NOT_FOUND\r\n'
|
2010-07-12 17:03:45 -05:00
|
|
|
def readline(self):
|
2011-02-23 11:44:36 -08:00
|
|
|
if self.read_return_none:
|
|
|
|
return None
|
2010-07-12 17:03:45 -05:00
|
|
|
if self.down:
|
|
|
|
raise Exception('mock is down')
|
|
|
|
if '\n' in self.outbuf:
|
|
|
|
response, self.outbuf = self.outbuf.split('\n', 1)
|
|
|
|
return response+'\n'
|
|
|
|
def read(self, size):
|
|
|
|
if self.down:
|
|
|
|
raise Exception('mock is down')
|
|
|
|
if len(self.outbuf) >= size:
|
|
|
|
response = self.outbuf[:size]
|
|
|
|
self.outbuf = self.outbuf[size:]
|
|
|
|
return response
|
|
|
|
|
|
|
|
class TestMemcached(unittest.TestCase):
|
|
|
|
""" Tests for swift.common.memcached"""
|
|
|
|
|
|
|
|
def test_get_conns(self):
|
|
|
|
sock1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
|
|
|
sock1.bind(('127.0.0.1', 0))
|
|
|
|
sock1.listen(1)
|
|
|
|
sock1ipport = '%s:%s' % sock1.getsockname()
|
|
|
|
sock2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
|
|
|
sock2.bind(('127.0.0.1', 0))
|
|
|
|
sock2.listen(1)
|
2012-01-12 22:30:32 +00:00
|
|
|
orig_port = memcached.DEFAULT_MEMCACHED_PORT
|
|
|
|
try:
|
|
|
|
sock2ip, memcached.DEFAULT_MEMCACHED_PORT = sock2.getsockname()
|
|
|
|
sock2ipport = '%s:%s' % (sock2ip, memcached.DEFAULT_MEMCACHED_PORT)
|
|
|
|
# We're deliberately using sock2ip (no port) here to test that the
|
|
|
|
# default port is used.
|
|
|
|
memcache_client = memcached.MemcacheRing([sock1ipport, sock2ip])
|
|
|
|
one = two = True
|
|
|
|
while one or two: # Run until we match hosts one and two
|
|
|
|
key = uuid4().hex
|
|
|
|
for conn in memcache_client._get_conns(key):
|
|
|
|
peeripport = '%s:%s' % conn[2].getpeername()
|
|
|
|
self.assert_(peeripport in (sock1ipport, sock2ipport))
|
|
|
|
if peeripport == sock1ipport:
|
|
|
|
one = False
|
|
|
|
if peeripport == sock2ipport:
|
|
|
|
two = False
|
|
|
|
finally:
|
|
|
|
memcached.DEFAULT_MEMCACHED_PORT = orig_port
|
2010-07-12 17:03:45 -05:00
|
|
|
|
|
|
|
def test_set_get(self):
|
|
|
|
memcache_client = memcached.MemcacheRing(['1.2.3.4:11211'])
|
|
|
|
mock = MockMemcached()
|
|
|
|
memcache_client._client_cache['1.2.3.4:11211'] = [(mock, mock)] * 2
|
|
|
|
memcache_client.set('some_key', [1, 2, 3])
|
|
|
|
self.assertEquals(memcache_client.get('some_key'), [1, 2, 3])
|
|
|
|
memcache_client.set('some_key', [4, 5, 6])
|
|
|
|
self.assertEquals(memcache_client.get('some_key'), [4, 5, 6])
|
|
|
|
self.assert_(float(mock.cache.values()[0][1]) == 0)
|
|
|
|
esttimeout = time.time() + 10
|
|
|
|
memcache_client.set('some_key', [1, 2, 3], timeout=10)
|
|
|
|
self.assert_(-1 <= float(mock.cache.values()[0][1]) - esttimeout <= 1)
|
|
|
|
|
|
|
|
def test_incr(self):
|
|
|
|
memcache_client = memcached.MemcacheRing(['1.2.3.4:11211'])
|
|
|
|
mock = MockMemcached()
|
|
|
|
memcache_client._client_cache['1.2.3.4:11211'] = [(mock, mock)] * 2
|
|
|
|
memcache_client.incr('some_key', delta=5)
|
|
|
|
self.assertEquals(memcache_client.get('some_key'), '5')
|
|
|
|
memcache_client.incr('some_key', delta=5)
|
|
|
|
self.assertEquals(memcache_client.get('some_key'), '10')
|
|
|
|
memcache_client.incr('some_key', delta=1)
|
|
|
|
self.assertEquals(memcache_client.get('some_key'), '11')
|
2010-10-22 15:25:22 -07:00
|
|
|
memcache_client.incr('some_key', delta=-5)
|
|
|
|
self.assertEquals(memcache_client.get('some_key'), '6')
|
|
|
|
memcache_client.incr('some_key', delta=-15)
|
2010-10-25 12:52:25 -07:00
|
|
|
self.assertEquals(memcache_client.get('some_key'), '0')
|
2011-02-23 11:44:36 -08:00
|
|
|
mock.read_return_none = True
|
|
|
|
self.assertRaises(memcached.MemcacheConnectionError,
|
|
|
|
memcache_client.incr, 'some_key', delta=-15)
|
2010-10-25 12:52:25 -07:00
|
|
|
|
|
|
|
def test_decr(self):
|
|
|
|
memcache_client = memcached.MemcacheRing(['1.2.3.4:11211'])
|
|
|
|
mock = MockMemcached()
|
|
|
|
memcache_client._client_cache['1.2.3.4:11211'] = [(mock, mock)] * 2
|
|
|
|
memcache_client.decr('some_key', delta=5)
|
|
|
|
self.assertEquals(memcache_client.get('some_key'), '0')
|
|
|
|
memcache_client.incr('some_key', delta=15)
|
|
|
|
self.assertEquals(memcache_client.get('some_key'), '15')
|
|
|
|
memcache_client.decr('some_key', delta=4)
|
|
|
|
self.assertEquals(memcache_client.get('some_key'), '11')
|
|
|
|
memcache_client.decr('some_key', delta=15)
|
2010-10-22 15:25:22 -07:00
|
|
|
self.assertEquals(memcache_client.get('some_key'), '0')
|
2011-02-23 11:44:36 -08:00
|
|
|
mock.read_return_none = True
|
|
|
|
self.assertRaises(memcached.MemcacheConnectionError,
|
|
|
|
memcache_client.decr, 'some_key', delta=15)
|
|
|
|
|
2010-07-12 17:03:45 -05:00
|
|
|
|
|
|
|
def test_retry(self):
|
|
|
|
logging.getLogger().addHandler(NullLoggingHandler())
|
|
|
|
memcache_client = memcached.MemcacheRing(['1.2.3.4:11211', '1.2.3.5:11211'])
|
|
|
|
mock1 = ExplodingMockMemcached()
|
|
|
|
mock2 = MockMemcached()
|
|
|
|
memcache_client._client_cache['1.2.3.4:11211'] = [(mock2, mock2)]
|
|
|
|
memcache_client._client_cache['1.2.3.5:11211'] = [(mock1, mock1)]
|
|
|
|
memcache_client.set('some_key', [1, 2, 3])
|
|
|
|
self.assertEquals(memcache_client.get('some_key'), [1, 2, 3])
|
|
|
|
self.assertEquals(mock1.exploded, True)
|
|
|
|
|
|
|
|
def test_delete(self):
|
|
|
|
memcache_client = memcached.MemcacheRing(['1.2.3.4:11211'])
|
|
|
|
mock = MockMemcached()
|
|
|
|
memcache_client._client_cache['1.2.3.4:11211'] = [(mock, mock)] * 2
|
|
|
|
memcache_client.set('some_key', [1, 2, 3])
|
|
|
|
self.assertEquals(memcache_client.get('some_key'), [1, 2, 3])
|
|
|
|
memcache_client.delete('some_key')
|
|
|
|
self.assertEquals(memcache_client.get('some_key'), None)
|
|
|
|
|
|
|
|
def test_multi(self):
|
|
|
|
memcache_client = memcached.MemcacheRing(['1.2.3.4:11211'])
|
|
|
|
mock = MockMemcached()
|
|
|
|
memcache_client._client_cache['1.2.3.4:11211'] = [(mock, mock)] * 2
|
|
|
|
memcache_client.set_multi(
|
|
|
|
{'some_key1': [1, 2, 3], 'some_key2': [4, 5, 6]}, 'multi_key')
|
|
|
|
self.assertEquals(
|
|
|
|
memcache_client.get_multi(('some_key2', 'some_key1'), 'multi_key'),
|
|
|
|
[[4, 5, 6], [1, 2, 3]])
|
|
|
|
esttimeout = time.time() + 10
|
|
|
|
memcache_client.set_multi(
|
|
|
|
{'some_key1': [1, 2, 3], 'some_key2': [4, 5, 6]}, 'multi_key',
|
|
|
|
timeout=10)
|
|
|
|
self.assert_(-1 <= float(mock.cache.values()[0][1]) - esttimeout <= 1)
|
|
|
|
self.assert_(-1 <= float(mock.cache.values()[1][1]) - esttimeout <= 1)
|
|
|
|
self.assertEquals(memcache_client.get_multi(('some_key2', 'some_key1',
|
|
|
|
'not_exists'), 'multi_key'), [[4, 5, 6], [1, 2, 3], None])
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
|
|
|
unittest.main()
|
|
|
|
|