| 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 |
|
| 24 |
|
| 25 |
def _get_remote(rule): |
| 26 |
if rule['remote_ip_prefix']: |
| 27 |
remote = '%s (CIDR)' % rule['remote_ip_prefix'] |
| 28 |
elif rule['remote_group_id']: |
| 29 |
remote = '%s (group)' % rule['remote_group_id'] |
| 30 |
else: |
| 31 |
remote = None |
| 32 |
return remote |
| 33 |
|
| 34 |
|
| 35 |
def _get_protocol_port(rule): |
| 36 |
proto = rule['protocol'] |
| 37 |
port_min = rule['port_range_min'] |
| 38 |
port_max = rule['port_range_max'] |
| 39 |
if proto in ('tcp', 'udp'): |
| 40 |
if (port_min and port_min == port_max): |
| 41 |
protocol_port = '%s/%s' % (port_min, proto) |
| 42 |
elif port_min: |
| 43 |
protocol_port = '%s-%s/%s' % (port_min, port_max, proto) |
| 44 |
else: |
| 45 |
protocol_port = proto |
| 46 |
elif proto == 'icmp': |
| 47 |
icmp_opts = [] |
| 48 |
if port_min is not None: |
| 49 |
icmp_opts.append('type:%s' % port_min) |
| 50 |
if port_max is not None: |
| 51 |
icmp_opts.append('code:%s' % port_max) |
| 52 |
|
| 53 |
if icmp_opts: |
| 54 |
protocol_port = 'icmp (%s)' % ', '.join(icmp_opts) |
| 55 |
else: |
| 56 |
protocol_port = 'icmp' |
| 57 |
elif proto is not None: |
| 58 |
# port_range_min/max are not recognized for protocol |
| 59 |
# other than TCP, UDP and ICMP. |
| 60 |
protocol_port = proto |
| 61 |
else: |
| 62 |
protocol_port = None |
| 63 |
|
| 64 |
return protocol_port |
| 65 |
|
| 66 |
|
| 67 |
def _format_sg_rule(rule): |
| 68 |
formatted = [] |
| 69 |
for field in ['direction', |
| 70 |
'ethertype', |
| 71 |
('protocol_port', _get_protocol_port), |
| 72 |
'remote_ip_prefix', |
| 73 |
'remote_group_id']: |
| 74 |
if isinstance(field, tuple): |
| 75 |
field, get_method = field |
| 76 |
data = get_method(rule) |
| 77 |
else: |
| 78 |
data = rule[field] |
| 79 |
if not data: |
| 80 |
continue |
| 81 |
if field in ('remote_ip_prefix', 'remote_group_id'): |
| 82 |
data = '%s: %s' % (field, data) |
| 83 |
formatted.append(data) |
| 84 |
return ', '.join(formatted) |
| 85 |
|
| 86 |
|
| 87 |
def _format_sg_rules(secgroup): |
| 88 |
try: |
| 89 |
return '\n'.join(sorted([_format_sg_rule(rule) for rule |
| 90 |
in secgroup['security_group_rules']])) |
| 91 |
except Exception: |
| 92 |
return '' |
| 93 |
|
| 94 |
|
| 95 |
def generate_default_ethertype(protocol): |
| 96 |
if protocol == 'icmpv6': |
| 97 |
return 'IPv6' |
| 98 |
return 'IPv4' |
| 99 |
|
| 100 |
|
| 101 |
class ListSecurityGroup(neutronV20.ListCommand): |
| 102 |
"""List security groups that belong to a given tenant.""" |
| 103 |
|
| 104 |
resource = 'security_group' |
| 105 |
list_columns = ['id', 'name', 'security_group_rules'] |
| 106 |
_formatters = {'security_group_rules': _format_sg_rules} |
| 107 |
pagination_support = True |
| 108 |
sorting_support = True |
| 109 |
|
| 110 |
|
| 111 |
class ShowSecurityGroup(neutronV20.ShowCommand): |
| 112 |
"""Show information of a given security group.""" |
| 113 |
|
| 114 |
resource = 'security_group' |
| 115 |
allow_names = True |
| 116 |
json_indent = 5 |
| 117 |
|
| 118 |
|
| 119 |
class CreateSecurityGroup(neutronV20.CreateCommand): |
| 120 |
"""Create a security group.""" |
| 121 |
|
| 122 |
resource = 'security_group' |
| 123 |
|
| 124 |
def add_known_arguments(self, parser): |
| 125 |
parser.add_argument( |
| 126 |
'name', metavar='NAME', |
| 127 |
help=_('Name of the security group to be created.')) |
| 128 |
parser.add_argument( |
| 129 |
'--description', |
| 130 |
help=_('Description of the security group to be created.')) |
| 131 |
|
| 132 |
def args2body(self, parsed_args): |
| 133 |
body = {'name': parsed_args.name} |
| 134 |
neutronV20.update_dict(parsed_args, body, |
| 135 |
['description', 'tenant_id']) |
| 136 |
return {'security_group': body} |
| 137 |
|
| 138 |
|
| 139 |
class DeleteSecurityGroup(neutronV20.DeleteCommand): |
| 140 |
"""Delete a given security group.""" |
| 141 |
|
| 142 |
resource = 'security_group' |
| 143 |
allow_names = True |
| 144 |
|
| 145 |
|
| 146 |
class UpdateSecurityGroup(neutronV20.UpdateCommand): |
| 147 |
"""Update a given security group.""" |
| 148 |
|
| 149 |
resource = 'security_group' |
| 150 |
|
| 151 |
def add_known_arguments(self, parser): |
| 152 |
parser.add_argument( |
| 153 |
'--name', |
| 154 |
help=_('Updated name of the security group.')) |
| 155 |
parser.add_argument( |
| 156 |
'--description', |
| 157 |
help=_('Updated description of the security group.')) |
| 158 |
|
| 159 |
def args2body(self, parsed_args): |
| 160 |
body = {} |
| 161 |
neutronV20.update_dict(parsed_args, body, |
| 162 |
['name', 'description']) |
| 163 |
return {'security_group': body} |
| 164 |
|
| 165 |
|
| 166 |
class ListSecurityGroupRule(neutronV20.ListCommand): |
| 167 |
"""List security group rules that belong to a given tenant.""" |
| 168 |
|
| 169 |
resource = 'security_group_rule' |
| 170 |
list_columns = ['id', 'security_group_id', 'direction', |
| 171 |
'ethertype', 'port/protocol', 'remote'] |
| 172 |
# replace_rules: key is an attribute name in Neutron API and |
| 173 |
# corresponding value is a display name shown by CLI. |
| 174 |
replace_rules = {'security_group_id': 'security_group', |
| 175 |
'remote_group_id': 'remote_group'} |
| 176 |
digest_fields = { |
| 177 |
# The entry 'protocol/port' is left deliberately for backwards |
| 178 |
# compatibility. |
| 179 |
'remote': { |
| 180 |
'method': _get_remote, |
| 181 |
'depends_on': ['remote_ip_prefix', 'remote_group_id']}, |
| 182 |
'port/protocol': { |
| 183 |
'method': _get_protocol_port, |
| 184 |
'depends_on': ['protocol', 'port_range_min', 'port_range_max']}, |
| 185 |
'protocol/port': { |
| 186 |
'method': _get_protocol_port, |
| 187 |
'depends_on': ['protocol', 'port_range_min', 'port_range_max']}} |
| 188 |
pagination_support = True |
| 189 |
sorting_support = True |
| 190 |
|
| 191 |
def get_parser(self, prog_name): |
| 192 |
parser = super(ListSecurityGroupRule, self).get_parser(prog_name) |
| 193 |
parser.add_argument( |
| 194 |
'--no-nameconv', action='store_true', |
| 195 |
help=_('Do not convert security group ID to its name.')) |
| 196 |
return parser |
| 197 |
|
| 198 |
@staticmethod |
| 199 |
def replace_columns(cols, rules, reverse=False): |
| 200 |
if reverse: |
| 201 |
rules = dict((rules[k], k) for k in rules.keys()) |
| 202 |
return [rules.get(col, col) for col in cols] |
| 203 |
|
| 204 |
def get_required_fields(self, fields): |
| 205 |
fields = self.replace_columns(fields, self.replace_rules, reverse=True) |
| 206 |
for field, digest_fields in self.digest_fields.items(): |
| 207 |
if field in fields: |
| 208 |
fields += digest_fields['depends_on'] |
| 209 |
fields.remove(field) |
| 210 |
return fields |
| 211 |
|
| 212 |
def retrieve_list(self, parsed_args): |
| 213 |
parsed_args.fields = self.get_required_fields(parsed_args.fields) |
| 214 |
return super(ListSecurityGroupRule, self).retrieve_list(parsed_args) |
| 215 |
|
| 216 |
def _get_sg_name_dict(self, data, page_size, no_nameconv): |
| 217 |
"""Get names of security groups referred in the retrieved rules. |
| 218 |
|
| 219 |
:return: a dict from secgroup ID to secgroup name |
| 220 |
""" |
| 221 |
if no_nameconv: |
| 222 |
return {} |
| 223 |
neutron_client = self.get_client() |
| 224 |
search_opts = {'fields': ['id', 'name']} |
| 225 |
if self.pagination_support: |
| 226 |
if page_size: |
| 227 |
search_opts.update({'limit': page_size}) |
| 228 |
sec_group_ids = set() |
| 229 |
for rule in data: |
| 230 |
for key in self.replace_rules: |
| 231 |
if rule.get(key): |
| 232 |
sec_group_ids.add(rule[key]) |
| 233 |
sec_group_ids = list(sec_group_ids) |
| 234 |
|
| 235 |
def _get_sec_group_list(sec_group_ids): |
| 236 |
search_opts['id'] = sec_group_ids |
| 237 |
return neutron_client.list_security_groups( |
| 238 |
**search_opts).get('security_groups', []) |
| 239 |
|
| 240 |
try: |
| 241 |
secgroups = _get_sec_group_list(sec_group_ids) |
| 242 |
except exceptions.RequestURITooLong as uri_len_exc: |
| 243 |
# Length of a query filter on security group rule id |
| 244 |
# id=<uuid>& (with len(uuid)=36) |
| 245 |
sec_group_id_filter_len = 40 |
| 246 |
# The URI is too long because of too many sec_group_id filters |
| 247 |
# Use the excess attribute of the exception to know how many |
| 248 |
# sec_group_id filters can be inserted into a single request |
| 249 |
sec_group_count = len(sec_group_ids) |
| 250 |
max_size = ((sec_group_id_filter_len * sec_group_count) - |
| 251 |
uri_len_exc.excess) |
| 252 |
chunk_size = max_size // sec_group_id_filter_len |
| 253 |
secgroups = [] |
| 254 |
for i in range(0, sec_group_count, chunk_size): |
| 255 |
secgroups.extend( |
| 256 |
_get_sec_group_list(sec_group_ids[i: i + chunk_size])) |
| 257 |
|
| 258 |
return dict([(sg['id'], sg['name']) |
| 259 |
for sg in secgroups if sg['name']]) |
| 260 |
|
| 261 |
@staticmethod |
| 262 |
def _has_fields(rule, required_fields): |
| 263 |
return all([key in rule for key in required_fields]) |
| 264 |
|
| 265 |
def extend_list(self, data, parsed_args): |
| 266 |
sg_dict = self._get_sg_name_dict(data, parsed_args.page_size, |
| 267 |
parsed_args.no_nameconv) |
| 268 |
for rule in data: |
| 269 |
# Replace security group UUID with its name. |
| 270 |
for key in self.replace_rules: |
| 271 |
if key in rule: |
| 272 |
rule[key] = sg_dict.get(rule[key], rule[key]) |
| 273 |
for field, digest_rule in self.digest_fields.items(): |
| 274 |
if self._has_fields(rule, digest_rule['depends_on']): |
| 275 |
rule[field] = digest_rule['method'](rule) or 'any' |
| 276 |
|
| 277 |
def setup_columns(self, info, parsed_args): |
| 278 |
# Translate the specified columns from the command line |
| 279 |
# into field names used in "info". |
| 280 |
parsed_args.columns = self.replace_columns(parsed_args.columns, |
| 281 |
self.replace_rules, |
| 282 |
reverse=True) |
| 283 |
# NOTE(amotoki): 2nd element of the tuple returned by setup_columns() |
| 284 |
# is a generator, so if you need to create a look using the generator |
| 285 |
# object, you need to recreate a generator to show a list expectedly. |
| 286 |
info = super(ListSecurityGroupRule, self).setup_columns(info, |
| 287 |
parsed_args) |
| 288 |
cols = info[0] |
| 289 |
if not parsed_args.no_nameconv: |
| 290 |
# Replace column names in the header line (in info[0]) |
| 291 |
cols = self.replace_columns(info[0], self.replace_rules) |
| 292 |
parsed_args.columns = cols |
| 293 |
return (cols, info[1]) |
| 294 |
|
| 295 |
|
| 296 |
class ShowSecurityGroupRule(neutronV20.ShowCommand): |
| 297 |
"""Show information of a given security group rule.""" |
| 298 |
|
| 299 |
resource = 'security_group_rule' |
| 300 |
allow_names = False |
| 301 |
|
| 302 |
|
| 303 |
class CreateSecurityGroupRule(neutronV20.CreateCommand): |
| 304 |
"""Create a security group rule.""" |
| 305 |
|
| 306 |
resource = 'security_group_rule' |
| 307 |
|
| 308 |
def add_known_arguments(self, parser): |
| 309 |
parser.add_argument( |
| 310 |
'--description', |
| 311 |
help=_('Description of security group rule.')) |
| 312 |
parser.add_argument( |
| 313 |
'security_group_id', metavar='SECURITY_GROUP', |
| 314 |
help=_('ID or name of the security group to ' |
| 315 |
'which the rule is added.')) |
| 316 |
parser.add_argument( |
| 317 |
'--direction', |
| 318 |
type=utils.convert_to_lowercase, |
| 319 |
default='ingress', choices=['ingress', 'egress'], |
| 320 |
help=_('Direction of traffic: ingress/egress.')) |
| 321 |
parser.add_argument( |
| 322 |
'--ethertype', |
| 323 |
help=_('IPv4/IPv6')) |
| 324 |
parser.add_argument( |
| 325 |
'--protocol', |
| 326 |
type=utils.convert_to_lowercase, |
| 327 |
help=_('Protocol of packet. Allowed values are ' |
| 328 |
'[icmp, icmpv6, tcp, udp] and ' |
| 329 |
'integer representations [0-255].')) |
| 330 |
parser.add_argument( |
| 331 |
'--port-range-min', |
| 332 |
help=_('Starting port range. For ICMP it is type.')) |
| 333 |
parser.add_argument( |
| 334 |
'--port_range_min', |
| 335 |
help=argparse.SUPPRESS) |
| 336 |
parser.add_argument( |
| 337 |
'--port-range-max', |
| 338 |
help=_('Ending port range. For ICMP it is code.')) |
| 339 |
parser.add_argument( |
| 340 |
'--port_range_max', |
| 341 |
help=argparse.SUPPRESS) |
| 342 |
parser.add_argument( |
| 343 |
'--remote-ip-prefix', |
| 344 |
help=_('CIDR to match on.')) |
| 345 |
parser.add_argument( |
| 346 |
'--remote_ip_prefix', |
| 347 |
help=argparse.SUPPRESS) |
| 348 |
parser.add_argument( |
| 349 |
'--remote-group-id', metavar='REMOTE_GROUP', |
| 350 |
help=_('ID or name of the remote security group ' |
| 351 |
'to which the rule is applied.')) |
| 352 |
parser.add_argument( |
| 353 |
'--remote_group_id', |
| 354 |
help=argparse.SUPPRESS) |
| 355 |
|
| 356 |
def args2body(self, parsed_args): |
| 357 |
_security_group_id = neutronV20.find_resourceid_by_name_or_id( |
| 358 |
self.get_client(), 'security_group', parsed_args.security_group_id) |
| 359 |
body = {'security_group_id': _security_group_id, |
| 360 |
'direction': parsed_args.direction, |
| 361 |
'ethertype': parsed_args.ethertype or |
| 362 |
generate_default_ethertype(parsed_args.protocol)} |
| 363 |
neutronV20.update_dict(parsed_args, body, |
| 364 |
['protocol', 'port_range_min', 'port_range_max', |
| 365 |
'remote_ip_prefix', 'tenant_id', |
| 366 |
'description']) |
| 367 |
if parsed_args.remote_group_id: |
| 368 |
_remote_group_id = neutronV20.find_resourceid_by_name_or_id( |
| 369 |
self.get_client(), 'security_group', |
| 370 |
parsed_args.remote_group_id) |
| 371 |
body['remote_group_id'] = _remote_group_id |
| 372 |
return {'security_group_rule': body} |
| 373 |
|
| 374 |
|
| 375 |
class DeleteSecurityGroupRule(neutronV20.DeleteCommand): |
| 376 |
"""Delete a given security group rule.""" |
| 377 |
|
| 378 |
resource = 'security_group_rule' |
| 379 |
allow_names = False |