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('/')
129 print '%s/%s is an object' %(container, object)
133 t = _time.strptime(self.until, self.format)
134 params['until'] = int(_time.mktime(t))
136 l = self.client.list_objects(container, self.detail, params, headers)
141 syntax = '[<container>[/<object>]]'
142 description = 'get the metadata of an account, a container or an object'
144 def add_options(self, parser):
145 parser.add_option('-r', action='store_true', dest='restricted',
146 default=False, help='show only user defined metadata')
147 parser.add_option('--until', action='store', dest='until',
148 default=False, help='show metadata until that date')
149 parser.add_option('--format', action='store', dest='format',
150 default='%d/%m/%Y', help='format to parse until date')
151 parser.add_option('--version', action='store', dest='version',
152 default=None, help='show specific version \
153 (applies only for objects)')
155 def execute(self, path=''):
156 container, sep, object = path.partition('/')
158 t = _time.strptime(self.until, self.format)
159 self.until = int(_time.mktime(t))
161 meta = self.client.retrieve_object_metadata(container, object,
165 meta = self.client.retrieve_container_metadata(container,
169 meta = self.client.account_metadata(self.restricted, self.until)
171 print 'Entity does not exist'
173 print_dict(meta, header=None)
175 @cli_command('create')
176 class CreateContainer(Command):
177 syntax = '<container> [key=val] [...]'
178 description = 'create a container'
180 def execute(self, container, *args):
183 key, sep, val = arg.partition('=')
184 headers['X_CONTAINER_META_%s' %key.strip().upper()] = val.strip()
185 ret = self.client.create_container(container, headers)
187 print 'Container already exists'
189 @cli_command('delete', 'rm')
190 class Delete(Command):
191 syntax = '<container>[/<object>]'
192 description = 'delete a container or an object'
194 def execute(self, path):
195 container, sep, object = path.partition('/')
197 self.client.delete_object(container, object)
199 self.client.delete_container(container)
202 class GetObject(Command):
203 syntax = '<container>/<object>'
204 description = 'get the data of an object'
206 def add_options(self, parser):
207 parser.add_option('-l', action='store_true', dest='detail',
208 default=False, help='show detailed output')
209 parser.add_option('--range', action='store', dest='range',
210 default=None, help='show range of data')
211 parser.add_option('--if-match', action='store', dest='if-match',
212 default=None, help='show output if ETags match')
213 parser.add_option('--if-none-match', action='store',
214 dest='if-none-match', default=None,
215 help='show output if ETags don\'t match')
216 parser.add_option('--if-modified-since', action='store', type='str',
217 dest='if-modified-since', default=None,
218 help='show output if modified since then')
219 parser.add_option('--if-unmodified-since', action='store', type='str',
220 dest='if-unmodified-since', default=None,
221 help='show output if not modified since then')
222 parser.add_option('-f', action='store', type='str',
223 dest='file', default=None,
224 help='save output in file')
225 parser.add_option('--version', action='store', type='str',
226 dest='version', default='list',
227 help='if \'list\' and in detailed mode get object\'s \
228 full version list otherwise get the specific \
231 def execute(self, path):
234 headers['RANGE'] = 'bytes=%s' %self.range
235 attrs = ['if-match', 'if-none-match', 'if-modified-since',
236 'if-unmodified-since']
237 attrs = [a for a in attrs if getattr(self, a)]
239 headers[a.replace('-', '_').upper()] = getattr(self, a)
240 container, sep, object = path.partition('/')
241 data = self.client.retrieve_object(container, object, self.detail,
242 headers, self.version)
243 f = self.file and open(self.file, 'w') or stdout
245 data = json.loads(data)
246 if self.version == 'list':
247 print_versions(data, f=f)
249 print_dict(data, f=f)
255 class PutObject(Command):
256 syntax = '<container>/<object> <path> [key=val] [...]'
257 description = 'create/override object with path contents or standard input'
259 def add_options(self, parser):
260 parser.add_option('--chunked', action='store_true', dest='chunked',
261 default=False, help='set chunked transfer mode')
262 parser.add_option('--etag', action='store', dest='etag',
263 default=None, help='check written data')
264 parser.add_option('--content-encoding', action='store',
265 dest='content-encoding', default=None,
266 help='provide the object MIME content type')
267 parser.add_option('--content-disposition', action='store', type='str',
268 dest='content-disposition', default=None,
269 help='provide the presentation style of the object')
270 parser.add_option('--manifest', action='store', type='str',
271 dest='manifest', default=None,
272 help='use for large file support')
273 parser.add_option('--touch', action='store_true',
274 dest='touch', default=False,
275 help='create object with zero data')
277 def execute(self, path, srcpath='-', *args):
280 headers['X_OBJECT_MANIFEST'] = self.manifest
282 attrs = ['etag', 'content-encoding', 'content-disposition']
283 attrs = [a for a in attrs if getattr(self, a)]
285 headers[a.replace('-', '_').upper()] = getattr(self, a)
287 #prepare user defined meta
289 key, sep, val = arg.partition('=')
290 headers['X_OBJECT_META_%s' %key.strip().upper()] = val.strip()
292 container, sep, object = path.partition('/')
297 f = srcpath != '-' and open(srcpath) or stdin
298 chunked = (self.chunked or f == stdin) and True or False
299 self.client.create_object(container, object, f, chunked=chunked,
304 @cli_command('copy', 'cp')
305 class CopyObject(Command):
306 syntax = '<src container>/<src object> [<dst container>/]<dst object>'
307 description = 'copies an object to a different location'
309 def execute(self, src, dst):
310 src_container, sep, src_object = src.partition('/')
311 dst_container, sep, dst_object = dst.partition('/')
313 dst_container = src_container
315 self.client.copy_object(src_container, src_object, dst_container,
319 class SetMeta(Command):
320 syntax = '[<container>[/<object>]] key=val [key=val] [...]'
321 description = 'set metadata'
323 def execute(self, path, *args):
324 #in case of account fix the args
325 if path.find('=') != -1:
332 key, sep, val = arg.partition('=')
333 meta[key.strip()] = val.strip()
334 container, sep, object = path.partition('/')
336 self.client.update_object_metadata(container, object, **meta)
338 self.client.update_container_metadata(container, **meta)
340 self.client.update_account_metadata(**meta)
342 @cli_command('update')
343 class UpdateObject(Command):
344 syntax = '<container>/<object> path [key=val] [...]'
345 description = 'update object metadata/data (default mode: append)'
347 def add_options(self, parser):
348 parser.add_option('-a', action='store_true', dest='append',
349 default=True, help='append data')
350 parser.add_option('--start', action='store',
352 default=None, help='range of data to be updated')
353 parser.add_option('--range', action='store', dest='content-range',
354 default=None, help='range of data to be updated')
355 parser.add_option('--chunked', action='store_true', dest='chunked',
356 default=False, help='set chunked transfer mode')
357 parser.add_option('--content-encoding', action='store',
358 dest='content-encoding', default=None,
359 help='provide the object MIME content type')
360 parser.add_option('--content-disposition', action='store', type='str',
361 dest='content-disposition', default=None,
362 help='provide the presentation style of the object')
363 parser.add_option('--manifest', action='store', type='str',
364 dest='manifest', default=None,
365 help='use for large file support')
367 def execute(self, path, srcpath='-', *args):
370 headers['X_OBJECT_MANIFEST'] = self.manifest
373 headers['CONTENT_RANGE'] = 'bytes */*'
375 headers['CONTENT_RANGE'] = 'bytes %s-/*' % self.first-byte-pos
377 attrs = ['content-encoding', 'content-disposition']
378 attrs = [a for a in attrs if getattr(self, a)]
380 headers[a.replace('-', '_').upper()] = getattr(self, a)
382 #prepare user defined meta
384 key, sep, val = arg.partition('=')
385 headers['X_OBJECT_META_%s' %key.strip().upper()] = val.strip()
387 container, sep, object = path.partition('/')
389 f = srcpath != '-' and open(srcpath) or stdin
390 chunked = (self.chunked or f == stdin) and True or False
391 self.client.update_object(container, object, f, chunked=chunked,
395 @cli_command('move', 'mv')
396 class MoveObject(Command):
397 syntax = '<src container>/<src object> [<dst container>/]<dst object>'
398 description = 'moves an object to a different location'
400 def execute(self, src, dst):
401 src_container, sep, src_object = src.partition('/')
402 dst_container, sep, dst_object = dst.partition('/')
404 dst_container = src_container
406 self.client.move_object(src_container, src_object, dst_container,
412 parser.usage = '%prog <command> [options]'
416 for cls in set(_cli_commands.values()):
417 name = ', '.join(cls.commands)
418 description = getattr(cls, 'description', '')
419 commands.append(' %s %s' % (name.ljust(12), description))
420 print '\nCommands:\n' + '\n'.join(sorted(commands))
422 def print_dict(d, header='name', f=stdout):
423 header = header in d and header or 'subdir'
424 if header and header in d:
425 f.write('%s\n' %d.pop(header))
426 patterns = ['^x_(account|container|object)_meta_(\w+)$']
427 patterns.append(patterns[0].replace('_', '-'))
428 for key, val in sorted(d.items()):
434 f.write('%s: %s\n' % (key.rjust(30), val))
436 def print_list(l, verbose=False, f=stdout):
438 #if it's empty string continue
441 if type(elem) == types.DictionaryType:
442 print_dict(elem, f=f)
443 elif type(elem) == types.StringType:
445 elem = elem.split('Traceback')[0]
446 f.write('%s\n' % elem)
448 f.write('%s\n' % elem)
450 def print_versions(data, f=stdout):
451 if 'versions' not in data:
452 f.write('%s\n' %data)
454 f.write('versions:\n')
455 for id, t in data['versions']:
456 f.write('%s @ %s\n' % (str(id).rjust(30), datetime.fromtimestamp(t)))
461 cls = class_for_cli_command(name)
462 except (IndexError, KeyError):
469 cmd.execute(*cmd.args)
472 cmd.parser.usage = '%%prog %s [options] %s' % (name, cmd.syntax)
473 cmd.parser.print_help()
476 print f.status, f.data
478 if __name__ == '__main__':