Statistics
| Branch: | Tag: | Revision:

root / kamaki / cli / commands / network.py @ 1c366ac9

History | View | Annotate | Download (21.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 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 = ('MAC_FILTERED', 'CUSTOM', 'IP_LESS_ROUTED', 'PHYSICAL_VLAN')
161

    
162
    @property
163
    def value(self):
164
        return getattr(self, '_value', self.types[0])
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 (default type: MAC_FILTERED)"""
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

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

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

    
201

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

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

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

    
217

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

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

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

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

    
236

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

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

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

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

    
271

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

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

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

    
286

    
287
class AllocationPoolArgument(RepeatableArgument):
288

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

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

    
306

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

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

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

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

    
340

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

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

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

    
355

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

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

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

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

    
377

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

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

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

    
392

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

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

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

    
407

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

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

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

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

    
428

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

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

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

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

    
448

    
449
class _port_create(_init_network, _optional_json, _port_wait):
450

    
451
    def connect(self, network_id, device_id):
452
        fixed_ips = [dict(
453
            subnet_id=self['subnet_id'], ip_address=self['ip_address'])] if (
454
                self['subnet_id']) else None
455
        r = self.client.create_port(
456
            network_id, device_id,
457
            name=self['name'],
458
            security_groups=self['security_group_id'],
459
            fixed_ips=fixed_ips)
460
        if self['wait']:
461
            self._wait(r['id'], r['status'])
462
        self._print(r, self.print_dict)
463

    
464

    
465
@command(port_cmds)
466
class port_create(_init_network):
467
    """Create a new port (== connect server to network)"""
468

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

    
487
    @errors.generic.all
488
    @errors.cyclades.connection
489
    @errors.cyclades.network_id
490
    @errors.cyclades.server_id
491
    def _run(self, network_id, server_id):
492
        self.connect(network_id, server_id)
493

    
494
    def main(self):
495
        super(self.__class__, self)._run()
496
        self._run(network_id=self['network_id'], server_id=self['device_id'])
497

    
498

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

    
503
    arguments = dict(
504
        timeout=IntArgument(
505
            'Wait limit in seconds (default: 60)', '--timeout', default=60)
506
    )
507

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

    
520
    def main(self, port_id, current_status='BUILD'):
521
        super(self.__class__, self)._run()
522
        self._run(port_id=port_id, current_status=current_status)
523

    
524

    
525
@command(ip_cmds)
526
class ip_list(_init_network, _optional_json):
527
    """List reserved floating IPs"""
528

    
529
    @errors.generic.all
530
    @errors.cyclades.connection
531
    def _run(self):
532
        self._print(self.client.list_floatingips())
533

    
534
    def main(self):
535
        super(self.__class__, self)._run()
536
        self._run()
537

    
538

    
539
@command(ip_cmds)
540
class ip_info(_init_network, _optional_json):
541
    """Get details on a floating IP"""
542

    
543
    @errors.generic.all
544
    @errors.cyclades.connection
545
    def _run(self, ip_id):
546
        self._print(
547
            self.client.get_floatingip_details(ip_id), self.print_dict)
548

    
549
    def main(self, ip_id):
550
        super(self.__class__, self)._run()
551
        self._run(ip_id=ip_id)
552

    
553

    
554
@command(ip_cmds)
555
class ip_create(_init_network, _optional_json):
556
    """Reserve an IP on a network"""
557

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

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

    
574
    def main(self):
575
        super(self.__class__, self)._run()
576
        self._run(network_id=self['network_id'])
577

    
578

    
579
@command(ip_cmds)
580
class ip_delete(_init_network, _optional_output_cmd):
581
    """Unreserve an IP (also delete the port, if attached)"""
582

    
583
    def _run(self, ip_id):
584
        self._optional_output(self.client.delete_floatingip(ip_id))
585

    
586
    def main(self, ip_id):
587
        super(self.__class__, self)._run()
588
        self._run(ip_id=ip_id)
589

    
590

    
591
#  Warn users for some importand changes
592

    
593
@command(network_cmds)
594
class network_connect(_port_create):
595
    """Connect a network with a device (server or router)"""
596

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

    
610
    @errors.generic.all
611
    @errors.cyclades.connection
612
    @errors.cyclades.network_id
613
    @errors.cyclades.server_id
614
    def _run(self, network_id, server_id):
615
        self.connect(network_id, server_id)
616

    
617
    def main(self, network_id, device_id):
618
        super(self.__class__, self)._run()
619
        self._run(network_id=network_id, device_id=device_id)
620

    
621

    
622
@command(network_cmds)
623
class network_disconnect(_init_network, _port_wait, _optional_json):
624
    """Disconnnect a network from a device"""
625

    
626
    def _cyclades_client(self):
627
        auth = getattr(self, 'auth_base')
628
        endpoints = auth.get_service_endpoints('compute')
629
        URL = endpoints['publicURL']
630
        from kamaki.clients.cyclades import CycladesClient
631
        return CycladesClient(URL, self.client.token)
632

    
633
    arguments = dict(
634
        wait=FlagArgument('Wait network to disconnect', ('-w', '--wait'))
635
    )
636

    
637
    @errors.generic.all
638
    @errors.cyclades.connection
639
    @errors.cyclades.network_id
640
    @errors.cyclades.server_id
641
    def _run(self, network_id, device_id):
642
        vm = self._cyclades_client().get_server_details(device_id)
643
        nets = [net for net in vm['attachments'] if net['network_id'] not in (
644
            'network_id', )]
645
        if not nets:
646
            raiseCLIError('Network %s is not connected to device %s' % (
647
                network_id, device_id))
648
        for net in nets:
649
            self.client.port_delete(net['id'])
650
            self.error('Deleting this connection:')
651
            self.print_dict(net)
652
            if self['wait']:
653
                self._wait(net['id'], net['status'])
654

    
655
    def main(self, network_id, device_id):
656
        super(self.__class__, self)._run()
657
        self._run(network_id=network_id, device_id=device_id)