summaryrefslogtreecommitdiff
path: root/openstackclient/api/object_store_v1.py
blob: ac40cf6c52f998cbdb1b7d66cc9b4b14faa25bc3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
#   Licensed under the Apache License, Version 2.0 (the "License"); you may
#   not use this file except in compliance with the License. You may obtain
#   a copy of the License at
#
#        http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#   WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#   License for the specific language governing permissions and limitations
#   under the License.
#

"""Object Store v1 API Library"""

import io
import logging
import os
import sys
import urllib

from osc_lib import utils

from openstackclient.api import api


GLOBAL_READ_ACL = ".r:*"
LIST_CONTENTS_ACL = ".rlistings"
PUBLIC_CONTAINER_ACLS = [GLOBAL_READ_ACL, LIST_CONTENTS_ACL]


class APIv1(api.BaseAPI):
    """Object Store v1 API"""

    def __init__(self, **kwargs):
        super(APIv1, self).__init__(**kwargs)

    def container_create(
        self, container=None, public=False, storage_policy=None
    ):
        """Create a container

        :param string container:
            name of container to create
        :param bool public:
            Boolean value indicating if the container should be publicly
            readable. Defaults to False.
        :param string storage_policy:
            Name of the a specific storage policy to use. If not specified
            swift will use its default storage policy.
        :returns:
            dict of returned headers
        """

        headers = {}
        if public:
            headers['x-container-read'] = ",".join(PUBLIC_CONTAINER_ACLS)
        if storage_policy is not None:
            headers['x-storage-policy'] = storage_policy

        response = self.create(
            urllib.parse.quote(container), method='PUT', headers=headers
        )

        data = {
            'account': self._find_account_id(),
            'container': container,
            'x-trans-id': response.headers.get('x-trans-id'),
        }

        return data

    def container_delete(
        self,
        container=None,
    ):
        """Delete a container

        :param string container:
            name of container to delete
        """

        if container:
            self.delete(urllib.parse.quote(container))

    def container_list(
        self,
        full_listing=False,
        limit=None,
        marker=None,
        end_marker=None,
        prefix=None,
        **params
    ):
        """Get containers in an account

        :param boolean full_listing:
            if True, return a full listing, else returns a max of
            10000 listings
        :param integer limit:
            query return count limit
        :param string marker:
            query marker
        :param string end_marker:
            query end_marker
        :param string prefix:
            query prefix
        :returns:
            list of container names
        """

        params['format'] = 'json'

        if full_listing:
            data = listing = self.container_list(
                limit=limit,
                marker=marker,
                end_marker=end_marker,
                prefix=prefix,
                **params
            )
            while listing:
                marker = listing[-1]['name']
                listing = self.container_list(
                    limit=limit,
                    marker=marker,
                    end_marker=end_marker,
                    prefix=prefix,
                    **params
                )
                if listing:
                    data.extend(listing)
            return data

        if limit:
            params['limit'] = limit
        if marker:
            params['marker'] = marker
        if end_marker:
            params['end_marker'] = end_marker
        if prefix:
            params['prefix'] = prefix

        return self.list('', **params)

    def container_save(
        self,
        container=None,
    ):
        """Save all the content from a container

        :param string container:
            name of container to save
        """

        objects = self.object_list(container=container)
        for object in objects:
            self.object_save(container=container, object=object['name'])

    def container_set(
        self,
        container,
        properties,
    ):
        """Set container properties

        :param string container:
            name of container to modify
        :param dict properties:
            properties to add or update for the container
        """

        headers = self._set_properties(properties, 'X-Container-Meta-%s')
        if headers:
            self.create(urllib.parse.quote(container), headers=headers)

    def container_show(
        self,
        container=None,
    ):
        """Get container details

        :param string container:
            name of container to show
        :returns:
            dict of returned headers
        """

        response = self._request('HEAD', urllib.parse.quote(container))
        data = {
            'account': self._find_account_id(),
            'container': container,
            'object_count': response.headers.get('x-container-object-count'),
            'bytes_used': response.headers.get('x-container-bytes-used'),
            'storage_policy': response.headers.get('x-storage-policy'),
        }

        if 'x-container-read' in response.headers:
            data['read_acl'] = response.headers.get('x-container-read')
        if 'x-container-write' in response.headers:
            data['write_acl'] = response.headers.get('x-container-write')
        if 'x-container-sync-to' in response.headers:
            data['sync_to'] = response.headers.get('x-container-sync-to')
        if 'x-container-sync-key' in response.headers:
            data['sync_key'] = response.headers.get('x-container-sync-key')

        properties = self._get_properties(
            response.headers, 'x-container-meta-'
        )
        if properties:
            data['properties'] = properties

        return data

    def container_unset(
        self,
        container,
        properties,
    ):
        """Unset container properties

        :param string container:
            name of container to modify
        :param dict properties:
            properties to remove from the container
        """

        headers = self._unset_properties(
            properties, 'X-Remove-Container-Meta-%s'
        )
        if headers:
            self.create(urllib.parse.quote(container), headers=headers)

    def object_create(
        self,
        container=None,
        object=None,
        name=None,
    ):
        """Create an object inside a container

        :param string container:
            name of container to store object
        :param string object:
            local path to object
        :param string name:
            name of object to create
        :returns:
            dict of returned headers
        """

        if container is None or object is None:
            # TODO(dtroyer): What exception to raise here?
            return {}

        # For uploading a file, if name is provided then set it as the
        # object's name in the container.
        object_name_str = name if name else object

        full_url = "%s/%s" % (
            urllib.parse.quote(container),
            urllib.parse.quote(object_name_str),
        )
        with io.open(object, 'rb') as f:
            response = self.create(
                full_url,
                method='PUT',
                data=f,
            )
        data = {
            'account': self._find_account_id(),
            'container': container,
            'object': object_name_str,
            'x-trans-id': response.headers.get('X-Trans-Id'),
            'etag': response.headers.get('Etag'),
        }

        return data

    def object_delete(
        self,
        container=None,
        object=None,
    ):
        """Delete an object from a container

        :param string container:
            name of container that stores object
        :param string object:
            name of object to delete
        """

        if container is None or object is None:
            return

        self.delete(
            "%s/%s"
            % (urllib.parse.quote(container), urllib.parse.quote(object))
        )

    def object_list(
        self,
        container=None,
        full_listing=False,
        limit=None,
        marker=None,
        end_marker=None,
        delimiter=None,
        prefix=None,
        **params
    ):
        """List objects in a container

        :param string container:
            container name to get a listing for
        :param boolean full_listing:
            if True, return a full listing, else returns a max of
            10000 listings
        :param integer limit:
            query return count limit
        :param string marker:
            query marker
        :param string end_marker:
            query end_marker
        :param string prefix:
            query prefix
        :param string delimiter:
            string to delimit the queries on
        :returns: a tuple of (response headers, a list of objects) The response
            headers will be a dict and all header names will be lowercase.
        """

        if container is None:
            return None

        params['format'] = 'json'
        if full_listing:
            data = listing = self.object_list(
                container=container,
                limit=limit,
                marker=marker,
                end_marker=end_marker,
                prefix=prefix,
                delimiter=delimiter,
                **params
            )
            while listing:
                if delimiter:
                    marker = listing[-1].get('name', listing[-1].get('subdir'))
                else:
                    marker = listing[-1]['name']
                listing = self.object_list(
                    container=container,
                    limit=limit,
                    marker=marker,
                    end_marker=end_marker,
                    prefix=prefix,
                    delimiter=delimiter,
                    **params
                )
                if listing:
                    data.extend(listing)
            return data

        if limit:
            params['limit'] = limit
        if marker:
            params['marker'] = marker
        if end_marker:
            params['end_marker'] = end_marker
        if prefix:
            params['prefix'] = prefix
        if delimiter:
            params['delimiter'] = delimiter

        return self.list(urllib.parse.quote(container), **params)

    def object_save(
        self,
        container=None,
        object=None,
        file=None,
    ):
        """Save an object stored in a container

        :param string container:
            name of container that stores object
        :param string object:
            name of object to save
        :param string file:
            local name of object
        """

        if not file:
            file = object

        response = self._request(
            'GET',
            "%s/%s"
            % (urllib.parse.quote(container), urllib.parse.quote(object)),
            stream=True,
        )
        if response.status_code == 200:
            if file == '-':
                with os.fdopen(sys.stdout.fileno(), 'wb') as f:
                    for chunk in response.iter_content(64 * 1024):
                        f.write(chunk)
            else:
                if not os.path.exists(os.path.dirname(file)):
                    if len(os.path.dirname(file)) > 0:
                        os.makedirs(os.path.dirname(file))
                with open(file, 'wb') as f:
                    for chunk in response.iter_content(64 * 1024):
                        f.write(chunk)

    def object_set(
        self,
        container,
        object,
        properties,
    ):
        """Set object properties

        :param string container:
            container name for object to modify
        :param string object:
            name of object to modify
        :param dict properties:
            properties to add or update for the container
        """

        headers = self._set_properties(properties, 'X-Object-Meta-%s')
        if headers:
            self.create(
                "%s/%s"
                % (urllib.parse.quote(container), urllib.parse.quote(object)),
                headers=headers,
            )

    def object_unset(
        self,
        container,
        object,
        properties,
    ):
        """Unset object properties

        :param string container:
            container name for object to modify
        :param string object:
            name of object to modify
        :param dict properties:
            properties to remove from the object
        """

        headers = self._unset_properties(properties, 'X-Remove-Object-Meta-%s')
        if headers:
            self.create(
                "%s/%s"
                % (urllib.parse.quote(container), urllib.parse.quote(object)),
                headers=headers,
            )

    def object_show(
        self,
        container=None,
        object=None,
    ):
        """Get object details

        :param string container:
            container name for object to get
        :param string object:
            name of object to get
        :returns:
            dict of object properties
        """

        if container is None or object is None:
            return {}

        response = self._request(
            'HEAD',
            "%s/%s"
            % (urllib.parse.quote(container), urllib.parse.quote(object)),
        )

        data = {
            'account': self._find_account_id(),
            'container': container,
            'object': object,
            'content-type': response.headers.get('content-type'),
        }
        if 'content-length' in response.headers:
            data['content-length'] = response.headers.get('content-length')
        if 'last-modified' in response.headers:
            data['last-modified'] = response.headers.get('last-modified')
        if 'etag' in response.headers:
            data['etag'] = response.headers.get('etag')
        if 'x-object-manifest' in response.headers:
            data['x-object-manifest'] = response.headers.get(
                'x-object-manifest'
            )

        properties = self._get_properties(response.headers, 'x-object-meta-')
        if properties:
            data['properties'] = properties

        return data

    def account_set(
        self,
        properties,
    ):
        """Set account properties

        :param dict properties:
            properties to add or update for the account
        """

        headers = self._set_properties(properties, 'X-Account-Meta-%s')
        if headers:
            # NOTE(stevemar): The URL (first argument) in this case is already
            # set to the swift account endpoint, because that's how it's
            # registered in the catalog
            self.create("", headers=headers)

    def account_show(self):
        """Show account details"""

        # NOTE(stevemar): Just a HEAD request to the endpoint already in the
        # catalog should be enough.
        response = self._request("HEAD", "")
        data = {}

        properties = self._get_properties(response.headers, 'x-account-meta-')
        if properties:
            data['properties'] = properties

        # Map containers, bytes and objects a bit nicer
        data['Containers'] = response.headers.get('x-account-container-count')
        data['Objects'] = response.headers.get('x-account-object-count')
        data['Bytes'] = response.headers.get('x-account-bytes-used')
        # Add in Account info too
        data['Account'] = self._find_account_id()
        return data

    def account_unset(
        self,
        properties,
    ):
        """Unset account properties

        :param dict properties:
            properties to remove from the account
        """

        headers = self._unset_properties(
            properties, 'X-Remove-Account-Meta-%s'
        )
        if headers:
            self.create("", headers=headers)

    def _find_account_id(self):
        url_parts = urllib.parse.urlparse(self.endpoint)
        return url_parts.path.split('/')[-1]

    def _unset_properties(self, properties, header_tag):
        # NOTE(stevemar): As per the API, the headers have to be in the form
        # of "X-Remove-Account-Meta-Book: x". In the case where metadata is
        # removed, we can set the value of the header to anything, so it's
        # set to 'x'. In the case of a Container property we use:
        # "X-Remove-Container-Meta-Book: x", and the same logic applies for
        # Object properties

        headers = {}
        for k in properties:
            header_name = header_tag % k
            headers[header_name] = 'x'
        return headers

    def _set_properties(self, properties, header_tag):
        # NOTE(stevemar): As per the API, the headers have to be in the form
        # of "X-Account-Meta-Book: MobyDick". In the case of a Container
        # property we use: "X-Add-Container-Meta-Book: MobyDick", and the same
        # logic applies for Object properties

        log = logging.getLogger(__name__ + '._set_properties')

        headers = {}
        for k, v in properties.items():
            if not utils.is_ascii(k) or not utils.is_ascii(v):
                log.error('Cannot set property %s to non-ascii value', k)
                continue

            header_name = header_tag % k
            headers[header_name] = v
        return headers

    def _get_properties(self, headers, header_tag):
        # Add in properties as a top level key, this is consistent with other
        # OSC commands
        properties = {}
        for k, v in headers.items():
            if k.lower().startswith(header_tag):
                properties[k[len(header_tag) :]] = v
        return properties