Statistics
| Branch: | Tag: | Revision:

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

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

    
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):
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
        :returns: a dict with the new virtual server details
68

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

    
79
        return super(CycladesClient, self).create_server(
80
            name, flavor_id, image_id,
81
            metadata=metadata, personality=personality, networks=networks)
82

    
83
    def set_firewall_profile(self, server_id, profile, port_id):
84
        """Set the firewall profile for the public interface of a server
85
        :param server_id: integer (str or int)
86
        :param profile: (str) ENABLED | DISABLED | PROTECTED
87
        :param port_id: (str) This port must connect to a public network
88
        :returns: (dict) response headers
89
        """
90
        req = {'firewallProfile': {'profile': profile, 'nic': port_id}}
91
        r = self.servers_action_post(server_id, json_data=req, success=202)
92
        return r.headers
93

    
94
    def start_server(self, server_id):
95
        """Submit a startup request
96

97
        :param server_id: integer (str or int)
98

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

    
105
    def shutdown_server(self, server_id):
106
        """Submit a shutdown request
107

108
        :param server_id: integer (str or int)
109

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

    
116
    def get_server_console(self, server_id):
117
        """
118
        :param server_id: integer (str or int)
119

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

    
126
    def get_server_stats(self, server_id):
127
        """
128
        :param server_id: integer (str or int)
129

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

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

139
        :returns: (list)
140
        """
141
        r = self.servers_diagnostics_get(server_id)
142
        return r.json
143

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

150
        :param server_id: integer (str or int)
151

152
        :param current_status: (str) BUILD|ACTIVE|STOPPED|DELETED|REBOOT
153

154
        :param delay: time interval between retries
155

156
        :max_wait: (int) timeout in secconds
157

158
        :param wait_cb: if set a progressbar is used to show progress
159

160
        :returns: (str) the new mode if succesfull, (bool) False if timed out
161
        """
162

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

    
168
        return self._wait(
169
            server_id, current_status, get_status, delay, max_wait, wait_cb)
170

    
171

    
172
class CycladesNetworkClient(NetworkClient):
173
    """Cyclades Network API extentions"""
174

    
175
    network_types = (
176
        'CUSTOM', 'MAC_FILTERED', 'IP_LESS_ROUTED', 'PHYSICAL_VLAN')
177

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

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

    
192
    def list_ports(self, detail=None):
193
        path = path4url('ports', 'detail' if detail else '')
194
        r = self.get(path, success=200)
195
        return r.json['ports']
196

    
197
    def create_port(
198
            self, network_id,
199
            device_id=None, security_groups=None, name=None, fixed_ips=None):
200
        """
201
        :param fixed_ips: (list of dicts) [{"ip_address": IPv4}, ...]
202
        """
203
        port = dict(network_id=network_id)
204
        if device_id:
205
            port['device_id'] = device_id
206
        if security_groups:
207
            port['security_groups'] = security_groups
208
        if name:
209
            port['name'] = name
210
        if fixed_ips:
211
            for fixed_ip in fixed_ips or []:
212
                if not 'ip_address' in fixed_ip:
213
                    raise ValueError('Invalid fixed_ip [%s]' % fixed_ip)
214
            port['fixed_ips'] = fixed_ips
215
        r = self.ports_post(json_data=dict(port=port), success=201)
216
        return r.json['port']
217

    
218
    def create_floatingip(self, floating_network_id, floating_ip_address=''):
219
        return super(CycladesNetworkClient, self).create_floatingip(
220
            floating_network_id, floating_ip_address=floating_ip_address)