Statistics
| Branch: | Tag: | Revision:

root / tools / store @ e3fd7f91

History | View | Annotate | Download (18.4 kB)

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
        parser.add_option('--version', action='store', dest='version',
152
                          default=None, help='show specific version \
153
                                  (applies only for objects)')
154

    
155
    def execute(self, path=''):
156
        container, sep, object = path.partition('/')
157
        if self.until:
158
            t = _time.strptime(self.until, self.format)
159
            self.until = int(_time.mktime(t))
160
        if object:
161
            meta = self.client.retrieve_object_metadata(container, object,
162
                                                        self.restricted)
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

    
225
    def execute(self, path):
226
        headers = {}
227
        if self.range:
228
            headers['RANGE'] = 'bytes=%s' %self.range
229
        attrs = ['if-match', 'if-none-match', 'if-modified-since',
230
                 'if-unmodified-since']
231
        attrs = [a for a in attrs if getattr(self, a)]
232
        for a in attrs:
233
            headers[a.replace('-', '_').upper()] = getattr(self, a)
234
        container, sep, object = path.partition('/')
235
        data = self.client.retrieve_object(container, object, self.detail,
236
                                          headers)
237
        if self.file:
238
            if self.detail:
239
                f = self.file and open(self.file, 'w') or stdout
240
                data = json.loads(data)
241
                print_dict(data, f=f)
242
            else:
243
                fw = open(self.file, 'w')
244
                fw.write(data)
245
                fw.close()
246
        else:
247
            print data
248

    
249
@cli_command('put')
250
class PutObject(Command):
251
    syntax = '<container>/<object> <path> [key=val] [...]'
252
    description = 'create/override object with path contents or standard input'
253

    
254
    def add_options(self, parser):
255
        parser.add_option('--chunked', action='store_true', dest='chunked',
256
                          default=False, help='set chunked transfer mode')
257
        parser.add_option('--etag', action='store', dest='etag',
258
                          default=None, help='check written data')
259
        parser.add_option('--content-encoding', action='store',
260
                          dest='content-encoding', default=None,
261
                          help='provide the object MIME content type')
262
        parser.add_option('--content-disposition', action='store', type='str',
263
                          dest='content-disposition', default=None,
264
                          help='provide the presentation style of the object')
265
        parser.add_option('--manifest', action='store', type='str',
266
                          dest='manifest', default=None,
267
                          help='use for large file support')
268
        parser.add_option('--touch', action='store_true',
269
                          dest='touch', default=False,
270
                          help='create object with zero data')
271

    
272
    def execute(self, path, srcpath='-', *args):
273
        headers = {}
274
        if self.manifest:
275
            headers['X_OBJECT_MANIFEST'] = self.manifest
276
            
277
        attrs = ['etag', 'content-encoding', 'content-disposition']
278
        attrs = [a for a in attrs if getattr(self, a)]
279
        for a in attrs:
280
            headers[a.replace('-', '_').upper()] = getattr(self, a)
281
        
282
        #prepare user defined meta
283
        for arg in args:
284
            key, sep, val = arg.partition('=')
285
            headers['X_OBJECT_META_%s' %key.strip().upper()] = val.strip()
286
        
287
        container, sep, object = path.partition('/')
288
        
289
        f = None
290
        chunked = False
291
        if not self.touch:
292
            f = srcpath != '-' and open(srcpath) or stdin
293
            chunked = (self.chunked or f == stdin) and True or False
294
        self.client.create_object(container, object, f, chunked=chunked,
295
                                  headers=headers)
296
        if f:
297
            f.close()
298

    
299
@cli_command('copy', 'cp')
300
class CopyObject(Command):
301
    syntax = '<src container>/<src object> [<dst container>/]<dst object>'
302
    description = 'copies an object to a different location'
303
    
304
    def execute(self, src, dst):
305
        src_container, sep, src_object = src.partition('/')
306
        dst_container, sep, dst_object = dst.partition('/')
307
        if not sep:
308
            dst_container = src_container
309
            dst_object = dst
310
        self.client.copy_object(src_container, src_object, dst_container,
311
                                dst_object)
312

    
313
@cli_command('set')
314
class SetMeta(Command):
315
    syntax = '[<container>[/<object>]] key=val [key=val] [...]'
316
    description = 'set metadata'
317
    
318
    def execute(self, path, *args):
319
        #in case of account fix the args
320
        if path.find('=') != -1:
321
            args = list(args)
322
            args.append(path)
323
            args = tuple(args)
324
            path = ''
325
        meta = {}
326
        for arg in args:
327
            key, sep, val = arg.partition('=')
328
            meta[key.strip()] = val.strip()
329
        container, sep, object = path.partition('/')
330
        if object:
331
            self.client.update_object_metadata(container, object, **meta)
332
        elif container:
333
            self.client.update_container_metadata(container, **meta)
334
        else:
335
            self.client.update_account_metadata(**meta)
336

    
337
@cli_command('update')
338
class UpdateObject(Command):
339
    syntax = '<container>/<object> path [key=val] [...]'
340
    description = 'update object metadata/data (default mode: append)'
341
    
342
    def add_options(self, parser):
343
        parser.add_option('-a', action='store_true', dest='append',
344
                          default=True, help='append data')
345
        parser.add_option('--start', action='store',
346
                          dest='start',
347
                          default=None, help='range of data to be updated')
348
        parser.add_option('--range', action='store', dest='content-range',
349
                          default=None, help='range of data to be updated')
350
        parser.add_option('--chunked', action='store_true', dest='chunked',
351
                          default=False, help='set chunked transfer mode')
352
        parser.add_option('--content-encoding', action='store',
353
                          dest='content-encoding', default=None,
354
                          help='provide the object MIME content type')
355
        parser.add_option('--content-disposition', action='store', type='str',
356
                          dest='content-disposition', default=None,
357
                          help='provide the presentation style of the object')
358
        parser.add_option('--manifest', action='store', type='str',
359
                          dest='manifest', default=None,
360
                          help='use for large file support')
361

    
362
    def execute(self, path, srcpath='-', *args):
363
        headers = {}
364
        if self.manifest:
365
            headers['X_OBJECT_MANIFEST'] = self.manifest
366
        
367
        if self.append:
368
            headers['CONTENT_RANGE'] = 'bytes */*'
369
        elif self.start:
370
            headers['CONTENT_RANGE'] = 'bytes %s-/*' % self.first-byte-pos
371
        
372
        attrs = ['content-encoding', 'content-disposition']
373
        attrs = [a for a in attrs if getattr(self, a)]
374
        for a in attrs:
375
            headers[a.replace('-', '_').upper()] = getattr(self, a)
376
        
377
        #prepare user defined meta
378
        for arg in args:
379
            key, sep, val = arg.partition('=')
380
            headers['X_OBJECT_META_%s' %key.strip().upper()] = val.strip()
381
        
382
        container, sep, object = path.partition('/')
383
        
384
        f = srcpath != '-' and open(srcpath) or stdin
385
        chunked = (self.chunked or f == stdin) and True or False
386
        self.client.update_object(container, object, f, chunked=chunked,
387
                                  headers=headers)
388
        f.close()
389

    
390
@cli_command('move', 'mv')
391
class MoveObject(Command):
392
    syntax = '<src container>/<src object> [<dst container>/]<dst object>'
393
    description = 'moves an object to a different location'
394
    
395
    def execute(self, src, dst):
396
        src_container, sep, src_object = src.partition('/')
397
        dst_container, sep, dst_object = dst.partition('/')
398
        if not sep:
399
            dst_container = src_container
400
            dst_object = dst
401
        self.client.move_object(src_container, src_object, dst_container,
402
                                dst_object)
403

    
404
def print_usage():
405
    cmd = Command([])
406
    parser = cmd.parser
407
    parser.usage = '%prog <command> [options]'
408
    parser.print_help()
409
    
410
    commands = []
411
    for cls in set(_cli_commands.values()):
412
        name = ', '.join(cls.commands)
413
        description = getattr(cls, 'description', '')
414
        commands.append('  %s %s' % (name.ljust(12), description))
415
    print '\nCommands:\n' + '\n'.join(sorted(commands))
416

    
417
def print_dict(d, header='name', f=stdout):
418
    header = header in d and header or 'subdir'
419
    if header and header in d:
420
        f.write('%s\n' %d.pop(header))
421
    patterns = ['^x_(account|container|object)_meta_(\w+)$']
422
    patterns.append(patterns[0].replace('_', '-'))
423
    for key, val in sorted(d.items()):
424
        for p in patterns:
425
            p = re.compile(p)
426
            m = p.match(key)
427
            if m:
428
                key = m.group(2)
429
        f.write('%s: %s\n' % (key.rjust(30), val))
430

    
431
def print_list(l, verbose=False, f=stdout):
432
    for elem in l:
433
        #if it's empty string continue
434
        if not elem:
435
            continue
436
        if type(elem) == types.DictionaryType:
437
            print_dict(elem, f=f)
438
        elif type(elem) == types.StringType:
439
            if not verbose:
440
                elem = elem.split('Traceback')[0]
441
            f.write('%s\n' % elem)
442
        else:
443
            f.write('%s\n' % elem)
444

    
445
def main():
446
    try:
447
        name = argv[1]
448
        cls = class_for_cli_command(name)
449
    except (IndexError, KeyError):
450
        print_usage()
451
        exit(1)
452
    
453
    cmd = cls(argv[2:])
454
    
455
    try:
456
        cmd.execute(*cmd.args)
457
    except TypeError, e:
458
        print e
459
        cmd.parser.usage = '%%prog %s [options] %s' % (name, cmd.syntax)
460
        cmd.parser.print_help()
461
        exit(1)
462
    except Fault, f:
463
        print f.status, f.data
464

    
465
if __name__ == '__main__':
466
    main()