Statistics
| Branch: | Tag: | Revision:

root / kamaki / clients / cyclades.py @ 02846a75

History | View | Annotate | Download (9.6 kB)

1
# Copyright 2011 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 time import sleep
35

    
36
from kamaki.clients.cyclades_rest_api import CycladesClientApi
37
from kamaki.clients import ClientError
38
from sys import stdout
39

    
40

    
41
class CycladesClient(CycladesClientApi):
42
    """GRNet Cyclades API client"""
43

    
44
    def start_server(self, server_id):
45
        """Submit a startup request
46

47
        :param server_id: integer (str or int)
48
        """
49
        req = {'start': {}}
50
        r = self.servers_post(server_id, 'action', json_data=req, success=202)
51
        r.release()
52

    
53
    def shutdown_server(self, server_id):
54
        """Submit a shutdown request
55

56
        :param server_id: integer (str or int)
57
        """
58
        req = {'shutdown': {}}
59
        r = self.servers_post(server_id, 'action', json_data=req, success=202)
60
        r.release()
61

    
62
    def get_server_console(self, server_id):
63
        """
64
        :param server_id: integer (str or int)
65

66
        :returns: (dict) info to set a VNC connection to VM
67
        """
68
        req = {'console': {'type': 'vnc'}}
69
        r = self.servers_post(server_id, 'action', json_data=req, success=200)
70
        return r.json['console']
71

    
72
    def get_firewall_profile(self, server_id):
73
        """
74
        :param server_id: integer (str or int)
75

76
        :returns: (str) ENABLED | DISABLED | PROTECTED
77

78
        :raises ClientError: 520 No Firewall Profile
79
        """
80
        r = self.get_server_details(server_id)
81
        try:
82
            return r['attachments']['values'][0]['firewallProfile']
83
        except KeyError:
84
            raise ClientError('No Firewall Profile', 520,
85
                details='Server %s is missing a firewall profile' % server_id)
86

    
87
    def set_firewall_profile(self, server_id, profile):
88
        """Set the firewall profile for the public interface of a server
89

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

92
        :param profile: (str) ENABLED | DISABLED | PROTECTED
93
        """
94
        req = {'firewallProfile': {'profile': profile}}
95
        r = self.servers_post(server_id, 'action', json_data=req, success=202)
96
        r.release()
97

    
98
    def list_servers(self, detail=False, changes_since=None):
99
        """
100
        :param detail: (bool) append full server details to each item if true
101

102
        :param changes_since: (date)
103

104
        :returns: list of server ids and names
105
        """
106
        detail = 'detail' if detail else ''
107
        r = self.servers_get(command=detail, changes_since=changes_since)
108
        return r.json['servers']['values']
109

    
110
    def list_server_nics(self, server_id):
111
        """
112
        :param server_id: integer (str or int)
113

114
        :returns: (dict) network interface connections
115
        """
116
        r = self.servers_get(server_id, 'ips')
117
        return r.json['addresses']['values']
118

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

123
        :returns: (dict) auto-generated graphs of statistics (urls)
124
        """
125
        r = self.servers_get(server_id, 'stats')
126
        return r.json['stats']
127

    
128
    def list_networks(self, detail=False):
129
        """
130
        :param detail: (bool)
131

132
        :returns: (list) id,name if not detail else full info per network
133
        """
134
        detail = 'detail' if detail else ''
135
        r = self.networks_get(command=detail)
136
        return r.json['networks']['values']
137

    
138
    def list_network_nics(self, network_id):
139
        """
140
        :param network_id: integer (str or int)
141

142
        :returns: (list)
143
        """
144
        r = self.networks_get(network_id=network_id)
145
        return r.json['network']['attachments']['values']
146

    
147
    def create_network(self,
148
        name, cidr=None, gateway=None, type=None, dhcp=None):
149
        """
150
        :param name: (str)
151

152
        :param cidr: (str)
153

154
        :param geteway: (str)
155

156
        :param type: (str)
157

158
        :param dhcp: (str)
159

160
        :returns: (dict) network detailed info
161
        """
162
        net = dict(name=name)
163
        if cidr:
164
            net['cidr'] = cidr
165
        if gateway:
166
            net['gateway'] = gateway
167
        if type:
168
            net['type'] = type
169
        if dhcp:
170
            net['dhcp'] = dhcp
171
        req = dict(network=net)
172
        r = self.networks_post(json_data=req, success=202)
173
        return r.json['network']
174

    
175
    def get_network_details(self, network_id):
176
        """
177
        :param network_id: integer (str or int)
178

179
        :returns: (dict)
180
        """
181
        r = self.networks_get(network_id=network_id)
182
        return r.json['network']
183

    
184
    def update_network_name(self, network_id, new_name):
185
        """
186
        :param network_id: integer (str or int)
187

188
        :param new_name: (str)
189
        """
190
        req = {'network': {'name': new_name}}
191
        r = self.networks_put(network_id=network_id, json_data=req)
192
        r.release()
193

    
194
    def delete_network(self, network_id):
195
        """
196
        :param network_id: integer (str or int)
197

198
        :raises ClientError: 421 Network in use
199
        """
200
        try:
201
            r = self.networks_delete(network_id)
202
        except ClientError as err:
203
            if err.status == 421:
204
                err.details = [
205
                'Network may be still connected to at least one server']
206
            raise err
207
        r.release()
208

    
209
    def connect_server(self, server_id, network_id):
210
        """ Connect a server to a network
211

212
        :param server_id: integer (str or int)
213

214
        :param network_id: integer (str or int)
215
        """
216
        req = {'add': {'serverRef': server_id}}
217
        r = self.networks_post(network_id, 'action', json_data=req)
218
        r.release()
219

    
220
    def disconnect_server(self, server_id, nic_id):
221
        """
222
        :param server_id: integer (str or int)
223

224
        :param nic_id: (str)
225
        """
226
        server_nets = self.list_server_nics(server_id)
227
        nets = [(net['id'], net['network_id']) for net in server_nets\
228
            if nic_id == net['id']]
229
        num_of_disconnections = 0
230
        for (nic_id, network_id) in nets:
231
            req = {'remove': {'attachment': unicode(nic_id)}}
232
            r = self.networks_post(network_id, 'action', json_data=req)
233
            r.release()
234
            num_of_disconnections += 1
235
        return num_of_disconnections
236

    
237
    def disconnect_network_nics(self, netid):
238
        """
239
        :param netid: integer (str or int)
240
        """
241
        for nic in self.list_network_nics(netid):
242
            req = dict(remove=dict(attachment=nic))
243
            r = self.networks_post(netid, 'action', json_data=req)
244
            r.release()
245

    
246
    def wait_server(self, server_id,
247
        current_status='BUILD',
248
        delay=0.5,
249
        max_wait=128,
250
        wait_cb=None):
251
        """Wait for server while its status is current_status
252

253
        :param server_id: integer (str or int)
254

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

257
        :param delay: time interval between retries
258

259
        :param wait_cb: if set a progressbar is used to show progress
260

261
        :returns: (str) the new mode if succesfull, (bool) False if timed out
262
        """
263
        r = self.get_server_details(server_id)
264
        if r['status'] != current_status:
265
            return r['status']
266
        old_wait = total_wait = 0
267

    
268
        if current_status == 'BUILD':
269
            max_wait = 100
270
            wait_gen = wait_cb(max_wait) if wait_cb else None
271
        elif wait_cb:
272
            wait_gen = wait_cb(1 + max_wait // delay)
273
            wait_gen.next()
274

    
275
        while r['status'] == current_status and total_wait <= max_wait:
276
            if current_status == 'BUILD':
277
                total_wait = int(r['progress'])
278
                if wait_cb:
279
                    for i in range(int(old_wait), int(total_wait)):
280
                        wait_gen.next()
281
                    old_wait = total_wait
282
                else:
283
                    stdout.write('.')
284
                    stdout.flush()
285
            else:
286
                if wait_cb:
287
                    wait_gen.next()
288
                else:
289
                    stdout.write('.')
290
                    stdout.flush()
291
                total_wait += delay
292
            sleep(delay)
293
            r = self.get_server_details(server_id)
294

    
295
        if r['status'] != current_status:
296
            if wait_cb:
297
                try:
298
                    while True:
299
                        wait_gen.next()
300
                except:
301
                    pass
302
            return r['status']
303
        return False