Debian Codegraph @

neutronclient/neutron/v2_0/subnet.py

raw
1 # Copyright 2012 OpenStack Foundation.
2 # All Rights Reserved
3 #
4 # Licensed under the Apache License, Version 2.0 (the "License"); you may
5 # not use this file except in compliance with the License. You may obtain
6 # a copy of the License at
7 #
8 # http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 # License for the specific language governing permissions and limitations
14 # under the License.
15 #
16
17 import argparse
18
19 from oslo_serialization import jsonutils
20
21 from neutronclient._i18n import _
22 from neutronclient.common import exceptions
23 from neutronclient.common import utils
24 from neutronclient.neutron import v2_0 as neutronV20
25
26
27 def _format_allocation_pools(subnet):
28 try:
29 return '\n'.join([jsonutils.dumps(pool) for pool in
30 subnet['allocation_pools']])
31 except (TypeError, KeyError):
32 return ''
33
34
35 def _format_dns_nameservers(subnet):
36 try:
37 return '\n'.join([jsonutils.dumps(server) for server in
38 subnet['dns_nameservers']])
39 except (TypeError, KeyError):
40 return ''
41
42
43 def _format_host_routes(subnet):
44 try:
45 return '\n'.join([jsonutils.dumps(route) for route in
46 subnet['host_routes']])
47 except (TypeError, KeyError):
48 return ''
49
50
51 def add_updatable_arguments(parser):
52 parser.add_argument(
53 '--name',
54 help=_('Name of this subnet.'))
55 parser.add_argument(
56 '--description',
57 help=_('Description of this subnet.'))
58 gateway_sg = parser.add_mutually_exclusive_group()
59 gateway_sg.add_argument(
60 '--gateway', metavar='GATEWAY_IP',
61 help=_('Gateway IP of this subnet.'))
62 gateway_sg.add_argument(
63 '--no-gateway',
64 action='store_true',
65 help=_('Do not configure a gateway for this subnet.'))
66 parser.add_argument(
67 '--allocation-pool', metavar='start=IP_ADDR,end=IP_ADDR',
68 action='append', dest='allocation_pools',
69 type=utils.str2dict_type(required_keys=['start', 'end']),
70 help=_('Allocation pool IP addresses for this subnet '
71 '(This option can be repeated).'))
72 parser.add_argument(
73 '--allocation_pool',
74 action='append', dest='allocation_pools',
75 type=utils.str2dict_type(required_keys=['start', 'end']),
76 help=argparse.SUPPRESS)
77 parser.add_argument(
78 '--host-route', metavar='destination=CIDR,nexthop=IP_ADDR',
79 action='append', dest='host_routes',
80 type=utils.str2dict_type(required_keys=['destination', 'nexthop']),
81 help=_('Additional route (This option can be repeated).'))
82 parser.add_argument(
83 '--dns-nameserver', metavar='DNS_NAMESERVER',
84 action='append', dest='dns_nameservers',
85 help=_('DNS name server for this subnet '
86 '(This option can be repeated).'))
87 parser.add_argument(
88 '--disable-dhcp',
89 action='store_true',
90 help=_('Disable DHCP for this subnet.'))
91 parser.add_argument(
92 '--enable-dhcp',
93 action='store_true',
94 help=_('Enable DHCP for this subnet.'))
95 # NOTE(ihrachys): yes, that's awful, but should be left as-is for
96 # backwards compatibility for versions <=2.3.4 that passed the
97 # boolean values through to the server without any argument
98 # validation.
99 parser.add_argument(
100 '--enable-dhcp=True',
101 action='store_true',
102 dest='enable_dhcp',
103 help=argparse.SUPPRESS)
104 parser.add_argument(
105 '--enable-dhcp=False',
106 action='store_true',
107 dest='disable_dhcp',
108 help=argparse.SUPPRESS)
109
110
111 def updatable_args2body(parsed_args, body, for_create=True, ip_version=None):
112 if parsed_args.disable_dhcp and parsed_args.enable_dhcp:
113 raise exceptions.CommandError(_(
114 "You cannot enable and disable DHCP at the same time."))
115
116 neutronV20.update_dict(parsed_args, body,
117 ['name', 'allocation_pools',
118 'host_routes', 'dns_nameservers',
119 'description'])
120 if parsed_args.no_gateway:
121 body['gateway_ip'] = None
122 elif parsed_args.gateway:
123 body['gateway_ip'] = parsed_args.gateway
124 if parsed_args.disable_dhcp:
125 body['enable_dhcp'] = False
126 if parsed_args.enable_dhcp:
127 body['enable_dhcp'] = True
128 if for_create and parsed_args.ipv6_ra_mode:
129 if ip_version == 4:
130 raise exceptions.CommandError(_("--ipv6-ra-mode is invalid "
131 "when --ip-version is 4"))
132 body['ipv6_ra_mode'] = parsed_args.ipv6_ra_mode
133 if for_create and parsed_args.ipv6_address_mode:
134 if ip_version == 4:
135 raise exceptions.CommandError(_("--ipv6-address-mode is "
136 "invalid when --ip-version "
137 "is 4"))
138 body['ipv6_address_mode'] = parsed_args.ipv6_address_mode
139
140
141 class ListSubnet(neutronV20.ListCommand):
142 """List subnets that belong to a given tenant."""
143
144 resource = 'subnet'
145 _formatters = {'allocation_pools': _format_allocation_pools,
146 'dns_nameservers': _format_dns_nameservers,
147 'host_routes': _format_host_routes, }
148 list_columns = ['id', 'name', 'cidr', 'allocation_pools']
149 pagination_support = True
150 sorting_support = True
151
152
153 class ShowSubnet(neutronV20.ShowCommand):
154 """Show information of a given subnet."""
155
156 resource = 'subnet'
157
158
159 class CreateSubnet(neutronV20.CreateCommand):
160 """Create a subnet for a given tenant."""
161
162 resource = 'subnet'
163
164 def add_known_arguments(self, parser):
165 add_updatable_arguments(parser)
166 parser.add_argument(
167 '--ip-version',
168 type=int,
169 default=4, choices=[4, 6],
170 help=_('IP version to use, default is 4. '
171 'Note that when subnetpool is specified, '
172 'IP version is determined from the subnetpool '
173 'and this option is ignored.'))
174 parser.add_argument(
175 '--ip_version',
176 type=int,
177 choices=[4, 6],
178 help=argparse.SUPPRESS)
179 parser.add_argument(
180 'network_id', metavar='NETWORK',
181 help=_('Network ID or name this subnet belongs to.'))
182 parser.add_argument(
183 'cidr', nargs='?', metavar='CIDR',
184 help=_('CIDR of subnet to create.'))
185 parser.add_argument(
186 '--ipv6-ra-mode',
187 type=utils.convert_to_lowercase,
188 choices=['dhcpv6-stateful', 'dhcpv6-stateless', 'slaac'],
189 help=_('IPv6 RA (Router Advertisement) mode.'))
190 parser.add_argument(
191 '--ipv6-address-mode',
192 type=utils.convert_to_lowercase,
193 choices=['dhcpv6-stateful', 'dhcpv6-stateless', 'slaac'],
194 help=_('IPv6 address mode.'))
195 parser.add_argument(
196 '--subnetpool', metavar='SUBNETPOOL',
197 help=_('ID or name of subnetpool from which this subnet '
198 'will obtain a CIDR.'))
199 parser.add_argument(
200 '--use-default-subnetpool',
201 action='store_true',
202 help=_('Use default subnetpool for ip_version, if it exists.'))
203 parser.add_argument(
204 '--prefixlen', metavar='PREFIX_LENGTH',
205 help=_('Prefix length for subnet allocation from subnetpool.'))
206 parser.add_argument(
207 '--segment', metavar='SEGMENT',
208 help=_('ID of segment with which this subnet will be associated.'))
209
210 def args2body(self, parsed_args):
211 _network_id = neutronV20.find_resourceid_by_name_or_id(
212 self.get_client(), 'network', parsed_args.network_id)
213 body = {'network_id': _network_id}
214
215 if parsed_args.prefixlen:
216 body['prefixlen'] = parsed_args.prefixlen
217 ip_version = parsed_args.ip_version
218 if parsed_args.use_default_subnetpool:
219 body['use_default_subnetpool'] = True
220 if parsed_args.segment:
221 body['segment_id'] = neutronV20.find_resourceid_by_name_or_id(
222 self.get_client(), 'segment', parsed_args.segment)
223 if parsed_args.subnetpool:
224 if parsed_args.subnetpool == 'None':
225 _subnetpool_id = None
226 else:
227 _subnetpool = neutronV20.find_resource_by_name_or_id(
228 self.get_client(), 'subnetpool', parsed_args.subnetpool)
229 _subnetpool_id = _subnetpool['id']
230 # Now that we have the pool_id - let's just have a check on the
231 # ip version used in the pool
232 ip_version = _subnetpool['ip_version']
233 body['subnetpool_id'] = _subnetpool_id
234
235 # IP version needs to be set as IP version can be
236 # determined by subnetpool.
237 body['ip_version'] = ip_version
238
239 if parsed_args.cidr:
240 # With subnetpool, cidr is now optional for creating subnet.
241 cidr = parsed_args.cidr
242 body['cidr'] = cidr
243 unusable_cidr = '/32' if ip_version == 4 else '/128'
244 if cidr.endswith(unusable_cidr):
245 self.log.warning(_("An IPv%(ip)d subnet with a %(cidr)s CIDR "
246 "will have only one usable IP address so "
247 "the device attached to it will not have "
248 "any IP connectivity."),
249 {"ip": ip_version,
250 "cidr": unusable_cidr})
251
252 updatable_args2body(parsed_args, body, ip_version=ip_version)
253 if parsed_args.tenant_id:
254 body['tenant_id'] = parsed_args.tenant_id
255
256 return {'subnet': body}
257
258
259 class DeleteSubnet(neutronV20.DeleteCommand):
260 """Delete a given subnet."""
261
262 resource = 'subnet'
263
264
265 class UpdateSubnet(neutronV20.UpdateCommand):
266 """Update subnet's information."""
267
268 resource = 'subnet'
269
270 def add_known_arguments(self, parser):
271 add_updatable_arguments(parser)
272
273 def args2body(self, parsed_args):
274 body = {}
275 updatable_args2body(parsed_args, body, for_create=False)
276 return {'subnet': body}