Debian Codegraph @

neutronclient/neutron/v2_0/network.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 neutronclient._i18n import _
20 from neutronclient.common import exceptions
21 from neutronclient.common import utils
22 from neutronclient.neutron import v2_0 as neutronV20
23 from neutronclient.neutron.v2_0 import availability_zone
24 from neutronclient.neutron.v2_0 import dns
25 from neutronclient.neutron.v2_0.qos import policy as qos_policy
26
27
28 def _format_subnets(network):
29 try:
30 return '\n'.join([' '.join([s['id'], s.get('cidr', '')])
31 for s in network['subnets']])
32 except (TypeError, KeyError):
33 return ''
34
35
36 def args2body_common(body, parsed_args):
37 neutronV20.update_dict(parsed_args, body,
38 ['name', 'description'])
39
40
41 class ListNetwork(neutronV20.ListCommand):
42 """List networks that belong to a given tenant."""
43
44 # Length of a query filter on subnet id
45 # id=<uuid>& (with len(uuid)=36)
46 subnet_id_filter_len = 40
47 # Length of a marker in pagination
48 # &marker=<uuid> (with len(uuid)=36)
49 marker_len = 44
50 resource = 'network'
51 _formatters = {'subnets': _format_subnets, }
52 list_columns = ['id', 'name', 'subnets']
53 pagination_support = True
54 sorting_support = True
55
56 filter_attrs = [
57 'tenant_id',
58 'name',
59 'admin_state_up',
60 {'name': 'status',
61 'help': _("Filter %s according to their operation status."
62 "(For example: ACTIVE, ERROR etc)"),
63 'boolean': False,
64 'argparse_kwargs': {'type': utils.convert_to_uppercase}},
65 {'name': 'shared',
66 'help': _('Filter and list the networks which are shared.'),
67 'boolean': True},
68 {'name': 'router:external',
69 'help': _('Filter and list the networks which are external.'),
70 'boolean': True},
71 {'name': 'tags',
72 'help': _("Filter and list %s which has all given tags. "
73 "Multiple tags can be set like --tags <tag[,tag...]>"),
74 'boolean': False,
75 'argparse_kwargs': {'metavar': 'TAG'}},
76 {'name': 'tags_any',
77 'help': _("Filter and list %s which has any given tags. "
78 "Multiple tags can be set like --tags-any <tag[,tag...]>"),
79 'boolean': False,
80 'argparse_kwargs': {'metavar': 'TAG'}},
81 {'name': 'not_tags',
82 'help': _("Filter and list %s which does not have all given tags. "
83 "Multiple tags can be set like --not-tags <tag[,tag...]>"),
84 'boolean': False,
85 'argparse_kwargs': {'metavar': 'TAG'}},
86 {'name': 'not_tags_any',
87 'help': _("Filter and list %s which does not have any given tags. "
88 "Multiple tags can be set like --not-tags-any "
89 "<tag[,tag...]>"),
90 'boolean': False,
91 'argparse_kwargs': {'metavar': 'TAG'}},
92 ]
93
94 def extend_list(self, data, parsed_args):
95 """Add subnet information to a network list."""
96 neutron_client = self.get_client()
97 search_opts = {'fields': ['id', 'cidr']}
98 if self.pagination_support:
99 page_size = parsed_args.page_size
100 if page_size:
101 search_opts.update({'limit': page_size})
102 subnet_ids = []
103 for n in data:
104 if 'subnets' in n:
105 subnet_ids.extend(n['subnets'])
106
107 def _get_subnet_list(sub_ids):
108 search_opts['id'] = sub_ids
109 return neutron_client.list_subnets(
110 **search_opts).get('subnets', [])
111
112 try:
113 subnets = _get_subnet_list(subnet_ids)
114 except exceptions.RequestURITooLong as uri_len_exc:
115 # The URI is too long because of too many subnet_id filters
116 # Use the excess attribute of the exception to know how many
117 # subnet_id filters can be inserted into a single request
118 subnet_count = len(subnet_ids)
119 max_size = ((self.subnet_id_filter_len * subnet_count) -
120 uri_len_exc.excess)
121 if self.pagination_support:
122 max_size -= self.marker_len
123 chunk_size = max_size // self.subnet_id_filter_len
124 subnets = []
125 for i in range(0, subnet_count, chunk_size):
126 subnets.extend(
127 _get_subnet_list(subnet_ids[i: i + chunk_size]))
128
129 subnet_dict = dict([(s['id'], s) for s in subnets])
130 for n in data:
131 if 'subnets' in n:
132 n['subnets'] = [(subnet_dict.get(s) or {"id": s})
133 for s in n['subnets']]
134
135
136 class ListExternalNetwork(ListNetwork):
137 """List external networks that belong to a given tenant."""
138
139 pagination_support = True
140 sorting_support = True
141
142 def retrieve_list(self, parsed_args):
143 external = '--router:external=True'
144 if external not in self.values_specs:
145 self.values_specs.append('--router:external=True')
146 return super(ListExternalNetwork, self).retrieve_list(parsed_args)
147
148
149 class ShowNetwork(neutronV20.ShowCommand):
150 """Show information of a given network."""
151
152 resource = 'network'
153
154
155 class CreateNetwork(neutronV20.CreateCommand, qos_policy.CreateQosPolicyMixin):
156 """Create a network for a given tenant."""
157
158 resource = 'network'
159
160 def add_known_arguments(self, parser):
161 parser.add_argument(
162 '--admin-state-down',
163 dest='admin_state', action='store_false',
164 help=_('Set admin state up to false.'))
165 parser.add_argument(
166 '--admin_state_down',
167 dest='admin_state', action='store_false',
168 help=argparse.SUPPRESS)
169 parser.add_argument(
170 '--shared',
171 action='store_true',
172 help=_('Set the network as shared.'),
173 default=argparse.SUPPRESS)
174 parser.add_argument(
175 '--provider:network_type',
176 metavar='<network_type>',
177 help=_('The physical mechanism by which the virtual network'
178 ' is implemented.'))
179 parser.add_argument(
180 '--provider:physical_network',
181 metavar='<physical_network_name>',
182 help=_('Name of the physical network over which the virtual '
183 'network is implemented.'))
184 parser.add_argument(
185 '--provider:segmentation_id',
186 metavar='<segmentation_id>',
187 help=_('VLAN ID for VLAN networks or tunnel-id for GRE/VXLAN '
188 'networks.'))
189 utils.add_boolean_argument(
190 parser,
191 '--vlan-transparent',
192 default=argparse.SUPPRESS,
193 help=_('Create a VLAN transparent network.'))
194 parser.add_argument(
195 'name', metavar='NAME',
196 help=_('Name of the network to be created.'))
197 parser.add_argument(
198 '--description',
199 help=_('Description of network.'))
200
201 self.add_arguments_qos_policy(parser)
202 availability_zone.add_az_hint_argument(parser, self.resource)
203 dns.add_dns_argument_create(parser, self.resource, 'domain')
204
205 def args2body(self, parsed_args):
206 body = {'admin_state_up': parsed_args.admin_state}
207 args2body_common(body, parsed_args)
208 neutronV20.update_dict(parsed_args, body,
209 ['shared', 'tenant_id',
210 'vlan_transparent',
211 'provider:network_type',
212 'provider:physical_network',
213 'provider:segmentation_id',
214 'description'])
215 self.args2body_qos_policy(parsed_args, body)
216 availability_zone.args2body_az_hint(parsed_args, body)
217 dns.args2body_dns_create(parsed_args, body, 'domain')
218 return {'network': body}
219
220
221 class DeleteNetwork(neutronV20.DeleteCommand):
222 """Delete a given network."""
223
224 resource = 'network'
225
226
227 class UpdateNetwork(neutronV20.UpdateCommand, qos_policy.UpdateQosPolicyMixin):
228 """Update network's information."""
229
230 resource = 'network'
231
232 def add_known_arguments(self, parser):
233 parser.add_argument(
234 '--name',
235 help=_('Name of the network.'))
236 parser.add_argument(
237 '--description',
238 help=_('Description of this network.'))
239 self.add_arguments_qos_policy(parser)
240 dns.add_dns_argument_update(parser, self.resource, 'domain')
241
242 def args2body(self, parsed_args):
243 body = {}
244 args2body_common(body, parsed_args)
245 self.args2body_qos_policy(parsed_args, body)
246 dns.args2body_dns_update(parsed_args, body, 'domain')
247 return {'network': body}