3 from getpass import getuser
4 from optparse import OptionParser
5 from os.path import basename
6 from sys import argv, exit, stdin, stdout
7 from pithos.lib.client import Client, Fault
13 DEFAULT_HOST = '127.0.0.1:8000'
18 def cli_command(*args):
22 _cli_commands[name] = cls
26 def class_for_cli_command(name):
27 return _cli_commands[name]
29 class Command(object):
30 def __init__(self, argv):
31 parser = OptionParser()
32 parser.add_option('--host', dest='host', metavar='HOST',
33 default=DEFAULT_HOST, help='use server HOST')
34 parser.add_option('--user', dest='user', metavar='USERNAME',
35 default=getuser(), help='use account USERNAME')
36 parser.add_option('--api', dest='api', metavar='API',
37 default=DEFAULT_API, help='use api API')
38 parser.add_option('-v', action='store_true', dest='verbose',
39 default=False, help='use verbose output')
40 parser.add_option('-d', action='store_true', dest='debug',
41 default=False, help='use debug output')
42 self.add_options(parser)
43 options, args = parser.parse_args(argv)
46 for opt in parser.option_list:
49 val = getattr(options, key)
50 setattr(self, key, val)
52 self.client = Client(self.host, self.user, self.api, self.verbose,
58 def add_options(self, parser):
61 def execute(self, *args):
64 @cli_command('list', 'ls')
66 syntax = '[<container>[/<object>]]'
67 description = 'list containers or objects'
69 def add_options(self, parser):
70 parser.add_option('-l', action='store_true', dest='detail',
71 default=False, help='show detailed output')
72 parser.add_option('-n', action='store', type='int', dest='limit',
73 default=1000, help='show limited output')
74 parser.add_option('--marker', action='store', type='str',
75 dest='marker', default=None,
76 help='show output greater then marker')
77 parser.add_option('--prefix', action='store', type='str',
78 dest='prefix', default=None,
79 help='show output starting with prefix')
80 parser.add_option('--delimiter', action='store', type='str',
81 dest='delimiter', default=None,
82 help='show output up to the delimiter')
83 parser.add_option('--path', action='store', type='str',
84 dest='path', default=None,
85 help='show output starting with prefix up to /')
86 parser.add_option('--meta', action='store', type='str',
87 dest='meta', default=None,
88 help='show output having the specified meta keys')
89 parser.add_option('--if-modified-since', action='store', type='str',
90 dest='if_modified_since', default=None,
91 help='show output if modified since then')
92 parser.add_option('--if-unmodified-since', action='store', type='str',
93 dest='if_unmodified_since', default=None,
94 help='show output if not modified since then')
96 def execute(self, container=None):
98 self.list_objects(container)
100 self.list_containers()
102 def list_containers(self):
103 params = {'limit':self.limit, 'marker':self.marker}
104 headers = {'IF_MODIFIED_SINCE':self.if_modified_since,
105 'IF_UNMODIFIED_SINCE':self.if_unmodified_since}
106 l = self.client.list_containers(self.detail, params, headers)
109 def list_objects(self, container):
110 params = {'limit':self.limit, 'marker':self.marker,
111 'prefix':self.prefix, 'delimiter':self.delimiter,
112 'path':self.path, 'meta':self.meta}
113 headers = {'IF_MODIFIED_SINCE':self.if_modified_since,
114 'IF_UNMODIFIED_SINCE':self.if_unmodified_since}
115 l = self.client.list_objects(container, self.detail, params, headers)
120 syntax = '[<container>[/<object>]]'
121 description = 'get the metadata of an account, a container or an object'
123 def execute(self, path=''):
124 container, sep, object = path.partition('/')
126 meta = self.client.retrieve_object_metadata(container, object)
128 meta = self.client.retrieve_container_metadata(container)
130 meta = self.client.account_metadata()
132 print 'Entity does not exist'
134 print_dict(meta, header=None)
136 @cli_command('create')
137 class CreateContainer(Command):
138 syntax = '<container> [key=val] [...]'
139 description = 'create a container'
141 def execute(self, container, *args):
144 key, sep, val = arg.partition('=')
145 headers['X_CONTAINER_META_%s' %key.strip().upper()] = val.strip()
146 ret = self.client.create_container(container, headers)
148 print 'Container already exists'
150 @cli_command('delete', 'rm')
151 class Delete(Command):
152 syntax = '<container>[/<object>]'
153 description = 'delete a container or an object'
155 def execute(self, path):
156 container, sep, object = path.partition('/')
158 self.client.delete_object(container, object)
160 self.client.delete_container(container)
163 class GetObject(Command):
164 syntax = '<container>/<object>'
165 description = 'get the data of an object'
167 def add_options(self, parser):
168 parser.add_option('-l', action='store_true', dest='detail',
169 default=False, help='show detailed output')
170 parser.add_option('--range', action='store', dest='range',
171 default=None, help='show range of data')
172 parser.add_option('--if-match', action='store', dest='if-match',
173 default=None, help='show output if ETags match')
174 parser.add_option('--if-none-match', action='store',
175 dest='if-none-match', default=None,
176 help='show output if ETags don\'t match')
177 parser.add_option('--if-modified-since', action='store', type='str',
178 dest='if-modified-since', default=None,
179 help='show output if modified since then')
180 parser.add_option('--if-unmodified-since', action='store', type='str',
181 dest='if-unmodified-since', default=None,
182 help='show output if not modified since then')
183 parser.add_option('-f', action='store', type='str',
184 dest='file', default=None,
185 help='save output in file')
187 def execute(self, path):
190 headers['RANGE'] = 'bytes=%s' %self.range
191 attrs = ['if-match', 'if-none-match', 'if-modified-since',
192 'if-unmodified-since']
193 attrs = [a for a in attrs if getattr(self, a)]
195 headers[a.replace('-', '_').upper()] = getattr(self, a)
196 container, sep, object = path.partition('/')
197 data = self.client.retrieve_object(container, object, self.detail,
201 f = self.file and open(self.file, 'w') or stdout
202 data = json.loads(data)
203 print_dict(data, f=f)
205 fw = open(self.file, 'w')
212 class PutObject(Command):
213 syntax = '<container>/<object> <path> [key=val] [...]'
214 description = 'create/override object with path contents or standard input'
216 def add_options(self, parser):
217 parser.add_option('--chunked', action='store_true', dest='chunked',
218 default=False, help='set chunked transfer mode')
219 parser.add_option('--etag', action='store', dest='etag',
220 default=None, help='check written data')
221 parser.add_option('--content-encoding', action='store',
222 dest='content-encoding', default=None,
223 help='provide the object MIME content type')
224 parser.add_option('--content-disposition', action='store', type='str',
225 dest='content-disposition', default=None,
226 help='provide the presentation style of the object')
227 parser.add_option('--manifest', action='store', type='str',
228 dest='manifest', default=None,
229 help='use for large file support')
231 def execute(self, path, srcpath, *args):
234 headers['X_OBJECT_MANIFEST'] = self.manifest
236 attrs = ['etag', 'content-encoding', 'content-disposition']
237 attrs = [a for a in attrs if getattr(self, a)]
239 headers[a.replace('-', '_').upper()] = getattr(self, a)
241 #prepare user defined meta
243 key, sep, val = arg.partition('=')
244 headers['X_OBJECT_META_%s' %key.strip().upper()] = val.strip()
246 container, sep, object = path.partition('/')
248 f = srcpath != '-' and open(srcpath) or stdin
249 chunked = (self.chunked or f == stdin) and True or False
250 self.client.create_object(container, object, f, chunked=chunked,
254 @cli_command('copy', 'cp')
255 class CopyObject(Command):
256 syntax = '<src container>/<src object> [<dst container>/]<dst object>'
257 description = 'copies an object to a different location'
259 def execute(self, src, dst):
260 src_container, sep, src_object = src.partition('/')
261 dst_container, sep, dst_object = dst.partition('/')
263 dst_container = src_container
265 self.client.copy_object(src_container, src_object, dst_container,
269 class SetMeta(Command):
270 syntax = '[<container>[/<object>]] key=val [key=val] [...]'
271 description = 'set metadata'
273 def execute(self, path, *args):
274 #in case of account fix the args
275 if path.find('=') != -1:
282 key, sep, val = arg.partition('=')
283 meta[key.strip()] = val.strip()
284 container, sep, object = path.partition('/')
286 self.client.update_object_metadata(container, object, **meta)
288 self.client.update_container_metadata(container, **meta)
290 self.client.update_account_metadata(**meta)
292 @cli_command('update')
293 class UpdateObject(Command):
294 syntax = '<container>/<object> path [key=val] [...]'
295 description = 'update object metadata/data'
297 def add_options(self, parser):
298 parser.add_option('-a', action='store_true', dest='append',
299 default=None, help='append data')
300 parser.add_option('--start', action='store',
302 default=None, help='range of data to be updated')
303 parser.add_option('--range', action='store', dest='content-range',
304 default=None, help='range of data to be updated')
305 parser.add_option('--chunked', action='store_true', dest='chunked',
306 default=False, help='set chunked transfer mode')
307 parser.add_option('--content-encoding', action='store',
308 dest='content-encoding', default=None,
309 help='provide the object MIME content type')
310 parser.add_option('--content-disposition', action='store', type='str',
311 dest='content-disposition', default=None,
312 help='provide the presentation style of the object')
313 parser.add_option('--manifest', action='store', type='str',
314 dest='manifest', default=None,
315 help='use for large file support')
317 def execute(self, path, srcpath, *args):
320 headers['X_OBJECT_MANIFEST'] = self.manifest
323 headers['CONTENT_RANGE'] = 'bytes */*'
325 headers['CONTENT_RANGE'] = 'bytes %s-/*' % self.first-byte-pos
327 attrs = ['content-encoding', 'content-disposition']
328 attrs = [a for a in attrs if getattr(self, a)]
330 headers[a.replace('-', '_').upper()] = getattr(self, a)
332 #prepare user defined meta
334 key, sep, val = arg.partition('=')
335 headers['X_OBJECT_META_%s' %key.strip().upper()] = val.strip()
337 container, sep, object = path.partition('/')
339 f = srcpath != '-' and open(srcpath) or stdin
340 chunked = (self.chunked or f == stdin) and True or False
341 self.client.update_object(container, object, f, chunked=chunked,
345 @cli_command('move', 'mv')
346 class MoveObject(Command):
347 syntax = '<src container>/<src object> [<dst container>/]<dst object>'
348 description = 'moves an object to a different location'
350 def execute(self, src, dst):
351 src_container, sep, src_object = src.partition('/')
352 dst_container, sep, dst_object = dst.partition('/')
354 dst_container = src_container
356 self.client.move_object(src_container, src_object, dst_container,
362 parser.usage = '%prog <command> [options]'
366 for cls in set(_cli_commands.values()):
367 name = ', '.join(cls.commands)
368 description = getattr(cls, 'description', '')
369 commands.append(' %s %s' % (name.ljust(12), description))
370 print '\nCommands:\n' + '\n'.join(sorted(commands))
372 def print_dict(d, header='name', f=stdout):
373 header = header in d and header or 'subdir'
374 if header and header in d:
375 f.write('%s\n' %d.pop(header))
376 for key, val in sorted(d.items()):
377 f.write('%s: %s\n' % (key.rjust(15), val))
379 def print_list(l, verbose=False, f=stdout):
381 #if it's empty string continue
384 if type(elem) == types.DictionaryType:
385 print_dict(elem, f=f)
386 elif type(elem) == types.StringType:
388 elem = elem.split('Traceback')[0]
389 f.write('%s\n' % elem)
391 f.write('%s\n' % elem)
396 cls = class_for_cli_command(name)
397 except (IndexError, KeyError):
403 cmd.execute(*cmd.args)
406 # cmd.execute(*cmd.args)
408 # cmd.parser.usage = '%%prog %s [options] %s' % (name, cmd.syntax)
409 # cmd.parser.print_help()
414 if __name__ == '__main__':