Statistics
| Branch: | Tag: | Revision:

root / tools / store @ f7ab99df

History | View | Annotate | Download (21.9 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
            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('mkdir')
259
class PutMarker(Command):
260
    syntax = '<container>/<directory marker>'
261
    description = 'create a directory marker'
262
    
263
    def execute(self, path):
264
        container, sep, object = path.partition('/')
265
        self.client.create_directory_marker(container, object)
266

    
267
@cli_command('put')
268
class PutObject(Command):
269
    syntax = '<container>/<object> <path> [key=val] [...]'
270
    description = 'create/override object with path contents or standard input'
271
    
272
    def add_options(self, parser):
273
        parser.add_option('--chunked', action='store_true', dest='chunked',
274
                          default=False, help='set chunked transfer mode')
275
        parser.add_option('--etag', action='store', dest='etag',
276
                          default=None, help='check written data')
277
        parser.add_option('--content-encoding', action='store',
278
                          dest='content-encoding', default=None,
279
                          help='provide the object MIME content type')
280
        parser.add_option('--content-disposition', action='store', type='str',
281
                          dest='content-disposition', default=None,
282
                          help='provide the presentation style of the object')
283
        parser.add_option('--manifest', action='store', type='str',
284
                          dest='manifest', default=None,
285
                          help='use for large file support')
286
        parser.add_option('--type', action='store',
287
                          dest='content-type', default=False,
288
                          help='create object with specific content type')
289
        parser.add_option('--touch', action='store_true',
290
                          dest='touch', default=False,
291
                          help='create object with zero data')
292
    
293
    def execute(self, path, srcpath='-', *args):
294
        headers = {}
295
        if self.manifest:
296
            headers['X_OBJECT_MANIFEST'] = self.manifest
297
            
298
        attrs = ['etag', 'content-encoding', 'content-disposition']
299
        
300
        attrs = ['etag', 'content-encoding', 'content-disposition',
301
                 'content-type']
302
        attrs = [a for a in attrs if getattr(self, a)]
303
        for a in attrs:
304
            headers[a.replace('-', '_').upper()] = getattr(self, a)
305
        
306
        #prepare user defined meta
307
        for arg in args:
308
            key, sep, val = arg.partition('=')
309
            headers['X_OBJECT_META_%s' %key.strip().upper()] = val.strip()
310
        
311
        container, sep, object = path.partition('/')
312
        
313
        f = None
314
        chunked = False
315
        if not self.touch:
316
            f = srcpath != '-' and open(srcpath) or stdin
317
            chunked = (self.chunked or f == stdin) and True or False
318
        self.client.create_object(container, object, f, chunked=chunked,
319
                                  headers=headers)
320
        if f:
321
            f.close()
322

    
323
@cli_command('copy', 'cp')
324
class CopyObject(Command):
325
    syntax = '<src container>/<src object> [<dst container>/]<dst object>'
326
    description = 'copies an object to a different location'
327
    
328
    def add_options(self, parser):
329
        parser.add_option('--version', action='store',
330
                          dest='version', default=False,
331
                          help='copy specific version')
332
    
333
    def execute(self, src, dst):
334
        src_container, sep, src_object = src.partition('/')
335
        dst_container, sep, dst_object = dst.partition('/')
336
        if not sep:
337
            dst_container = src_container
338
            dst_object = dst
339
        version = getattr(self, 'version')
340
        if version:
341
            headers = {}
342
            headers['X_SOURCE_VERSION'] = version
343
        self.client.copy_object(src_container, src_object, dst_container,
344
                                dst_object, headers)
345

    
346
@cli_command('set')
347
class SetMeta(Command):
348
    syntax = '[<container>[/<object>]] key=val [key=val] [...]'
349
    description = 'set metadata'
350
    
351
    def execute(self, path, *args):
352
        #in case of account fix the args
353
        if path.find('=') != -1:
354
            args = list(args)
355
            args.append(path)
356
            args = tuple(args)
357
            path = ''
358
        meta = {}
359
        for arg in args:
360
            key, sep, val = arg.partition('=')
361
            meta[key.strip()] = val.strip()
362
        container, sep, object = path.partition('/')
363
        if object:
364
            self.client.update_object_metadata(container, object, **meta)
365
        elif container:
366
            self.client.update_container_metadata(container, **meta)
367
        else:
368
            self.client.update_account_metadata(**meta)
369

    
370
@cli_command('update')
371
class UpdateObject(Command):
372
    syntax = '<container>/<object> path [key=val] [...]'
373
    description = 'update object metadata/data (default mode: append)'
374
    
375
    def add_options(self, parser):
376
        parser.add_option('-a', action='store_true', dest='append',
377
                          default=True, help='append data')
378
        parser.add_option('--start', action='store',
379
                          dest='start',
380
                          default=None, help='range of data to be updated')
381
        parser.add_option('--range', action='store', dest='content-range',
382
                          default=None, help='range of data to be updated')
383
        parser.add_option('--chunked', action='store_true', dest='chunked',
384
                          default=False, help='set chunked transfer mode')
385
        parser.add_option('--content-encoding', action='store',
386
                          dest='content-encoding', default=None,
387
                          help='provide the object MIME content type')
388
        parser.add_option('--content-disposition', action='store', type='str',
389
                          dest='content-disposition', default=None,
390
                          help='provide the presentation style of the object')
391
        parser.add_option('--manifest', action='store', type='str',
392
                          dest='manifest', default=None,
393
                          help='use for large file support')
394
    
395
    def execute(self, path, srcpath='-', *args):
396
        headers = {}
397
        if self.manifest:
398
            headers['X_OBJECT_MANIFEST'] = self.manifest
399
        
400
        if getattr(self, 'start'):
401
            headers['CONTENT_RANGE'] = 'bytes %s-/*' % getattr(self, 'start')
402
        elif self.append:
403
            headers['CONTENT_RANGE'] = 'bytes */*'
404
        
405
        attrs = ['content-encoding', 'content-disposition']
406
        attrs = [a for a in attrs if getattr(self, a)]
407
        for a in attrs:
408
            headers[a.replace('-', '_').upper()] = getattr(self, a)
409
        
410
        #prepare user defined meta
411
        for arg in args:
412
            key, sep, val = arg.partition('=')
413
            headers['X_OBJECT_META_%s' %key.strip().upper()] = val.strip()
414
        
415
        container, sep, object = path.partition('/')
416
        
417
        f = srcpath != '-' and open(srcpath) or stdin
418
        chunked = (self.chunked or f == stdin) and True or False
419
        self.client.update_object(container, object, f, chunked=chunked,
420
                                  headers=headers)
421
        f.close()
422

    
423
@cli_command('move', 'mv')
424
class MoveObject(Command):
425
    syntax = '<src container>/<src object> [<dst container>/]<dst object>'
426
    description = 'moves an object to a different location'
427
    
428
    def add_options(self, parser):
429
        parser.add_option('--version', action='store',
430
                          dest='version', default=False,
431
                          help='move specific version')
432

    
433
    def execute(self, src, dst):
434
        src_container, sep, src_object = src.partition('/')
435
        dst_container, sep, dst_object = dst.partition('/')
436
        if not sep:
437
            dst_container = src_container
438
            dst_object = dst
439
        
440
        version = getattr(self, 'version')
441
        if version:
442
            headers = {}
443
            headers['X_SOURCE_VERSION'] = version 
444
        self.client.move_object(src_container, src_object, dst_container,
445
                                dst_object, headers)
446

    
447
@cli_command('remove', 'rm')
448
class TrashObject(Command):
449
    syntax = '<container>/<object>'
450
    description = 'trashes an object'
451
    
452
    def execute(self, src):
453
        src_container, sep, src_object = src.partition('/')
454
        
455
        self.client.trash_object(src_container, src_object)
456

    
457
@cli_command('restore')
458
class TrashObject(Command):
459
    syntax = '<container>/<object>'
460
    description = 'trashes an object'
461
    
462
    def execute(self, src):
463
        src_container, sep, src_object = src.partition('/')
464
        
465
        self.client.restore_object(src_container, src_object)
466

    
467
@cli_command('unset')
468
class TrashObject(Command):
469
    syntax = '<container>/[<object>] key [key] [...]'
470
    description = 'deletes metadata info'
471
    
472
    def execute(self, path, *args):
473
        #in case of account fix the args
474
        if path.find('=') != -1:
475
            args = list(args)
476
            args.append(path)
477
            args = tuple(args)
478
            path = ''
479
        meta = []
480
        for key in args:
481
            meta.append(key)
482
        container, sep, object = path.partition('/')
483
        if object:
484
            self.client.delete_object_metadata(container, object, meta)
485
        elif container:
486
            self.client.delete_container_metadata(container, meta)
487
        else:
488
            self.client.delete_account_metadata(meta)
489

    
490
def print_usage():
491
    cmd = Command([])
492
    parser = cmd.parser
493
    parser.usage = '%prog <command> [options]'
494
    parser.print_help()
495
    
496
    commands = []
497
    for cls in set(_cli_commands.values()):
498
        name = ', '.join(cls.commands)
499
        description = getattr(cls, 'description', '')
500
        commands.append('  %s %s' % (name.ljust(12), description))
501
    print '\nCommands:\n' + '\n'.join(sorted(commands))
502

    
503
def print_dict(d, header='name', f=stdout):
504
    header = header in d and header or 'subdir'
505
    if header and header in d:
506
        f.write('%s\n' %d.pop(header))
507
    patterns = ['^x_(account|container|object)_meta_(\w+)$']
508
    patterns.append(patterns[0].replace('_', '-'))
509
    for key, val in sorted(d.items()):
510
        for p in patterns:
511
            p = re.compile(p)
512
            m = p.match(key)
513
            if m:
514
                key = m.group(2)
515
        f.write('%s: %s\n' % (key.rjust(30), val))
516

    
517
def print_list(l, verbose=False, f=stdout):
518
    for elem in l:
519
        #if it's empty string continue
520
        if not elem:
521
            continue
522
        if type(elem) == types.DictionaryType:
523
            print_dict(elem, f=f)
524
        elif type(elem) == types.StringType:
525
            if not verbose:
526
                elem = elem.split('Traceback')[0]
527
            f.write('%s\n' % elem)
528
        else:
529
            f.write('%s\n' % elem)
530

    
531
def print_versions(data, f=stdout):
532
    if 'versions' not in data:
533
        f.write('%s\n' %data)
534
        return
535
    f.write('versions:\n')
536
    for id, t in data['versions']:
537
        f.write('%s @ %s\n' % (str(id).rjust(30), datetime.fromtimestamp(t)))
538

    
539
def main():
540
    try:
541
        name = argv[1]
542
        cls = class_for_cli_command(name)
543
    except (IndexError, KeyError):
544
        print_usage()
545
        exit(1)
546
    
547
    cmd = cls(argv[2:])
548
    
549
    try:
550
        cmd.execute(*cmd.args)
551
    except TypeError, e:
552
        print e
553
        cmd.parser.usage = '%%prog %s [options] %s' % (name, cmd.syntax)
554
        cmd.parser.print_help()
555
        exit(1)
556
    except Fault, f:
557
        print f.status, f.data
558
        status = f.status and '%s ' % f.status or ''
559
        print '%s%s' % (status, f.data)
560

    
561
if __name__ == '__main__':
562
    main()