Statistics
| Branch: | Tag: | Revision:

root / kamaki / clients / compute.py @ 606fe15f

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

    
34
from kamaki.clients import ClientError
35
from kamaki.clients.compute_rest_api import ComputeClientApi
36
from kamaki.clients.utils import path4url
37
import json
38

    
39

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

    
43
    def list_servers(self, detail=False):
44
        """List servers, returned detailed output if detailed is True"""
45
        detail = 'detail' if detail else ''
46
        r = self.servers_get(command=detail)
47
        return r.json['servers']['values']
48

    
49
    def get_server_details(self, server_id, **kwargs):
50
        """Return detailed output on a server specified by its id"""
51
        r = self.servers_get(server_id, **kwargs)
52
        return r.json['server']
53

    
54
    def create_server(self, name, flavor_id, image_id, personality=None):
55
        """Submit request to create a new server
56

57
        The flavor_id specifies the hardware configuration to use,
58
        the image_id specifies the OS Image to be deployed inside the new
59
        server.
60

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

64
        The call returns a dictionary describing the newly created server.
65
        """
66
        req = {'server': {'name': name,
67
                          'flavorRef': flavor_id,
68
                          'imageRef': image_id}}
69

    
70
        image = self.get_image_details(image_id)
71
        img_meta = image['metadata']['values']
72
        metadata = {}
73
        for key in ('os', 'users'):
74
            try:
75
                metadata[key] = img_meta[key]
76
            except KeyError:
77
                pass
78
        if metadata:
79
            req['server']['metadata'] = metadata
80

    
81
        if personality:
82
            req['server']['personality'] = personality
83

    
84
        try:
85
            r = self.servers_post(json_data=req)
86
        except ClientError as err:
87
            try:
88
                tmp_err = err.details.split(',')
89
                tmp_err = tmp_err[0].split(':')
90
                tmp_err = tmp_err[2].split('"')
91
                err.message = tmp_err[1]
92
            finally:
93
                raise err
94
        return r.json['server']
95

    
96
    def update_server_name(self, server_id, new_name):
97
        """Update the name of the server as reported by the API.
98

99
        This call does not modify the hostname actually used by the server
100
        internally.
101
        """
102
        req = {'server': {'name': new_name}}
103
        r = self.servers_put(server_id, json_data=req)
104
        r.release()
105

    
106
    def delete_server(self, server_id):
107
        """Submit a deletion request for a server specified by id"""
108
        r = self.servers_delete(server_id)
109
        r.release()
110

    
111
    def reboot_server(self, server_id, hard=False):
112
        """Submit a reboot request for a server specified by id"""
113
        type = 'HARD' if hard else 'SOFT'
114
        req = {'reboot': {'type': type}}
115
        r = self.servers_post(server_id, 'action', json_data=req)
116
        r.release()
117

    
118
    def get_server_metadata(self, server_id, key=''):
119
        command = path4url('meta', key)
120
        r = self.servers_get(server_id, command)
121
        return r.json['meta'] if key != '' else r.json['metadata']['values']
122

    
123
    def create_server_metadata(self, server_id, key, val):
124
        req = {'meta': {key: val}}
125
        r = self.servers_put(server_id,
126
            'meta/' + key,
127
            json_data=req,
128
            success=201)
129
        return r.json['meta']
130

    
131
    def update_server_metadata(self, server_id, **metadata):
132
        req = {'metadata': metadata}
133
        r = self.servers_post(server_id, 'meta', json_data=req, success=201)
134
        return r.json['metadata']
135

    
136
    def delete_server_metadata(self, server_id, key):
137
        r = self.servers_delete(server_id, 'meta/' + key)
138
        r.release()
139

    
140
    def flavors_get(self, flavor_id='', command='', **kwargs):
141
        """GET base_url[/flavor_id][/command]
142
        @param flavor_id
143
        @param command
144
        """
145
        path = path4url('flavors', flavor_id, command)
146
        success = kwargs.pop('success', 200)
147
        return self.get(path, success=success, **kwargs)
148

    
149
    def list_flavors(self, detail=False):
150
        detail = 'detail' if detail else ''
151
        r = self.flavors_get(command='detail')
152
        return r.json['flavors']['values']
153

    
154
    def get_flavor_details(self, flavor_id):
155
        r = self.flavors_get(flavor_id)
156
        return r.json['flavor']
157

    
158
    def images_get(self, image_id='', command='', **kwargs):
159
        """GET base_url[/image_id][/command]
160
        @param image_id
161
        @param command
162
        """
163
        path = path4url('images', image_id, command)
164
        success = kwargs.pop('success', 200)
165
        return self.get(path, success=success, **kwargs)
166

    
167
    def images_delete(self, image_id='', command='', **kwargs):
168
        """DEL ETE base_url[/image_id][/command]
169
        @param image_id
170
        @param command
171
        """
172
        path = path4url('images', image_id, command)
173
        success = kwargs.pop('success', 204)
174
        return self.delete(path, success=success, **kwargs)
175

    
176
    def images_post(self, image_id='', command='', json_data=None, **kwargs):
177
        """POST base_url/images[/image_id]/[command] request
178
        @param image_id or ''
179
        @param command: can be 'action' or ''
180
        @param json_data: a json valid dict that will be send as data
181
        """
182
        data = json_data
183
        if json_data is not None:
184
            data = json.dumps(json_data)
185
            self.set_header('Content-Type', 'application/json')
186
            self.set_header('Content-Length', len(data))
187

    
188
        path = path4url('images', image_id, command)
189
        success = kwargs.pop('success', 201)
190
        return self.post(path, data=data, success=success, **kwargs)
191

    
192
    def images_put(self, image_id='', command='', json_data=None, **kwargs):
193
        """PUT base_url/images[/image_id]/[command] request
194
        @param image_id or ''
195
        @param command: can be 'action' or ''
196
        @param json_data: a json valid dict that will be send as data
197
        """
198
        data = json_data
199
        if json_data is not None:
200
            data = json.dumps(json_data)
201
            self.set_header('Content-Type', 'application/json')
202
            self.set_header('Content-Length', len(data))
203

    
204
        path = path4url('images', image_id, command)
205
        success = kwargs.pop('success', 201)
206
        return self.put(path, data=data, success=success, **kwargs)
207

    
208
    def list_images(self, detail=False):
209
        detail = 'detail' if detail else ''
210
        r = self.images_get(command=detail)
211
        return r.json['images']['values']
212

    
213
    def get_image_details(self, image_id, **kwargs):
214
        r = self.images_get(image_id, **kwargs)
215
        try:
216
            return r.json['image']
217
        except KeyError:
218
            raise ClientError('Image not available', 404,
219
                details='Image %d not found or not accessible')
220

    
221
    def delete_image(self, image_id):
222
        r = self.images_delete(image_id)
223
        r.release()
224

    
225
    def get_image_metadata(self, image_id, key=''):
226
        command = path4url('meta', key)
227
        r = self.images_get(image_id, command)
228
        return r.json['meta'] if key != '' else r.json['metadata']['values']
229

    
230
    def create_image_metadata(self, image_id, key, val):
231
        req = {'meta': {key: val}}
232
        r = self.images_put(image_id, 'meta/' + key, json_data=req)
233
        return r.json['meta']
234

    
235
    def update_image_metadata(self, image_id, **metadata):
236
        req = {'metadata': metadata}
237
        r = self.images_post(image_id, 'meta', json_data=req)
238
        return r.json['metadata']
239

    
240
    def delete_image_metadata(self, image_id, key):
241
        command = path4url('meta', key)
242
        r = self.images_delete(image_id, command)
243
        r.release()