Statistics
| Branch: | Tag: | Revision:

root / kamaki / clients / storage.py @ b482315a

History | View | Annotate | Download (10.9 kB)

1
#a Copyright 2011 GRNET S.A. All rights reserved.
2
#
3
# Redistribution and use in source and binary forms, with or
4
# without modification, are permitted provided that the following
5
# conditions are met:
6
#
7
#   1. Redistributions of source code must retain the above
8
#      copyright notice, this list of conditions and the following
9
#      disclaimer.
10
#
11
#   2. Redistributions in binary form must reproduce the above
12
#      copyright notice, this list of conditions and the following
13
#      disclaimer in the documentation and/or other materials
14
#      provided with the distribution.
15
#
16
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
17
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
19
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
20
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
23
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
24
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
26
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27
# POSSIBILITY OF SUCH DAMAGE.
28
#
29
# The views and conclusions contained in the software and
30
# documentation are those of the authors and should not be
31
# interpreted as representing official policies, either expressed
32
# or implied, of GRNET S.A.
33

    
34
from kamaki.clients import Client, ClientError
35
from kamaki.clients.utils import filter_in, filter_out, path4url
36

    
37

    
38
class StorageClient(Client):
39
    """OpenStack Object Storage API 1.0 client"""
40

    
41
    def __init__(self, base_url, token, account=None, container=None):
42
        super(StorageClient, self).__init__(base_url, token)
43
        self.account = account
44
        self.container = container
45

    
46
    def _assert_account(self):
47
        if not self.account:
48
            raise ClientError("No account provided")
49

    
50
    def _assert_container(self):
51
        self._assert_account()
52
        if not self.container:
53
            raise ClientError("No container provided")
54

    
55
    def get_account_info(self):
56
        """
57
        :returns: (dict)
58
        """
59
        self._assert_account()
60
        path = path4url(self.account)
61
        r = self.head(path, success=(204, 401))
62
        if r.status_code == 401:
63
            raise ClientError("No authorization")
64
        reply = r.headers
65
        return reply
66

    
67
    def replace_account_meta(self, metapairs):
68
        """
69
        :param metapais: (dict) key:val metadata pairs
70
        """
71
        self._assert_account()
72
        path = path4url(self.account)
73
        for key, val in metapairs:
74
            self.set_header('X-Account-Meta-' + key, val)
75
        r = self.post(path, success=202)
76
        r.release()
77

    
78
    def del_account_meta(self, metakey):
79
        """
80
        :param metakey: (str) metadatum key
81
        """
82
        headers = self.get_account_info()
83
        self.headers = filter_out(headers,
84
            'X-Account-Meta-' + metakey,
85
            exactMatch=True)
86
        if len(self.headers) == len(headers):
87
            raise ClientError('X-Account-Meta-%s not found' % metakey, 404)
88
        path = path4url(self.account)
89
        r = self.post(path, success=202)
90
        r.release()
91

    
92
    def create_container(self, container):
93
        """
94
        :param container: (str)
95

96
        :raises ClientError: 202 Container already exists
97
        """
98
        self._assert_account()
99
        path = path4url(self.account, container)
100
        r = self.put(path, success=(201, 202))
101
        r.release()
102
        if r.status_code == 202:
103
            raise ClientError("Container already exists", r.status_code)
104

    
105
    def get_container_info(self, container):
106
        """
107
        :param container: (str)
108

109
        :returns: (dict)
110

111
        :raises ClientError: 404 Container does not exist
112
        """
113
        self._assert_account()
114
        path = path4url(self.account, container)
115
        r = self.head(path, success=(204, 404))
116
        if r.status_code == 404:
117
            raise ClientError("Container does not exist", r.status_code)
118
        reply = r.headers
119
        return reply
120

    
121
    def delete_container(self, container):
122
        """
123
        :param container: (str)
124

125
        :raises ClientError: 404 Container does not exist
126
        :raises ClientError: 409 Container not empty
127
        """
128
        self._assert_account()
129
        path = path4url(self.account, container)
130
        r = self.delete(path, success=(204, 404, 409))
131
        if r.status_code == 404:
132
            raise ClientError("Container does not exist", r.status_code)
133
        elif r.status_code == 409:
134
            raise ClientError("Container is not empty", r.status_code)
135

    
136
    def list_containers(self):
137
        """
138
        :returns: (dict)
139
        """
140
        self._assert_account()
141
        self.set_param('format', 'json')
142
        path = path4url(self.account)
143
        r = self.get(path, success=(200, 204))
144
        reply = r.json
145
        return reply
146

    
147
    def upload_object(self, obj, f, size=None):
148
        """ A simple (naive) implementation.
149

150
        :param obj: (str)
151

152
        :param f: an open for reading file descriptor
153

154
        :param size: (int) number of bytes to upload
155
        """
156
        self._assert_container()
157
        path = path4url(self.account, self.container, obj)
158
        data = f.read(size) if size is not None else f.read()
159
        r = self.put(path, data=data, success=201)
160
        r.release()
161

    
162
    def create_object(self,
163
        obj,
164
        content_type='application/octet-stream',
165
        content_length=0):
166
        """
167
        :param obj: (str) directory-object name
168
        :param content_type: (str) explicitly set content_type
169
        :param content_length: (int) explicitly set content length
170
        """
171
        self._assert_container()
172
        path = path4url(self.account, self.container, obj)
173
        self.set_header('Content-Type', content_type)
174
        self.set_header('Content-length', str(content_length))
175
        r = self.put(path, success=201)
176
        r.release()
177

    
178
    def create_directory(self, obj):
179
        """
180
        :param obj: (str) directory-object name
181
        """
182
        self._assert_container()
183
        path = path4url(self.account, self.container, obj)
184
        self.set_header('Content-Type', 'application/directory')
185
        self.set_header('Content-length', '0')
186
        r = self.put(path, success=201)
187
        r.release()
188

    
189
    def get_object_info(self, obj):
190
        """
191
        :param obj: (str)
192

193
        :returns: (dict)
194
        """
195
        self._assert_container()
196
        path = path4url(self.account, self.container, obj)
197
        r = self.head(path, success=200)
198
        reply = r.headers
199
        return reply
200

    
201
    def get_object_meta(self, obj):
202
        """
203
        :param obj: (str)
204

205
        :returns: (dict)
206
        """
207
        r = filter_in(self.get_object_info(obj), 'X-Object-Meta-')
208
        reply = {}
209
        for (key, val) in r.items():
210
            metakey = key.split('-')[-1]
211
            reply[metakey] = val
212
        return reply
213

    
214
    def del_object_meta(self, obj, metakey):
215
        """
216
        :param obj: (str)
217

218
        :param metakey: (str) the metadatum key
219
        """
220
        self._assert_container()
221
        self.set_header('X-Object-Meta-' + metakey, '')
222
        path = path4url(self.account, self.container, obj)
223
        r = self.post(path, success=202)
224
        r.release()
225

    
226
    def replace_object_meta(self, metapairs):
227
        """
228
        :param metapairs: (dict) key:val metadata
229
        """
230
        self._assert_container()
231
        path = path4url(self.account, self.container)
232
        for key, val in metapairs:
233
            self.set_header('X-Object-Meta-' + key, val)
234
        r = self.post(path, success=202)
235
        r.release()
236

    
237
    def get_object(self, obj):
238
        """
239
        :param obj: (str)
240

241
        :returns: (int, int) # of objects, size in bytes
242
        """
243
        self._assert_container()
244
        path = path4url(self.account, self.container, obj)
245
        r = self.get(path, success=200)
246
        size = int(r.headers['content-length'])
247
        cnt = r.content
248
        return cnt, size
249

    
250
    def copy_object(self, src_container, src_object, dst_container,
251
        dst_object=False):
252
        """Copy an objects from src_contaier:src_object to
253
            dst_container[:dst_object]
254

255
        :param src_container: (str)
256

257
        :param src_object: (str)
258

259
        :param dst_container: (str)
260

261
        :param dst_object: (str)
262
        """
263
        self._assert_account()
264
        dst_object = dst_object or src_object
265
        dst_path = path4url(self.account, dst_container, dst_object)
266
        self.set_header('X-Copy-From', path4url(src_container, src_object))
267
        self.set_header('Content-Length', 0)
268
        r = self.put(dst_path, success=201)
269
        r.release()
270

    
271
    def move_object(self, src_container, src_object, dst_container,
272
        dst_object=False):
273
        """Move an objects from src_contaier:src_object to
274
            dst_container[:dst_object]
275

276
        :param src_container: (str)
277

278
        :param src_object: (str)
279

280
        :param dst_container: (str)
281

282
        :param dst_object: (str)
283
        """
284
        self._assert_account()
285
        dst_object = dst_object or src_object
286
        dst_path = path4url(self.account, dst_container, dst_object)
287
        self.set_header('X-Move-From', path4url(src_container, src_object))
288
        self.set_header('Content-Length', 0)
289
        r = self.put(dst_path, success=201)
290
        r.release()
291

    
292
    def delete_object(self, obj):
293
        """
294
        :param obj: (str)
295

296
        :raises ClientError: 404 Object not found
297
        """
298
        self._assert_container()
299
        path = path4url(self.account, self.container, obj)
300
        r = self.delete(path, success=(204, 404))
301
        if r.status_code == 404:
302
            raise ClientError("Object %s not found" % obj, r.status_code)
303

    
304
    def list_objects(self):
305
        """
306
        :returns: (dict)
307

308
        :raises ClientError: 404 Invalid account
309
        """
310
        self._assert_container()
311
        path = path4url(self.account, self.container)
312
        self.set_param('format', 'json')
313
        r = self.get(path, success=(200, 204, 304, 404), )
314
        if r.status_code == 404:
315
            raise ClientError(\
316
                "Invalid account (%s) for that container" % self.account,
317
                r.status_code)
318
        elif r.status_code == 304:
319
            return []
320
        reply = r.json
321
        return reply
322

    
323
    def list_objects_in_path(self, path_prefix):
324
        """
325
        :param path_prefix: (str)
326

327
        :raises ClientError: 404 Invalid account
328

329
        :returns: (dict)
330
        """
331
        self._assert_container()
332
        path = path4url(self.account, self.container)
333
        self.set_param('format', 'json')
334
        self.set_param('path', 'path_prefix')
335
        r = self.get(path, success=(200, 204, 404))
336
        if r.status_code == 404:
337
            raise ClientError(\
338
                "Invalid account (%s) for that container" % self.account,
339
                r.status_code)
340
        reply = r.json
341
        return reply