Commit 1d54f4cf authored by Giorgos Verigakis's avatar Giorgos Verigakis
Browse files

Add a simple client for the API

parent b031b9f8
#!/usr/bin/env python
from getpass import getuser
from httplib import HTTPConnection
from optparse import OptionParser
from os.path import basename
from sys import argv, exit, stdin
import json
import logging
class Fault(Exception):
def __init__(self, data=''):
Exception.__init__(self, data) = data
class Client(object):
def __init__(self, host, account, api='v1', verbose=False, debug=False):
"""`host` can also include a port, e.g ''.""" = host
self.account = account
self.api = api
self.verbose = verbose or debug
self.debug = debug
def req(self, method, path, body=None, headers=None, format='text'):
full_path = '/%s/%s%s?format=%s' % (self.api, self.account, path, format)
conn = HTTPConnection(
kwargs = {}
kwargs['headers'] = headers or {}
if body:
kwargs['headers']['Content-Length'] = len(body)
kwargs['body'] = body
conn.request(method, full_path, **kwargs)
resp = conn.getresponse()
headers = dict(resp.getheaders())
if self.verbose:
print '%d %s' % (resp.status, resp.reason)
for key, val in headers.items():
print '%s: %s' % (key.capitalize(), val)
data =
if self.debug:
print data
if format == 'json':
data = json.loads(data)
return resp.status, headers, data
def delete(self, path, format='text'):
return self.req('DELETE', path, format=format)
def get(self, path, format='text'):
return self.req('GET', path, format=format)
def head(self, path, format='text'):
return self.req('HEAD', path, format=format)
def post(self, path, body=None, format='text', headers=None):
return self.req('POST', path, body, headers=headers, format=format)
def put(self, path, body=None, format='text', headers=None):
return self.req('PUT', path, body, headers=headers, format=format)
def _list(self, path, detail=False):
format = 'json' if detail else 'text'
status, headers, data = self.get(path, format=format)
return data
def _get_metadata(self, path, prefix):
status, headers, data = self.head(path)
prefixlen = len(prefix)
meta = {}
for key, val in headers.items():
if key.startswith(prefix):
key = key[prefixlen:]
meta[key] = val
return meta
# Storage Account Services
def list_containers(self, detail=False):
return self._list('', detail)
def account_metadata(self):
return self._get_metadata('', 'x-account-')
# Storage Container Services
def list_objects(self, container, detail=False):
return self._list('/' + container, detail)
def create_container(self, container):
status, header, data = self.put('/' + container)
if status == 202:
return False
elif status != 201:
raise Fault(data)
return True
def delete_container(self, container):
self.delete('/' + container)
def retrieve_container_metadata(self, container):
return self._get_metadata('/%s' % container, 'x-container-')
# Storage Object Services
def retrieve_object(self, container, object):
path = '/%s/%s' % (container, object)
status, headers, data = self.get(path)
return data
def create_object(self, container, object, data):
path = '/%s/%s' % (container, object)
self.put(path, data)
def copy_object(self, src_container, src_object, dst_container, dst_object):
path = '/%s/%s' % (dst_container, dst_object)
headers = {}
headers['X-Copy-From'] = '/%s/%s' % (src_container, src_object)
headers['Content-Length'] = 0
self.put(path, headers=headers)
def delete_object(self, container, object):
self.delete('/%s/%s' % (container, object))
def retrieve_object_metadata(self, container, object):
path = '/%s/%s' % (container, object)
return self._get_metadata(path, 'x-object-meta-')
def update_object_metadata(self, container, object, **meta):
path = '/%s/%s' % (container, object)
headers = {}
for key, val in meta.items():
http_key = 'X-Object-Meta-' + key
headers[http_key] = val, headers=headers)
_cli_commands = {}
def cli_command(*args):
def decorator(cls):
cls.commands = args
for name in args:
_cli_commands[name] = cls
return cls
return decorator
def class_for_cli_command(name):
return _cli_commands[name]
def print_dict(d, header='name'):
if header:
print d.pop(header)
for key, val in sorted(d.items()):
print '%s: %s' % (key.rjust(15), val)
class Command(object):
def __init__(self, argv):
parser = OptionParser()
parser.add_option('--host', dest='host', metavar='HOST', default=DEFAULT_HOST,
help='use server HOST')
parser.add_option('--user', dest='user', metavar='USERNAME', default=getuser(),
help='use account USERNAME')
parser.add_option('--api', dest='api', metavar='API', default=DEFAULT_API,
help='use api API')
parser.add_option('-v', action='store_true', dest='verbose', default=False,
help='use verbose output')
parser.add_option('-d', action='store_true', dest='debug', default=False,
help='use debug output')
options, args = parser.parse_args(argv)
# Add options to self
for opt in parser.option_list:
key = opt.dest
if key:
val = getattr(options, key)
setattr(self, key, val)
self.client = Client(, self.user, self.api, self.verbose, self.debug)
self.parser = parser
self.args = args
def add_options(self, parser):
def execute(self, *args):
@cli_command('list', 'ls')
class List(Command):
syntax = '[container]'
description = 'list containers or objects'
def add_options(self, parser):
parser.add_option('-l', action='store_true', dest='detail', default=False,
help='show detailed output')
def execute(self, container=None):
if container:
def list_containers(self):
if self.detail:
for container in self.client.list_containers(detail=True):
print self.client.list_containers().strip()
def list_objects(self, container):
if self.detail:
for obj in self.client.list_objects(container, detail=True):
print self.client.list_objects(container).strip()
class Meta(Command):
syntax = '[<container>[/<object>]]'
description = 'get the metadata of an account, a container or an object'
def execute(self, path=''):
container, sep, object = path.partition('/')
if object:
meta = self.client.retrieve_object_metadata(container, object)
elif container:
meta = self.client.retrieve_container_metadata(container)
meta = self.client.account_metadata()
print_dict(meta, header=None)
class CreateContainer(Command):
syntax = '<container>'
description = 'create a container'
def execute(self, container):
ret = self.client.create_container(container)
if not ret:
print 'Container already exists'
@cli_command('delete', 'rm')
class Delete(Command):
syntax = '<container>[/<object>]'
description = 'delete a container or an object'
def execute(self, path):
container, sep, object = path.partition('/')
if object:
self.client.delete_object(container, object)
class GetObject(Command):
syntax = '<container>/<object>'
description = 'get the data of an object'
def execute(self, path):
container, sep, object = path.partition('/')
print self.client.retrieve_object(container, object)
class PutObject(Command):
syntax = '<container>/<object> <path>'
description = 'create or update an object with contents of path'
def execute(self, path, srcpath):
container, sep, object = path.partition('/')
f = open(srcpath) if srcpath != '-' else stdin
data =
self.client.create_object(container, object, data)
@cli_command('copy', 'cp')
class CopyObject(Command):
syntax = '<src container>/<src object> [<dst container>/]<dst object>'
description = 'copies an object to a different location'
def execute(self, src, dst):
src_container, sep, src_object = src.partition('/')
dst_container, sep, dst_object = dst.partition('/')
if not sep:
dst_container = src_container
dst_object = dst
self.client.copy_object(src_container, src_object, dst_container, dst_object)
class SetOjectMeta(Command):
syntax = '<container>/<object> key=val [key=val] [...]'
description = 'set object metadata'
def execute(self, path, *args):
container, sep, object = path.partition('/')
meta = {}
for arg in args:
key, sep, val = arg.partition('=')
meta[key.strip()] = val.strip()
self.client.update_object_metadata(container, object, **meta)
def print_usage():
cmd = Command([])
parser = cmd.parser
parser.usage = '%prog <command> [options]'
commands = []
for cls in set(_cli_commands.values()):
name = ', '.join(cls.commands)
description = getattr(cls, 'description', '')
commands.append(' %s %s' % (name.ljust(12), description))
print '\nCommands:\n' + '\n'.join(sorted(commands))
def main():
name = argv[1]
cls = class_for_cli_command(name)
except (IndexError, KeyError):
cmd = cls(argv[2:])
except TypeError:
cmd.parser.usage = '%%prog %s [options] %s' % (name, cmd.syntax)
except Fault, f:
if __name__ == '__main__':
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment