Statistics
| Branch: | Tag: | Revision:

root / kamaki / clients / compute.py @ 71286858

History | View | Annotate | Download (11 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 . import Client, ClientError
35
from .connection.request import HTTPRequest
36
from .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
        self.servers_put(server_id, json_data=req)
151
    
152
    def delete_server(self, server_id):
153
        """Submit a deletion request for a server specified by id"""
154
        self.servers_delete(server_id)
155
    
156
    def reboot_server(self, server_id, hard=False):
157
        """Submit a reboot request for a server specified by id"""
158
        type = 'HARD' if hard else 'SOFT'
159
        req = {'reboot': {'type': type}}
160
        self.servers_post(server_id, 'action', json_data=req)
161
    
162
    def get_server_metadata(self, server_id, key=''):
163
        command = path4url('meta', key)
164
        r = self.servers_get(server_id, command)
165
        return r.json['meta'] if key != '' else r.json['metadata']['values']
166
    
167
    def create_server_metadata(self, server_id, key, val):
168
        req = {'meta': {key: val}}
169
        r = self.servers_put(server_id, 'meta/'+key, json_data=req, success=201)
170
        return r.json['meta']
171
    
172
    def update_server_metadata(self, server_id, **metadata):
173
        req = {'metadata': metadata}
174
        r = self.servers_post(server_id, 'meta', json_data=req, success=201)
175
        return r.json['metadata']
176
    
177
    def delete_server_metadata(self, server_id, key):
178
        self.servers_delete(server_id, 'meta/'+key)
179

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

    
190
    def list_flavors(self, detail=False):
191
        detail = 'detail' if detail else ''
192
        r = self.flavors_get(command='detail')
193
        return r.json['flavors']['values']
194

    
195
    def get_flavor_details(self, flavor_id):
196
        r = self.flavors_get(flavor_id)
197
        return r.json['flavor']
198
    
199

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

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

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

    
230
        path = path4url('images', image_id, command)
231
        success = kwargs.pop('success', 201)
232
        return self.post(path, data=data, success=success, **kwargs)
233

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

    
246
        path = path4url('images', image_id, command)
247
        success = kwargs.pop('success', 201)
248
        return self.put(path, data=data, success=success, **kwargs)
249

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

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

    
276
    def update_image_metadata(self, image_id, **metadata):
277
        req = {'metadata': metadata}
278
        r - self.images_post(image_id, 'meta', json_data=req)
279
        return r.json['metadata']
280

    
281
    def delete_image_metadata(self, image_id, key):
282
        command = path4url('meta', key)
283
        self.images_delete(image_id, command)