| 1 |
# Copyright 2014 NEC Corporation |
| 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 netaddr |
| 17 |
|
| 18 |
from neutronclient._i18n import _ |
| 19 |
from neutronclient.common import exceptions |
| 20 |
|
| 21 |
|
| 22 |
def validate_int_range(parsed_args, attr_name, min_value=None, max_value=None): |
| 23 |
val = getattr(parsed_args, attr_name, None) |
| 24 |
if val is None: |
| 25 |
return |
| 26 |
try: |
| 27 |
if not isinstance(val, int): |
| 28 |
int_val = int(val, 0) |
| 29 |
else: |
| 30 |
int_val = val |
| 31 |
if ((min_value is None or min_value <= int_val) and |
| 32 |
(max_value is None or int_val <= max_value)): |
| 33 |
return |
| 34 |
except (ValueError, TypeError): |
| 35 |
pass |
| 36 |
|
| 37 |
if min_value is not None and max_value is not None: |
| 38 |
msg = (_('%(attr_name)s "%(val)s" should be an integer ' |
| 39 |
'[%(min)i:%(max)i].') % |
| 40 |
{'attr_name': attr_name.replace('_', '-'), |
| 41 |
'val': val, 'min': min_value, 'max': max_value}) |
| 42 |
elif min_value is not None: |
| 43 |
msg = (_('%(attr_name)s "%(val)s" should be an integer ' |
| 44 |
'greater than or equal to %(min)i.') % |
| 45 |
{'attr_name': attr_name.replace('_', '-'), |
| 46 |
'val': val, 'min': min_value}) |
| 47 |
elif max_value is not None: |
| 48 |
msg = (_('%(attr_name)s "%(val)s" should be an integer ' |
| 49 |
'smaller than or equal to %(max)i.') % |
| 50 |
{'attr_name': attr_name.replace('_', '-'), |
| 51 |
'val': val, 'max': max_value}) |
| 52 |
else: |
| 53 |
msg = (_('%(attr_name)s "%(val)s" should be an integer.') % |
| 54 |
{'attr_name': attr_name.replace('_', '-'), |
| 55 |
'val': val}) |
| 56 |
|
| 57 |
raise exceptions.CommandError(msg) |
| 58 |
|
| 59 |
|
| 60 |
def validate_ip_subnet(parsed_args, attr_name): |
| 61 |
val = getattr(parsed_args, attr_name) |
| 62 |
if not val: |
| 63 |
return |
| 64 |
try: |
| 65 |
netaddr.IPNetwork(val) |
| 66 |
except (netaddr.AddrFormatError, ValueError): |
| 67 |
raise exceptions.CommandError( |
| 68 |
(_('%(attr_name)s "%(val)s" is not a valid CIDR.') % |
| 69 |
{'attr_name': attr_name.replace('_', '-'), 'val': val})) |