__init__.py 7.51 KB
Newer Older
1
# Copyright 2011-2013 GRNET S.A. All rights reserved.
Giorgos Verigakis's avatar
Giorgos Verigakis committed
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#
# Redistribution and use in source and binary forms, with or
# without modification, are permitted provided that the following
# conditions are met:
#
#   1. Redistributions of source code must retain the above
#      copyright notice, this list of conditions and the following
#      disclaimer.
#
#   2. Redistributions in binary form must reproduce the above
#      copyright notice, this list of conditions and the following
#      disclaimer in the documentation and/or other materials
#      provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# The views and conclusions contained in the software and
# documentation are those of the authors and should not be
# interpreted as representing official policies, either expressed
# or implied, of GRNET S.A.

34
from kamaki.clients.cyclades.rest_api import CycladesRestClient
35
from kamaki.clients.network import NetworkClient
36
from kamaki.clients.utils import path4url
Stavros Sachtouris's avatar
Stavros Sachtouris committed
37
from kamaki.clients import ClientError, Waiter
Giorgos Verigakis's avatar
Giorgos Verigakis committed
38

39

Stavros Sachtouris's avatar
Stavros Sachtouris committed
40
class CycladesClient(CycladesRestClient, Waiter):
41
    """Synnefo Cyclades Compute API client"""
42

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

        :param name: (str)

        :param flavor_id: integer id denoting a preset hardware configuration

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

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

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

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

67
        :returns: a dict with the new virtual server details
68
69
70
71
72
73
74
75
76
77
78

        :raises ClientError: wraps request errors
        """
        image = self.get_image_details(image_id)
        metadata = metadata or dict()
        for key in ('os', 'users'):
            try:
                metadata[key] = image['metadata'][key]
            except KeyError:
                pass

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

Giorgos Verigakis's avatar
Giorgos Verigakis committed
83
    def start_server(self, server_id):
84
85
86
        """Submit a startup request

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

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

Giorgos Verigakis's avatar
Giorgos Verigakis committed
94
    def shutdown_server(self, server_id):
95
96
97
        """Submit a shutdown request

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

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

Giorgos Verigakis's avatar
Giorgos Verigakis committed
105
    def get_server_console(self, server_id):
106
107
108
        """
        :param server_id: integer (str or int)

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

Giorgos Verigakis's avatar
Giorgos Verigakis committed
115
    def get_server_stats(self, server_id):
116
117
118
119
120
        """
        :param server_id: integer (str or int)

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

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

        :param server_id: integer (str or int)

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

        :param delay: time interval between retries

136
137
        :max_wait: (int) timeout in secconds

138
139
140
141
142
143
144
145
146
147
148
149
150
        :param wait_cb: if set a progressbar is used to show progress

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

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

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

151

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

    network_types = (
        'CUSTOM', 'MAC_FILTERED', 'IP_LESS_ROUTED', 'PHYSICAL_VLAN')

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

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

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

Stavros Sachtouris's avatar
Stavros Sachtouris committed
177
    def create_port(
178
179
            self, network_id,
            device_id=None, security_groups=None, name=None, fixed_ips=None):
180
181
182
        """
        :param fixed_ips: (list of dicts) [{"ip_address": IPv4}, ...]
        """
183
184
185
        port = dict(network_id=network_id)
        if device_id:
            port['device_id'] = device_id
186
187
        if security_groups:
            port['security_groups'] = security_groups
Stavros Sachtouris's avatar
Stavros Sachtouris committed
188
189
        if name:
            port['name'] = name
190
        if fixed_ips:
191
192
            for fixed_ip in fixed_ips or []:
                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']
Stavros Sachtouris's avatar
Stavros Sachtouris committed
197

198
199
200
    def create_floatingip(self, floating_network_id, floating_ip_address=''):
        return super(CycladesNetworkClient, self).create_floatingip(
            floating_network_id, floating_ip_address=floating_ip_address)
Stavros Sachtouris's avatar
Stavros Sachtouris committed
201

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