Statistics
| Branch: | Tag: | Revision:

root / kamaki / clients / cyclades / __init__.py @ 03033b54

History | View | Annotate | Download (13.3 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 sys import stdout
35
from time import sleep
36

    
37
from kamaki.clients.cyclades.rest_api import CycladesRestClient
38
from kamaki.clients import ClientError
39

    
40

    
41
class CycladesClient(CycladesRestClient):
42
    """Synnefo Cyclades Compute 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
        :returns: (dict) response headers
50
        """
51
        req = {'start': {}}
52
        r = self.servers_post(server_id, 'action', json_data=req, success=202)
53
        return r.headers
54

    
55
    def shutdown_server(self, server_id):
56
        """Submit a shutdown request
57

58
        :param server_id: integer (str or int)
59

60
        :returns: (dict) response headers
61
        """
62
        req = {'shutdown': {}}
63
        r = self.servers_post(server_id, 'action', json_data=req, success=202)
64
        return r.headers
65

    
66
    def get_server_console(self, server_id):
67
        """
68
        :param server_id: integer (str or int)
69

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

    
76
    def get_firewall_profile(self, server_id):
77
        """
78
        :param server_id: integer (str or int)
79

80
        :returns: (str) ENABLED | DISABLED | PROTECTED
81

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

    
92
    def set_firewall_profile(self, server_id, profile):
93
        """Set the firewall profile for the public interface of a server
94

95
        :param server_id: integer (str or int)
96

97
        :param profile: (str) ENABLED | DISABLED | PROTECTED
98

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

    
105
    def list_servers(self, detail=False, changes_since=None):
106
        """
107
        :param detail: (bool) append full server details to each item if true
108

109
        :param changes_since: (date)
110

111
        :returns: list of server ids and names
112
        """
113
        detail = 'detail' if detail else ''
114
        r = self.servers_get(command=detail, changes_since=changes_since)
115
        return r.json['servers']
116

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

121
        :returns: (dict) network interface connections
122
        """
123
        r = self.servers_get(server_id, 'ips')
124
        return r.json['addresses']
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_get(server_id, 'stats')
133
        return r.json['stats']
134

    
135
    def list_networks(self, detail=False):
136
        """
137
        :param detail: (bool)
138

139
        :returns: (list) id,name if not detail else full info per network
140
        """
141
        detail = 'detail' if detail else ''
142
        r = self.networks_get(command=detail)
143
        return r.json['networks']
144

    
145
    def list_network_nics(self, network_id):
146
        """
147
        :param network_id: integer (str or int)
148

149
        :returns: (list)
150
        """
151
        r = self.networks_get(network_id=network_id)
152
        return r.json['network']['attachments']
153

    
154
    def create_network(
155
            self, name,
156
            cidr=None, gateway=None, type=None, dhcp=False):
157
        """
158
        :param name: (str)
159

160
        :param cidr: (str)
161

162
        :param geteway: (str)
163

164
        :param type: (str) if None, will use MAC_FILTERED as default
165
            Valid values: CUSTOM, IP_LESS_ROUTED, MAC_FILTERED, PHYSICAL_VLAN
166

167
        :param dhcp: (bool)
168

169
        :returns: (dict) network detailed info
170
        """
171
        net = dict(name=name)
172
        if cidr:
173
            net['cidr'] = cidr
174
        if gateway:
175
            net['gateway'] = gateway
176
        net['type'] = type or 'MAC_FILTERED'
177
        net['dhcp'] = True if dhcp else False
178
        req = dict(network=net)
179
        r = self.networks_post(json_data=req, success=202)
180
        return r.json['network']
181

    
182
    def get_network_details(self, network_id):
183
        """
184
        :param network_id: integer (str or int)
185

186
        :returns: (dict)
187
        """
188
        r = self.networks_get(network_id=network_id)
189
        return r.json['network']
190

    
191
    def update_network_name(self, network_id, new_name):
192
        """
193
        :param network_id: integer (str or int)
194

195
        :param new_name: (str)
196

197
        :returns: (dict) response headers
198
        """
199
        req = {'network': {'name': new_name}}
200
        r = self.networks_put(network_id=network_id, json_data=req)
201
        return r.headers
202

    
203
    def delete_network(self, network_id):
204
        """
205
        :param network_id: integer (str or int)
206

207
        :returns: (dict) response headers
208

209
        :raises ClientError: 421 Network in use
210
        """
211
        try:
212
            r = self.networks_delete(network_id)
213
            return r.headers
214
        except ClientError as err:
215
            if err.status == 421:
216
                err.details = [
217
                    'Network may be still connected to at least one server']
218
            raise
219

    
220
    def connect_server(self, server_id, network_id):
221
        """ Connect a server to a network
222

223
        :param server_id: integer (str or int)
224

225
        :param network_id: integer (str or int)
226

227
        :returns: (dict) response headers
228
        """
229
        req = {'add': {'serverRef': server_id}}
230
        r = self.networks_post(network_id, 'action', json_data=req)
231
        return r.headers
232

    
233
    def disconnect_server(self, server_id, nic_id):
234
        """
235
        :param server_id: integer (str or int)
236

237
        :param nic_id: (str)
238

239
        :returns: (int) the number of nics disconnected
240
        """
241
        vm_nets = self.list_server_nics(server_id)
242
        num_of_disconnections = 0
243
        for (nic_id, network_id) in [(
244
                net['id'],
245
                net['network_id']) for net in vm_nets if nic_id == net['id']]:
246
            req = {'remove': {'attachment': '%s' % nic_id}}
247
            self.networks_post(network_id, 'action', json_data=req)
248
            num_of_disconnections += 1
249
        return num_of_disconnections
250

    
251
    def disconnect_network_nics(self, netid):
252
        """
253
        :param netid: integer (str or int)
254
        """
255
        for nic in self.list_network_nics(netid):
256
            req = dict(remove=dict(attachment=nic))
257
            self.networks_post(netid, 'action', json_data=req)
258

    
259
    def wait_server(
260
            self,
261
            server_id,
262
            current_status='BUILD',
263
            delay=0.5,
264
            max_wait=128,
265
            wait_cb=None):
266
        """Wait for server while its status is current_status
267

268
        :param server_id: integer (str or int)
269

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

272
        :param delay: time interval between retries
273

274
        :param wait_cb: if set a progressbar is used to show progress
275

276
        :returns: (str) the new mode if succesfull, (bool) False if timed out
277
        """
278
        r = self.get_server_details(server_id)
279
        if r['status'] != current_status:
280
            return r['status']
281
        old_wait = total_wait = 0
282

    
283
        if current_status == 'BUILD':
284
            max_wait = 100
285
            wait_gen = wait_cb(max_wait) if wait_cb else None
286
        elif wait_cb:
287
            wait_gen = wait_cb(1 + max_wait // delay)
288
            wait_gen.next()
289

    
290
        while r['status'] == current_status and total_wait <= max_wait:
291
            if current_status == 'BUILD':
292
                total_wait = int(r['progress'])
293
                if wait_cb:
294
                    for i in range(int(old_wait), int(total_wait)):
295
                        wait_gen.next()
296
                    old_wait = total_wait
297
                else:
298
                    stdout.write('.')
299
                    stdout.flush()
300
            else:
301
                if wait_cb:
302
                    wait_gen.next()
303
                else:
304
                    stdout.write('.')
305
                    stdout.flush()
306
                total_wait += delay
307
            sleep(delay)
308
            r = self.get_server_details(server_id)
309

    
310
        if r['status'] != current_status:
311
            if wait_cb:
312
                try:
313
                    while True:
314
                        wait_gen.next()
315
                except:
316
                    pass
317
            return r['status']
318
        return False
319

    
320
    def get_floating_ip_pools(self):
321
        """
322
        :returns: (dict) {floating_ip_pools:[{name: ...}, ...]}
323
        """
324
        r = self.floating_ip_pools_get()
325
        return r.json
326

    
327
    def get_floating_ips(self):
328
        """
329
        :returns: (dict) {floating_ips:[
330
            {fixed_ip: ..., id: ..., instance_id: ..., ip: ..., pool: ...},
331
            ... ]}
332
        """
333
        r = self.floating_ips_get()
334
        return r.json
335

    
336
    def alloc_floating_ip(self, pool=None, address=None):
337
        """
338
        :param pool: (str) pool of ips to allocate from
339

340
        :param address: (str) ip address to request
341

342
        :returns: (dict) {
343
                fixed_ip: ..., id: ..., instance_id: ..., ip: ..., pool: ...
344
            }
345
        """
346
        json_data = dict()
347
        if pool:
348
            json_data['pool'] = pool
349
            if address:
350
                json_data['address'] = address
351
        r = self.floating_ips_post(json_data)
352
        return r.json['floating_ip']
353

    
354
    def get_floating_ip(self, fip_id):
355
        """
356
        :param fip_id: (str) floating ip id
357

358
        :returns: (dict)
359
            {fixed_ip: ..., id: ..., instance_id: ..., ip: ..., pool: ...},
360

361
        :raises AssertionError: if fip_id is emtpy
362
        """
363
        assert fip_id, 'floating ip id is needed for get_floating_ip'
364
        r = self.floating_ips_get(fip_id)
365
        return r.json['floating_ip']
366

    
367
    def delete_floating_ip(self, fip_id=None):
368
        """
369
        :param fip_id: (str) floating ip id (if None, all ips are deleted)
370

371
        :returns: (dict) request headers
372

373
        :raises AssertionError: if fip_id is emtpy
374
        """
375
        assert fip_id, 'floating ip id is needed for delete_floating_ip'
376
        r = self.floating_ips_delete(fip_id)
377
        return r.headers
378

    
379
    def assoc_floating_ip_to_server(self, server_id, address):
380
        """Associate the address ip to server with server_id
381

382
        :param server_id: (int)
383

384
        :param address: (str) the ip address to assign to server (vm)
385

386
        :returns: (dict) request headers
387

388
        :raises ValueError: if server_id cannot be converted to int
389

390
        :raises ValueError: if server_id is not of a int-convertable type
391

392
        :raises AssertionError: if address is emtpy
393
        """
394
        server_id = int(server_id)
395
        assert address, 'address is needed for assoc_floating_ip_to_server'
396
        r = self.servers_post(
397
            server_id, 'action',
398
            json_data=dict(addFloatingIp=dict(address=address)))
399
        return r.headers
400

    
401
    def disassoc_floating_ip_to_server(self, server_id, address):
402
        """Disassociate an address ip from the server with server_id
403

404
        :param server_id: (int)
405

406
        :param address: (str) the ip address to assign to server (vm)
407

408
        :returns: (dict) request headers
409

410
        :raises ValueError: if server_id cannot be converted to int
411

412
        :raises ValueError: if server_id is not of a int-convertable type
413

414
        :raises AssertionError: if address is emtpy
415
        """
416
        server_id = int(server_id)
417
        assert address, 'address is needed for disassoc_floating_ip_to_server'
418
        r = self.servers_post(
419
            server_id, 'action',
420
            json_data=dict(removeFloatingIp=dict(address=address)))
421
        return r.headers