1
from nova import datastore
3
class RackspaceAPIIdTranslator(object):
5
Converts Rackspace API ids to and from the id format for a given
9
def __init__(self, id_type, service_name):
11
Creates a translator for ids of the given type (e.g. 'flavor'), for the
12
given storage service backend class name (e.g. 'LocalFlavorService').
15
self._store = datastore.Redis.instance()
16
key_prefix = "rsapi.idtranslator.%s.%s" % (id_type, service_name)
17
# Forward (strategy format -> RS format) and reverse translation keys
18
self._fwd_key = "%s.fwd" % key_prefix
19
self._rev_key = "%s.rev" % key_prefix
21
def to_rs_id(self, opaque_id):
22
"""Convert an id from a strategy-specific one to a Rackspace one."""
23
result = self._store.hget(self._fwd_key, str(opaque_id))
24
if result: # we have a mapping from opaque to RS for this strategy
28
nextid = self._store.incr("%s.lastid" % self._fwd_key)
29
if self._store.hsetnx(self._fwd_key, str(opaque_id), nextid):
30
# If someone else didn't beat us to it, store the reverse
32
self._store.hset(self._rev_key, nextid, str(opaque_id))
35
# Someone beat us to it; use their number instead, and
36
# discard nextid (which is OK -- we don't require that
37
# every int id be used.)
38
return int(self._store.hget(self._fwd_key, str(opaque_id)))
40
def from_rs_id(self, rs_id):
41
"""Convert a Rackspace id to a strategy-specific one."""
42
return self._store.hget(self._rev_key, rs_id)