Debian Codegraph @

neutronclient/osc/v2/sfc/sfc_flow_classifier.py

raw
1 # Copyright (c) 2017 Huawei Technologies India Pvt.Limited.
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 import argparse
17 import logging
18
19 from osc_lib.command import command
20 from osc_lib import exceptions
21 from osc_lib import utils
22 from osc_lib.utils import columns as column_util
23
24 from neutronclient._i18n import _
25 from neutronclient.common import exceptions as nc_exc
26
27 LOG = logging.getLogger(__name__)
28
29 resource = 'flow_classifier'
30
31 _attr_map = (
32 ('id', 'ID', column_util.LIST_BOTH),
33 ('name', 'Name', column_util.LIST_BOTH),
34 ('summary', 'Summary', column_util.LIST_SHORT_ONLY),
35 ('protocol', 'Protocol', column_util.LIST_LONG_ONLY),
36 ('ethertype', 'Ethertype', column_util.LIST_LONG_ONLY),
37 ('source_ip_prefix', 'Source IP',
38 column_util.LIST_LONG_ONLY),
39 ('destination_ip_prefix', 'Destination IP',
40 column_util.LIST_LONG_ONLY),
41 ('logical_source_port', 'Logical Source Port',
42 column_util.LIST_LONG_ONLY),
43 ('logical_destination_port', 'Logical Destination Port',
44 column_util.LIST_LONG_ONLY),
45 ('source_port_range_min', 'Source Port Range Min',
46 column_util.LIST_LONG_ONLY),
47 ('source_port_range_max', 'Source Port Range Max',
48 column_util.LIST_LONG_ONLY),
49 ('destination_port_range_min', 'Destination Port Range Min',
50 column_util.LIST_LONG_ONLY),
51 ('destination_port_range_max', 'Destination Port Range Max',
52 column_util.LIST_LONG_ONLY),
53 ('l7_parameters', 'L7 Parameters', column_util.LIST_LONG_ONLY),
54 ('description', 'Description', column_util.LIST_LONG_ONLY),
55 ('project_id', 'Project', column_util.LIST_LONG_ONLY),
56 )
57
58 _attr_map_dict = {
59 'id': 'ID',
60 'name': 'Name',
61 'description': 'Description',
62 'summary': 'Summary',
63 'protocol': 'Protocol',
64 'ethertype': 'Ethertype',
65 'source_ip_prefix': 'Source IP',
66 'destination_ip_prefix': 'Destination IP',
67 'logical_source_port': 'Logical Source Port',
68 'logical_destination_port': 'Logical Destination Port',
69 'source_port_range_min': 'Source Port Range Min',
70 'source_port_range_max': 'Source Port Range Max',
71 'destination_port_range_min': 'Destination Port Range Min',
72 'destination_port_range_max': 'Destination Port Range Max',
73 'l7_parameters': 'L7 Parameters',
74 'tenant_id': 'Project',
75 'project_id': 'Project',
76 }
77
78
79 class CreateSfcFlowClassifier(command.ShowOne):
80 _description = _("Create a flow classifier")
81
82 def get_parser(self, prog_name):
83 parser = super(CreateSfcFlowClassifier, self).get_parser(prog_name)
84 parser.add_argument(
85 'name',
86 metavar='<name>',
87 help=_('Name of the flow classifier'))
88 parser.add_argument(
89 '--description',
90 metavar='<description>',
91 help=_('Description for the flow classifier'))
92 parser.add_argument(
93 '--protocol',
94 metavar='<protocol>',
95 help=_('IP protocol name. Protocol name should be as per '
96 'IANA standard.'))
97 parser.add_argument(
98 '--ethertype',
99 metavar='{IPv4,IPv6}',
100 default='IPv4', choices=['IPv4', 'IPv6'],
101 help=_('L2 ethertype, default is IPv4'))
102 parser.add_argument(
103 '--source-port',
104 metavar='<min-port>:<max-port>',
105 help=_('Source protocol port (allowed range [1,65535]. Must be '
106 'specified as a:b, where a=min-port and b=max-port) '
107 'in the allowed range.'))
108 parser.add_argument(
109 '--destination-port',
110 metavar='<min-port>:<max-port>',
111 help=_('Destination protocol port (allowed range [1,65535]. Must '
112 'be specified as a:b, where a=min-port and b=max-port) '
113 'in the allowed range.'))
114 parser.add_argument(
115 '--source-ip-prefix',
116 metavar='<source-ip-prefix>',
117 help=_('Source IP address in CIDR notation'))
118 parser.add_argument(
119 '--destination-ip-prefix',
120 metavar='<destination-ip-prefix>',
121 help=_('Destination IP address in CIDR notation'))
122 parser.add_argument(
123 '--logical-source-port',
124 metavar='<logical-source-port>',
125 help=_('Neutron source port (name or ID)'))
126 parser.add_argument(
127 '--logical-destination-port',
128 metavar='<logical-destination-port>',
129 help=_('Neutron destination port (name or ID)'))
130 parser.add_argument(
131 '--l7-parameters',
132 help=_('Dictionary of L7 parameters. Currently, no value is '
133 'supported for this option.'))
134 return parser
135
136 def take_action(self, parsed_args):
137 client = self.app.client_manager.network
138 attrs = _get_common_attrs(self.app.client_manager, parsed_args)
139 obj = client.create_sfc_flow_classifier(**attrs)
140 display_columns, columns = utils.get_osc_show_columns_for_sdk_resource(
141 obj, _attr_map_dict, ['location', 'tenant_id', 'summary'])
142 data = utils.get_dict_properties(obj, columns)
143 return display_columns, data
144
145
146 class DeleteSfcFlowClassifier(command.Command):
147 _description = _("Delete a given flow classifier")
148
149 def get_parser(self, prog_name):
150 parser = super(DeleteSfcFlowClassifier, self).get_parser(prog_name)
151 parser.add_argument(
152 'flow_classifier',
153 metavar='<flow-classifier>',
154 nargs='+',
155 help=_("Flow classifier(s) to delete (name or ID)")
156 )
157 return parser
158
159 def take_action(self, parsed_args):
160 client = self.app.client_manager.network
161 result = 0
162 for fcl in parsed_args.flow_classifier:
163 try:
164 fc_id = client.find_sfc_flow_classifier(
165 fcl, ignore_missing=False)['id']
166 client.delete_sfc_flow_classifier(fc_id)
167 except Exception as e:
168 result += 1
169 LOG.error(_("Failed to delete flow classifier with name "
170 "or ID '%(fc)s': %(e)s"), {'fc': fcl, 'e': e})
171 if result > 0:
172 total = len(parsed_args.flow_classifier)
173 msg = (_("%(result)s of %(total)s flow classifier(s) "
174 "failed to delete.") % {'result': result, 'total': total})
175 raise exceptions.CommandError(msg)
176
177
178 class ListSfcFlowClassifier(command.Lister):
179 _description = _("List flow classifiers")
180
181 def get_parser(self, prog_name):
182 parser = super(ListSfcFlowClassifier, self).get_parser(prog_name)
183 parser.add_argument(
184 '--long',
185 action='store_true',
186 help=_("List additional fields in output")
187 )
188 return parser
189
190 def extend_list(self, data, parsed_args):
191 ext_data = []
192 for d in data:
193 val = []
194 protocol = d['protocol'].upper() if d['protocol'] else 'any'
195 val.append('protocol: ' + protocol)
196 val.append(self._get_protocol_port_details(d, 'source'))
197 val.append(self._get_protocol_port_details(d, 'destination'))
198 if 'logical_source_port' in d:
199 val.append('neutron_source_port: ' +
200 str(d['logical_source_port']))
201
202 if 'logical_destination_port' in d:
203 val.append('neutron_destination_port: ' +
204 str(d['logical_destination_port']))
205
206 if 'l7_parameters' in d:
207 l7_param = 'l7_parameters: {%s}' % ','.join(d['l7_parameters'])
208 val.append(l7_param)
209 d['summary'] = ',\n'.join(val)
210 ext_data.append(d)
211 return ext_data
212
213 def _get_protocol_port_details(self, data, val):
214 type_ip_prefix = val + '_ip_prefix'
215 ip_prefix = data.get(type_ip_prefix)
216 if not ip_prefix:
217 ip_prefix = 'any'
218 min_port = data.get(val + '_port_range_min')
219 if min_port is None:
220 min_port = 'any'
221 max_port = data.get(val + '_port_range_max')
222 if max_port is None:
223 max_port = 'any'
224 return '%s[port]: %s[%s:%s]' % (
225 val, ip_prefix, min_port, max_port)
226
227 def take_action(self, parsed_args):
228 client = self.app.client_manager.network
229 obj = client.sfc_flow_classifiers()
230 obj_extend = self.extend_list(obj, parsed_args)
231 headers, columns = column_util.get_column_definitions(
232 _attr_map, long_listing=parsed_args.long)
233 return (headers, (utils.get_dict_properties(
234 s, columns) for s in obj_extend))
235
236
237 class SetSfcFlowClassifier(command.Command):
238 _description = _("Set flow classifier properties")
239
240 def get_parser(self, prog_name):
241 parser = super(SetSfcFlowClassifier, self).get_parser(prog_name)
242 parser.add_argument(
243 '--name',
244 metavar='<name>',
245 help=_('Name of the flow classifier'))
246 parser.add_argument(
247 '--description',
248 metavar='<description>',
249 help=_('Description for the flow classifier'))
250 parser.add_argument(
251 'flow_classifier',
252 metavar='<flow-classifier>',
253 help=_("Flow classifier to modify (name or ID)")
254 )
255 return parser
256
257 def take_action(self, parsed_args):
258 client = self.app.client_manager.network
259 fc_id = client.find_sfc_flow_classifier(parsed_args.flow_classifier,
260 ignore_missing=False)['id']
261 attrs = _get_common_attrs(self.app.client_manager, parsed_args,
262 is_create=False)
263 try:
264 client.update_sfc_flow_classifier(fc_id, **attrs)
265 except Exception as e:
266 msg = (_("Failed to update flow classifier '%(fc)s': %(e)s")
267 % {'fc': parsed_args.flow_classifier, 'e': e})
268 raise exceptions.CommandError(msg)
269
270
271 class ShowSfcFlowClassifier(command.ShowOne):
272 _description = _("Display flow classifier details")
273
274 def get_parser(self, prog_name):
275 parser = super(ShowSfcFlowClassifier, self).get_parser(prog_name)
276 parser.add_argument(
277 'flow_classifier',
278 metavar='<flow-classifier>',
279 help=_("Flow classifier to display (name or ID)")
280 )
281 return parser
282
283 def take_action(self, parsed_args):
284 client = self.app.client_manager.network
285 fc_id = client.find_sfc_flow_classifier(parsed_args.flow_classifier,
286 ignore_missing=False)['id']
287 obj = client.get_sfc_flow_classifier(fc_id)
288 display_columns, columns = utils.get_osc_show_columns_for_sdk_resource(
289 obj, _attr_map_dict, ['location', 'tenant_id', 'summary'])
290 data = utils.get_dict_properties(obj, columns)
291 return display_columns, data
292
293
294 def _get_common_attrs(client_manager, parsed_args, is_create=True):
295 attrs = {}
296 if parsed_args.name is not None:
297 attrs['name'] = parsed_args.name
298 if parsed_args.description is not None:
299 attrs['description'] = parsed_args.description
300 if is_create:
301 _get_attrs(client_manager, attrs, parsed_args)
302 return attrs
303
304
305 def _get_attrs(client_manager, attrs, parsed_args):
306 if parsed_args.protocol is not None:
307 attrs['protocol'] = parsed_args.protocol
308 if parsed_args.ethertype:
309 attrs['ethertype'] = parsed_args.ethertype
310 if parsed_args.source_ip_prefix is not None:
311 attrs['source_ip_prefix'] = parsed_args.source_ip_prefix
312 if parsed_args.destination_ip_prefix is not None:
313 attrs['destination_ip_prefix'] = parsed_args.destination_ip_prefix
314 if parsed_args.logical_source_port is not None:
315 attrs['logical_source_port'] = client_manager.network.find_port(
316 parsed_args.logical_source_port, ignore_missing=False
317 )['id']
318 if parsed_args.logical_destination_port is not None:
319 attrs['logical_destination_port'] = client_manager.network.find_port(
320 parsed_args.logical_destination_port, ignore_missing=False
321 )['id']
322 if parsed_args.source_port is not None:
323 _fill_protocol_port_info(attrs, 'source',
324 parsed_args.source_port)
325 if parsed_args.destination_port is not None:
326 _fill_protocol_port_info(attrs, 'destination',
327 parsed_args.destination_port)
328 if parsed_args.l7_parameters is not None:
329 attrs['l7_parameters'] = parsed_args.l7_parameters
330
331
332 def _fill_protocol_port_info(attrs, port_type, port_val):
333 min_port, sep, max_port = port_val.partition(":")
334 if not min_port:
335 msg = ("Invalid port value '%s', expected format is "
336 "min-port:max-port or min-port.")
337 raise argparse.ArgumentTypeError(msg % port_val)
338 if not max_port:
339 max_port = min_port
340 try:
341 attrs[port_type + '_port_range_min'] = int(min_port)
342 attrs[port_type + '_port_range_max'] = int(max_port)
343 except ValueError:
344 message = (_("Protocol port value %s must be an integer "
345 "or integer:integer.") % port_val)
346 raise nc_exc.CommandError(message=message)