Statistics
| Branch: | Tag: | Revision:

root / kamaki / clients / image / __init__.py @ dad1b874

History | View | Annotate | Download (7.8 kB)

1
# Copyright 2011-2013 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 path4url
36

    
37

    
38
def _format_image_headers(headers):
39
    reply = dict(properties=dict())
40
    meta_prefix = 'x-image-meta-'
41
    property_prefix = 'x-image-meta-property-'
42

    
43
    for key, val in headers.items():
44
        key = key.lower()
45
        if key.startswith(property_prefix):
46
            key = key[len(property_prefix):].upper().replace('-', '_')
47
            reply['properties'][key] = val
48
        elif key.startswith(meta_prefix):
49
            key = key[len(meta_prefix):]
50
            reply[key] = val
51
    return reply
52

    
53

    
54
class ImageClient(Client):
55
    """Synnefo Plankton API client"""
56

    
57
    def __init__(self, base_url, token):
58
        super(ImageClient, self).__init__(base_url, token)
59

    
60
    def list_public(self, detail=False, filters={}, order=''):
61
        """
62
        :param detail: (bool)
63

64
        :param filters: (dict) request filters
65

66
        :param order: (str) order listing by field (default is ascending, - for
67
            descending)
68

69
        :returns: (list) id,name + full image info if detail
70
        """
71
        path = path4url('images', 'detail') if detail else (
72
            path4url('images') + '/')
73

    
74
        async_params = {}
75
        if isinstance(filters, dict):
76
            for key, value in filters.items():
77
                if value:
78
                    async_params[key] = value
79
        if order and order.startswith('-'):
80
            async_params['sort_dir'] = 'desc'
81
            order = order[1:]
82
        else:
83
            async_params['sort_dir'] = 'asc'
84
        if order:
85
            async_params['sort_key'] = order
86

    
87
        r = self.get(path, async_params=async_params, success=200)
88
        return r.json
89

    
90
    def get_meta(self, image_id):
91
        """
92
        :param image_id: (string)
93

94
        :returns: (list) image metadata (key:val)
95
        """
96
        path = path4url('images', image_id)
97
        r = self.head(path, success=200)
98

    
99
        return _format_image_headers(r.headers)
100

    
101
    def register(self, name, location, params={}, properties={}):
102
        """Register an image that is uploaded at location
103

104
        :param name: (str)
105

106
        :param location: (str or iterable) if iterable, then
107
            (user_uuid, container, image_path) else if string
108
            pithos://<user_uuid>/<container>/<image object>
109

110
        :param params: (dict) image metadata (X-Image-Meta) can be id, store,
111
            disc_format, container_format, size, checksum, is_public, owner
112

113
        :param properties: (dict) image properties (X-Image-Meta-Property)
114

115
        :returns: (dict) metadata of the created image
116
        """
117
        path = path4url('images') + '/'
118
        self.set_header('X-Image-Meta-Name', name)
119
        location = location if (
120
            isinstance(location, str) or isinstance(location, unicode)) else (
121
                'pithos://%s' % '/'.join(location))
122
        self.set_header('X-Image-Meta-Location', location)
123

    
124
        async_headers = {}
125
        for key, val in params.items():
126
            if key in ('store', 'disk_format', 'container_format',
127
                       'size', 'checksum', 'is_public', 'owner') and val:
128
                key = 'x-image-meta-' + key.replace('_', '-')
129
                async_headers[key] = val
130

    
131
        for key, val in properties.items():
132
            async_headers['x-image-meta-property-%s' % key] = val
133

    
134
        r = self.post(path, success=200, async_headers=async_headers)
135

    
136
        return _format_image_headers(r.headers)
137

    
138
    def unregister(self, image_id):
139
        """Unregister an image
140

141
        :param image_id: (str)
142

143
        :returns: (dict) response headers
144
        """
145
        path = path4url('images', image_id)
146
        r = self.delete(path, success=204)
147
        return r.headers
148

    
149
    def list_members(self, image_id):
150
        """
151
        :param image_id: (str)
152

153
        :returns: (list) users who can use current user's images
154
        """
155
        path = path4url('images', image_id, 'members')
156
        r = self.get(path, success=200)
157
        return r.json['members']
158

    
159
    def list_shared(self, member):
160
        """
161
        :param member: (str) sharers account
162

163
        :returns: (list) images shared by member
164
        """
165
        path = path4url('shared-images', member)
166
        #self.set_param('format', 'json')
167
        r = self.get(path, success=200)
168
        return r.json['shared_images']
169

    
170
    def add_member(self, image_id, member):
171
        """
172
        :param image_id: (str)
173

174
        :param member: (str) user to allow access to current user's images
175
        """
176
        path = path4url('images', image_id, 'members', member)
177
        self.set_header('Content-Length', len(member))
178
        r = self.put(path, success=204)
179
        return r.headers
180

    
181
    def remove_member(self, image_id, member):
182
        """
183
        :param image_id: (str)
184

185
        :param member: (str) user to deprive from current user's images
186
        """
187
        path = path4url('images', image_id, 'members', member)
188
        r = self.delete(path, success=204)
189
        return r.headers
190

    
191
    def set_members(self, image_id, members):
192
        """
193
        :param image_id: (str)
194

195
        :param members: (list) user to deprive from current user's images
196
        """
197
        path = path4url('images', image_id, 'members')
198
        req = {'memberships': [{'member_id': member} for member in members]}
199
        r = self.put(path, json=req, success=204)
200
        return r.headers
201

    
202
    def update_image(
203
            self, image_id,
204
            name=None, disk_format=None, container_format=None,
205
            status=None, public=None, owner_id=None, **properties):
206
        path = path4url('images', image_id)
207
        if name is not None:
208
            self.set_header('X-Image-Meta-Name', name)
209
        if disk_format is not None:
210
            self.set_header('X-Image-Meta-Disk-Format', disk_format)
211
        if container_format is not None:
212
            self.set_header('X-Image-Meta-Container-Format', container_format)
213
        if status is not None:
214
            self.set_header('X-Image-Meta-Status', status)
215
        if public is not None:
216
            self.set_header('X-Image-Meta-Is-Public', bool(public))
217
        if owner_id is not None:
218
            self.set_header('X-Image-Meta-Owner', owner_id)
219
        for k, v in properties.items():
220
            self.set_header('X-Image-Meta-Property-%s' % k, v)
221
        r = self.put(path, success=200)
222
        return r.headers