Statistics
| Branch: | Tag: | Revision:

root / kamaki / clients / image.py @ d86c3c7d

History | View | Annotate | Download (6.9 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

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

    
37

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

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

    
44
    def list_public(self, detail=False, filters={}, order=''):
45
        """
46
        :param detail: (bool)
47

48
        :param filters: (dict) request filters
49

50
        :param order: (str) order listing by field (default is ascending, - for
51
            descending)
52

53
        :returns: (list) id,name + full image info if detail
54
        """
55
        path = path4url('images', 'detail') if detail else (
56
            path4url('images') + '/')
57

    
58
        async_params = {}
59
        if isinstance(filters, dict):
60
            for key, value in filters.items():
61
                if value:
62
                    async_params[key] = value
63
        if order.startswith('-'):
64
            async_params['sort_dir'] = 'desc'
65
            order = order[1:]
66
        else:
67
            async_params['sort_dir'] = 'asc'
68
        if order:
69
            async_params['sort_key'] = order
70

    
71
        r = self.get(path, async_params=async_params, success=200)
72
        return r.json
73

    
74
    def get_meta(self, image_id):
75
        """
76
        :param image_id: (string)
77

78
        :returns: (list) image metadata (key:val)
79
        """
80
        path = path4url('images', image_id)
81
        r = self.head(path, success=200)
82

    
83
        reply = {}
84
        properties = {}
85
        meta_prefix = 'x-image-meta-'
86
        property_prefix = 'x-image-meta-property-'
87

    
88
        for key, val in r.headers.items():
89
            key = key.lower()
90
            if key.startswith(property_prefix):
91
                key = key[len(property_prefix):]
92
                properties[key] = val
93
            elif key.startswith(meta_prefix):
94
                key = key[len(meta_prefix):]
95
                reply[key] = val
96

    
97
        if properties:
98
            reply['properties'] = properties
99
        return reply
100

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

104
        :param name: (str)
105

106
        :param location: (str) pithos://<account>/<container>/<path>
107

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

111
        :param properties: (dict) image properties (X-Image-Meta-Property)
112
        """
113
        path = path4url('images') + '/'
114
        self.set_header('X-Image-Meta-Name', name)
115
        self.set_header('X-Image-Meta-Location', location)
116

    
117
        for key, val in params.items():
118
            if key in ('id', 'store', 'disk_format', 'container_format',
119
                       'size', 'checksum', 'is_public', 'owner'):
120
                key = 'x-image-meta-' + key.replace('_', '-')
121
                self.set_header(key, val)
122

    
123
        for key, val in properties.items():
124
            self.set_header('X-Image-Meta-Property-%s' % key, val)
125

    
126
        r = self.post(path, success=200)
127
        r.release()
128

    
129
    def reregister(self, location, name=None, params={}, properties={}):
130
        """Update existing image (key: location)
131

132
        :param location: (str) pithos://<account>/<container>/<path>
133

134
        :param name: (str)
135

136
        :param params: (dict) image metadata (X-Image-Meta) can be id, store,
137
            disc_format, container_format, size, checksum, is_public, owner
138

139
        :param properties: (dict) image properties (X-Image-Meta-Property)
140
        """
141
        path = path4url('images', 'detail')
142
        r = self.get(path, success=200)
143
        imgs = [img for img in r.json if img['location'] == location]
144
        for img in imgs:
145
            img_name = name if name else img['name']
146
            img_properties = img['properties']
147
            for k, v in properties.items():
148
                img_properties[k] = v
149
            self.register(img_name, location, params, img_properties)
150
        r.release()
151

    
152
    def list_members(self, image_id):
153
        """
154
        :param image_id: (str)
155

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

    
162
    def list_shared(self, member):
163
        """
164
        :param member: (str) sharers account
165

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

    
173
    def add_member(self, image_id, member):
174
        """
175
        :param image_id: (str)
176

177
        :param member: (str) user to allow access to current user's images
178
        """
179
        path = path4url('images', image_id, 'members', member)
180
        r = self.put(path, success=204)
181
        r.release()
182

    
183
    def remove_member(self, image_id, member):
184
        """
185
        :param image_id: (str)
186

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

    
193
    def set_members(self, image_id, members):
194
        """
195
        :param image_id: (str)
196

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