Statistics
| Branch: | Tag: | Revision:

root / kamaki / clients / cyclades / __init__.py @ 4e25b350

History | View | Annotate | Download (7.5 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
            [
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 start_server(self, server_id):
84
        """Submit a startup request
85

86
        :param server_id: integer (str or int)
87

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

    
94
    def shutdown_server(self, server_id):
95
        """Submit a shutdown request
96

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

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

    
105
    def get_server_console(self, server_id):
106
        """
107
        :param server_id: integer (str or int)
108

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

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

119
        :returns: (dict) auto-generated graphs of statistics (urls)
120
        """
121
        r = self.servers_stats_get(server_id)
122
        return r.json['stats']
123

    
124
    def wait_server(
125
            self, server_id,
126
            current_status='BUILD',
127
            delay=1, max_wait=100, wait_cb=None):
128
        """Wait for server while its status is current_status
129

130
        :param server_id: integer (str or int)
131

132
        :param current_status: (str) BUILD|ACTIVE|STOPPED|DELETED|REBOOT
133

134
        :param delay: time interval between retries
135

136
        :max_wait: (int) timeout in secconds
137

138
        :param wait_cb: if set a progressbar is used to show progress
139

140
        :returns: (str) the new mode if succesfull, (bool) False if timed out
141
        """
142

    
143
        def get_status(self, server_id):
144
            r = self.get_server_details(server_id)
145
            return r['status'], (r.get('progress', None) if (
146
                            current_status in ('BUILD', )) else None)
147

    
148
        return self._wait(
149
            server_id, current_status, get_status, delay, max_wait, wait_cb)
150

    
151

    
152
class CycladesNetworkClient(NetworkClient):
153
    """Cyclades Network API extentions"""
154

    
155
    network_types = (
156
        'CUSTOM', 'MAC_FILTERED', 'IP_LESS_ROUTED', 'PHYSICAL_VLAN')
157

    
158
    def list_networks(self, detail=None):
159
        path = path4url('networks', 'detail' if detail else '')
160
        r = self.get(path, success=200)
161
        return r.json['networks']
162

    
163
    def create_network(self, type, name=None, shared=None):
164
        req = dict(network=dict(type=type, admin_state_up=True))
165
        if name:
166
            req['network']['name'] = name
167
        if shared not in (None, ):
168
            req['network']['shared'] = bool(shared)
169
        r = self.networks_post(json_data=req, success=201)
170
        return r.json['network']
171

    
172
    def list_ports(self, detail=None):
173
        path = path4url('ports', 'detail' if detail else '')
174
        r = self.get(path, success=200)
175
        return r.json['ports']
176

    
177
    def create_port(
178
            self, network_id,
179
            device_id=None, security_groups=None, name=None, fixed_ips=None):
180
        """
181
        :param fixed_ips: (list of dicts) [{"ip_address": IPv4}, ...]
182
        """
183
        port = dict(network_id=network_id)
184
        if device_id:
185
            port['device_id'] = device_id
186
        if security_groups:
187
            port['security_groups'] = security_groups
188
        if name:
189
            port['name'] = name
190
        if fixed_ips:
191
            for fixed_ip in fixed_ips or []:
192
                if not 'ip_address' in fixed_ip:
193
                    raise ValueError('Invalid fixed_ip [%s]' % fixed_ip)
194
            port['fixed_ips'] = fixed_ips
195
        r = self.ports_post(json_data=dict(port=port), success=201)
196
        return r.json['port']
197

    
198
    def create_floatingip(self, floating_network_id, floating_ip_address=''):
199
        return super(CycladesNetworkClient, self).create_floatingip(
200
            floating_network_id, floating_ip_address=floating_ip_address)
201

    
202
    def update_floatingip(self, floating_network_id, floating_ip_address=''):
203
        """To nullify something optional, use None"""
204
        return super(CycladesNetworkClient, self).update_floatingip(
205
            floating_network_id, floating_ip_address=floating_ip_address)