Statistics
| Branch: | Tag: | Revision:

root / kamaki / cli / commands / network.py @ fd981f77

History | View | Annotate | Download (20.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 io import StringIO
35
from pydoc import pager
36

    
37
from kamaki.cli import command
38
from kamaki.cli.command_tree import CommandTree
39
from kamaki.cli.errors import (
40
    CLIBaseUrlError, CLIInvalidArgument, raiseCLIError)
41
from kamaki.clients.cyclades import CycladesNetworkClient
42
from kamaki.cli.argument import (
43
    FlagArgument, ValueArgument, RepeatableArgument, IntArgument)
44
from kamaki.cli.commands import _command_init, errors, addLogSettings
45
from kamaki.cli.commands import (
46
    _optional_output_cmd, _optional_json, _name_filter, _id_filter)
47
from kamaki.cli.utils import filter_dicts_by_dict
48
from kamaki.cli.commands.cyclades import _service_wait
49

    
50

    
51
network_cmds = CommandTree('network', 'Networking API network commands')
52
port_cmds = CommandTree('port', 'Networking API network commands')
53
subnet_cmds = CommandTree('subnet', 'Networking API network commands')
54
ip_cmds = CommandTree('ip', 'Networking API floatingip commands')
55
_commands = [network_cmds, port_cmds, subnet_cmds, ip_cmds]
56

    
57

    
58
about_authentication = '\nUser Authentication:\
59
    \n* to check authentication: /user authenticate\
60
    \n* to set authentication token: /config set cloud.<cloud>.token <token>'
61

    
62

    
63
class _port_wait(_service_wait):
64

    
65
    def _wait(self, port_id, current_status, timeout=60):
66
        super(_port_wait, self)._wait(
67
            'Port', port_id, self.client.wait_port, current_status,
68
            timeout=timeout)
69

    
70

    
71
class _init_network(_command_init):
72
    @errors.generic.all
73
    @addLogSettings
74
    def _run(self, service='network'):
75
        if getattr(self, 'cloud', None):
76
            base_url = self._custom_url(service) or self._custom_url(
77
                'network')
78
            if base_url:
79
                token = self._custom_token(service) or self._custom_token(
80
                    'network') or self.config.get_cloud('token')
81
                self.client = CycladesNetworkClient(
82
                  base_url=base_url, token=token)
83
                return
84
        else:
85
            self.cloud = 'default'
86
        if getattr(self, 'auth_base', False):
87
            network_endpoints = self.auth_base.get_service_endpoints(
88
                self._custom_type('network') or 'network',
89
                self._custom_version('network') or '')
90
            base_url = network_endpoints['publicURL']
91
            token = self.auth_base.token
92
            self.client = CycladesNetworkClient(base_url=base_url, token=token)
93
        else:
94
            raise CLIBaseUrlError(service='network')
95

    
96
    def main(self):
97
        self._run()
98

    
99

    
100
@command(network_cmds)
101
class network_list(_init_network, _optional_json, _name_filter, _id_filter):
102
    """List networks
103
    Use filtering arguments (e.g., --name-like) to manage long server lists
104
    """
105

    
106
    arguments = dict(
107
        detail=FlagArgument('show detailed output', ('-l', '--details')),
108
        more=FlagArgument(
109
            'output results in pages (-n to set items per page, default 10)',
110
            '--more'),
111
        user_id=ValueArgument(
112
            'show only networks belonging to user with this id', '--user-id')
113
    )
114

    
115
    def _filter_by_user_id(self, nets):
116
        return filter_dicts_by_dict(nets, dict(user_id=self['user_id'])) if (
117
            self['user_id']) else nets
118

    
119
    @errors.generic.all
120
    @errors.cyclades.connection
121
    def _run(self):
122
        nets = self.client.list_networks()
123
        nets = self._filter_by_user_id(nets)
124
        nets = self._filter_by_name(nets)
125
        nets = self._filter_by_id(nets)
126
        if not self['detail']:
127
            nets = [dict(
128
                id=n['id'], name=n['name'], links=n['links']) for n in nets]
129
        kwargs = dict()
130
        if self['more']:
131
            kwargs['out'] = StringIO()
132
            kwargs['title'] = ()
133
        self._print(nets, **kwargs)
134
        if self['more']:
135
            pager(kwargs['out'].getvalue())
136

    
137
    def main(self):
138
        super(self.__class__, self)._run()
139
        self._run()
140

    
141

    
142
@command(network_cmds)
143
class network_info(_init_network, _optional_json):
144
    """Get details about a network"""
145

    
146
    @errors.generic.all
147
    @errors.cyclades.connection
148
    @errors.cyclades.network_id
149
    def _run(self, network_id):
150
        net = self.client.get_network_details(network_id)
151
        self._print(net, self.print_dict)
152

    
153
    def main(self, network_id):
154
        super(self.__class__, self)._run()
155
        self._run(network_id=network_id)
156

    
157

    
158
class NetworkTypeArgument(ValueArgument):
159

    
160
    types = ('CUSTOM', 'MAC_FILTERED', 'IP_LESS_ROUTED', 'PHYSICAL_VLAN')
161

    
162
    @property
163
    def value(self):
164
        return getattr(self, '_value', None)
165

    
166
    @value.setter
167
    def value(self, new_value):
168
        if new_value and new_value.upper() in self.types:
169
            self._value = new_value.upper()
170
        elif new_value:
171
            raise CLIInvalidArgument(
172
                'Invalid network type %s' % new_value, details=[
173
                    'Valid types: %s' % ', '.join(self.types), ])
174

    
175

    
176
@command(network_cmds)
177
class network_create(_init_network, _optional_json):
178
    """Create a new network"""
179

    
180
    arguments = dict(
181
        name=ValueArgument('Network name', '--name'),
182
        shared=FlagArgument(
183
            'Make network shared (special privileges required)', '--shared'),
184
        network_type=NetworkTypeArgument(
185
            'Valid network types: %s' % (', '.join(NetworkTypeArgument.types)),
186
            '--type')
187
    )
188
    required = ('network_type', )
189

    
190
    @errors.generic.all
191
    @errors.cyclades.connection
192
    @errors.cyclades.network_type
193
    def _run(self, network_type):
194
        net = self.client.create_network(
195
            network_type, name=self['name'], shared=self['shared'])
196
        self._print(net, self.print_dict)
197

    
198
    def main(self):
199
        super(self.__class__, self)._run()
200
        self._run(network_type=self['network_type'])
201

    
202

    
203
@command(network_cmds)
204
class network_delete(_init_network, _optional_output_cmd):
205
    """Delete a network"""
206

    
207
    @errors.generic.all
208
    @errors.cyclades.connection
209
    @errors.cyclades.network_id
210
    def _run(self, network_id):
211
        r = self.client.delete_network(network_id)
212
        self._optional_output(r)
213

    
214
    def main(self, network_id):
215
        super(self.__class__, self)._run()
216
        self._run(network_id=network_id)
217

    
218

    
219
@command(network_cmds)
220
class network_modify(_init_network, _optional_json):
221
    """Modify network attributes"""
222

    
223
    arguments = dict(new_name=ValueArgument('Rename the network', '--name'))
224
    required = ['new_name', ]
225

    
226
    @errors.generic.all
227
    @errors.cyclades.connection
228
    @errors.cyclades.network_id
229
    def _run(self, network_id):
230
        r = self.client.update_network(network_id, name=self['new_name'])
231
        self._print(r, self.print_dict)
232

    
233
    def main(self, network_id):
234
        super(self.__class__, self)._run()
235
        self._run(network_id=network_id)
236

    
237

    
238
@command(subnet_cmds)
239
class subnet_list(_init_network, _optional_json, _name_filter, _id_filter):
240
    """List subnets
241
    Use filtering arguments (e.g., --name-like) to manage long server lists
242
    """
243

    
244
    arguments = dict(
245
        detail=FlagArgument('show detailed output', ('-l', '--details')),
246
        more=FlagArgument(
247
            'output results in pages (-n to set items per page, default 10)',
248
            '--more')
249
    )
250

    
251
    @errors.generic.all
252
    @errors.cyclades.connection
253
    def _run(self):
254
        nets = self.client.list_subnets()
255
        nets = self._filter_by_name(nets)
256
        nets = self._filter_by_id(nets)
257
        if not self['detail']:
258
            nets = [dict(
259
                id=n['id'], name=n['name'], links=n['links']) for n in nets]
260
        kwargs = dict()
261
        if self['more']:
262
            kwargs['out'] = StringIO()
263
            kwargs['title'] = ()
264
        self._print(nets, **kwargs)
265
        if self['more']:
266
            pager(kwargs['out'].getvalue())
267

    
268
    def main(self):
269
        super(self.__class__, self)._run()
270
        self._run()
271

    
272

    
273
@command(subnet_cmds)
274
class subnet_info(_init_network, _optional_json):
275
    """Get details about a subnet"""
276

    
277
    @errors.generic.all
278
    @errors.cyclades.connection
279
    def _run(self, subnet_id):
280
        net = self.client.get_subnet_details(subnet_id)
281
        self._print(net, self.print_dict)
282

    
283
    def main(self, subnet_id):
284
        super(self.__class__, self)._run()
285
        self._run(subnet_id=subnet_id)
286

    
287

    
288
class AllocationPoolArgument(RepeatableArgument):
289

    
290
    @property
291
    def value(self):
292
        return super(AllocationPoolArgument, self).value or []
293

    
294
    @value.setter
295
    def value(self, new_pools):
296
        new_list = []
297
        for pool in new_pools:
298
            start, comma, end = pool.partition(',')
299
            if not (start and comma and end):
300
                raise CLIInvalidArgument(
301
                    'Invalid allocation pool argument %s' % pool, details=[
302
                    'Allocation values must be of the form:',
303
                    '  <start address>,<end address>'])
304
            new_list.append(dict(start=start, end=end))
305
        self._value = new_list
306

    
307

    
308
@command(subnet_cmds)
309
class subnet_create(_init_network, _optional_json):
310
    """Create a new subnet"""
311

    
312
    arguments = dict(
313
        name=ValueArgument('Subnet name', '--name'),
314
        allocation_pools=AllocationPoolArgument(
315
            'start_address,end_address of allocation pool (can be repeated)'
316
            ' e.g., --alloc-pool=123.45.67.1,123.45.67.8',
317
            '--alloc-pool'),
318
        gateway=ValueArgument('Gateway IP', '--gateway'),
319
        subnet_id=ValueArgument('The id for the subnet', '--id'),
320
        ipv6=FlagArgument('If set, IP version is set to 6, else 4', '--ipv6'),
321
        enable_dhcp=FlagArgument('Enable dhcp (default: off)', '--with-dhcp'),
322
        network_id=ValueArgument('Set the network ID', '--network-id'),
323
        cidr=ValueArgument('Set the CIDR', '--cidr')
324
    )
325
    required = ('network_id', 'cidr')
326

    
327
    @errors.generic.all
328
    @errors.cyclades.connection
329
    @errors.cyclades.network_id
330
    def _run(self, network_id, cidr):
331
        net = self.client.create_subnet(
332
            network_id, cidr,
333
            self['name'], self['allocation_pools'], self['gateway'],
334
            self['subnet_id'], self['ipv6'], self['enable_dhcp'])
335
        self._print(net, self.print_dict)
336

    
337
    def main(self):
338
        super(self.__class__, self)._run()
339
        self._run(network_id=self['network_id'], cidr=self['cidr'])
340

    
341

    
342
# @command(subnet_cmds)
343
# class subnet_delete(_init_network, _optional_output_cmd):
344
#     """Delete a subnet"""
345

    
346
#     @errors.generic.all
347
#     @errors.cyclades.connection
348
#     def _run(self, subnet_id):
349
#         r = self.client.delete_subnet(subnet_id)
350
#         self._optional_output(r)
351

    
352
#     def main(self, subnet_id):
353
#         super(self.__class__, self)._run()
354
#         self._run(subnet_id=subnet_id)
355

    
356

    
357
@command(subnet_cmds)
358
class subnet_modify(_init_network, _optional_json):
359
    """Modify the attributes of a subnet"""
360

    
361
    arguments = dict(
362
        new_name=ValueArgument('New name of the subnet', '--name')
363
    )
364
    required = ['new_name']
365

    
366
    @errors.generic.all
367
    @errors.cyclades.connection
368
    def _run(self, subnet_id):
369
        r = self.client.get_subnet_details(subnet_id)
370
        r = self.client.update_subnet(
371
            subnet_id, r['network_id'], name=self['new_name'])
372
        self._print(r, self.print_dict)
373

    
374
    def main(self, subnet_id):
375
        super(self.__class__, self)._run()
376
        self._run(subnet_id=subnet_id)
377

    
378

    
379
@command(port_cmds)
380
class port_list(_init_network, _optional_json):
381
    """List all ports"""
382

    
383
    @errors.generic.all
384
    @errors.cyclades.connection
385
    def _run(self):
386
        net = self.client.list_ports()
387
        self._print(net)
388

    
389
    def main(self):
390
        super(self.__class__, self)._run()
391
        self._run()
392

    
393

    
394
@command(port_cmds)
395
class port_info(_init_network, _optional_json):
396
    """Get details about a port"""
397

    
398
    @errors.generic.all
399
    @errors.cyclades.connection
400
    def _run(self, port_id):
401
        net = self.client.get_port_details(port_id)
402
        self._print(net, self.print_dict)
403

    
404
    def main(self, port_id):
405
        super(self.__class__, self)._run()
406
        self._run(port_id=port_id)
407

    
408

    
409
@command(port_cmds)
410
class port_delete(_init_network, _optional_output_cmd, _port_wait):
411
    """Delete a port (== disconnect server from network)"""
412

    
413
    arguments = dict(
414
        wait=FlagArgument('Wait port to be established', ('-w', '--wait'))
415
    )
416

    
417
    @errors.generic.all
418
    @errors.cyclades.connection
419
    def _run(self, port_id):
420
        r = self.client.delete_port(port_id)
421
        if self['wait']:
422
            self._wait(r['id'], r['status'])
423
        self._optional_output(r)
424

    
425
    def main(self, port_id):
426
        super(self.__class__, self)._run()
427
        self._run(port_id=port_id)
428

    
429

    
430
@command(port_cmds)
431
class port_modify(_init_network, _optional_json):
432
    """Modify the attributes of a port"""
433

    
434
    arguments = dict(new_name=ValueArgument('New name of the port', '--name'))
435
    required = ['new_name', ]
436

    
437
    @errors.generic.all
438
    @errors.cyclades.connection
439
    def _run(self, port_id):
440
        r = self.client.get_port_details(port_id)
441
        r = self.client.update_port(
442
            port_id, r['network_id'], name=self['new_name'])
443
        self._print(r, self.print_dict)
444

    
445
    def main(self, port_id):
446
        super(self.__class__, self)._run()
447
        self._run(port_id=port_id)
448

    
449

    
450
class _port_create(_init_network):
451

    
452
    @errors.generic.all
453
    @errors.cyclades.connection
454
    @errors.cyclades.network_id
455
    def _run(self, network_id, device_id):
456
        fixed_ips = [dict(
457
            subnet_id=self['subnet_id'], ip_address=self['ip_address'])] if (
458
                self['subnet_id']) else None
459
        r = self.client.create_port(
460
            network_id, device_id,
461
            name=self['name'],
462
            security_groups=self['security_group_id'],
463
            fixed_ips=fixed_ips)
464
        if self['wait']:
465
            self._wait(r['id'], r['status'])
466
        self._print(r, self.print_dict)
467

    
468

    
469
@command(port_cmds)
470
class port_create(_init_network, _optional_json, _port_wait):
471
    """Create a new port (== connect server to network)"""
472

    
473
    arguments = dict(
474
        name=ValueArgument('A human readable name', '--name'),
475
        security_group_id=RepeatableArgument(
476
            'Add a security group id (can be repeated)',
477
            ('-g', '--security-group')),
478
        subnet_id=ValueArgument(
479
            'Subnet id for fixed ips (used with --ip-address)',
480
            '--subnet-id'),
481
        ip_address=ValueArgument(
482
            'IP address for subnet id (used with --subnet-id', '--ip-address'),
483
        network_id=ValueArgument('Set the network ID', '--network-id'),
484
        device_id=ValueArgument(
485
            'The device is either a virtual server or a virtual router',
486
            '--device-id'),
487
        wait=FlagArgument('Wait port to be established', ('-w', '--wait')),
488
    )
489
    required = ('network_id', 'device_id')
490

    
491
    def main(self):
492
        super(self.__class__, self)._run()
493
        self._run(network_id=self['network_id'], device_id=self['device_id'])
494

    
495

    
496
@command(port_cmds)
497
class port_wait(_init_network, _port_wait):
498
    """Wait for port to finish [ACTIVE, DOWN, BUILD, ERROR]"""
499

    
500
    arguments = dict(
501
        timeout=IntArgument(
502
            'Wait limit in seconds (default: 60)', '--timeout', default=60)
503
    )
504

    
505
    @errors.generic.all
506
    @errors.cyclades.connection
507
    def _run(self, port_id, current_status):
508
        port = self.client.get_port_details(port_id)
509
        if port['status'].lower() == current_status.lower():
510
            self._wait(port_id, current_status, timeout=self['timeout'])
511
        else:
512
            self.error(
513
                'Port %s: Cannot wait for status %s, '
514
                'status is already %s' % (
515
                    port_id, current_status, port['status']))
516

    
517
    def main(self, port_id, current_status='BUILD'):
518
        super(self.__class__, self)._run()
519
        self._run(port_id=port_id, current_status=current_status)
520

    
521

    
522
@command(ip_cmds)
523
class ip_list(_init_network, _optional_json):
524
    """List reserved floating IPs"""
525

    
526
    @errors.generic.all
527
    @errors.cyclades.connection
528
    def _run(self):
529
        self._print(self.client.list_floatingips())
530

    
531
    def main(self):
532
        super(self.__class__, self)._run()
533
        self._run()
534

    
535

    
536
@command(ip_cmds)
537
class ip_info(_init_network, _optional_json):
538
    """Get details on a floating IP"""
539

    
540
    @errors.generic.all
541
    @errors.cyclades.connection
542
    def _run(self, ip_id):
543
        self._print(
544
            self.client.get_floatingip_details(ip_id), self.print_dict)
545

    
546
    def main(self, ip_id):
547
        super(self.__class__, self)._run()
548
        self._run(ip_id=ip_id)
549

    
550

    
551
@command(ip_cmds)
552
class ip_create(_init_network, _optional_json):
553
    """Reserve an IP on a network"""
554

    
555
    arguments = dict(
556
        network_id=ValueArgument(
557
            'The network to preserve the IP on', '--network-id'),
558
        ip_address=ValueArgument('Allocate a specific IP address', '--address')
559
    )
560
    required = ('network_id', )
561

    
562
    @errors.generic.all
563
    @errors.cyclades.connection
564
    @errors.cyclades.network_id
565
    def _run(self, network_id):
566
        self._print(
567
            self.client.create_floatingip(
568
                network_id, floating_ip_address=self['ip_address']),
569
            self.print_dict)
570

    
571
    def main(self):
572
        super(self.__class__, self)._run()
573
        self._run(network_id=self['network_id'])
574

    
575

    
576
@command(ip_cmds)
577
class ip_delete(_init_network, _optional_output_cmd):
578
    """Unreserve an IP (also delete the port, if attached)"""
579

    
580
    def _run(self, ip_id):
581
        self._optional_output(self.client.delete_floatingip(ip_id))
582

    
583
    def main(self, ip_id):
584
        super(self.__class__, self)._run()
585
        self._run(ip_id=ip_id)
586

    
587

    
588
#  Warn users for some importand changes
589

    
590
@command(network_cmds)
591
class network_connect(_port_create):
592
    """Connect a network with a device (server or router)"""
593

    
594
    arguments = dict(
595
        name=ValueArgument('A human readable name', '--name'),
596
        security_group_id=RepeatableArgument(
597
            'Add a security group id (can be repeated)',
598
            ('-g', '--security-group')),
599
        subnet_id=ValueArgument(
600
            'Subnet id for fixed ips (used with --ip-address)',
601
            '--subnet-id'),
602
        ip_address=ValueArgument(
603
            'IP address for subnet id (used with --subnet-id', '--ip-address'),
604
        wait=FlagArgument('Wait port to be established', ('-w', '--wait')),
605
    )
606

    
607
    def main(self, network_id, device_id):
608
        super(self.__class__, self)._run()
609
        self._run(network_id=network_id, device_id=device_id)
610

    
611

    
612
@command(network_cmds)
613
class network_disconnect(_init_network, _optional_json):
614
    """Disconnnect a network from a device"""
615

    
616
    def _cyclades_client(self):
617
        auth = getattr(self, 'auth_base')
618
        endpoints = auth.get_service_endpoints('compute')
619
        URL = endpoints['publicURL']
620
        from kamaki.clients.cyclades import CycladesClient
621
        return CycladesClient(URL, self.client.token)
622

    
623
    @errors.generic.all
624
    @errors.cyclades.connection
625
    @errors.cyclades.network_id
626
    @errors.cyclades.server_id
627
    def _run(self, network_id, device_id):
628
        vm = self._cyclades_client().get_server_details(device_id)
629
        nets = [net for net in vm['attachments'] if net['network_id'] not in (
630
            'network_id', )]
631
        if not nets:
632
            raiseCLIError('Network %s is not connected to device %s' % (
633
                network_id, device_id))
634
        for net in nets:
635
            self.client.port_delete(net['id'])
636
            self.error('Deleted connection:')
637
            self.print_dict(net)
638

    
639
    def main(self, network_id, device_id):
640
        super(self.__class__, self)._run()
641
        self._run(network_id=network_id, device_id=device_id)