#!/usr/bin/env python from getpass import getuser from optparse import OptionParser from os.path import basename from sys import argv, exit, stdin from pithos.lib.client import Client, Fault import json import logging DEFAULT_HOST = '127.0.0.1:8000' DEFAULT_API = 'v1' _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') self.add_options(parser) 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.host, self.user, self.api, self.verbose, self.debug) self.parser = parser self.args = args def add_options(self, parser): pass def execute(self, *args): pass @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') parser.add_option('-n', action='store', type='int', dest='limit', default=1000, help='show limited output') parser.add_option('--marker', action='store', type='str', dest='marker', default=None, help='show output greater then marker') parser.add_option('--prefix', action='store', type='str', dest='prefix', default=None, help='show output starting with prefix') parser.add_option('--delimiter', action='store', type='str', dest='delimiter', default=None, help='show output up to the delimiter') parser.add_option('--path', action='store', type='str', dest='path', default=None, help='show output starting with prefix up to /') parser.add_option('--meta', action='store', type='str', dest='meta', default=None, help='show output having the specified meta keys') parser.add_option('--if-modified-since', action='store', type='str', dest='if_modified_since', default=None, help='show output if modified since then') parser.add_option('--if-unmodified-since', action='store', type='str', dest='if_unmodified_since', default=None, help='show output if not modified since then') def execute(self, container=None): if container: self.list_objects(container) else: self.list_containers() def list_containers(self): l = self.client.list_containers(self.detail, self.limit, self.marker, self.if_modified_since, self.if_unmodified_since) if self.detail: for container in l: print_dict(container) print else: if self.verbose: print l else: print l.split('Traceback')[0] def list_objects(self, container): l = self.client.list_objects(container, self.detail, self.limit, self.marker, self.prefix, self.delimiter, self.path, self.meta, self.if_modified_since, self.if_unmodified_since) if self.detail: for obj in l: print_dict(obj) print else: if self.verbose: print l else: print l.split('Traceback')[0] @cli_command('meta') class Meta(Command): syntax = '[[/]]' 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) else: meta = self.client.account_metadata() print_dict(meta, header=None) @cli_command('create') class CreateContainer(Command): syntax = '' 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 = '[/]' description = 'delete a container or an object' def execute(self, path): container, sep, object = path.partition('/') if object: self.client.delete_object(container, object) else: self.client.delete_container(container) @cli_command('get') class GetObject(Command): syntax = '/' description = 'get the data of an object' def execute(self, path): container, sep, object = path.partition('/') print self.client.retrieve_object(container, object) @cli_command('put') class PutObject(Command): syntax = '/ ' 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 = f.read() self.client.create_object(container, object, data) f.close() @cli_command('copy', 'cp') class CopyObject(Command): syntax = '/ [/]' 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) @cli_command('set') class SetMeta(Command): syntax = '[[/]] key=val [key=val] [...]' description = 'set metadata' def execute(self, path, *args): #in case of account fix the args print path if path.find('='): args = list(args) args.append(path) args = tuple(args) path = '' meta = {} for arg in args: key, sep, val = arg.partition('=') meta[key.strip()] = val.strip() container, sep, object = path.partition('/') if object: self.client.update_object_metadata(container, object, **meta) elif container: self.client.update_container_metadata(container, **meta) else: self.client.update_account_metadata(**meta) def print_usage(): cmd = Command([]) parser = cmd.parser parser.usage = '%prog [options]' parser.print_help() 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(): try: name = argv[1] cls = class_for_cli_command(name) except (IndexError, KeyError): print_usage() exit(1) cmd = cls(argv[2:]) try: cmd.execute(*cmd.args) except TypeError: cmd.parser.usage = '%%prog %s [options] %s' % (name, cmd.syntax) cmd.parser.print_help() exit(1) except Fault, f: print f.data if __name__ == '__main__': main()