support for object version move
[pithos] / tools / store
1 #!/usr/bin/env python
2
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
9
10 import json
11 import logging
12 import types
13 import re
14 import time as _time
15
16 DEFAULT_HOST = 'pithos.dev.grnet.gr'
17 DEFAULT_API = 'v1'
18
19 _cli_commands = {}
20
21 def cli_command(*args):
22     def decorator(cls):
23         cls.commands = args
24         for name in args:
25             _cli_commands[name] = cls
26         return cls
27     return decorator
28
29 def class_for_cli_command(name):
30     return _cli_commands[name]
31
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)
47         
48         # Add options to self
49         for opt in parser.option_list:
50             key = opt.dest
51             if key:
52                 val = getattr(options, key)
53                 setattr(self, key, val)
54         
55         self.client = Client(self.host, self.user, self.api, self.verbose,
56                              self.debug)
57         
58         self.parser = parser
59         self.args = args
60
61     def add_options(self, parser):
62         pass
63
64     def execute(self, *args):
65         pass
66
67 @cli_command('list', 'ls')
68 class List(Command):
69     syntax = '[<container>[/<object>]]'
70     description = 'list containers or objects'
71     
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')
102
103     def execute(self, container=None):
104         if container:
105             self.list_objects(container)
106         else:
107             self.list_containers()
108
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}
113         
114         if self.until:
115             t = _time.strptime(self.until, self.format)
116             params['until'] = int(_time.mktime(t))
117         
118         l = self.client.list_containers(self.detail, params, headers)
119         print_list(l)
120
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('/')
128         if object:
129             return
130         
131         if self.until:
132             t = _time.strptime(self.until, self.format)
133             params['until'] = int(_time.mktime(t))
134         
135         l = self.client.list_objects(container, self.detail, params, headers)
136         print_list(l)
137
138 @cli_command('meta')
139 class Meta(Command):
140     syntax = '[<container>[/<object>]]'
141     description = 'get the metadata of an account, a container or an object'
142     
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)')
153
154     def execute(self, path=''):
155         container, sep, object = path.partition('/')
156         if self.until:
157             t = _time.strptime(self.until, self.format)
158             self.until = int(_time.mktime(t))
159         if object:
160             meta = self.client.retrieve_object_metadata(container, object,
161                                                         self.restricted,
162                                                         self.version)
163         elif container:
164             meta = self.client.retrieve_container_metadata(container,
165                                                            self.restricted,
166                                                            self.until)
167         else:
168             meta = self.client.account_metadata(self.restricted, self.until)
169         if meta == None:
170             print 'Entity does not exist'
171         else:
172             print_dict(meta, header=None)
173
174 @cli_command('create')
175 class CreateContainer(Command):
176     syntax = '<container> [key=val] [...]'
177     description = 'create a container'
178     
179     def execute(self, container, *args):
180         headers = {}
181         for arg in 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)
185         if not ret:
186             print 'Container already exists'
187
188 @cli_command('delete', 'rm')
189 class Delete(Command):
190     syntax = '<container>[/<object>]'
191     description = 'delete a container or an object'
192     
193     def execute(self, path):
194         container, sep, object = path.partition('/')
195         if object:
196             self.client.delete_object(container, object)
197         else:
198             self.client.delete_container(container)
199
200 @cli_command('get')
201 class GetObject(Command):
202     syntax = '<container>/<object>'
203     description = 'get the data of an object'
204     
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 \
227                                version')
228         parser.add_option('--versionlist', action='store_true',
229                           dest='versionlist', default=False,
230                           help='get the full object version list')
231
232     def execute(self, path):
233         headers = {}
234         if self.range:
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)]
239         for a in attrs:
240             headers[a.replace('-', '_').upper()] = getattr(self, a)
241         container, sep, object = path.partition('/')
242         if self.versionlist:
243             self.version = 'list'
244             self.detail = True
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
248         if self.detail:
249             data = json.loads(data)
250             if self.versionlist:
251                 print_versions(data, f=f)
252             else:
253                 print_dict(data, f=f)
254         else:
255             f.write(data)
256         f.close()
257
258 @cli_command('put')
259 class PutObject(Command):
260     syntax = '<container>/<object> <path> [key=val] [...]'
261     description = 'create/override object with path contents or standard input'
262
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')
280
281     def execute(self, path, srcpath='-', *args):
282         headers = {}
283         if self.manifest:
284             headers['X_OBJECT_MANIFEST'] = self.manifest
285             
286         attrs = ['etag', 'content-encoding', 'content-disposition']
287         attrs = [a for a in attrs if getattr(self, a)]
288         for a in attrs:
289             headers[a.replace('-', '_').upper()] = getattr(self, a)
290         
291         #prepare user defined meta
292         for arg in args:
293             key, sep, val = arg.partition('=')
294             headers['X_OBJECT_META_%s' %key.strip().upper()] = val.strip()
295         
296         container, sep, object = path.partition('/')
297         
298         f = None
299         chunked = False
300         if not self.touch:
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,
304                                   headers=headers)
305         if f:
306             f.close()
307
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'
312     
313     def add_options(self, parser):
314         parser.add_option('--version', action='store',
315                           dest='version', default=False,
316                           help='copy specific version')
317
318     def execute(self, src, dst):
319         src_container, sep, src_object = src.partition('/')
320         dst_container, sep, dst_object = dst.partition('/')
321         if not sep:
322             dst_container = src_container
323             dst_object = dst
324         version = getattr(self, 'version')
325         if version:
326             headers = {}
327             headers['SOURCE_VERSION'] = version 
328         self.client.copy_object(src_container, src_object, dst_container,
329                                 dst_object)
330
331 @cli_command('set')
332 class SetMeta(Command):
333     syntax = '[<container>[/<object>]] key=val [key=val] [...]'
334     description = 'set metadata'
335     
336     def execute(self, path, *args):
337         #in case of account fix the args
338         if path.find('=') != -1:
339             args = list(args)
340             args.append(path)
341             args = tuple(args)
342             path = ''
343         meta = {}
344         for arg in args:
345             key, sep, val = arg.partition('=')
346             meta[key.strip()] = val.strip()
347         container, sep, object = path.partition('/')
348         if object:
349             self.client.update_object_metadata(container, object, **meta)
350         elif container:
351             self.client.update_container_metadata(container, **meta)
352         else:
353             self.client.update_account_metadata(**meta)
354
355 @cli_command('update')
356 class UpdateObject(Command):
357     syntax = '<container>/<object> path [key=val] [...]'
358     description = 'update object metadata/data (default mode: append)'
359     
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',
364                           dest='start',
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')
379
380     def execute(self, path, srcpath='-', *args):
381         headers = {}
382         if self.manifest:
383             headers['X_OBJECT_MANIFEST'] = self.manifest
384         
385         if self.append:
386             headers['CONTENT_RANGE'] = 'bytes */*'
387         elif self.start:
388             headers['CONTENT_RANGE'] = 'bytes %s-/*' % self.first-byte-pos
389         
390         attrs = ['content-encoding', 'content-disposition']
391         attrs = [a for a in attrs if getattr(self, a)]
392         for a in attrs:
393             headers[a.replace('-', '_').upper()] = getattr(self, a)
394         
395         #prepare user defined meta
396         for arg in args:
397             key, sep, val = arg.partition('=')
398             headers['X_OBJECT_META_%s' %key.strip().upper()] = val.strip()
399         
400         container, sep, object = path.partition('/')
401         
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,
405                                   headers=headers)
406         f.close()
407
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'
412     
413     def add_options(self, parser):
414         parser.add_option('--version', action='store',
415                           dest='version', default=False,
416                           help='move specific version')
417
418     def execute(self, src, dst):
419         src_container, sep, src_object = src.partition('/')
420         dst_container, sep, dst_object = dst.partition('/')
421         if not sep:
422             dst_container = src_container
423             dst_object = dst
424         
425         version = getattr(self, 'version')
426         if version:
427             headers = {}
428             headers['SOURCE_VERSION'] = version 
429         self.client.move_object(src_container, src_object, dst_container,
430                                 dst_object, headers)
431
432 def print_usage():
433     cmd = Command([])
434     parser = cmd.parser
435     parser.usage = '%prog <command> [options]'
436     parser.print_help()
437     
438     commands = []
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))
444
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()):
452         for p in patterns:
453             p = re.compile(p)
454             m = p.match(key)
455             if m:
456                 key = m.group(2)
457         f.write('%s: %s\n' % (key.rjust(30), val))
458
459 def print_list(l, verbose=False, f=stdout):
460     for elem in l:
461         #if it's empty string continue
462         if not elem:
463             continue
464         if type(elem) == types.DictionaryType:
465             print_dict(elem, f=f)
466         elif type(elem) == types.StringType:
467             if not verbose:
468                 elem = elem.split('Traceback')[0]
469             f.write('%s\n' % elem)
470         else:
471             f.write('%s\n' % elem)
472
473 def print_versions(data, f=stdout):
474     if 'versions' not in data:
475         f.write('%s\n' %data)
476         return
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)))
480
481 def main():
482     try:
483         name = argv[1]
484         cls = class_for_cli_command(name)
485     except (IndexError, KeyError):
486         print_usage()
487         exit(1)
488     
489     cmd = cls(argv[2:])
490     
491     try:
492         cmd.execute(*cmd.args)
493     except TypeError, e:
494         print e
495         cmd.parser.usage = '%%prog %s [options] %s' % (name, cmd.syntax)
496         cmd.parser.print_help()
497         exit(1)
498     except Fault, f:
499         print f.status, f.data
500
501 if __name__ == '__main__':
502     main()