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
8 from datetime import datetime
16 DEFAULT_HOST = 'pithos.dev.grnet.gr'
21 def cli_command(*args):
25 _cli_commands[name] = cls
29 def class_for_cli_command(name):
30 return _cli_commands[name]
32 class Command(object):
33 def __init__(self, argv):
34 parser = OptionParser()
35 parser.add_option('--host', dest='host', metavar='HOST',
36 default=DEFAULT_HOST, help='use server HOST')
37 parser.add_option('--user', dest='user', metavar='USERNAME',
38 default=getuser(), help='use account USERNAME')
39 parser.add_option('--api', dest='api', metavar='API',
40 default=DEFAULT_API, help='use api API')
41 parser.add_option('-v', action='store_true', dest='verbose',
42 default=False, help='use verbose output')
43 parser.add_option('-d', action='store_true', dest='debug',
44 default=False, help='use debug output')
45 self.add_options(parser)
46 options, args = parser.parse_args(argv)
49 for opt in parser.option_list:
52 val = getattr(options, key)
53 setattr(self, key, val)
55 self.client = Client(self.host, self.user, self.api, self.verbose,
61 def add_options(self, parser):
64 def execute(self, *args):
67 @cli_command('list', 'ls')
69 syntax = '[<container>[/<object>]]'
70 description = 'list containers or objects'
72 def add_options(self, parser):
73 parser.add_option('-l', action='store_true', dest='detail',
74 default=False, help='show detailed output')
75 parser.add_option('-n', action='store', type='int', dest='limit',
76 default=1000, help='show limited output')
77 parser.add_option('--marker', action='store', type='str',
78 dest='marker', default=None,
79 help='show output greater then marker')
80 parser.add_option('--prefix', action='store', type='str',
81 dest='prefix', default=None,
82 help='show output starting with prefix')
83 parser.add_option('--delimiter', action='store', type='str',
84 dest='delimiter', default=None,
85 help='show output up to the delimiter')
86 parser.add_option('--path', action='store', type='str',
87 dest='path', default=None,
88 help='show output starting with prefix up to /')
89 parser.add_option('--meta', action='store', type='str',
90 dest='meta', default=None,
91 help='show output having the specified meta keys')
92 parser.add_option('--if-modified-since', action='store', type='str',
93 dest='if_modified_since', default=None,
94 help='show output if modified since then')
95 parser.add_option('--if-unmodified-since', action='store', type='str',
96 dest='if_unmodified_since', default=None,
97 help='show output if not modified since then')
98 parser.add_option('--until', action='store', dest='until',
99 default=False, help='show metadata until that date')
100 parser.add_option('--format', action='store', dest='format',
101 default='%d/%m/%Y', help='format to parse until date')
103 def execute(self, container=None):
105 self.list_objects(container)
107 self.list_containers()
109 def list_containers(self):
110 params = {'limit':self.limit, 'marker':self.marker}
111 headers = {'IF_MODIFIED_SINCE':self.if_modified_since,
112 'IF_UNMODIFIED_SINCE':self.if_unmodified_since}
115 t = _time.strptime(self.until, self.format)
116 params['until'] = int(_time.mktime(t))
118 l = self.client.list_containers(self.detail, params, headers)
121 def list_objects(self, container):
122 params = {'limit':self.limit, 'marker':self.marker,
123 'prefix':self.prefix, 'delimiter':self.delimiter,
124 'path':self.path, 'meta':self.meta}
125 headers = {'IF_MODIFIED_SINCE':self.if_modified_since,
126 'IF_UNMODIFIED_SINCE':self.if_unmodified_since}
127 container, sep, object = container.partition('/')
132 t = _time.strptime(self.until, self.format)
133 params['until'] = int(_time.mktime(t))
135 l = self.client.list_objects(container, self.detail, params, headers)
140 syntax = '[<container>[/<object>]]'
141 description = 'get the metadata of an account, a container or an object'
143 def add_options(self, parser):
144 parser.add_option('-r', action='store_true', dest='restricted',
145 default=False, help='show only user defined metadata')
146 parser.add_option('--until', action='store', dest='until',
147 default=False, help='show metadata until that date')
148 parser.add_option('--format', action='store', dest='format',
149 default='%d/%m/%Y', help='format to parse until date')
150 parser.add_option('--version', action='store', dest='version',
151 default=None, help='show specific version \
152 (applies only for objects)')
154 def execute(self, path=''):
155 container, sep, object = path.partition('/')
157 t = _time.strptime(self.until, self.format)
158 self.until = int(_time.mktime(t))
160 meta = self.client.retrieve_object_metadata(container, object,
164 meta = self.client.retrieve_container_metadata(container,
168 meta = self.client.account_metadata(self.restricted, self.until)
170 print 'Entity does not exist'
172 print_dict(meta, header=None)
174 @cli_command('create')
175 class CreateContainer(Command):
176 syntax = '<container> [key=val] [...]'
177 description = 'create a container'
179 def execute(self, container, *args):
182 key, sep, val = arg.partition('=')
183 headers['X_CONTAINER_META_%s' %key.strip().upper()] = val.strip()
184 ret = self.client.create_container(container, headers)
186 print 'Container already exists'
188 @cli_command('delete', 'rm')
189 class Delete(Command):
190 syntax = '<container>[/<object>]'
191 description = 'delete a container or an object'
193 def execute(self, path):
194 container, sep, object = path.partition('/')
196 self.client.delete_object(container, object)
198 self.client.delete_container(container)
201 class GetObject(Command):
202 syntax = '<container>/<object>'
203 description = 'get the data of an object'
205 def add_options(self, parser):
206 parser.add_option('-l', action='store_true', dest='detail',
207 default=False, help='show detailed output')
208 parser.add_option('--range', action='store', dest='range',
209 default=None, help='show range of data')
210 parser.add_option('--if-match', action='store', dest='if-match',
211 default=None, help='show output if ETags match')
212 parser.add_option('--if-none-match', action='store',
213 dest='if-none-match', default=None,
214 help='show output if ETags don\'t match')
215 parser.add_option('--if-modified-since', action='store', type='str',
216 dest='if-modified-since', default=None,
217 help='show output if modified since then')
218 parser.add_option('--if-unmodified-since', action='store', type='str',
219 dest='if-unmodified-since', default=None,
220 help='show output if not modified since then')
221 parser.add_option('-f', action='store', type='str',
222 dest='file', default=None,
223 help='save output in file')
224 parser.add_option('--version', action='store', type='str',
225 dest='version', default=None,
226 help='get the specific \
228 parser.add_option('--versionlist', action='store_true',
229 dest='versionlist', default=False,
230 help='get the full object version list')
232 def execute(self, path):
235 headers['RANGE'] = 'bytes=%s' %self.range
236 attrs = ['if-match', 'if-none-match', 'if-modified-since',
237 'if-unmodified-since']
238 attrs = [a for a in attrs if getattr(self, a)]
240 headers[a.replace('-', '_').upper()] = getattr(self, a)
241 container, sep, object = path.partition('/')
243 self.version = 'list'
245 data = self.client.retrieve_object(container, object, self.detail,
246 headers, self.version)
247 f = self.file and open(self.file, 'w') or stdout
249 data = json.loads(data)
251 print_versions(data, f=f)
253 print_dict(data, f=f)
259 class PutObject(Command):
260 syntax = '<container>/<object> <path> [key=val] [...]'
261 description = 'create/override object with path contents or standard input'
263 def add_options(self, parser):
264 parser.add_option('--chunked', action='store_true', dest='chunked',
265 default=False, help='set chunked transfer mode')
266 parser.add_option('--etag', action='store', dest='etag',
267 default=None, help='check written data')
268 parser.add_option('--content-encoding', action='store',
269 dest='content-encoding', default=None,
270 help='provide the object MIME content type')
271 parser.add_option('--content-disposition', action='store', type='str',
272 dest='content-disposition', default=None,
273 help='provide the presentation style of the object')
274 parser.add_option('--manifest', action='store', type='str',
275 dest='manifest', default=None,
276 help='use for large file support')
277 parser.add_option('--touch', action='store_true',
278 dest='touch', default=False,
279 help='create object with zero data')
281 def execute(self, path, srcpath='-', *args):
284 headers['X_OBJECT_MANIFEST'] = self.manifest
286 attrs = ['etag', 'content-encoding', 'content-disposition']
287 attrs = [a for a in attrs if getattr(self, a)]
289 headers[a.replace('-', '_').upper()] = getattr(self, a)
291 #prepare user defined meta
293 key, sep, val = arg.partition('=')
294 headers['X_OBJECT_META_%s' %key.strip().upper()] = val.strip()
296 container, sep, object = path.partition('/')
301 f = srcpath != '-' and open(srcpath) or stdin
302 chunked = (self.chunked or f == stdin) and True or False
303 self.client.create_object(container, object, f, chunked=chunked,
308 @cli_command('copy', 'cp')
309 class CopyObject(Command):
310 syntax = '<src container>/<src object> [<dst container>/]<dst object>'
311 description = 'copies an object to a different location'
313 def add_options(self, parser):
314 parser.add_option('--version', action='store',
315 dest='version', default=False,
316 help='copy specific version')
318 def execute(self, src, dst):
319 src_container, sep, src_object = src.partition('/')
320 dst_container, sep, dst_object = dst.partition('/')
322 dst_container = src_container
324 version = getattr(self, 'version')
327 headers['SOURCE_VERSION'] = version
328 self.client.copy_object(src_container, src_object, dst_container,
332 class SetMeta(Command):
333 syntax = '[<container>[/<object>]] key=val [key=val] [...]'
334 description = 'set metadata'
336 def execute(self, path, *args):
337 #in case of account fix the args
338 if path.find('=') != -1:
345 key, sep, val = arg.partition('=')
346 meta[key.strip()] = val.strip()
347 container, sep, object = path.partition('/')
349 self.client.update_object_metadata(container, object, **meta)
351 self.client.update_container_metadata(container, **meta)
353 self.client.update_account_metadata(**meta)
355 @cli_command('update')
356 class UpdateObject(Command):
357 syntax = '<container>/<object> path [key=val] [...]'
358 description = 'update object metadata/data (default mode: append)'
360 def add_options(self, parser):
361 parser.add_option('-a', action='store_true', dest='append',
362 default=True, help='append data')
363 parser.add_option('--start', action='store',
365 default=None, help='range of data to be updated')
366 parser.add_option('--range', action='store', dest='content-range',
367 default=None, help='range of data to be updated')
368 parser.add_option('--chunked', action='store_true', dest='chunked',
369 default=False, help='set chunked transfer mode')
370 parser.add_option('--content-encoding', action='store',
371 dest='content-encoding', default=None,
372 help='provide the object MIME content type')
373 parser.add_option('--content-disposition', action='store', type='str',
374 dest='content-disposition', default=None,
375 help='provide the presentation style of the object')
376 parser.add_option('--manifest', action='store', type='str',
377 dest='manifest', default=None,
378 help='use for large file support')
380 def execute(self, path, srcpath='-', *args):
383 headers['X_OBJECT_MANIFEST'] = self.manifest
386 headers['CONTENT_RANGE'] = 'bytes */*'
388 headers['CONTENT_RANGE'] = 'bytes %s-/*' % self.first-byte-pos
390 attrs = ['content-encoding', 'content-disposition']
391 attrs = [a for a in attrs if getattr(self, a)]
393 headers[a.replace('-', '_').upper()] = getattr(self, a)
395 #prepare user defined meta
397 key, sep, val = arg.partition('=')
398 headers['X_OBJECT_META_%s' %key.strip().upper()] = val.strip()
400 container, sep, object = path.partition('/')
402 f = srcpath != '-' and open(srcpath) or stdin
403 chunked = (self.chunked or f == stdin) and True or False
404 self.client.update_object(container, object, f, chunked=chunked,
408 @cli_command('move', 'mv')
409 class MoveObject(Command):
410 syntax = '<src container>/<src object> [<dst container>/]<dst object>'
411 description = 'moves an object to a different location'
413 def add_options(self, parser):
414 parser.add_option('--version', action='store',
415 dest='version', default=False,
416 help='move specific version')
418 def execute(self, src, dst):
419 src_container, sep, src_object = src.partition('/')
420 dst_container, sep, dst_object = dst.partition('/')
422 dst_container = src_container
425 version = getattr(self, 'version')
428 headers['SOURCE_VERSION'] = version
429 self.client.move_object(src_container, src_object, dst_container,
435 parser.usage = '%prog <command> [options]'
439 for cls in set(_cli_commands.values()):
440 name = ', '.join(cls.commands)
441 description = getattr(cls, 'description', '')
442 commands.append(' %s %s' % (name.ljust(12), description))
443 print '\nCommands:\n' + '\n'.join(sorted(commands))
445 def print_dict(d, header='name', f=stdout):
446 header = header in d and header or 'subdir'
447 if header and header in d:
448 f.write('%s\n' %d.pop(header))
449 patterns = ['^x_(account|container|object)_meta_(\w+)$']
450 patterns.append(patterns[0].replace('_', '-'))
451 for key, val in sorted(d.items()):
457 f.write('%s: %s\n' % (key.rjust(30), val))
459 def print_list(l, verbose=False, f=stdout):
461 #if it's empty string continue
464 if type(elem) == types.DictionaryType:
465 print_dict(elem, f=f)
466 elif type(elem) == types.StringType:
468 elem = elem.split('Traceback')[0]
469 f.write('%s\n' % elem)
471 f.write('%s\n' % elem)
473 def print_versions(data, f=stdout):
474 if 'versions' not in data:
475 f.write('%s\n' %data)
477 f.write('versions:\n')
478 for id, t in data['versions']:
479 f.write('%s @ %s\n' % (str(id).rjust(30), datetime.fromtimestamp(t)))
484 cls = class_for_cli_command(name)
485 except (IndexError, KeyError):
492 cmd.execute(*cmd.args)
495 cmd.parser.usage = '%%prog %s [options] %s' % (name, cmd.syntax)
496 cmd.parser.print_help()
499 print f.status, f.data
501 if __name__ == '__main__':