Statistics
| Branch: | Tag: | Revision:

root / kamaki / clients / cyclades / __init__.py @ b6afe2ec

History | View | Annotate | Download (9.9 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 set_firewall_profile(self, server_id, profile, port_id):
87
        """Set the firewall profile for the public interface of a server
88
        :param server_id: integer (str or int)
89
        :param profile: (str) ENABLED | DISABLED | PROTECTED
90
        :param port_id: (str) This port must connect to a public network
91
        :returns: (dict) response headers
92
        """
93
        req = {'firewallProfile': {'profile': profile, 'nic': port_id}}
94
        r = self.servers_action_post(server_id, json_data=req, success=202)
95
        return r.headers
96

    
97
    def start_server(self, server_id):
98
        """Submit a startup request
99

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

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

    
108
    def shutdown_server(self, server_id):
109
        """Submit a shutdown request
110

111
        :param server_id: integer (str or int)
112

113
        :returns: (dict) response headers
114
        """
115
        req = {'shutdown': {}}
116
        r = self.servers_action_post(server_id, json_data=req, success=202)
117
        return r.headers
118

    
119
    def get_server_console(self, server_id):
120
        """
121
        :param server_id: integer (str or int)
122

123
        :returns: (dict) info to set a VNC connection to virtual server
124
        """
125
        req = {'console': {'type': 'vnc'}}
126
        r = self.servers_action_post(server_id, json_data=req, success=200)
127
        return r.json['console']
128

    
129
    def reassign_server(self, server_id, project):
130
        req = {'reassign': {'project': project}}
131
        r = self.servers_action_post(server_id, json_data=req, success=200)
132
        return r.headers
133

    
134
    def get_server_stats(self, server_id):
135
        """
136
        :param server_id: integer (str or int)
137

138
        :returns: (dict) auto-generated graphs of statistics (urls)
139
        """
140
        r = self.servers_stats_get(server_id)
141
        return r.json['stats']
142

    
143
    def get_server_diagnostics(self, server_id):
144
        """
145
        :param server_id: integer (str or int)
146

147
        :returns: (list)
148
        """
149
        r = self.servers_diagnostics_get(server_id)
150
        return r.json
151

    
152
    def wait_server(
153
            self, server_id,
154
            current_status='BUILD',
155
            delay=1, max_wait=100, wait_cb=None):
156
        """Wait for server while its status is current_status
157

158
        :param server_id: integer (str or int)
159

160
        :param current_status: (str) BUILD|ACTIVE|STOPPED|DELETED|REBOOT
161

162
        :param delay: time interval between retries
163

164
        :max_wait: (int) timeout in secconds
165

166
        :param wait_cb: if set a progressbar is used to show progress
167

168
        :returns: (str) the new mode if succesfull, (bool) False if timed out
169
        """
170

    
171
        def get_status(self, server_id):
172
            r = self.get_server_details(server_id)
173
            return r['status'], (r.get('progress', None) if (
174
                            current_status in ('BUILD', )) else None)
175

    
176
        return self._wait(
177
            server_id, current_status, get_status, delay, max_wait, wait_cb)
178

    
179

    
180
class CycladesNetworkClient(NetworkClient):
181
    """Cyclades Network API extentions"""
182

    
183
    network_types = (
184
        'CUSTOM', 'MAC_FILTERED', 'IP_LESS_ROUTED', 'PHYSICAL_VLAN')
185

    
186
    def list_networks(self, detail=None):
187
        path = path4url('networks', 'detail' if detail else '')
188
        r = self.get(path, success=200)
189
        return r.json['networks']
190

    
191
    def create_network(self, type, name=None, shared=None, project=None):
192
        req = dict(network=dict(type=type, admin_state_up=True))
193
        if name:
194
            req['network']['name'] = name
195
        if shared not in (None, ):
196
            req['network']['shared'] = bool(shared)
197
        if project is not None:
198
            req['network']['project'] = project
199
        r = self.networks_post(json_data=req, success=201)
200
        return r.json['network']
201

    
202
    def networks_action_post(
203
            self, network_id='', json_data=None, success=202, **kwargs):
204
        """POST base_url/networks/<network_id>/action
205

206
        :returns: request response
207
        """
208
        if json_data:
209
            json_data = json.dumps(json_data)
210
            self.set_header('Content-Type', 'application/json')
211
            self.set_header('Content-Length', len(json_data))
212
        path = path4url('networks', network_id, 'action')
213
        return self.post(path, data=json_data, success=success, **kwargs)
214

    
215
    def reassign_network(self, network_id, project):
216
        req = {'reassign': {'project': project}}
217
        r = self.networks_action_post(network_id, json_data=req, success=200)
218
        return r.headers
219

    
220
    def list_ports(self, detail=None):
221
        path = path4url('ports', 'detail' if detail else '')
222
        r = self.get(path, success=200)
223
        return r.json['ports']
224

    
225
    def create_port(
226
            self, network_id,
227
            device_id=None, security_groups=None, name=None, fixed_ips=None):
228
        """
229
        :param fixed_ips: (list of dicts) [{"ip_address": IPv4}, ...]
230
        """
231
        port = dict(network_id=network_id)
232
        if device_id:
233
            port['device_id'] = device_id
234
        if security_groups:
235
            port['security_groups'] = security_groups
236
        if name:
237
            port['name'] = name
238
        if fixed_ips:
239
            for fixed_ip in fixed_ips or []:
240
                if not 'ip_address' in fixed_ip:
241
                    raise ValueError('Invalid fixed_ip [%s]' % fixed_ip)
242
            port['fixed_ips'] = fixed_ips
243
        r = self.ports_post(json_data=dict(port=port), success=201)
244
        return r.json['port']
245

    
246
    def create_floatingip(self, floating_network_id, floating_ip_address='',
247
                          project=None):
248
        args = {"project": project}
249
        return super(CycladesNetworkClient, self).create_floatingip(
250
            floating_network_id,
251
            floating_ip_address=floating_ip_address, args=args)
252

    
253
    def floating_ip_action_post(
254
            self, fip_id, json_data=None, success=202, **kwargs):
255
        """POST base_url/floatingips/<fip_id>/action
256

257
        :returns: request response
258
        """
259
        if json_data:
260
            json_data = json.dumps(json_data)
261
            self.set_header('Content-Type', 'application/json')
262
            self.set_header('Content-Length', len(json_data))
263
        path = path4url('floatingips', fip_id, 'action')
264
        return self.post(path, data=json_data, success=success, **kwargs)
265

    
266
    def reassign_floating_ip(self, floating_network_id, project):
267
        req = {'reassign': {'project': project}}
268
        r = self.floating_ip_action_post(floating_network_id, json_data=req)