Bump version to 0.9.3-2~wheezy
[snf-image] / snf-image-host / pithcat
1 #!/usr/bin/env python
2
3 # Copyright (C) 2011-2013 GRNET S.A.
4 #
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 2 of the License, or
8 # (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13 # General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this program; if not, write to the Free Software
17 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
18 # 02110-1301, USA.
19
20 """
21 A tool that connects to the Pithos backend and returns the size and contents
22 of a pithos object.
23
24 Since the backend does not have a "root" account we use the account given in
25 the URL as the user when connecting to the backend.
26 """
27
28 from optparse import OptionParser
29 from sys import exit, stdout, stderr
30 from os import environ
31 from binascii import hexlify, unhexlify
32 from collections import namedtuple
33
34 try:
35     from pithos.backends.modular import ModularBackend
36 except ImportError:
37     stderr.write("Pithos backend was not found.\n")
38     exit(2)
39
40
41 parser = OptionParser(usage='%prog [options] <URL>')
42 parser.add_option('--db', dest='db', metavar='URI',
43                   help='SQLAlchemy URI of the database [REQUIRED]')
44 parser.add_option('--data', dest='data', metavar='DIR',
45                   help='path to the directory where data are'
46                        ' stored [REQUIRED]')
47 parser.add_option('-s', action='store_true', dest='size', default=False,
48                   help='print file size and exit')
49
50 LocationURL = namedtuple('LocationURL', ['account', 'container', 'object'])
51 HashmapURL = namedtuple('HashmapURL', ['hash', 'size'])
52
53
54 def parse_url(url):
55     if url.startswith('pithos://'):
56         t = url.split('/', 4)
57         assert len(t) == 5, "Invalid URL"
58         return LocationURL(*t[2:5])
59     elif url.startswith('pithosmap://'):
60         t = url.split('/', 3)
61         assert len(t) == 4, "Invalid URL"
62         return HashmapURL(*t[2:4])
63     else:
64         raise Exception("Invalid URL")
65
66
67 def print_size(backend, url):
68     """Writes object's size to stdout."""
69     if type(url) is LocationURL:
70         account, container, object = url
71         meta = backend.get_object_meta(account, account, container, object,
72                                        None)
73         print meta['bytes']
74     elif type(url) is HashmapURL:
75         print url.size
76     else:
77         raise Exception("Invalid URL")
78
79
80 def print_data(backend, url):
81     """Writes object's size to stdout."""
82
83     if type(url) is LocationURL:
84         account, container, object = url
85         size, hashmap = backend.get_object_hashmap(account, account, container,
86                                                    object)
87     elif type(url) is HashmapURL:
88         hashmap = [hexlify(x)
89                    for x in backend.store.map_get(unhexlify(url.hash))]
90         size = int(url.size)
91     else:
92         raise Exception("Invalid URL")
93
94     for hash in hashmap:
95         block = backend.get_block(hash)
96         if len(block) > size:
97             block = block[:size]
98         stdout.write(block)
99         size -= len(block)
100
101
102 def main():
103     options, args = parser.parse_args()
104     if len(args) != 1:
105         parser.print_help()
106         exit(1)
107
108     url = parse_url(args[0])
109
110     if not options.data and 'PITHCAT_INPUT_DATA' not in environ:
111         stderr.write("Pithos data directory path is missing.\n")
112         exit(1)
113
114     data_path = environ['PITHCAT_INPUT_DATA'] if not options.data else \
115         options.data
116
117     if not options.db and 'PITHCAT_INPUT_DB' not in environ:
118         stderr.write("Pithos database uri is missing.\n")
119         exit(1)
120
121     db_uri = environ['PITHCAT_INPUT_DB'] if not options.db else options.db
122
123     backend = ModularBackend(None,
124                              db_uri if type(url) is LocationURL
125                                     else None,
126                              None,
127                              data_path)
128
129     if options.size:
130         print_size(backend, url)
131     else:
132         print_data(backend, url)
133
134 if __name__ == '__main__':
135     main()