Statistics
| Branch: | Tag: | Revision:

root / kamaki / clients / cyclades / __init__.py @ 89a1c636

History | View | Annotate | Download (9.7 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.cyclades.rest_api import CycladesRestClient
35
from kamaki.clients.network import NetworkClient
36
from kamaki.clients.utils import path4url
37
from kamaki.clients import ClientError, Waiter
38
import json
39

    
40
class CycladesClient(CycladesRestClient, Waiter):
41
    """Synnefo Cyclades Compute API client"""
42

    
43
    def create_server(
44
            self, name, flavor_id, image_id,
45
            metadata=None, personality=None, networks=None, project=None):
46
        """Submit request to create a new server
47

48
        :param name: (str)
49

50
        :param flavor_id: integer id denoting a preset hardware configuration
51

52
        :param image_id: (str) id denoting the OS image to run on virt. server
53

54
        :param metadata: (dict) vm metadata updated by os/users image metadata
55

56
        :param personality: a list of (file path, file contents) tuples,
57
            describing files to be injected into virtual server upon creation
58

59
        :param networks: (list of dicts) Networks to connect to, list this:
60
            "networks": [
61
            {"uuid": <network_uuid>},
62
            {"uuid": <network_uuid>, "fixed_ip": address},
63
            {"port": <port_id>}, ...]
64
            ATTENTION: Empty list is different to None. None means ' do not
65
            mention it', empty list means 'automatically get an ip'
66

67
        :param project: the project where to assign the server
68

69
        :returns: a dict with the new virtual server details
70

71
        :raises ClientError: wraps request errors
72
        """
73
        image = self.get_image_details(image_id)
74
        metadata = metadata or dict()
75
        for key in ('os', 'users'):
76
            try:
77
                metadata[key] = image['metadata'][key]
78
            except KeyError:
79
                pass
80

    
81
        return super(CycladesClient, self).create_server(
82
            name, flavor_id, image_id,
83
            metadata=metadata, personality=personality, networks=networks,
84
            project=project)
85

    
86
    def start_server(self, server_id):
87
        """Submit a startup request
88

89
        :param server_id: integer (str or int)
90

91
        :returns: (dict) response headers
92
        """
93
        req = {'start': {}}
94
        r = self.servers_action_post(server_id, json_data=req, success=202)
95
        return r.headers
96

    
97
    def shutdown_server(self, server_id):
98
        """Submit a shutdown request
99

100
        :param server_id: integer (str or int)
101

102
        :returns: (dict) response headers
103
        """
104
        req = {'shutdown': {}}
105
        r = self.servers_action_post(server_id, json_data=req, success=202)
106
        return r.headers
107

    
108
    def get_server_console(self, server_id):
109
        """
110
        :param server_id: integer (str or int)
111

112
        :returns: (dict) info to set a VNC connection to virtual server
113
        """
114
        req = {'console': {'type': 'vnc'}}
115
        r = self.servers_action_post(server_id, json_data=req, success=200)
116
        return r.json['console']
117

    
118
    def reassign_server(self, server_id, project):
119
        req = {'reassign': {'project': project}}
120
        r = self.servers_action_post(server_id, json_data=req, success=200)
121
        return r.headers
122

    
123
    def get_server_stats(self, server_id):
124
        """
125
        :param server_id: integer (str or int)
126

127
        :returns: (dict) auto-generated graphs of statistics (urls)
128
        """
129
        r = self.servers_stats_get(server_id)
130
        return r.json['stats']
131

    
132
    def get_server_diagnostics(self, server_id):
133
        """
134
        :param server_id: integer (str or int)
135

136
        :returns: (list)
137
        """
138
        r = self.servers_diagnostics_get(server_id)
139
        return r.json
140

    
141
    def wait_server(
142
            self, server_id,
143
            current_status='BUILD',
144
            delay=1, max_wait=100, wait_cb=None):
145
        """Wait for server while its status is current_status
146

147
        :param server_id: integer (str or int)
148

149
        :param current_status: (str) BUILD|ACTIVE|STOPPED|DELETED|REBOOT
150

151
        :param delay: time interval between retries
152

153
        :max_wait: (int) timeout in secconds
154

155
        :param wait_cb: if set a progressbar is used to show progress
156

157
        :returns: (str) the new mode if succesfull, (bool) False if timed out
158
        """
159

    
160
        def get_status(self, server_id):
161
            r = self.get_server_details(server_id)
162
            return r['status'], (r.get('progress', None) if (
163
                            current_status in ('BUILD', )) else None)
164

    
165
        return self._wait(
166
            server_id, current_status, get_status, delay, max_wait, wait_cb)
167

    
168

    
169
class CycladesNetworkClient(NetworkClient):
170
    """Cyclades Network API extentions"""
171

    
172
    network_types = (
173
        'CUSTOM', 'MAC_FILTERED', 'IP_LESS_ROUTED', 'PHYSICAL_VLAN')
174

    
175
    def list_networks(self, detail=None):
176
        path = path4url('networks', 'detail' if detail else '')
177
        r = self.get(path, success=200)
178
        return r.json['networks']
179

    
180
    def create_network(self, type, name=None, shared=None, project=None):
181
        req = dict(network=dict(type=type, admin_state_up=True))
182
        if name:
183
            req['network']['name'] = name
184
        if shared not in (None, ):
185
            req['network']['shared'] = bool(shared)
186
        if project is not None:
187
            req['network']['project'] = project
188
        r = self.networks_post(json_data=req, success=201)
189
        return r.json['network']
190

    
191
    def networks_action_post(
192
            self, network_id='', json_data=None, success=202, **kwargs):
193
        """POST base_url/networks/<network_id>/action
194

195
        :returns: request response
196
        """
197
        if json_data:
198
            json_data = json.dumps(json_data)
199
            self.set_header('Content-Type', 'application/json')
200
            self.set_header('Content-Length', len(json_data))
201
        path = path4url('networks', network_id, 'action')
202
        return self.post(path, data=json_data, success=success, **kwargs)
203

    
204
    def reassign_network(self, network_id, project):
205
        req = {'reassign': {'project': project}}
206
        r = self.networks_action_post(network_id, json_data=req, success=200)
207
        return r.headers
208

    
209
    def list_ports(self, detail=None):
210
        path = path4url('ports', 'detail' if detail else '')
211
        r = self.get(path, success=200)
212
        return r.json['ports']
213

    
214
    def create_port(
215
            self, network_id,
216
            device_id=None, security_groups=None, name=None, fixed_ips=None):
217
        """
218
        :param fixed_ips: (list of dicts) [{"ip_address": IPv4}, ...]
219
        """
220
        port = dict(network_id=network_id)
221
        if device_id:
222
            port['device_id'] = device_id
223
        if security_groups:
224
            port['security_groups'] = security_groups
225
        if name:
226
            port['name'] = name
227
        if fixed_ips:
228
            for fixed_ip in fixed_ips or []:
229
                if not 'ip_address' in fixed_ip:
230
                    raise ValueError('Invalid fixed_ip [%s]' % fixed_ip)
231
            port['fixed_ips'] = fixed_ips
232
        r = self.ports_post(json_data=dict(port=port), success=201)
233
        return r.json['port']
234

    
235
    def create_floatingip(self, floating_network_id, floating_ip_address='',
236
                          project=None):
237
        args = {"project": project}
238
        return super(CycladesNetworkClient, self).create_floatingip(
239
            floating_network_id, floating_ip_address=floating_ip_address,
240
            args=args)
241

    
242
    def update_floatingip(self, floating_network_id, floating_ip_address=''):
243
        """To nullify something optional, use None"""
244
        return super(CycladesNetworkClient, self).update_floatingip(
245
            floating_network_id, floating_ip_address=floating_ip_address)
246

    
247
    def floating_ip_action_post(
248
            self, fip_id, json_data=None, success=202, **kwargs):
249
        """POST base_url/floatingips/<fip_id>/action
250

251
        :returns: request response
252
        """
253
        if json_data:
254
            json_data = json.dumps(json_data)
255
            self.set_header('Content-Type', 'application/json')
256
            self.set_header('Content-Length', len(json_data))
257
        path = path4url('floatingips', fip_id, 'action')
258
        return self.post(path, data=json_data, success=success, **kwargs)
259

    
260
    def reassign_floating_ip(self, floating_network_id, project):
261
        req = {'reassign': {'project': project}}
262
        r = self.floating_ip_action_post(floating_network_id, json_data=req)