Statistics
| Branch: | Tag: | Revision:

root / kamaki / clients / image.py @ 3dabe5d2

History | View | Annotate | Download (5.1 kB)

1
# 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
from kamaki.clients import Client, ClientError
34
from kamaki.clients.utils import path4url
35

    
36

    
37
class ImageClient(Client):
38
    """OpenStack Image Service API 1.0 and GRNET Plankton client"""
39

    
40
    def __init__(self, base_url, token):
41
        super(ImageClient, self).__init__(base_url, token)
42

    
43
    def raise_for_status(self, r):
44
        if r.status_code == 404:
45
            raise ClientError("Image not found", r.status_code)
46

    
47
        # Fallback to the default
48
        super(ImageClient, self).raise_for_status(r)
49

    
50
    def list_public(self, detail=False, filters={}, order=''):
51
        path = path4url('images', 'detail') if detail else path4url('images/')
52

    
53
        if isinstance(filters, dict):
54
            self.http_client.params.update(filters)
55
        if order.startswith('-'):
56
            self.set_param('sort_dir', 'desc')
57
            order = order[1:]
58
        else:
59
            self.set_param('sort_dir', 'asc')
60
        self.set_param('sort_key', order, iff=order)
61

    
62
        r = self.get(path, success=200)
63
        return r.json
64

    
65
    def get_meta(self, image_id):
66
        path = path4url('images', image_id)
67
        r = self.head(path, success=200)
68

    
69
        reply = {}
70
        properties = {}
71
        meta_prefix = 'x-image-meta-'
72
        property_prefix = 'x-image-meta-property-'
73

    
74
        for key, val in r.headers.items():
75
            key = key.lower()
76
            if key.startswith(property_prefix):
77
                key = key[len(property_prefix):]
78
                properties[key] = val
79
            elif key.startswith(meta_prefix):
80
                key = key[len(meta_prefix):]
81
                reply[key] = val
82

    
83
        if properties:
84
            reply['properties'] = properties
85
        return reply
86

    
87
    def register(self, name, location, params={}, properties={}):
88
        path = path4url('images/')
89
        self.set_header('X-Image-Meta-Name', name)
90
        self.set_header('X-Image-Meta-Location', location)
91

    
92
        for key, val in params.items():
93
            if key in ('id', 'store', 'disk_format', 'container_format',
94
                       'size', 'checksum', 'is_public', 'owner'):
95
                key = 'x-image-meta-' + key.replace('_', '-')
96
                self.set_header(key, val)
97

    
98
        for key, val in properties.items():
99
            self.set_header('X-Image-Meta-Property-%s' % key, val)
100

    
101
        try:
102
            r = self.post(path, success=200)
103
        except ClientError as err:
104
            try:
105
                prefix, suffix = err.details.split('File not found')
106
                details = '%s Location %s not found %s' %\
107
                    (prefix, location, suffix)
108
                raise ClientError(err.message, err.status, details)
109
            except ValueError:
110
                pass
111
            raise err
112
        r.release()
113

    
114
    def list_members(self, image_id):
115
        path = path4url('images', image_id, 'members')
116
        r = self.get(path, success=200)
117
        return r.json['members']
118

    
119
    def list_shared(self, member):
120
        path = path4url('shared-images', member)
121
        #self.set_param('format', 'json')
122
        r = self.get(path, success=200)
123
        return r.json['shared_images']
124

    
125
    def add_member(self, image_id, member):
126
        path = path4url('images', image_id, 'members', member)
127
        r = self.put(path, success=204)
128
        r.release()
129

    
130
    def remove_member(self, image_id, member):
131
        path = path4url('images', image_id, 'members', member)
132
        r = self.delete(path, success=204)
133
        r.release()
134

    
135
    def set_members(self, image_id, members):
136
        path = path4url('images', image_id, 'members')
137
        req = {'memberships': [{'member_id': member} for member in members]}
138
        r = self.put(path, json=req, success=204)
139
        r.release()