support for account/container HEAD/GET until parameter
[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             print '%s/%s is an object' %(container, object)
130             return
131         
132         if self.until:
133             t = _time.strptime(self.until, self.format)
134             params['until'] = int(_time.mktime(t))
135         
136         l = self.client.list_objects(container, self.detail, params, headers)
137         print_list(l)
138
139 @cli_command('meta')
140 class Meta(Command):
141     syntax = '[<container>[/<object>]]'
142     description = 'get the metadata of an account, a container or an object'
143     
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
152     def execute(self, path=''):
153         container, sep, object = path.partition('/')
154         if self.until:
155             t = _time.strptime(self.until, self.format)
156             self.until = int(_time.mktime(t))
157         if object:
158             meta = self.client.retrieve_object_metadata(container, object,
159                                                         self.restricted)
160         elif container:
161             meta = self.client.retrieve_container_metadata(container,
162                                                            self.restricted,
163                                                            self.until)
164         else:
165             meta = self.client.account_metadata(self.restricted, self.until)
166         if meta == None:
167             print 'Entity does not exist'
168         else:
169             print_dict(meta, header=None)
170
171 @cli_command('create')
172 class CreateContainer(Command):
173     syntax = '<container> [key=val] [...]'
174     description = 'create a container'
175     
176     def execute(self, container, *args):
177         headers = {}
178         for arg in 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)
182         if not ret:
183             print 'Container already exists'
184
185 @cli_command('delete', 'rm')
186 class Delete(Command):
187     syntax = '<container>[/<object>]'
188     description = 'delete a container or an object'
189     
190     def execute(self, path):
191         container, sep, object = path.partition('/')
192         if object:
193             self.client.delete_object(container, object)
194         else:
195             self.client.delete_container(container)
196
197 @cli_command('get')
198 class GetObject(Command):
199     syntax = '<container>/<object>'
200     description = 'get the data of an object'
201     
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')
221
222     def execute(self, path):
223         headers = {}
224         if self.range:
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)]
229         for a in attrs:
230             headers[a.replace('-', '_').upper()] = getattr(self, a)
231         container, sep, object = path.partition('/')
232         data = self.client.retrieve_object(container, object, self.detail,
233                                           headers)
234         if self.file:
235             if self.detail:
236                 f = self.file and open(self.file, 'w') or stdout
237                 data = json.loads(data)
238                 print_dict(data, f=f)
239             else:
240                 fw = open(self.file, 'w')
241                 fw.write(data)
242                 fw.close()
243         else:
244             print data
245
246 @cli_command('put')
247 class PutObject(Command):
248     syntax = '<container>/<object> <path> [key=val] [...]'
249     description = 'create/override object with path contents or standard input'
250
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')
268
269     def execute(self, path, srcpath='-', *args):
270         headers = {}
271         if self.manifest:
272             headers['X_OBJECT_MANIFEST'] = self.manifest
273             
274         attrs = ['etag', 'content-encoding', 'content-disposition']
275         attrs = [a for a in attrs if getattr(self, a)]
276         for a in attrs:
277             headers[a.replace('-', '_').upper()] = getattr(self, a)
278         
279         #prepare user defined meta
280         for arg in args:
281             key, sep, val = arg.partition('=')
282             headers['X_OBJECT_META_%s' %key.strip().upper()] = val.strip()
283         
284         container, sep, object = path.partition('/')
285         
286         f = None
287         chunked = False
288         if not self.touch:
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,
292                                   headers=headers)
293         if f:
294             f.close()
295
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'
300     
301     def execute(self, src, dst):
302         src_container, sep, src_object = src.partition('/')
303         dst_container, sep, dst_object = dst.partition('/')
304         if not sep:
305             dst_container = src_container
306             dst_object = dst
307         self.client.copy_object(src_container, src_object, dst_container,
308                                 dst_object)
309
310 @cli_command('set')
311 class SetMeta(Command):
312     syntax = '[<container>[/<object>]] key=val [key=val] [...]'
313     description = 'set metadata'
314     
315     def execute(self, path, *args):
316         #in case of account fix the args
317         if path.find('=') != -1:
318             args = list(args)
319             args.append(path)
320             args = tuple(args)
321             path = ''
322         meta = {}
323         for arg in args:
324             key, sep, val = arg.partition('=')
325             meta[key.strip()] = val.strip()
326         container, sep, object = path.partition('/')
327         if object:
328             self.client.update_object_metadata(container, object, **meta)
329         elif container:
330             self.client.update_container_metadata(container, **meta)
331         else:
332             self.client.update_account_metadata(**meta)
333
334 @cli_command('update')
335 class UpdateObject(Command):
336     syntax = '<container>/<object> path [key=val] [...]'
337     description = 'update object metadata/data'
338     
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',
343                           dest='start',
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')
358
359     def execute(self, path, srcpath, *args):
360         headers = {}
361         if self.manifest:
362             headers['X_OBJECT_MANIFEST'] = self.manifest
363         
364         if self.append:
365             headers['CONTENT_RANGE'] = 'bytes */*'
366         elif self.start:
367             headers['CONTENT_RANGE'] = 'bytes %s-/*' % self.first-byte-pos
368         
369         attrs = ['content-encoding', 'content-disposition']
370         attrs = [a for a in attrs if getattr(self, a)]
371         for a in attrs:
372             headers[a.replace('-', '_').upper()] = getattr(self, a)
373         
374         #prepare user defined meta
375         for arg in args:
376             key, sep, val = arg.partition('=')
377             headers['X_OBJECT_META_%s' %key.strip().upper()] = val.strip()
378         
379         container, sep, object = path.partition('/')
380         
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,
384                                   headers=headers)
385         f.close()
386
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'
391     
392     def execute(self, src, dst):
393         src_container, sep, src_object = src.partition('/')
394         dst_container, sep, dst_object = dst.partition('/')
395         if not sep:
396             dst_container = src_container
397             dst_object = dst
398         self.client.move_object(src_container, src_object, dst_container,
399                                 dst_object)
400
401 def print_usage():
402     cmd = Command([])
403     parser = cmd.parser
404     parser.usage = '%prog <command> [options]'
405     parser.print_help()
406     
407     commands = []
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))
413
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()):
421         for p in patterns:
422             p = re.compile(p)
423             m = p.match(key)
424             if m:
425                 key = m.group(2)
426         f.write('%s: %s\n' % (key.rjust(30), val))
427
428 def print_list(l, verbose=False, f=stdout):
429     for elem in l:
430         #if it's empty string continue
431         if not elem:
432             continue
433         if type(elem) == types.DictionaryType:
434             print_dict(elem, f=f)
435         elif type(elem) == types.StringType:
436             if not verbose:
437                 elem = elem.split('Traceback')[0]
438             f.write('%s\n' % elem)
439         else:
440             f.write('%s\n' % elem)
441
442 def main():
443     try:
444         name = argv[1]
445         cls = class_for_cli_command(name)
446     except (IndexError, KeyError):
447         print_usage()
448         exit(1)
449     
450     cmd = cls(argv[2:])
451     
452     try:
453         cmd.execute(*cmd.args)
454     except TypeError:
455         cmd.parser.usage = '%%prog %s [options] %s' % (name, cmd.syntax)
456         cmd.parser.print_help()
457         exit(1)
458     except Fault, f:
459         print f.data
460
461 if __name__ == '__main__':
462     main()