Statistics
| Branch: | Tag: | Revision:

root / kamaki / clients / compute.py @ c270fe96

History | View | Annotate | Download (11.2 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.connection.request import HTTPRequest
36
from kamaki.clients.utils import path4url
37
import json
38

    
39

    
40
class ComputeClient(Client):
41
    """OpenStack Compute API 1.1 client"""
42

    
43
    def raise_for_status(self, r):
44
        try:
45
            d = r.json
46
            key = d.keys()[0]
47
            val = d[key]
48
            message = '%s: %s' % (key, val.get('message', ''))
49
            details = val.get('details', '')
50
        except AttributeError:
51
            message = 'Request responded with error code '+unicode(r.status_code)
52
            details = unicode(r.request.method)+' '+unicode(r.request.url)
53
        raise ClientError(message, r.status_code, details)
54
    
55
    def servers_get(self, server_id='', command='', **kwargs):
56
        """GET base_url/servers[/server_id][/command] request
57
        @param server_id or ''
58
        @param command: can be 'ips', 'stats', or ''
59
        """
60
        path = path4url('servers', server_id, command)
61
        success = kwargs.pop('success', 200)
62
        return self.get(path, success=success, **kwargs)
63

    
64
    def servers_delete(self, server_id='', command='', **kwargs):
65
        """DEL ETE base_url/servers[/server_id][/command] request
66
        @param server_id or ''
67
        @param command: can be 'ips', 'stats', or ''
68
        """
69
        path = path4url('servers', server_id, command)
70
        success = kwargs.pop('success', 204)
71
        return self.delete(path, success=success, **kwargs)
72

    
73
    def servers_post(self, server_id='', command='', json_data=None, **kwargs):
74
        """POST base_url/servers[/server_id]/[command] request
75
        @param server_id or ''
76
        @param command: can be 'action' or ''
77
        @param json_data: a json valid dict that will be send as data
78
        """
79
        data = json_data
80
        if json_data is not None:
81
            data = json.dumps(json_data)
82
            self.set_header('Content-Type', 'application/json')
83
            self.set_header('Content-Length', len(data))
84

    
85
        path = path4url('servers', server_id, command)
86
        success = kwargs.pop('success', 202)
87
        return self.post(path, data=data, success=success, **kwargs)
88

    
89
    def servers_put(self, server_id='', command='', json_data=None, **kwargs):
90
        """PUT base_url/servers[/server_id]/[command] request
91
        @param server_id or ''
92
        @param command: can be 'action' or ''
93
        @param json_data: a json valid dict that will be send as data
94
        """
95
        data = json_data
96
        if json_data is not None:
97
            data = json.dumps(json_data)
98
            self.set_header('Content-Type', 'application/json')
99
            self.set_header('Content-Length', len(data))
100

    
101
        path = path4url('servers', server_id, command)
102
        success = kwargs.pop('success', 204)
103
        return self.put(path, data=data, success=success, **kwargs)
104

    
105
    def list_servers(self, detail=False):
106
        """List servers, returned detailed output if detailed is True"""
107
        detail = 'detail' if detail else ''
108
        r = self.servers_get(command=detail)
109
        return r.json['servers']['values']
110
    
111
    def get_server_details(self, server_id, **kwargs):
112
        """Return detailed output on a server specified by its id"""
113
        r = self.servers_get(server_id, **kwargs)
114
        return r.json['server']
115
    
116
    def create_server(self, name, flavor_id, image_id, personality=None):
117
        """Submit request to create a new server
118

119
        The flavor_id specifies the hardware configuration to use,
120
        the image_id specifies the OS Image to be deployed inside the new
121
        server.
122

123
        The personality argument is a list of (file path, file contents)
124
        tuples, describing files to be injected into the server upon creation.
125

126
        The call returns a dictionary describing the newly created server.
127
        """
128
        req = {'server': {'name': name,
129
                          'flavorRef': flavor_id,
130
                          'imageRef': image_id}}
131
        if personality:
132
            req['server']['personality'] = personality
133
        
134
        try:
135
            r = self.servers_post(json_data=req)
136
        except ClientError as err:
137
            try:
138
                err.message = err.details.split(',')[0].split(':')[2].split('"')[1]
139
            finally:
140
                raise err
141
        return r.json['server']
142
    
143
    def update_server_name(self, server_id, new_name):
144
        """Update the name of the server as reported by the API.
145

146
        This call does not modify the hostname actually used by the server
147
        internally.
148
        """
149
        req = {'server': {'name': new_name}}
150
        r = self.servers_put(server_id, json_data=req)
151
        r.release()
152
    
153
    def delete_server(self, server_id):
154
        """Submit a deletion request for a server specified by id"""
155
        r = self.servers_delete(server_id)
156
        r.release()
157

    
158
    def reboot_server(self, server_id, hard=False):
159
        """Submit a reboot request for a server specified by id"""
160
        type = 'HARD' if hard else 'SOFT'
161
        req = {'reboot': {'type': type}}
162
        r = self.servers_post(server_id, 'action', json_data=req)
163
        r.release()
164
    
165
    def get_server_metadata(self, server_id, key=''):
166
        command = path4url('meta', key)
167
        r = self.servers_get(server_id, command)
168
        return r.json['meta'] if key != '' else r.json['metadata']['values']
169
    
170
    def create_server_metadata(self, server_id, key, val):
171
        req = {'meta': {key: val}}
172
        r = self.servers_put(server_id, 'meta/'+key, json_data=req, success=201)
173
        return r.json['meta']
174
    
175
    def update_server_metadata(self, server_id, **metadata):
176
        req = {'metadata': metadata}
177
        r = self.servers_post(server_id, 'meta', json_data=req, success=201)
178
        return r.json['metadata']
179
    
180
    def delete_server_metadata(self, server_id, key):
181
        r = self.servers_delete(server_id, 'meta/'+key)
182
        r.release()
183

    
184
   
185
    def flavors_get(self, flavor_id='', command='', **kwargs):
186
        """GET base_url[/flavor_id][/command]
187
        @param flavor_id
188
        @param command
189
        """
190
        path = path4url('flavors', flavor_id, command)
191
        success=kwargs.pop('success', 200)
192
        return self.get(path, success=success, **kwargs)
193

    
194
    def list_flavors(self, detail=False):
195
        detail = 'detail' if detail else ''
196
        r = self.flavors_get(command='detail')
197
        return r.json['flavors']['values']
198

    
199
    def get_flavor_details(self, flavor_id):
200
        r = self.flavors_get(flavor_id)
201
        return r.json['flavor']
202
    
203

    
204
    def images_get(self, image_id='', command='', **kwargs):
205
        """GET base_url[/image_id][/command]
206
        @param image_id
207
        @param command
208
        """
209
        path = path4url('images', image_id, command)
210
        success=kwargs.pop('success', 200)
211
        return self.get(path, success=success, **kwargs)
212

    
213
    def images_delete(self, image_id='', command='', **kwargs):
214
        """DEL ETE base_url[/image_id][/command]
215
        @param image_id
216
        @param command
217
        """
218
        path = path4url('images', image_id, command)
219
        success=kwargs.pop('success', 204)
220
        return self.delete(path, success=success, **kwargs)
221

    
222
    def images_post(self, image_id='', command='', json_data=None, **kwargs):
223
        """POST base_url/images[/image_id]/[command] request
224
        @param image_id or ''
225
        @param command: can be 'action' or ''
226
        @param json_data: a json valid dict that will be send as data
227
        """
228
        data = json_data
229
        if json_data is not None:
230
            data = json.dumps(json_data)
231
            self.set_header('Content-Type', 'application/json')
232
            self.set_header('Content-Length', len(data))
233

    
234
        path = path4url('images', image_id, command)
235
        success = kwargs.pop('success', 201)
236
        return self.post(path, data=data, success=success, **kwargs)
237

    
238
    def images_put(self, image_id='', command='', json_data=None, **kwargs):
239
        """PUT base_url/images[/image_id]/[command] request
240
        @param image_id or ''
241
        @param command: can be 'action' or ''
242
        @param json_data: a json valid dict that will be send as data
243
        """
244
        data = json_data
245
        if json_data is not None:
246
            data = json.dumps(json_data)
247
            self.set_header('Content-Type', 'application/json')
248
            self.set_header('Content-Length', len(data))
249

    
250
        path = path4url('images', image_id, command)
251
        success = kwargs.pop('success', 201)
252
        return self.put(path, data=data, success=success, **kwargs)
253

    
254
    def list_images(self, detail=False):
255
        detail = 'detail' if detail else ''
256
        r = self.images_get(command=detail)
257
        return r.json['images']['values']
258
    
259
    def get_image_details(self, image_id, **kwargs):
260
        r = self.images_get(image_id, **kwargs)
261
        try:
262
            return r.json['image']
263
        except KeyError:
264
            raise ClientError('Image not available', 404,
265
                details='Image %d not found or not accessible')
266
    
267
    def delete_image(self, image_id):
268
        r = self.images_delete(image_id)
269
        r.release()
270

    
271
    def get_image_metadata(self, image_id, key=''):
272
        command = path4url('meta', key)
273
        r = self.images_get(image_id, command)
274
        return r.json['meta'] if key != '' else r.json['metadata']['values']
275
    
276
    def create_image_metadata(self, image_id, key, val):
277
        req = {'meta': {key: val}}
278
        r = self.images_put(image_id, 'meta/'+key, json_data=req)
279
        return r.json['meta']
280

    
281
    def update_image_metadata(self, image_id, **metadata):
282
        req = {'metadata': metadata}
283
        r - self.images_post(image_id, 'meta', json_data=req)
284
        return r.json['metadata']
285

    
286
    def delete_image_metadata(self, image_id, key):
287
        command = path4url('meta', key)
288
        r = self.images_delete(image_id, command)
289
        r.release()