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')
152 def execute(self, path=''):
153 container, sep, object = path.partition('/')
155 t = _time.strptime(self.until, self.format)
156 self.until = int(_time.mktime(t))
158 meta = self.client.retrieve_object_metadata(container, object,
161 meta = self.client.retrieve_container_metadata(container,
165 meta = self.client.account_metadata(self.restricted, self.until)
167 print 'Entity does not exist'
169 print_dict(meta, header=None)
171 @cli_command('create')
172 class CreateContainer(Command):
173 syntax = '<container> [key=val] [...]'
174 description = 'create a container'
176 def execute(self, container, *args):
179 key, sep, val = arg.partition('=')
180 headers['X_CONTAINER_META_%s' %key.strip().upper()] = val.strip()
181 ret = self.client.create_container(container, headers)
183 print 'Container already exists'
185 @cli_command('delete', 'rm')
186 class Delete(Command):
187 syntax = '<container>[/<object>]'
188 description = 'delete a container or an object'
190 def execute(self, path):
191 container, sep, object = path.partition('/')
193 self.client.delete_object(container, object)
195 self.client.delete_container(container)
198 class GetObject(Command):
199 syntax = '<container>/<object>'
200 description = 'get the data of an object'
202 def add_options(self, parser):
203 parser.add_option('-l', action='store_true', dest='detail',
204 default=False, help='show detailed output')
205 parser.add_option('--range', action='store', dest='range',
206 default=None, help='show range of data')
207 parser.add_option('--if-match', action='store', dest='if-match',
208 default=None, help='show output if ETags match')
209 parser.add_option('--if-none-match', action='store',
210 dest='if-none-match', default=None,
211 help='show output if ETags don\'t match')
212 parser.add_option('--if-modified-since', action='store', type='str',
213 dest='if-modified-since', default=None,
214 help='show output if modified since then')
215 parser.add_option('--if-unmodified-since', action='store', type='str',
216 dest='if-unmodified-since', default=None,
217 help='show output if not modified since then')
218 parser.add_option('-f', action='store', type='str',
219 dest='file', default=None,
220 help='save output in file')
222 def execute(self, path):
225 headers['RANGE'] = 'bytes=%s' %self.range
226 attrs = ['if-match', 'if-none-match', 'if-modified-since',
227 'if-unmodified-since']
228 attrs = [a for a in attrs if getattr(self, a)]
230 headers[a.replace('-', '_').upper()] = getattr(self, a)
231 container, sep, object = path.partition('/')
232 data = self.client.retrieve_object(container, object, self.detail,
236 f = self.file and open(self.file, 'w') or stdout
237 data = json.loads(data)
238 print_dict(data, f=f)
240 fw = open(self.file, 'w')
247 class PutObject(Command):
248 syntax = '<container>/<object> <path> [key=val] [...]'
249 description = 'create/override object with path contents or standard input'
251 def add_options(self, parser):
252 parser.add_option('--chunked', action='store_true', dest='chunked',
253 default=False, help='set chunked transfer mode')
254 parser.add_option('--etag', action='store', dest='etag',
255 default=None, help='check written data')
256 parser.add_option('--content-encoding', action='store',
257 dest='content-encoding', default=None,
258 help='provide the object MIME content type')
259 parser.add_option('--content-disposition', action='store', type='str',
260 dest='content-disposition', default=None,
261 help='provide the presentation style of the object')
262 parser.add_option('--manifest', action='store', type='str',
263 dest='manifest', default=None,
264 help='use for large file support')
265 parser.add_option('--touch', action='store_true',
266 dest='touch', default=True,
267 help='create object with zero data')
269 def execute(self, path, srcpath='-', *args):
272 headers['X_OBJECT_MANIFEST'] = self.manifest
274 attrs = ['etag', 'content-encoding', 'content-disposition']
275 attrs = [a for a in attrs if getattr(self, a)]
277 headers[a.replace('-', '_').upper()] = getattr(self, a)
279 #prepare user defined meta
281 key, sep, val = arg.partition('=')
282 headers['X_OBJECT_META_%s' %key.strip().upper()] = val.strip()
284 container, sep, object = path.partition('/')
289 f = srcpath != '-' and open(srcpath) or stdin
290 chunked = (self.chunked or f == stdin) and True or False
291 self.client.create_object(container, object, f, chunked=chunked,
296 @cli_command('copy', 'cp')
297 class CopyObject(Command):
298 syntax = '<src container>/<src object> [<dst container>/]<dst object>'
299 description = 'copies an object to a different location'
301 def execute(self, src, dst):
302 src_container, sep, src_object = src.partition('/')
303 dst_container, sep, dst_object = dst.partition('/')
305 dst_container = src_container
307 self.client.copy_object(src_container, src_object, dst_container,
311 class SetMeta(Command):
312 syntax = '[<container>[/<object>]] key=val [key=val] [...]'
313 description = 'set metadata'
315 def execute(self, path, *args):
316 #in case of account fix the args
317 if path.find('=') != -1:
324 key, sep, val = arg.partition('=')
325 meta[key.strip()] = val.strip()
326 container, sep, object = path.partition('/')
328 self.client.update_object_metadata(container, object, **meta)
330 self.client.update_container_metadata(container, **meta)
332 self.client.update_account_metadata(**meta)
334 @cli_command('update')
335 class UpdateObject(Command):
336 syntax = '<container>/<object> path [key=val] [...]'
337 description = 'update object metadata/data'
339 def add_options(self, parser):
340 parser.add_option('-a', action='store_true', dest='append',
341 default=None, help='append data')
342 parser.add_option('--start', action='store',
344 default=None, help='range of data to be updated')
345 parser.add_option('--range', action='store', dest='content-range',
346 default=None, help='range of data to be updated')
347 parser.add_option('--chunked', action='store_true', dest='chunked',
348 default=False, help='set chunked transfer mode')
349 parser.add_option('--content-encoding', action='store',
350 dest='content-encoding', default=None,
351 help='provide the object MIME content type')
352 parser.add_option('--content-disposition', action='store', type='str',
353 dest='content-disposition', default=None,
354 help='provide the presentation style of the object')
355 parser.add_option('--manifest', action='store', type='str',
356 dest='manifest', default=None,
357 help='use for large file support')
359 def execute(self, path, srcpath, *args):
362 headers['X_OBJECT_MANIFEST'] = self.manifest
365 headers['CONTENT_RANGE'] = 'bytes */*'
367 headers['CONTENT_RANGE'] = 'bytes %s-/*' % self.first-byte-pos
369 attrs = ['content-encoding', 'content-disposition']
370 attrs = [a for a in attrs if getattr(self, a)]
372 headers[a.replace('-', '_').upper()] = getattr(self, a)
374 #prepare user defined meta
376 key, sep, val = arg.partition('=')
377 headers['X_OBJECT_META_%s' %key.strip().upper()] = val.strip()
379 container, sep, object = path.partition('/')
381 f = srcpath != '-' and open(srcpath) or stdin
382 chunked = (self.chunked or f == stdin) and True or False
383 self.client.update_object(container, object, f, chunked=chunked,
387 @cli_command('move', 'mv')
388 class MoveObject(Command):
389 syntax = '<src container>/<src object> [<dst container>/]<dst object>'
390 description = 'moves an object to a different location'
392 def execute(self, src, dst):
393 src_container, sep, src_object = src.partition('/')
394 dst_container, sep, dst_object = dst.partition('/')
396 dst_container = src_container
398 self.client.move_object(src_container, src_object, dst_container,
404 parser.usage = '%prog <command> [options]'
408 for cls in set(_cli_commands.values()):
409 name = ', '.join(cls.commands)
410 description = getattr(cls, 'description', '')
411 commands.append(' %s %s' % (name.ljust(12), description))
412 print '\nCommands:\n' + '\n'.join(sorted(commands))
414 def print_dict(d, header='name', f=stdout):
415 header = header in d and header or 'subdir'
416 if header and header in d:
417 f.write('%s\n' %d.pop(header))
418 patterns = ['^x_(account|container|object)_meta_(\w+)$']
419 patterns.append(patterns[0].replace('_', '-'))
420 for key, val in sorted(d.items()):
426 f.write('%s: %s\n' % (key.rjust(30), val))
428 def print_list(l, verbose=False, f=stdout):
430 #if it's empty string continue
433 if type(elem) == types.DictionaryType:
434 print_dict(elem, f=f)
435 elif type(elem) == types.StringType:
437 elem = elem.split('Traceback')[0]
438 f.write('%s\n' % elem)
440 f.write('%s\n' % elem)
445 cls = class_for_cli_command(name)
446 except (IndexError, KeyError):
453 cmd.execute(*cmd.args)
455 cmd.parser.usage = '%%prog %s [options] %s' % (name, cmd.syntax)
456 cmd.parser.print_help()
461 if __name__ == '__main__':