Debian Codegraph @

neutronclient/neutron/v2_0/router.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 from neutronclient.neutron.v2_0 import availability_zone
26
27
28 def _format_external_gateway_info(router):
29 try:
30 return jsonutils.dumps(router['external_gateway_info'])
31 except (TypeError, KeyError):
32 return ''
33
34
35 class ListRouter(neutronV20.ListCommand):
36 """List routers that belong to a given tenant."""
37
38 resource = 'router'
39 _formatters = {'external_gateway_info': _format_external_gateway_info, }
40 list_columns = ['id', 'name', 'external_gateway_info', 'distributed', 'ha']
41 pagination_support = True
42 sorting_support = True
43
44
45 class ShowRouter(neutronV20.ShowCommand):
46 """Show information of a given router."""
47
48 resource = 'router'
49
50
51 class CreateRouter(neutronV20.CreateCommand):
52 """Create a router for a given tenant."""
53
54 resource = 'router'
55 _formatters = {'external_gateway_info': _format_external_gateway_info, }
56
57 def add_known_arguments(self, parser):
58 parser.add_argument(
59 '--admin-state-down',
60 dest='admin_state', action='store_false',
61 help=_('Set admin state up to false.'))
62 parser.add_argument(
63 '--admin_state_down',
64 dest='admin_state', action='store_false',
65 help=argparse.SUPPRESS)
66 parser.add_argument(
67 'name', metavar='NAME',
68 help=_('Name of the router to be created.'))
69 parser.add_argument(
70 '--description',
71 help=_('Description of router.'))
72 parser.add_argument(
73 '--flavor',
74 help=_('ID or name of flavor.'))
75 utils.add_boolean_argument(
76 parser, '--distributed', dest='distributed',
77 help=_('Create a distributed router.'))
78 utils.add_boolean_argument(
79 parser, '--ha', dest='ha',
80 help=_('Create a highly available router.'))
81
82 availability_zone.add_az_hint_argument(parser, self.resource)
83
84 def args2body(self, parsed_args):
85 body = {'admin_state_up': parsed_args.admin_state}
86 if parsed_args.flavor:
87 _flavor_id = neutronV20.find_resourceid_by_name_or_id(
88 self.get_client(), 'flavor', parsed_args.flavor)
89 body['flavor_id'] = _flavor_id
90 neutronV20.update_dict(parsed_args, body,
91 ['name', 'tenant_id', 'distributed', 'ha',
92 'description'])
93 availability_zone.args2body_az_hint(parsed_args, body)
94 return {self.resource: body}
95
96
97 class DeleteRouter(neutronV20.DeleteCommand):
98 """Delete a given router."""
99
100 resource = 'router'
101
102
103 class UpdateRouter(neutronV20.UpdateCommand):
104 """Update router's information."""
105
106 resource = 'router'
107
108 def add_known_arguments(self, parser):
109 parser.add_argument(
110 '--name',
111 help=_('Updated name of the router.'))
112 parser.add_argument(
113 '--description',
114 help=_('Description of router.'))
115 utils.add_boolean_argument(
116 parser, '--admin-state-up', dest='admin_state',
117 help=_('Specify the administrative state of the router '
118 '(True means "Up").'))
119 utils.add_boolean_argument(
120 parser, '--admin_state_up', dest='admin_state',
121 help=argparse.SUPPRESS)
122 utils.add_boolean_argument(
123 parser, '--distributed', dest='distributed',
124 help=_('True means this router should operate in '
125 'distributed mode.'))
126 routes_group = parser.add_mutually_exclusive_group()
127 routes_group.add_argument(
128 '--route', metavar='destination=CIDR,nexthop=IP_ADDR',
129 action='append', dest='routes',
130 type=utils.str2dict_type(required_keys=['destination', 'nexthop']),
131 help=_('Route to associate with the router.'
132 ' You can repeat this option.'))
133 routes_group.add_argument(
134 '--no-routes',
135 action='store_true',
136 help=_('Remove routes associated with the router.'))
137
138 def args2body(self, parsed_args):
139 body = {}
140 if hasattr(parsed_args, 'admin_state'):
141 body['admin_state_up'] = parsed_args.admin_state
142 neutronV20.update_dict(parsed_args, body,
143 ['name', 'distributed', 'description'])
144 if parsed_args.no_routes:
145 body['routes'] = None
146 elif parsed_args.routes:
147 body['routes'] = parsed_args.routes
148 return {self.resource: body}
149
150
151 class RouterInterfaceCommand(neutronV20.NeutronCommand):
152 """Based class to Add/Remove router interface."""
153
154 resource = 'router'
155
156 def call_api(self, neutron_client, router_id, body):
157 raise NotImplementedError()
158
159 def success_message(self, router_id, portinfo):
160 raise NotImplementedError()
161
162 def get_parser(self, prog_name):
163 parser = super(RouterInterfaceCommand, self).get_parser(prog_name)
164 parser.add_argument(
165 'router', metavar='ROUTER',
166 help=_('ID or name of the router.'))
167 parser.add_argument(
168 'interface', metavar='INTERFACE',
169 help=_('The format is "SUBNET|subnet=SUBNET|port=PORT". '
170 'Either a subnet or port must be specified. '
171 'Both ID and name are accepted as SUBNET or PORT. '
172 'Note that "subnet=" can be omitted when specifying a '
173 'subnet.'))
174 return parser
175
176 def take_action(self, parsed_args):
177 neutron_client = self.get_client()
178
179 if '=' in parsed_args.interface:
180 resource, value = parsed_args.interface.split('=', 1)
181 if resource not in ['subnet', 'port']:
182 exceptions.CommandError(_('You must specify either subnet or '
183 'port for INTERFACE parameter.'))
184 else:
185 resource = 'subnet'
186 value = parsed_args.interface
187
188 _router_id = neutronV20.find_resourceid_by_name_or_id(
189 neutron_client, self.resource, parsed_args.router)
190
191 _interface_id = neutronV20.find_resourceid_by_name_or_id(
192 neutron_client, resource, value)
193 body = {'%s_id' % resource: _interface_id}
194
195 portinfo = self.call_api(neutron_client, _router_id, body)
196 print(self.success_message(parsed_args.router, portinfo),
197 file=self.app.stdout)
198
199
200 class AddInterfaceRouter(RouterInterfaceCommand):
201 """Add an internal network interface to a router."""
202
203 def call_api(self, neutron_client, router_id, body):
204 return neutron_client.add_interface_router(router_id, body)
205
206 def success_message(self, router_id, portinfo):
207 return (_('Added interface %(port)s to router %(router)s.') %
208 {'router': router_id, 'port': portinfo['port_id']})
209
210
211 class RemoveInterfaceRouter(RouterInterfaceCommand):
212 """Remove an internal network interface from a router."""
213
214 def call_api(self, neutron_client, router_id, body):
215 return neutron_client.remove_interface_router(router_id, body)
216
217 def success_message(self, router_id, portinfo):
218 # portinfo is not used since it is None for router-interface-delete.
219 return _('Removed interface from router %s.') % router_id
220
221
222 class SetGatewayRouter(neutronV20.NeutronCommand):
223 """Set the external network gateway for a router."""
224
225 resource = 'router'
226
227 def get_parser(self, prog_name):
228 parser = super(SetGatewayRouter, self).get_parser(prog_name)
229 parser.add_argument(
230 'router', metavar='ROUTER',
231 help=_('ID or name of the router.'))
232 parser.add_argument(
233 'external_network', metavar='EXTERNAL-NETWORK',
234 help=_('ID or name of the external network for the gateway.'))
235 parser.add_argument(
236 '--enable-snat', action='store_true',
237 help=_('Enable source NAT on the router gateway.'))
238 parser.add_argument(
239 '--disable-snat', action='store_true',
240 help=_('Disable source NAT on the router gateway.'))
241 parser.add_argument(
242 '--fixed-ip', metavar='subnet_id=SUBNET,ip_address=IP_ADDR',
243 action='append',
244 type=utils.str2dict_type(optional_keys=['subnet_id',
245 'ip_address']),
246 help=_('Desired IP and/or subnet on external network: '
247 'subnet_id=<name_or_id>,ip_address=<ip>. '
248 'You can specify both of subnet_id and ip_address or '
249 'specify one of them as well. '
250 'You can repeat this option.'))
251 return parser
252
253 def take_action(self, parsed_args):
254 neutron_client = self.get_client()
255 _router_id = neutronV20.find_resourceid_by_name_or_id(
256 neutron_client, self.resource, parsed_args.router)
257 _ext_net_id = neutronV20.find_resourceid_by_name_or_id(
258 neutron_client, 'network', parsed_args.external_network)
259 router_dict = {'network_id': _ext_net_id}
260 if parsed_args.enable_snat:
261 router_dict['enable_snat'] = True
262 if parsed_args.disable_snat:
263 router_dict['enable_snat'] = False
264 if parsed_args.fixed_ip:
265 ips = []
266 for ip_spec in parsed_args.fixed_ip:
267 subnet_name_id = ip_spec.get('subnet_id')
268 if subnet_name_id:
269 subnet_id = neutronV20.find_resourceid_by_name_or_id(
270 neutron_client, 'subnet', subnet_name_id)
271 ip_spec['subnet_id'] = subnet_id
272 ips.append(ip_spec)
273 router_dict['external_fixed_ips'] = ips
274 neutron_client.add_gateway_router(_router_id, router_dict)
275 print(_('Set gateway for router %s') % parsed_args.router,
276 file=self.app.stdout)
277
278
279 class RemoveGatewayRouter(neutronV20.NeutronCommand):
280 """Remove an external network gateway from a router."""
281
282 resource = 'router'
283
284 def get_parser(self, prog_name):
285 parser = super(RemoveGatewayRouter, self).get_parser(prog_name)
286 parser.add_argument(
287 'router', metavar='ROUTER',
288 help=_('ID or name of the router.'))
289 return parser
290
291 def take_action(self, parsed_args):
292 neutron_client = self.get_client()
293 _router_id = neutronV20.find_resourceid_by_name_or_id(
294 neutron_client, self.resource, parsed_args.router)
295 neutron_client.remove_gateway_router(_router_id)
296 print(_('Removed gateway from router %s') % parsed_args.router,
297 file=self.app.stdout)