diff options
Diffstat (limited to 'quantumclient/quantum')
| -rw-r--r-- | quantumclient/quantum/client.py | 64 | ||||
| -rw-r--r-- | quantumclient/quantum/v2_0/__init__.py | 574 | ||||
| -rw-r--r-- | quantumclient/quantum/v2_0/agent.py | 65 | ||||
| -rw-r--r-- | quantumclient/quantum/v2_0/agentscheduler.py | 234 | ||||
| -rw-r--r-- | quantumclient/quantum/v2_0/extension.py | 44 | ||||
| -rw-r--r-- | quantumclient/quantum/v2_0/floatingip.py | 151 | ||||
| -rw-r--r-- | quantumclient/quantum/v2_0/lb/__init__.py | 16 | ||||
| -rw-r--r-- | quantumclient/quantum/v2_0/lb/healthmonitor.py | 174 | ||||
| -rw-r--r-- | quantumclient/quantum/v2_0/lb/member.py | 99 | ||||
| -rw-r--r-- | quantumclient/quantum/v2_0/lb/pool.py | 124 | ||||
| -rw-r--r-- | quantumclient/quantum/v2_0/lb/vip.py | 115 | ||||
| -rw-r--r-- | quantumclient/quantum/v2_0/network.py | 152 | ||||
| -rw-r--r-- | quantumclient/quantum/v2_0/nvp_qos_queue.py | 89 | ||||
| -rw-r--r-- | quantumclient/quantum/v2_0/nvpnetworkgateway.py | 159 | ||||
| -rw-r--r-- | quantumclient/quantum/v2_0/port.py | 170 | ||||
| -rw-r--r-- | quantumclient/quantum/v2_0/quota.py | 232 | ||||
| -rw-r--r-- | quantumclient/quantum/v2_0/router.py | 230 | ||||
| -rw-r--r-- | quantumclient/quantum/v2_0/securitygroup.py | 259 | ||||
| -rw-r--r-- | quantumclient/quantum/v2_0/subnet.py | 168 |
19 files changed, 5 insertions, 3114 deletions
diff --git a/quantumclient/quantum/client.py b/quantumclient/quantum/client.py deleted file mode 100644 index 1661a63..0000000 --- a/quantumclient/quantum/client.py +++ /dev/null @@ -1,64 +0,0 @@ -# Copyright 2012 OpenStack LLC. -# All Rights Reserved -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. -# -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - -from quantumclient.common import exceptions -from quantumclient.common import utils - - -API_NAME = 'network' -API_VERSIONS = { - '2.0': 'quantumclient.v2_0.client.Client', -} - - -def make_client(instance): - """Returns an quantum client. - """ - quantum_client = utils.get_client_class( - API_NAME, - instance._api_version[API_NAME], - API_VERSIONS, - ) - instance.initialize() - url = instance._url - url = url.rstrip("/") - if '2.0' == instance._api_version[API_NAME]: - client = quantum_client(username=instance._username, - tenant_name=instance._tenant_name, - password=instance._password, - region_name=instance._region_name, - auth_url=instance._auth_url, - endpoint_url=url, - token=instance._token, - auth_strategy=instance._auth_strategy, - insecure=instance._insecure) - return client - else: - raise exceptions.UnsupportedVersion("API version %s is not supported" % - instance._api_version[API_NAME]) - - -def Client(api_version, *args, **kwargs): - """Return an quantum client. - @param api_version: only 2.0 is supported now - """ - quantum_client = utils.get_client_class( - API_NAME, - api_version, - API_VERSIONS, - ) - return quantum_client(*args, **kwargs) diff --git a/quantumclient/quantum/v2_0/__init__.py b/quantumclient/quantum/v2_0/__init__.py index 1be1d29..38e43ab 100644 --- a/quantumclient/quantum/v2_0/__init__.py +++ b/quantumclient/quantum/v2_0/__init__.py @@ -1,4 +1,4 @@ -# Copyright 2012 OpenStack LLC. +# Copyright 2013 OpenStack Foundation. # All Rights Reserved # # Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -15,574 +15,6 @@ # # vim: tabstop=4 shiftwidth=4 softtabstop=4 -import argparse -import logging -import re +from neutronclient.neutron.v2_0 import NeutronCommand -from cliff.formatters import table -from cliff import lister -from cliff import show - -from quantumclient.common import command -from quantumclient.common import exceptions -from quantumclient.common import utils -from quantumclient.openstack.common.gettextutils import _ - -HEX_ELEM = '[0-9A-Fa-f]' -UUID_PATTERN = '-'.join([HEX_ELEM + '{8}', HEX_ELEM + '{4}', - HEX_ELEM + '{4}', HEX_ELEM + '{4}', - HEX_ELEM + '{12}']) - - -def find_resourceid_by_name_or_id(client, resource, name_or_id): - obj_lister = getattr(client, "list_%ss" % resource) - # perform search by id only if we are passing a valid UUID - match = re.match(UUID_PATTERN, name_or_id) - collection = resource + "s" - if match: - data = obj_lister(id=name_or_id, fields='id') - if data and data[collection]: - return data[collection][0]['id'] - return _find_resourceid_by_name(client, resource, name_or_id) - - -def _find_resourceid_by_name(client, resource, name): - obj_lister = getattr(client, "list_%ss" % resource) - data = obj_lister(name=name, fields='id') - collection = resource + "s" - info = data[collection] - if len(info) > 1: - msg = (_("Multiple %(resource)s matches found for name '%(name)s'," - " use an ID to be more specific.") % - {'resource': resource, 'name': name}) - raise exceptions.QuantumClientException( - message=msg) - elif len(info) == 0: - not_found_message = (_("Unable to find %(resource)s with name " - "'%(name)s'") % - {'resource': resource, 'name': name}) - # 404 is used to simulate server side behavior - raise exceptions.QuantumClientException( - message=not_found_message, status_code=404) - else: - return info[0]['id'] - - -def add_show_list_common_argument(parser): - parser.add_argument( - '-D', '--show-details', - help='show detailed info', - action='store_true', - default=False, ) - parser.add_argument( - '--show_details', - action='store_true', - help=argparse.SUPPRESS) - parser.add_argument( - '--fields', - help=argparse.SUPPRESS, - action='append', - default=[]) - parser.add_argument( - '-F', '--field', - dest='fields', metavar='FIELD', - help='specify the field(s) to be returned by server,' - ' can be repeated', - action='append', - default=[]) - - -def add_pagination_argument(parser): - parser.add_argument( - '-P', '--page-size', - dest='page_size', metavar='SIZE', type=int, - help=("specify retrieve unit of each request, then split one request " - "to several requests"), - default=None) - - -def add_sorting_argument(parser): - parser.add_argument( - '--sort-key', - dest='sort_key', metavar='FIELD', - action='append', - help=("sort list by specified fields (This option can be repeated), " - "The number of sort_dir and sort_key should match each other, " - "more sort_dir specified will be omitted, less will be filled " - "with asc as default direction "), - default=[]) - parser.add_argument( - '--sort-dir', - dest='sort_dir', metavar='{asc,desc}', - help=("sort list in specified directions " - "(This option can be repeated)"), - action='append', - default=[], - choices=['asc', 'desc']) - - -def is_number(s): - try: - float(s) # for int, long and float - except ValueError: - try: - complex(s) # for complex - except ValueError: - return False - - return True - - -def parse_args_to_dict(values_specs): - '''It is used to analyze the extra command options to command. - - Besides known options and arguments, our commands also support user to - put more options to the end of command line. For example, - list_nets -- --tag x y --key1 value1, where '-- --tag x y --key1 value1' - is extra options to our list_nets. This feature can support V2.0 API's - fields selection and filters. For example, to list networks which has name - 'test4', we can have list_nets -- --name=test4. - - value spec is: --key type=int|bool|... value. Type is one of Python - built-in types. By default, type is string. The key without value is - a bool option. Key with two values will be a list option. - - ''' - # -- is a pseudo argument - values_specs_copy = values_specs[:] - if values_specs_copy and values_specs_copy[0] == '--': - del values_specs_copy[0] - _options = {} - current_arg = None - _values_specs = [] - _value_number = 0 - _list_flag = False - current_item = None - for _item in values_specs_copy: - if _item.startswith('--'): - if current_arg is not None: - if _value_number > 1 or _list_flag: - current_arg.update({'nargs': '+'}) - elif _value_number == 0: - current_arg.update({'action': 'store_true'}) - _temp = _item - if "=" in _item: - _item = _item.split('=')[0] - if _item in _options: - raise exceptions.CommandError( - "duplicated options %s" % ' '.join(values_specs)) - else: - _options.update({_item: {}}) - current_arg = _options[_item] - _item = _temp - elif _item.startswith('type='): - if current_arg is None: - raise exceptions.CommandError( - "invalid values_specs %s" % ' '.join(values_specs)) - if 'type' not in current_arg: - _type_str = _item.split('=', 2)[1] - current_arg.update({'type': eval(_type_str)}) - if _type_str == 'bool': - current_arg.update({'type': utils.str2bool}) - elif _type_str == 'dict': - current_arg.update({'type': utils.str2dict}) - continue - elif _item == 'list=true': - _list_flag = True - continue - if not _item.startswith('--'): - if (not current_item or '=' in current_item or - _item.startswith('-') and not is_number(_item)): - raise exceptions.CommandError( - "Invalid values_specs %s" % ' '.join(values_specs)) - _value_number += 1 - elif _item.startswith('--'): - current_item = _item - if '=' in current_item: - _value_number = 1 - else: - _value_number = 0 - _list_flag = False - _values_specs.append(_item) - if current_arg is not None: - if _value_number > 1 or _list_flag: - current_arg.update({'nargs': '+'}) - elif _value_number == 0: - current_arg.update({'action': 'store_true'}) - _args = None - if _values_specs: - _parser = argparse.ArgumentParser(add_help=False) - for opt, optspec in _options.iteritems(): - _parser.add_argument(opt, **optspec) - _args = _parser.parse_args(_values_specs) - result_dict = {} - if _args: - for opt in _options.iterkeys(): - _opt = opt.split('--', 2)[1] - _opt = _opt.replace('-', '_') - _value = getattr(_args, _opt) - if _value is not None: - result_dict.update({_opt: _value}) - return result_dict - - -def _merge_args(qCmd, parsed_args, _extra_values, value_specs): - """Merge arguments from _extra_values into parsed_args. - - If an argument value are provided in both and it is a list, - the values in _extra_values will be merged into parsed_args. - - @param parsed_args: the parsed args from known options - @param _extra_values: the other parsed arguments in unknown parts - @param values_specs: the unparsed unknown parts - """ - temp_values = _extra_values.copy() - for key, value in temp_values.iteritems(): - if hasattr(parsed_args, key): - arg_value = getattr(parsed_args, key) - if arg_value is not None and value is not None: - if isinstance(arg_value, list): - if value and isinstance(value, list): - if type(arg_value[0]) == type(value[0]): - arg_value.extend(value) - _extra_values.pop(key) - - -def update_dict(obj, dict, attributes): - for attribute in attributes: - if hasattr(obj, attribute) and getattr(obj, attribute): - dict[attribute] = getattr(obj, attribute) - - -class TableFormater(table.TableFormatter): - """This class is used to keep consistency with prettytable 0.6. - - https://bugs.launchpad.net/python-quantumclient/+bug/1165962 - """ - def emit_list(self, column_names, data, stdout, parsed_args): - if column_names: - super(TableFormater, self).emit_list(column_names, data, stdout, - parsed_args) - else: - stdout.write('\n') - - -class QuantumCommand(command.OpenStackCommand): - api = 'network' - log = logging.getLogger(__name__ + '.QuantumCommand') - values_specs = [] - json_indent = None - - def __init__(self, app, app_args): - super(QuantumCommand, self).__init__(app, app_args) - if hasattr(self, 'formatters'): - self.formatters['table'] = TableFormater() - - def get_client(self): - return self.app.client_manager.quantum - - def get_parser(self, prog_name): - parser = super(QuantumCommand, self).get_parser(prog_name) - parser.add_argument( - '--request-format', - help=_('the xml or json request format'), - default='json', - choices=['json', 'xml', ], ) - parser.add_argument( - '--request_format', - choices=['json', 'xml', ], - help=argparse.SUPPRESS) - - return parser - - def format_output_data(self, data): - # Modify data to make it more readable - if self.resource in data: - for k, v in data[self.resource].iteritems(): - if isinstance(v, list): - value = '\n'.join(utils.dumps( - i, indent=self.json_indent) if isinstance(i, dict) - else str(i) for i in v) - data[self.resource][k] = value - elif isinstance(v, dict): - value = utils.dumps(v, indent=self.json_indent) - data[self.resource][k] = value - elif v is None: - data[self.resource][k] = '' - - def add_known_arguments(self, parser): - pass - - def args2body(self, parsed_args): - return {} - - -class CreateCommand(QuantumCommand, show.ShowOne): - """Create a resource for a given tenant - - """ - - api = 'network' - resource = None - log = None - - def get_parser(self, prog_name): - parser = super(CreateCommand, self).get_parser(prog_name) - parser.add_argument( - '--tenant-id', metavar='TENANT_ID', - help=_('the owner tenant ID'), ) - parser.add_argument( - '--tenant_id', - help=argparse.SUPPRESS) - self.add_known_arguments(parser) - return parser - - def get_data(self, parsed_args): - self.log.debug('get_data(%s)' % parsed_args) - quantum_client = self.get_client() - quantum_client.format = parsed_args.request_format - _extra_values = parse_args_to_dict(self.values_specs) - _merge_args(self, parsed_args, _extra_values, - self.values_specs) - body = self.args2body(parsed_args) - body[self.resource].update(_extra_values) - obj_creator = getattr(quantum_client, - "create_%s" % self.resource) - data = obj_creator(body) - self.format_output_data(data) - # {u'network': {u'id': u'e9424a76-6db4-4c93-97b6-ec311cd51f19'}} - info = self.resource in data and data[self.resource] or None - if info: - print >>self.app.stdout, _('Created a new %s:') % self.resource - else: - info = {'': ''} - return zip(*sorted(info.iteritems())) - - -class UpdateCommand(QuantumCommand): - """Update resource's information - """ - - api = 'network' - resource = None - log = None - - def get_parser(self, prog_name): - parser = super(UpdateCommand, self).get_parser(prog_name) - parser.add_argument( - 'id', metavar=self.resource.upper(), - help='ID or name of %s to update' % self.resource) - self.add_known_arguments(parser) - return parser - - def run(self, parsed_args): - self.log.debug('run(%s)' % parsed_args) - quantum_client = self.get_client() - quantum_client.format = parsed_args.request_format - _extra_values = parse_args_to_dict(self.values_specs) - _merge_args(self, parsed_args, _extra_values, - self.values_specs) - body = self.args2body(parsed_args) - if self.resource in body: - body[self.resource].update(_extra_values) - else: - body[self.resource] = _extra_values - if not body[self.resource]: - raise exceptions.CommandError( - "Must specify new values to update %s" % self.resource) - _id = find_resourceid_by_name_or_id(quantum_client, - self.resource, - parsed_args.id) - obj_updator = getattr(quantum_client, - "update_%s" % self.resource) - obj_updator(_id, body) - print >>self.app.stdout, ( - _('Updated %(resource)s: %(id)s') % - {'id': parsed_args.id, 'resource': self.resource}) - return - - -class DeleteCommand(QuantumCommand): - """Delete a given resource - - """ - - api = 'network' - resource = None - log = None - allow_names = True - - def get_parser(self, prog_name): - parser = super(DeleteCommand, self).get_parser(prog_name) - if self.allow_names: - help_str = 'ID or name of %s to delete' - else: - help_str = 'ID of %s to delete' - parser.add_argument( - 'id', metavar=self.resource.upper(), - help=help_str % self.resource) - return parser - - def run(self, parsed_args): - self.log.debug('run(%s)' % parsed_args) - quantum_client = self.get_client() - quantum_client.format = parsed_args.request_format - obj_deleter = getattr(quantum_client, - "delete_%s" % self.resource) - if self.allow_names: - _id = find_resourceid_by_name_or_id(quantum_client, self.resource, - parsed_args.id) - else: - _id = parsed_args.id - obj_deleter(_id) - print >>self.app.stdout, (_('Deleted %(resource)s: %(id)s') - % {'id': parsed_args.id, - 'resource': self.resource}) - return - - -class ListCommand(QuantumCommand, lister.Lister): - """List resources that belong to a given tenant - - """ - - api = 'network' - resource = None - log = None - _formatters = {} - list_columns = [] - unknown_parts_flag = True - pagination_support = False - sorting_support = False - - def get_parser(self, prog_name): - parser = super(ListCommand, self).get_parser(prog_name) - add_show_list_common_argument(parser) - if self.pagination_support: - add_pagination_argument(parser) - if self.sorting_support: - add_sorting_argument(parser) - return parser - - def args2search_opts(self, parsed_args): - search_opts = {} - fields = parsed_args.fields - if parsed_args.fields: - search_opts.update({'fields': fields}) - if parsed_args.show_details: - search_opts.update({'verbose': 'True'}) - return search_opts - - def call_server(self, quantum_client, search_opts, parsed_args): - obj_lister = getattr(quantum_client, - "list_%ss" % self.resource) - data = obj_lister(**search_opts) - return data - - def retrieve_list(self, parsed_args): - """Retrieve a list of resources from Quantum server""" - quantum_client = self.get_client() - quantum_client.format = parsed_args.request_format - _extra_values = parse_args_to_dict(self.values_specs) - _merge_args(self, parsed_args, _extra_values, - self.values_specs) - search_opts = self.args2search_opts(parsed_args) - search_opts.update(_extra_values) - if self.pagination_support: - page_size = parsed_args.page_size - if page_size: - search_opts.update({'limit': page_size}) - if self.sorting_support: - keys = parsed_args.sort_key - if keys: - search_opts.update({'sort_key': keys}) - dirs = parsed_args.sort_dir - len_diff = len(keys) - len(dirs) - if len_diff > 0: - dirs += ['asc'] * len_diff - elif len_diff < 0: - dirs = dirs[:len(keys)] - if dirs: - search_opts.update({'sort_dir': dirs}) - data = self.call_server(quantum_client, search_opts, parsed_args) - collection = self.resource + "s" - return data.get(collection, []) - - def extend_list(self, data, parsed_args): - """Update a retrieved list. - - This method provides a way to modify a original list returned from - the quantum server. For example, you can add subnet cidr information - to a list network. - """ - pass - - def setup_columns(self, info, parsed_args): - _columns = len(info) > 0 and sorted(info[0].keys()) or [] - if not _columns: - # clean the parsed_args.columns so that cliff will not break - parsed_args.columns = [] - elif parsed_args.columns: - _columns = [x for x in parsed_args.columns if x in _columns] - elif self.list_columns: - # if no -c(s) by user and list_columns, we use columns in - # both list_columns and returned resource. - # Also Keep their order the same as in list_columns - _columns = [x for x in self.list_columns if x in _columns] - return (_columns, (utils.get_item_properties( - s, _columns, formatters=self._formatters, ) - for s in info), ) - - def get_data(self, parsed_args): - self.log.debug('get_data(%s)' % parsed_args) - data = self.retrieve_list(parsed_args) - self.extend_list(data, parsed_args) - return self.setup_columns(data, parsed_args) - - -class ShowCommand(QuantumCommand, show.ShowOne): - """Show information of a given resource - - """ - - api = 'network' - resource = None - log = None - allow_names = True - - def get_parser(self, prog_name): - parser = super(ShowCommand, self).get_parser(prog_name) - add_show_list_common_argument(parser) - if self.allow_names: - help_str = 'ID or name of %s to look up' - else: - help_str = 'ID of %s to look up' - parser.add_argument( - 'id', metavar=self.resource.upper(), - help=help_str % self.resource) - return parser - - def get_data(self, parsed_args): - self.log.debug('get_data(%s)' % parsed_args) - quantum_client = self.get_client() - quantum_client.format = parsed_args.request_format - - params = {} - if parsed_args.show_details: - params = {'verbose': 'True'} - if parsed_args.fields: - params = {'fields': parsed_args.fields} - if self.allow_names: - _id = find_resourceid_by_name_or_id(quantum_client, self.resource, - parsed_args.id) - else: - _id = parsed_args.id - - obj_shower = getattr(quantum_client, "show_%s" % self.resource) - data = obj_shower(_id, **params) - self.format_output_data(data) - resource = data[self.resource] - if self.resource in data: - return zip(*sorted(resource.iteritems())) - else: - return None +QuantumCommand = NeutronCommand diff --git a/quantumclient/quantum/v2_0/agent.py b/quantumclient/quantum/v2_0/agent.py deleted file mode 100644 index 67bf87e..0000000 --- a/quantumclient/quantum/v2_0/agent.py +++ /dev/null @@ -1,65 +0,0 @@ -# Copyright 2013 OpenStack LLC. -# All Rights Reserved -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. -# -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - -import logging - -from quantumclient.quantum import v2_0 as quantumV20 - - -def _format_timestamp(component): - try: - return component['heartbeat_timestamp'].split(".", 2)[0] - except Exception: - return '' - - -class ListAgent(quantumV20.ListCommand): - """List agents.""" - - resource = 'agent' - log = logging.getLogger(__name__ + '.ListAgent') - list_columns = ['id', 'agent_type', 'host', 'alive', 'admin_state_up'] - _formatters = {'heartbeat_timestamp': _format_timestamp} - - def extend_list(self, data, parsed_args): - for agent in data: - agent['alive'] = ":-)" if agent['alive'] else 'xxx' - - -class ShowAgent(quantumV20.ShowCommand): - """Show information of a given agent.""" - - resource = 'agent' - log = logging.getLogger(__name__ + '.ShowAgent') - allow_names = False - json_indent = 5 - - -class DeleteAgent(quantumV20.DeleteCommand): - """Delete a given agent.""" - - log = logging.getLogger(__name__ + '.DeleteAgent') - resource = 'agent' - allow_names = False - - -class UpdateAgent(quantumV20.UpdateCommand): - """Update a given agent.""" - - log = logging.getLogger(__name__ + '.UpdateAgent') - resource = 'agent' - allow_names = False diff --git a/quantumclient/quantum/v2_0/agentscheduler.py b/quantumclient/quantum/v2_0/agentscheduler.py deleted file mode 100644 index 8e41376..0000000 --- a/quantumclient/quantum/v2_0/agentscheduler.py +++ /dev/null @@ -1,234 +0,0 @@ -# Copyright 2013 OpenStack LLC. -# All Rights Reserved -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. -# -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - -import logging - -from quantumclient.openstack.common.gettextutils import _ -from quantumclient.quantum import v2_0 as quantumV20 -from quantumclient.quantum.v2_0 import network -from quantumclient.quantum.v2_0 import router -PERFECT_TIME_FORMAT = "%Y-%m-%dT%H:%M:%S.%f" - - -class AddNetworkToDhcpAgent(quantumV20.QuantumCommand): - """Add a network to a DHCP agent.""" - - log = logging.getLogger(__name__ + '.AddNetworkToDhcpAgent') - - def get_parser(self, prog_name): - parser = super(AddNetworkToDhcpAgent, self).get_parser(prog_name) - parser.add_argument( - 'dhcp_agent', - help='ID of the DHCP agent') - parser.add_argument( - 'network', - help='network to add') - return parser - - def run(self, parsed_args): - self.log.debug('run(%s)' % parsed_args) - quantum_client = self.get_client() - quantum_client.format = parsed_args.request_format - _net_id = quantumV20.find_resourceid_by_name_or_id( - quantum_client, 'network', parsed_args.network) - quantum_client.add_network_to_dhcp_agent(parsed_args.dhcp_agent, - {'network_id': _net_id}) - print >>self.app.stdout, ( - _('Added network %s to DHCP agent') % parsed_args.network) - - -class RemoveNetworkFromDhcpAgent(quantumV20.QuantumCommand): - """Remove a network from a DHCP agent.""" - log = logging.getLogger(__name__ + '.RemoveNetworkFromDhcpAgent') - - def get_parser(self, prog_name): - parser = super(RemoveNetworkFromDhcpAgent, self).get_parser(prog_name) - parser.add_argument( - 'dhcp_agent', - help='ID of the DHCP agent') - parser.add_argument( - 'network', - help='network to remove') - return parser - - def run(self, parsed_args): - self.log.debug('run(%s)' % parsed_args) - quantum_client = self.get_client() - quantum_client.format = parsed_args.request_format - _net_id = quantumV20.find_resourceid_by_name_or_id( - quantum_client, 'network', parsed_args.network) - quantum_client.remove_network_from_dhcp_agent( - parsed_args.dhcp_agent, _net_id) - print >>self.app.stdout, ( - _('Removed network %s to DHCP agent') % parsed_args.network) - - -class ListNetworksOnDhcpAgent(network.ListNetwork): - """List the networks on a DHCP agent.""" - - log = logging.getLogger(__name__ + '.ListNetworksOnDhcpAgent') - unknown_parts_flag = False - - def get_parser(self, prog_name): - parser = super(ListNetworksOnDhcpAgent, - self).get_parser(prog_name) - parser.add_argument( - 'dhcp_agent', - help='ID of the DHCP agent') - return parser - - def call_server(self, quantum_client, search_opts, parsed_args): - data = quantum_client.list_networks_on_dhcp_agent( - parsed_args.dhcp_agent, **search_opts) - return data - - -class ListDhcpAgentsHostingNetwork(quantumV20.ListCommand): - """List DHCP agents hosting a network.""" - - resource = 'agent' - _formatters = {} - log = logging.getLogger(__name__ + '.ListDhcpAgentsHostingNetwork') - list_columns = ['id', 'host', 'admin_state_up', 'alive'] - unknown_parts_flag = False - - def get_parser(self, prog_name): - parser = super(ListDhcpAgentsHostingNetwork, - self).get_parser(prog_name) - parser.add_argument( - 'network', - help='network to query') - return parser - - def extend_list(self, data, parsed_args): - for agent in data: - agent['alive'] = ":-)" if agent['alive'] else 'xxx' - - def call_server(self, quantum_client, search_opts, parsed_args): - _id = quantumV20.find_resourceid_by_name_or_id(quantum_client, - 'network', - parsed_args.network) - search_opts['network'] = _id - data = quantum_client.list_dhcp_agent_hosting_networks(**search_opts) - return data - - -class AddRouterToL3Agent(quantumV20.QuantumCommand): - """Add a router to a L3 agent.""" - - log = logging.getLogger(__name__ + '.AddRouterToL3Agent') - - def get_parser(self, prog_name): - parser = super(AddRouterToL3Agent, self).get_parser(prog_name) - parser.add_argument( - 'l3_agent', - help='ID of the L3 agent') - parser.add_argument( - 'router', - help='router to add') - return parser - - def run(self, parsed_args): - self.log.debug('run(%s)' % parsed_args) - quantum_client = self.get_client() - quantum_client.format = parsed_args.request_format - _id = quantumV20.find_resourceid_by_name_or_id( - quantum_client, 'router', parsed_args.router) - quantum_client.add_router_to_l3_agent(parsed_args.l3_agent, - {'router_id': _id}) - print >>self.app.stdout, ( - _('Added router %s to L3 agent') % parsed_args.router) - - -class RemoveRouterFromL3Agent(quantumV20.QuantumCommand): - """Remove a router from a L3 agent.""" - - log = logging.getLogger(__name__ + '.RemoveRouterFromL3Agent') - - def get_parser(self, prog_name): - parser = super(RemoveRouterFromL3Agent, self).get_parser(prog_name) - parser.add_argument( - 'l3_agent', - help='ID of the L3 agent') - parser.add_argument( - 'router', - help='router to remove') - return parser - - def run(self, parsed_args): - self.log.debug('run(%s)' % parsed_args) - quantum_client = self.get_client() - quantum_client.format = parsed_args.request_format - _id = quantumV20.find_resourceid_by_name_or_id( - quantum_client, 'router', parsed_args.router) - quantum_client.remove_router_from_l3_agent( - parsed_args.l3_agent, _id) - print >>self.app.stdout, ( - _('Removed Router %s to L3 agent') % parsed_args.router) - - -class ListRoutersOnL3Agent(quantumV20.ListCommand): - """List the routers on a L3 agent.""" - - log = logging.getLogger(__name__ + '.ListRoutersOnL3Agent') - _formatters = {'external_gateway_info': - router._format_external_gateway_info} - list_columns = ['id', 'name', 'external_gateway_info'] - resource = 'router' - unknown_parts_flag = False - - def get_parser(self, prog_name): - parser = super(ListRoutersOnL3Agent, - self).get_parser(prog_name) - parser.add_argument( - 'l3_agent', - help='ID of the L3 agent to query') - return parser - - def call_server(self, quantum_client, search_opts, parsed_args): - data = quantum_client.list_routers_on_l3_agent( - parsed_args.l3_agent, **search_opts) - return data - - -class ListL3AgentsHostingRouter(quantumV20.ListCommand): - """List L3 agents hosting a router.""" - - resource = 'agent' - _formatters = {} - log = logging.getLogger(__name__ + '.ListL3AgentsHostingRouter') - list_columns = ['id', 'host', 'admin_state_up', 'alive', 'default'] - unknown_parts_flag = False - - def get_parser(self, prog_name): - parser = super(ListL3AgentsHostingRouter, - self).get_parser(prog_name) - parser.add_argument('router', - help='router to query') - return parser - - def extend_list(self, data, parsed_args): - for agent in data: - agent['alive'] = ":-)" if agent['alive'] else 'xxx' - - def call_server(self, quantum_client, search_opts, parsed_args): - _id = quantumV20.find_resourceid_by_name_or_id(quantum_client, - 'router', - parsed_args.router) - search_opts['router'] = _id - data = quantum_client.list_l3_agent_hosting_routers(**search_opts) - return data diff --git a/quantumclient/quantum/v2_0/extension.py b/quantumclient/quantum/v2_0/extension.py deleted file mode 100644 index 1ebea6f..0000000 --- a/quantumclient/quantum/v2_0/extension.py +++ /dev/null @@ -1,44 +0,0 @@ -# Copyright 2012 OpenStack LLC. -# All Rights Reserved -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. -# -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - -import logging - -from quantumclient.quantum import v2_0 as cmd_base - - -class ListExt(cmd_base.ListCommand): - """List all extensions.""" - - resource = 'extension' - log = logging.getLogger(__name__ + '.ListExt') - list_columns = ['alias', 'name'] - - -class ShowExt(cmd_base.ShowCommand): - """Show information of a given resource.""" - - resource = "extension" - log = logging.getLogger(__name__ + '.ShowExt') - allow_names = False - - def get_parser(self, prog_name): - parser = super(cmd_base.ShowCommand, self).get_parser(prog_name) - cmd_base.add_show_list_common_argument(parser) - parser.add_argument( - 'id', metavar='EXT-ALIAS', - help='the extension alias') - return parser diff --git a/quantumclient/quantum/v2_0/floatingip.py b/quantumclient/quantum/v2_0/floatingip.py deleted file mode 100644 index 1d82444..0000000 --- a/quantumclient/quantum/v2_0/floatingip.py +++ /dev/null @@ -1,151 +0,0 @@ -# Copyright 2012 OpenStack LLC. -# All Rights Reserved -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. -# -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - -import argparse -import logging - -from quantumclient.openstack.common.gettextutils import _ -from quantumclient.quantum import v2_0 as quantumv20 - - -class ListFloatingIP(quantumv20.ListCommand): - """List floating ips that belong to a given tenant.""" - - resource = 'floatingip' - log = logging.getLogger(__name__ + '.ListFloatingIP') - list_columns = ['id', 'fixed_ip_address', 'floating_ip_address', - 'port_id'] - pagination_support = True - sorting_support = True - - -class ShowFloatingIP(quantumv20.ShowCommand): - """Show information of a given floating ip.""" - - resource = 'floatingip' - log = logging.getLogger(__name__ + '.ShowFloatingIP') - allow_names = False - - -class CreateFloatingIP(quantumv20.CreateCommand): - """Create a floating ip for a given tenant.""" - - resource = 'floatingip' - log = logging.getLogger(__name__ + '.CreateFloatingIP') - - def add_known_arguments(self, parser): - parser.add_argument( - 'floating_network_id', metavar='FLOATING_NETWORK', - help='Network name or id to allocate floating IP from') - parser.add_argument( - '--port-id', - help='ID of the port to be associated with the floatingip') - parser.add_argument( - '--port_id', - help=argparse.SUPPRESS) - parser.add_argument( - '--fixed-ip-address', - help=('IP address on the port (only required if port has multiple' - 'IPs)')) - parser.add_argument( - '--fixed_ip_address', - help=argparse.SUPPRESS) - - def args2body(self, parsed_args): - _network_id = quantumv20.find_resourceid_by_name_or_id( - self.get_client(), 'network', parsed_args.floating_network_id) - body = {self.resource: {'floating_network_id': _network_id}} - if parsed_args.port_id: - body[self.resource].update({'port_id': parsed_args.port_id}) - if parsed_args.tenant_id: - body[self.resource].update({'tenant_id': parsed_args.tenant_id}) - if parsed_args.fixed_ip_address: - body[self.resource].update({'fixed_ip_address': - parsed_args.fixed_ip_address}) - return body - - -class DeleteFloatingIP(quantumv20.DeleteCommand): - """Delete a given floating ip.""" - - log = logging.getLogger(__name__ + '.DeleteFloatingIP') - resource = 'floatingip' - allow_names = False - - -class AssociateFloatingIP(quantumv20.QuantumCommand): - """Create a mapping between a floating ip and a fixed ip.""" - - api = 'network' - log = logging.getLogger(__name__ + '.AssociateFloatingIP') - resource = 'floatingip' - - def get_parser(self, prog_name): - parser = super(AssociateFloatingIP, self).get_parser(prog_name) - parser.add_argument( - 'floatingip_id', metavar='FLOATINGIP_ID', - help='ID of the floating IP to associate') - parser.add_argument( - 'port_id', metavar='PORT', - help='ID or name of the port to be associated with the floatingip') - parser.add_argument( - '--fixed-ip-address', - help=('IP address on the port (only required if port has multiple' - 'IPs)')) - parser.add_argument( - '--fixed_ip_address', - help=argparse.SUPPRESS) - return parser - - def run(self, parsed_args): - self.log.debug('run(%s)' % parsed_args) - quantum_client = self.get_client() - quantum_client.format = parsed_args.request_format - update_dict = {} - if parsed_args.port_id: - update_dict['port_id'] = parsed_args.port_id - if parsed_args.fixed_ip_address: - update_dict['fixed_ip_address'] = parsed_args.fixed_ip_address - quantum_client.update_floatingip(parsed_args.floatingip_id, - {'floatingip': update_dict}) - print >>self.app.stdout, ( - _('Associated floatingip %s') % parsed_args.floatingip_id) - - -class DisassociateFloatingIP(quantumv20.QuantumCommand): - """Remove a mapping from a floating ip to a fixed ip. - """ - - api = 'network' - log = logging.getLogger(__name__ + '.DisassociateFloatingIP') - resource = 'floatingip' - - def get_parser(self, prog_name): - parser = super(DisassociateFloatingIP, self).get_parser(prog_name) - parser.add_argument( - 'floatingip_id', metavar='FLOATINGIP_ID', - help='ID of the floating IP to associate') - return parser - - def run(self, parsed_args): - self.log.debug('run(%s)' % parsed_args) - quantum_client = self.get_client() - quantum_client.format = parsed_args.request_format - quantum_client.update_floatingip(parsed_args.floatingip_id, - {'floatingip': {'port_id': None}}) - print >>self.app.stdout, ( - _('Disassociated floatingip %s') % parsed_args.floatingip_id) diff --git a/quantumclient/quantum/v2_0/lb/__init__.py b/quantumclient/quantum/v2_0/lb/__init__.py deleted file mode 100644 index 1668497..0000000 --- a/quantumclient/quantum/v2_0/lb/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ -# Copyright 2013 OpenStack LLC. -# All Rights Reserved -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. -# -# vim: tabstop=4 shiftwidth=4 softtabstop=4 diff --git a/quantumclient/quantum/v2_0/lb/healthmonitor.py b/quantumclient/quantum/v2_0/lb/healthmonitor.py deleted file mode 100644 index f0a828b..0000000 --- a/quantumclient/quantum/v2_0/lb/healthmonitor.py +++ /dev/null @@ -1,174 +0,0 @@ -# Copyright 2013 Mirantis Inc. -# All Rights Reserved -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. -# -# @author: Ilya Shakhat, Mirantis Inc. -# -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - -import logging - -from quantumclient.openstack.common.gettextutils import _ -from quantumclient.quantum import v2_0 as quantumv20 - - -class ListHealthMonitor(quantumv20.ListCommand): - """List healthmonitors that belong to a given tenant.""" - - resource = 'health_monitor' - log = logging.getLogger(__name__ + '.ListHealthMonitor') - list_columns = ['id', 'type', 'admin_state_up', 'status'] - pagination_support = True - sorting_support = True - - -class ShowHealthMonitor(quantumv20.ShowCommand): - """Show information of a given healthmonitor.""" - - resource = 'health_monitor' - log = logging.getLogger(__name__ + '.ShowHealthMonitor') - - -class CreateHealthMonitor(quantumv20.CreateCommand): - """Create a healthmonitor.""" - - resource = 'health_monitor' - log = logging.getLogger(__name__ + '.CreateHealthMonitor') - - def add_known_arguments(self, parser): - parser.add_argument( - '--admin-state-down', - dest='admin_state', action='store_false', - help='set admin state up to false') - parser.add_argument( - '--expected-codes', - help='the list of HTTP status codes expected in ' - 'response from the member to declare it healthy. This ' - 'attribute can contain one value, ' - 'or a list of values separated by comma, ' - 'or a range of values (e.g. "200-299"). If this attribute ' - 'is not specified, it defaults to "200". ') - parser.add_argument( - '--http-method', - help='the HTTP method used for requests by the monitor of type ' - 'HTTP.') - parser.add_argument( - '--url-path', - help='the HTTP path used in the HTTP request used by the monitor' - ' to test a member health. This must be a string ' - 'beginning with a / (forward slash)') - parser.add_argument( - '--delay', - required=True, - help='the minimum time in seconds between regular connections ' - 'of the member.') - parser.add_argument( - '--max-retries', - required=True, - help='number of permissible connection failures before changing ' - 'the member status to INACTIVE.') - parser.add_argument( - '--timeout', - required=True, - help='maximum number of seconds for a monitor to wait for a ' - 'connection to be established before it times out. The ' - 'value must be less than the delay value.') - parser.add_argument( - '--type', - required=True, - help='one of predefined health monitor types, e.g. RoundRobin') - - def args2body(self, parsed_args): - body = { - self.resource: { - 'admin_state_up': parsed_args.admin_state, - 'delay': parsed_args.delay, - 'max_retries': parsed_args.max_retries, - 'timeout': parsed_args.timeout, - 'type': parsed_args.type, - }, - } - quantumv20.update_dict(parsed_args, body[self.resource], - ['expected_codes', 'http_method', 'url_path', - 'tenant_id']) - return body - - -class UpdateHealthMonitor(quantumv20.UpdateCommand): - """Update a given healthmonitor.""" - - resource = 'health_monitor' - log = logging.getLogger(__name__ + '.UpdateHealthMonitor') - - -class DeleteHealthMonitor(quantumv20.DeleteCommand): - """Delete a given healthmonitor.""" - - resource = 'health_monitor' - log = logging.getLogger(__name__ + '.DeleteHealthMonitor') - - -class AssociateHealthMonitor(quantumv20.QuantumCommand): - """Create a mapping between a health monitor and a pool.""" - - log = logging.getLogger(__name__ + '.AssociateHealthMonitor') - resource = 'health_monitor' - - def get_parser(self, prog_name): - parser = super(AssociateHealthMonitor, self).get_parser(prog_name) - parser.add_argument( - 'health_monitor_id', - help='Health monitor to associate') - parser.add_argument( - 'pool_id', - help='ID of the pool to be associated with the health monitor') - return parser - - def run(self, parsed_args): - quantum_client = self.get_client() - quantum_client.format = parsed_args.request_format - body = {'health_monitor': {'id': parsed_args.health_monitor_id}} - pool_id = quantumv20.find_resourceid_by_name_or_id( - quantum_client, 'pool', parsed_args.pool_id) - quantum_client.associate_health_monitor(pool_id, body) - print >>self.app.stdout, (_('Associated health monitor ' - '%s') % parsed_args.health_monitor_id) - - -class DisassociateHealthMonitor(quantumv20.QuantumCommand): - """Remove a mapping from a health monitor to a pool.""" - - log = logging.getLogger(__name__ + '.DisassociateHealthMonitor') - resource = 'health_monitor' - - def get_parser(self, prog_name): - parser = super(DisassociateHealthMonitor, self).get_parser(prog_name) - parser.add_argument( - 'health_monitor_id', - help='Health monitor to associate') - parser.add_argument( - 'pool_id', - help='ID of the pool to be associated with the health monitor') - return parser - - def run(self, parsed_args): - quantum_client = self.get_client() - quantum_client.format = parsed_args.request_format - pool_id = quantumv20.find_resourceid_by_name_or_id( - quantum_client, 'pool', parsed_args.pool_id) - quantum_client.disassociate_health_monitor(pool_id, - parsed_args - .health_monitor_id) - print >>self.app.stdout, (_('Disassociated health monitor ' - '%s') % parsed_args.health_monitor_id) diff --git a/quantumclient/quantum/v2_0/lb/member.py b/quantumclient/quantum/v2_0/lb/member.py deleted file mode 100644 index 05fb430..0000000 --- a/quantumclient/quantum/v2_0/lb/member.py +++ /dev/null @@ -1,99 +0,0 @@ -# Copyright 2013 Mirantis Inc. -# All Rights Reserved -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. -# -# @author: Ilya Shakhat, Mirantis Inc. -# -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - -import logging - -from quantumclient.quantum import v2_0 as quantumv20 - - -class ListMember(quantumv20.ListCommand): - """List members that belong to a given tenant.""" - - resource = 'member' - log = logging.getLogger(__name__ + '.ListMember') - list_columns = [ - 'id', 'address', 'protocol_port', 'admin_state_up', 'status' - ] - pagination_support = True - sorting_support = True - - -class ShowMember(quantumv20.ShowCommand): - """Show information of a given member.""" - - resource = 'member' - log = logging.getLogger(__name__ + '.ShowMember') - - -class CreateMember(quantumv20.CreateCommand): - """Create a member.""" - - resource = 'member' - log = logging.getLogger(__name__ + '.CreateMember') - - def add_known_arguments(self, parser): - parser.add_argument( - 'pool_id', metavar='pool', - help='Pool id or name this vip belongs to') - parser.add_argument( - '--admin-state-down', - dest='admin_state', action='store_false', - help='set admin state up to false') - parser.add_argument( - '--weight', - help='weight of pool member in the pool') - parser.add_argument( - '--address', - required=True, - help='IP address of the pool member on the pool network. ') - parser.add_argument( - '--protocol-port', - required=True, - help='port on which the pool member listens for requests or ' - 'connections. ') - - def args2body(self, parsed_args): - _pool_id = quantumv20.find_resourceid_by_name_or_id( - self.get_client(), 'pool', parsed_args.pool_id) - body = { - self.resource: { - 'pool_id': _pool_id, - 'admin_state_up': parsed_args.admin_state, - }, - } - quantumv20.update_dict( - parsed_args, - body[self.resource], - ['address', 'protocol_port', 'weight', 'tenant_id'] - ) - return body - - -class UpdateMember(quantumv20.UpdateCommand): - """Update a given member.""" - - resource = 'member' - log = logging.getLogger(__name__ + '.UpdateMember') - - -class DeleteMember(quantumv20.DeleteCommand): - """Delete a given member.""" - - resource = 'member' - log = logging.getLogger(__name__ + '.DeleteMember') diff --git a/quantumclient/quantum/v2_0/lb/pool.py b/quantumclient/quantum/v2_0/lb/pool.py deleted file mode 100644 index 869cf7a..0000000 --- a/quantumclient/quantum/v2_0/lb/pool.py +++ /dev/null @@ -1,124 +0,0 @@ -# Copyright 2013 Mirantis Inc. -# All Rights Reserved -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. -# -# @author: Ilya Shakhat, Mirantis Inc. -# -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - -import logging - -from quantumclient.quantum import v2_0 as quantumv20 - - -class ListPool(quantumv20.ListCommand): - """List pools that belong to a given tenant.""" - - resource = 'pool' - log = logging.getLogger(__name__ + '.ListPool') - list_columns = ['id', 'name', 'lb_method', 'protocol', - 'admin_state_up', 'status'] - pagination_support = True - sorting_support = True - - -class ShowPool(quantumv20.ShowCommand): - """Show information of a given pool.""" - - resource = 'pool' - log = logging.getLogger(__name__ + '.ShowPool') - - -class CreatePool(quantumv20.CreateCommand): - """Create a pool.""" - - resource = 'pool' - log = logging.getLogger(__name__ + '.CreatePool') - - def add_known_arguments(self, parser): - parser.add_argument( - '--admin-state-down', - dest='admin_state', action='store_false', - help='set admin state up to false') - parser.add_argument( - '--description', - help='description of the pool') - parser.add_argument( - '--lb-method', - required=True, - help='the algorithm used to distribute load between the members ' - 'of the pool') - parser.add_argument( - '--name', - required=True, - help='the name of the pool') - parser.add_argument( - '--protocol', - required=True, - help='protocol for balancing') - parser.add_argument( - '--subnet-id', - required=True, - help='the subnet on which the members of the pool will be located') - - def args2body(self, parsed_args): - _subnet_id = quantumv20.find_resourceid_by_name_or_id( - self.get_client(), 'subnet', parsed_args.subnet_id) - body = { - self.resource: { - 'admin_state_up': parsed_args.admin_state, - 'subnet_id': _subnet_id, - }, - } - quantumv20.update_dict(parsed_args, body[self.resource], - ['description', 'lb_method', 'name', - 'protocol', 'tenant_id']) - return body - - -class UpdatePool(quantumv20.UpdateCommand): - """Update a given pool.""" - - resource = 'pool' - log = logging.getLogger(__name__ + '.UpdatePool') - - -class DeletePool(quantumv20.DeleteCommand): - """Delete a given pool.""" - - resource = 'pool' - log = logging.getLogger(__name__ + '.DeletePool') - - -class RetrievePoolStats(quantumv20.ShowCommand): - """Retrieve stats for a given pool.""" - - resource = 'pool' - log = logging.getLogger(__name__ + '.RetrievePoolStats') - - def get_data(self, parsed_args): - self.log.debug('run(%s)' % parsed_args) - quantum_client = self.get_client() - quantum_client.format = parsed_args.request_format - params = {} - if parsed_args.fields: - params = {'fields': parsed_args.fields} - - data = quantum_client.retrieve_pool_stats(parsed_args.id, **params) - self.format_output_data(data) - stats = data['stats'] - if 'stats' in data: - return zip(*sorted(stats.iteritems())) - else: - return None diff --git a/quantumclient/quantum/v2_0/lb/vip.py b/quantumclient/quantum/v2_0/lb/vip.py deleted file mode 100644 index ced5b20..0000000 --- a/quantumclient/quantum/v2_0/lb/vip.py +++ /dev/null @@ -1,115 +0,0 @@ -# Copyright 2013 Mirantis Inc. -# All Rights Reserved -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. -# -# @author: Ilya Shakhat, Mirantis Inc. -# -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - -import logging - -from quantumclient.quantum import v2_0 as quantumv20 - - -class ListVip(quantumv20.ListCommand): - """List vips that belong to a given tenant.""" - - resource = 'vip' - log = logging.getLogger(__name__ + '.ListVip') - list_columns = ['id', 'name', 'algorithm', 'address', 'protocol', - 'admin_state_up', 'status'] - pagination_support = True - sorting_support = True - - -class ShowVip(quantumv20.ShowCommand): - """Show information of a given vip.""" - - resource = 'vip' - log = logging.getLogger(__name__ + '.ShowVip') - - -class CreateVip(quantumv20.CreateCommand): - """Create a vip.""" - - resource = 'vip' - log = logging.getLogger(__name__ + '.CreateVip') - - def add_known_arguments(self, parser): - parser.add_argument( - 'pool_id', metavar='pool', - help='Pool id or name this vip belongs to') - parser.add_argument( - '--address', - help='IP address of the vip') - parser.add_argument( - '--admin-state-down', - dest='admin_state', action='store_false', - help='set admin state up to false') - parser.add_argument( - '--connection-limit', - help='the maximum number of connections per second allowed for ' - 'the vip') - parser.add_argument( - '--description', - help='description of the vip') - parser.add_argument( - '--name', - required=True, - help='name of the vip') - parser.add_argument( - '--protocol-port', - required=True, - help='TCP port on which to listen for client traffic that is ' - 'associated with the vip address') - parser.add_argument( - '--protocol', - required=True, - help='protocol for balancing') - parser.add_argument( - '--subnet-id', - required=True, - help='the subnet on which to allocate the vip address') - - def args2body(self, parsed_args): - _pool_id = quantumv20.find_resourceid_by_name_or_id( - self.get_client(), 'pool', parsed_args.pool_id) - _subnet_id = quantumv20.find_resourceid_by_name_or_id( - self.get_client(), 'subnet', parsed_args.subnet_id) - body = { - self.resource: { - 'pool_id': _pool_id, - 'admin_state_up': parsed_args.admin_state, - 'subnet_id': _subnet_id, - }, - } - quantumv20.update_dict(parsed_args, body[self.resource], - ['address', 'connection_limit', 'description', - 'name', 'protocol_port', 'protocol', - 'tenant_id']) - return body - - -class UpdateVip(quantumv20.UpdateCommand): - """Update a given vip.""" - - resource = 'vip' - log = logging.getLogger(__name__ + '.UpdateVip') - - -class DeleteVip(quantumv20.DeleteCommand): - """Delete a given vip.""" - - resource = 'vip' - log = logging.getLogger(__name__ + '.DeleteVip') diff --git a/quantumclient/quantum/v2_0/network.py b/quantumclient/quantum/v2_0/network.py deleted file mode 100644 index 31e621f..0000000 --- a/quantumclient/quantum/v2_0/network.py +++ /dev/null @@ -1,152 +0,0 @@ -# Copyright 2012 OpenStack LLC. -# All Rights Reserved -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. -# -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - -import argparse -import logging - -from quantumclient.common import exceptions -from quantumclient.quantum import v2_0 as quantumv20 - - -def _format_subnets(network): - try: - return '\n'.join([' '.join([s['id'], s.get('cidr', '')]) - for s in network['subnets']]) - except Exception: - return '' - - -class ListNetwork(quantumv20.ListCommand): - """List networks that belong to a given tenant.""" - - # Length of a query filter on subnet id - # id=<uuid>& (with len(uuid)=36) - subnet_id_filter_len = 40 - resource = 'network' - log = logging.getLogger(__name__ + '.ListNetwork') - _formatters = {'subnets': _format_subnets, } - list_columns = ['id', 'name', 'subnets'] - pagination_support = True - sorting_support = True - - def extend_list(self, data, parsed_args): - """Add subnet information to a network list.""" - quantum_client = self.get_client() - search_opts = {'fields': ['id', 'cidr']} - if self.pagination_support: - page_size = parsed_args.page_size - if page_size: - search_opts.update({'limit': page_size}) - subnet_ids = [] - for n in data: - if 'subnets' in n: - subnet_ids.extend(n['subnets']) - - def _get_subnet_list(sub_ids): - search_opts['id'] = sub_ids - return quantum_client.list_subnets( - **search_opts).get('subnets', []) - - try: - subnets = _get_subnet_list(subnet_ids) - except exceptions.RequestURITooLong as uri_len_exc: - # The URI is too long because of too many subnet_id filters - # Use the excess attribute of the exception to know how many - # subnet_id filters can be inserted into a single request - subnet_count = len(subnet_ids) - max_size = ((self.subnet_id_filter_len * subnet_count) - - uri_len_exc.excess) - chunk_size = max_size / self.subnet_id_filter_len - subnets = [] - for i in xrange(0, subnet_count, chunk_size): - subnets.extend( - _get_subnet_list(subnet_ids[i: i + chunk_size])) - - subnet_dict = dict([(s['id'], s) for s in subnets]) - for n in data: - if 'subnets' in n: - n['subnets'] = [(subnet_dict.get(s) or {"id": s}) - for s in n['subnets']] - - -class ListExternalNetwork(ListNetwork): - """List external networks that belong to a given tenant.""" - - log = logging.getLogger(__name__ + '.ListExternalNetwork') - pagination_support = True - sorting_support = True - - def retrieve_list(self, parsed_args): - external = '--router:external=True' - if external not in self.values_specs: - self.values_specs.append('--router:external=True') - return super(ListExternalNetwork, self).retrieve_list(parsed_args) - - -class ShowNetwork(quantumv20.ShowCommand): - """Show information of a given network.""" - - resource = 'network' - log = logging.getLogger(__name__ + '.ShowNetwork') - - -class CreateNetwork(quantumv20.CreateCommand): - """Create a network for a given tenant.""" - - resource = 'network' - log = logging.getLogger(__name__ + '.CreateNetwork') - - def add_known_arguments(self, parser): - parser.add_argument( - '--admin-state-down', - dest='admin_state', action='store_false', - help='Set Admin State Up to false') - parser.add_argument( - '--admin_state_down', - dest='admin_state', action='store_false', - help=argparse.SUPPRESS) - parser.add_argument( - '--shared', - action='store_true', - help='Set the network as shared') - parser.add_argument( - 'name', metavar='NAME', - help='Name of network to create') - - def args2body(self, parsed_args): - body = {'network': { - 'name': parsed_args.name, - 'admin_state_up': parsed_args.admin_state}, } - if parsed_args.tenant_id: - body['network'].update({'tenant_id': parsed_args.tenant_id}) - if parsed_args.shared: - body['network'].update({'shared': parsed_args.shared}) - return body - - -class DeleteNetwork(quantumv20.DeleteCommand): - """Delete a given network.""" - - log = logging.getLogger(__name__ + '.DeleteNetwork') - resource = 'network' - - -class UpdateNetwork(quantumv20.UpdateCommand): - """Update network's information.""" - - log = logging.getLogger(__name__ + '.UpdateNetwork') - resource = 'network' diff --git a/quantumclient/quantum/v2_0/nvp_qos_queue.py b/quantumclient/quantum/v2_0/nvp_qos_queue.py deleted file mode 100644 index 386b887..0000000 --- a/quantumclient/quantum/v2_0/nvp_qos_queue.py +++ /dev/null @@ -1,89 +0,0 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - -# Copyright 2013 Nicira Inc. -# All Rights Reserved -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -import logging - -from quantumclient.quantum import v2_0 as quantumv20 - - -class ListQoSQueue(quantumv20.ListCommand): - """List queues that belong to a given tenant.""" - - resource = 'qos_queue' - log = logging.getLogger(__name__ + '.ListQoSQueue') - list_columns = ['id', 'name', 'min', 'max', - 'qos_marking', 'dscp', 'default'] - - -class ShowQoSQueue(quantumv20.ShowCommand): - """Show information of a given queue.""" - - resource = 'qos_queue' - log = logging.getLogger(__name__ + '.ShowQoSQueue') - allow_names = True - - -class CreateQoSQueue(quantumv20.CreateCommand): - """Create a queue.""" - - resource = 'qos_queue' - log = logging.getLogger(__name__ + '.CreateQoSQueue') - - def add_known_arguments(self, parser): - parser.add_argument( - 'name', metavar='NAME', - help='Name of queue') - parser.add_argument( - '--min', - help='min-rate'), - parser.add_argument( - '--max', - help='max-rate'), - parser.add_argument( - '--qos-marking', - help='qos marking untrusted/trusted'), - parser.add_argument( - '--default', - default=False, - help=('If true all ports created with be the size of this queue' - ' if queue is not specified')), - parser.add_argument( - '--dscp', - help='Differentiated Services Code Point'), - - def args2body(self, parsed_args): - params = {'name': parsed_args.name, - 'default': parsed_args.default} - if parsed_args.min: - params['min'] = parsed_args.min - if parsed_args.max: - params['max'] = parsed_args.max - if parsed_args.qos_marking: - params['qos_marking'] = parsed_args.qos_marking - if parsed_args.dscp: - params['dscp'] = parsed_args.dscp - if parsed_args.tenant_id: - params['tenant_id'] = parsed_args.tenant_id - return {'qos_queue': params} - - -class DeleteQoSQueue(quantumv20.DeleteCommand): - """Delete a given queue.""" - - log = logging.getLogger(__name__ + '.DeleteQoSQueue') - resource = 'qos_queue' - allow_names = True diff --git a/quantumclient/quantum/v2_0/nvpnetworkgateway.py b/quantumclient/quantum/v2_0/nvpnetworkgateway.py deleted file mode 100644 index 1823b6f..0000000 --- a/quantumclient/quantum/v2_0/nvpnetworkgateway.py +++ /dev/null @@ -1,159 +0,0 @@ -# Copyright 2013 OpenStack LLC. -# All Rights Reserved -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. -# -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - -import logging - -from quantumclient.common import utils -from quantumclient.openstack.common.gettextutils import _ -from quantumclient.quantum import v2_0 as quantumv20 - -RESOURCE = 'network_gateway' - - -class ListNetworkGateway(quantumv20.ListCommand): - """List network gateways for a given tenant.""" - - resource = RESOURCE - log = logging.getLogger(__name__ + '.ListNetworkGateway') - list_columns = ['id', 'name'] - - -class ShowNetworkGateway(quantumv20.ShowCommand): - """Show information of a given network gateway.""" - - resource = RESOURCE - log = logging.getLogger(__name__ + '.ShowNetworkGateway') - - -class CreateNetworkGateway(quantumv20.CreateCommand): - """Create a network gateway.""" - - resource = RESOURCE - log = logging.getLogger(__name__ + '.CreateNetworkGateway') - - def add_known_arguments(self, parser): - parser.add_argument( - 'name', metavar='NAME', - help='Name of network gateway to create') - parser.add_argument( - '--device', - action='append', - help='device info for this gateway ' - 'device_id=<device identifier>,' - 'interface_name=<name_or_identifier> ' - 'It can be repeated for multiple devices for HA gateways') - - def args2body(self, parsed_args): - body = {self.resource: { - 'name': parsed_args.name}} - devices = [] - if parsed_args.device: - for device in parsed_args.device: - devices.append(utils.str2dict(device)) - if devices: - body[self.resource].update({'devices': devices}) - if parsed_args.tenant_id: - body[self.resource].update({'tenant_id': parsed_args.tenant_id}) - return body - - -class DeleteNetworkGateway(quantumv20.DeleteCommand): - """Delete a given network gateway.""" - - resource = RESOURCE - log = logging.getLogger(__name__ + '.DeleteNetworkGateway') - - -class UpdateNetworkGateway(quantumv20.UpdateCommand): - """Update the name for a network gateway.""" - - resource = RESOURCE - log = logging.getLogger(__name__ + '.UpdateNetworkGateway') - - -class NetworkGatewayInterfaceCommand(quantumv20.QuantumCommand): - """Base class for connecting/disconnecting networks to/from a gateway.""" - - resource = RESOURCE - - def get_parser(self, prog_name): - parser = super(NetworkGatewayInterfaceCommand, - self).get_parser(prog_name) - parser.add_argument( - 'net_gateway_id', metavar='NET-GATEWAY-ID', - help='ID of the network gateway') - parser.add_argument( - 'network_id', metavar='NETWORK-ID', - help='ID of the internal network to connect on the gateway') - parser.add_argument( - '--segmentation-type', - help=('L2 segmentation strategy on the external side of ' - 'the gateway (e.g.: VLAN, FLAT)')) - parser.add_argument( - '--segmentation-id', - help=('Identifier for the L2 segment on the external side ' - 'of the gateway')) - return parser - - def retrieve_ids(self, client, args): - gateway_id = quantumv20.find_resourceid_by_name_or_id( - client, self.resource, args.net_gateway_id) - network_id = quantumv20.find_resourceid_by_name_or_id( - client, 'network', args.network_id) - return (gateway_id, network_id) - - -class ConnectNetworkGateway(NetworkGatewayInterfaceCommand): - """Add an internal network interface to a router.""" - - log = logging.getLogger(__name__ + '.ConnectNetworkGateway') - - def run(self, parsed_args): - self.log.debug('run(%s)' % parsed_args) - quantum_client = self.get_client() - quantum_client.format = parsed_args.request_format - (gateway_id, network_id) = self.retrieve_ids(quantum_client, - parsed_args) - quantum_client.connect_network_gateway( - gateway_id, {'network_id': network_id, - 'segmentation_type': parsed_args.segmentation_type, - 'segmentation_id': parsed_args.segmentation_id}) - # TODO(Salvatore-Orlando): Do output formatting as - # any other command - print >>self.app.stdout, ( - _('Connected network to gateway %s') % gateway_id) - - -class DisconnectNetworkGateway(NetworkGatewayInterfaceCommand): - """Remove a network from a network gateway.""" - - log = logging.getLogger(__name__ + '.DisconnectNetworkGateway') - - def run(self, parsed_args): - self.log.debug('run(%s)' % parsed_args) - quantum_client = self.get_client() - quantum_client.format = parsed_args.request_format - (gateway_id, network_id) = self.retrieve_ids(quantum_client, - parsed_args) - quantum_client.disconnect_network_gateway( - gateway_id, {'network_id': network_id, - 'segmentation_type': parsed_args.segmentation_type, - 'segmentation_id': parsed_args.segmentation_id}) - # TODO(Salvatore-Orlando): Do output formatting as - # any other command - print >>self.app.stdout, ( - _('Disconnected network from gateway %s') % gateway_id) diff --git a/quantumclient/quantum/v2_0/port.py b/quantumclient/quantum/v2_0/port.py index 0d6af60..55b39e9 100644 --- a/quantumclient/quantum/v2_0/port.py +++ b/quantumclient/quantum/v2_0/port.py @@ -1,4 +1,4 @@ -# Copyright 2012 OpenStack LLC. +# Copyright 2013 OpenStack Foundation. # All Rights Reserved # # Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -15,170 +15,4 @@ # # vim: tabstop=4 shiftwidth=4 softtabstop=4 -import argparse -import logging - -from quantumclient.common import utils -from quantumclient.quantum import v2_0 as quantumv20 - - -def _format_fixed_ips(port): - try: - return '\n'.join([utils.dumps(ip) for ip in port['fixed_ips']]) - except Exception: - return '' - - -class ListPort(quantumv20.ListCommand): - """List ports that belong to a given tenant.""" - - resource = 'port' - log = logging.getLogger(__name__ + '.ListPort') - _formatters = {'fixed_ips': _format_fixed_ips, } - list_columns = ['id', 'name', 'mac_address', 'fixed_ips'] - pagination_support = True - sorting_support = True - - -class ListRouterPort(quantumv20.ListCommand): - """List ports that belong to a given tenant, with specified router.""" - - resource = 'port' - log = logging.getLogger(__name__ + '.ListRouterPort') - _formatters = {'fixed_ips': _format_fixed_ips, } - list_columns = ['id', 'name', 'mac_address', 'fixed_ips'] - pagination_support = True - sorting_support = True - - def get_parser(self, prog_name): - parser = super(ListRouterPort, self).get_parser(prog_name) - parser.add_argument( - 'id', metavar='router', - help='ID or name of router to look up') - return parser - - def get_data(self, parsed_args): - quantum_client = self.get_client() - quantum_client.format = parsed_args.request_format - _id = quantumv20.find_resourceid_by_name_or_id( - quantum_client, 'router', parsed_args.id) - self.values_specs.append('--device_id=%s' % _id) - return super(ListRouterPort, self).get_data(parsed_args) - - -class ShowPort(quantumv20.ShowCommand): - """Show information of a given port.""" - - resource = 'port' - log = logging.getLogger(__name__ + '.ShowPort') - - -class CreatePort(quantumv20.CreateCommand): - """Create a port for a given tenant.""" - - resource = 'port' - log = logging.getLogger(__name__ + '.CreatePort') - - def add_known_arguments(self, parser): - parser.add_argument( - '--name', - help='name of this port') - parser.add_argument( - '--admin-state-down', - dest='admin_state', action='store_false', - help='set admin state up to false') - parser.add_argument( - '--admin_state_down', - dest='admin_state', action='store_false', - help=argparse.SUPPRESS) - parser.add_argument( - '--mac-address', - help='mac address of this port') - parser.add_argument( - '--mac_address', - help=argparse.SUPPRESS) - parser.add_argument( - '--device-id', - help='device id of this port') - parser.add_argument( - '--device_id', - help=argparse.SUPPRESS) - parser.add_argument( - '--fixed-ip', metavar='ip_address=IP_ADDR', - action='append', - help='desired IP for this port: ' - 'subnet_id=<name_or_id>,ip_address=<ip>, ' - '(This option can be repeated.)') - parser.add_argument( - '--fixed_ip', - action='append', - help=argparse.SUPPRESS) - parser.add_argument( - '--security-group', metavar='SECURITY_GROUP', - default=[], action='append', dest='security_groups', - help='security group associated with the port ' - '(This option can be repeated)') - parser.add_argument( - 'network_id', metavar='NETWORK', - help='Network id or name this port belongs to') - - def args2body(self, parsed_args): - _network_id = quantumv20.find_resourceid_by_name_or_id( - self.get_client(), 'network', parsed_args.network_id) - body = {'port': {'admin_state_up': parsed_args.admin_state, - 'network_id': _network_id, }, } - if parsed_args.mac_address: - body['port'].update({'mac_address': parsed_args.mac_address}) - if parsed_args.device_id: - body['port'].update({'device_id': parsed_args.device_id}) - if parsed_args.tenant_id: - body['port'].update({'tenant_id': parsed_args.tenant_id}) - if parsed_args.name: - body['port'].update({'name': parsed_args.name}) - ips = [] - if parsed_args.fixed_ip: - for ip_spec in parsed_args.fixed_ip: - ip_dict = utils.str2dict(ip_spec) - if 'subnet_id' in ip_dict: - subnet_name_id = ip_dict['subnet_id'] - _subnet_id = quantumv20.find_resourceid_by_name_or_id( - self.get_client(), 'subnet', subnet_name_id) - ip_dict['subnet_id'] = _subnet_id - ips.append(ip_dict) - if ips: - body['port'].update({'fixed_ips': ips}) - - _sgids = [] - for sg in parsed_args.security_groups: - _sgids.append(quantumv20.find_resourceid_by_name_or_id( - self.get_client(), 'security_group', sg)) - if _sgids: - body['port']['security_groups'] = _sgids - - return body - - -class DeletePort(quantumv20.DeleteCommand): - """Delete a given port.""" - - resource = 'port' - log = logging.getLogger(__name__ + '.DeletePort') - - -class UpdatePort(quantumv20.UpdateCommand): - """Update port's information.""" - - resource = 'port' - log = logging.getLogger(__name__ + '.UpdatePort') - - def add_known_arguments(self, parser): - parser.add_argument( - '--no-security-groups', - action='store_true', - help='remove security groups from port') - - def args2body(self, parsed_args): - body = {'port': {}} - if parsed_args.no_security_groups: - body['port'].update({'security_groups': None}) - return body +from neutronclient.neutron.v2_0.port import _format_fixed_ips # noqa diff --git a/quantumclient/quantum/v2_0/quota.py b/quantumclient/quantum/v2_0/quota.py deleted file mode 100644 index 1c15192..0000000 --- a/quantumclient/quantum/v2_0/quota.py +++ /dev/null @@ -1,232 +0,0 @@ -# Copyright 2012 OpenStack LLC. -# All Rights Reserved -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. -# -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - -import argparse -import logging - -from cliff import lister -from cliff import show - -from quantumclient.common import exceptions -from quantumclient.common import utils -from quantumclient.openstack.common.gettextutils import _ -from quantumclient.quantum import v2_0 as quantumv20 - - -def get_tenant_id(tenant_id, client): - return (tenant_id if tenant_id else - client.get_quotas_tenant()['tenant']['tenant_id']) - - -class DeleteQuota(quantumv20.QuantumCommand): - """Delete defined quotas of a given tenant.""" - - api = 'network' - resource = 'quota' - log = logging.getLogger(__name__ + '.DeleteQuota') - - def get_parser(self, prog_name): - parser = super(DeleteQuota, self).get_parser(prog_name) - parser.add_argument( - '--tenant-id', metavar='tenant-id', - help='the owner tenant ID') - parser.add_argument( - '--tenant_id', - help=argparse.SUPPRESS) - return parser - - def run(self, parsed_args): - self.log.debug('run(%s)' % parsed_args) - quantum_client = self.get_client() - quantum_client.format = parsed_args.request_format - tenant_id = get_tenant_id(parsed_args.tenant_id, - quantum_client) - obj_deleter = getattr(quantum_client, - "delete_%s" % self.resource) - obj_deleter(tenant_id) - print >>self.app.stdout, (_('Deleted %(resource)s: %(tenant_id)s') - % {'tenant_id': tenant_id, - 'resource': self.resource}) - return - - -class ListQuota(quantumv20.QuantumCommand, lister.Lister): - """List defined quotas of all tenants.""" - - api = 'network' - resource = 'quota' - log = logging.getLogger(__name__ + '.ListQuota') - - def get_parser(self, prog_name): - parser = super(ListQuota, self).get_parser(prog_name) - return parser - - def get_data(self, parsed_args): - self.log.debug('get_data(%s)' % parsed_args) - quantum_client = self.get_client() - search_opts = {} - self.log.debug('search options: %s', search_opts) - quantum_client.format = parsed_args.request_format - obj_lister = getattr(quantum_client, - "list_%ss" % self.resource) - data = obj_lister(**search_opts) - info = [] - collection = self.resource + "s" - if collection in data: - info = data[collection] - _columns = len(info) > 0 and sorted(info[0].keys()) or [] - return (_columns, (utils.get_item_properties(s, _columns) - for s in info)) - - -class ShowQuota(quantumv20.QuantumCommand, show.ShowOne): - """Show quotas of a given tenant - - """ - api = 'network' - resource = "quota" - log = logging.getLogger(__name__ + '.ShowQuota') - - def get_parser(self, prog_name): - parser = super(ShowQuota, self).get_parser(prog_name) - parser.add_argument( - '--tenant-id', metavar='tenant-id', - help='the owner tenant ID') - parser.add_argument( - '--tenant_id', - help=argparse.SUPPRESS) - return parser - - def get_data(self, parsed_args): - self.log.debug('get_data(%s)' % parsed_args) - quantum_client = self.get_client() - quantum_client.format = parsed_args.request_format - tenant_id = get_tenant_id(parsed_args.tenant_id, - quantum_client) - params = {} - obj_shower = getattr(quantum_client, - "show_%s" % self.resource) - data = obj_shower(tenant_id, **params) - if self.resource in data: - for k, v in data[self.resource].iteritems(): - if isinstance(v, list): - value = "" - for _item in v: - if value: - value += "\n" - if isinstance(_item, dict): - value += utils.dumps(_item) - else: - value += str(_item) - data[self.resource][k] = value - elif v is None: - data[self.resource][k] = '' - return zip(*sorted(data[self.resource].iteritems())) - else: - return None - - -class UpdateQuota(quantumv20.QuantumCommand, show.ShowOne): - """Define tenant's quotas not to use defaults.""" - - resource = 'quota' - log = logging.getLogger(__name__ + '.UpdateQuota') - - def get_parser(self, prog_name): - parser = super(UpdateQuota, self).get_parser(prog_name) - parser.add_argument( - '--tenant-id', metavar='tenant-id', - help='the owner tenant ID') - parser.add_argument( - '--tenant_id', - help=argparse.SUPPRESS) - parser.add_argument( - '--network', metavar='networks', - help='the limit of networks') - parser.add_argument( - '--subnet', metavar='subnets', - help='the limit of subnets') - parser.add_argument( - '--port', metavar='ports', - help='the limit of ports') - parser.add_argument( - '--router', metavar='routers', - help='the limit of routers') - parser.add_argument( - '--floatingip', metavar='floatingips', - help='the limit of floating IPs') - parser.add_argument( - '--security-group', metavar='security_groups', - help='the limit of security groups') - parser.add_argument( - '--security-group-rule', metavar='security_group_rules', - help='the limit of security groups rules') - return parser - - def _validate_int(self, name, value): - try: - return_value = int(value) - except Exception: - message = (_('quota limit for %(name)s must be an integer') % - {'name': name}) - raise exceptions.QuantumClientException(message=message) - return return_value - - def args2body(self, parsed_args): - quota = {} - for resource in ('network', 'subnet', 'port', 'router', 'floatingip', - 'security_group', 'security_group_rule'): - if getattr(parsed_args, resource): - quota[resource] = self._validate_int( - resource, - getattr(parsed_args, resource)) - return {self.resource: quota} - - def get_data(self, parsed_args): - self.log.debug('run(%s)' % parsed_args) - quantum_client = self.get_client() - quantum_client.format = parsed_args.request_format - _extra_values = quantumv20.parse_args_to_dict(self.values_specs) - quantumv20._merge_args(self, parsed_args, _extra_values, - self.values_specs) - body = self.args2body(parsed_args) - if self.resource in body: - body[self.resource].update(_extra_values) - else: - body[self.resource] = _extra_values - obj_updator = getattr(quantum_client, - "update_%s" % self.resource) - tenant_id = get_tenant_id(parsed_args.tenant_id, - quantum_client) - data = obj_updator(tenant_id, body) - if self.resource in data: - for k, v in data[self.resource].iteritems(): - if isinstance(v, list): - value = "" - for _item in v: - if value: - value += "\n" - if isinstance(_item, dict): - value += utils.dumps(_item) - else: - value += str(_item) - data[self.resource][k] = value - elif v is None: - data[self.resource][k] = '' - return zip(*sorted(data[self.resource].iteritems())) - else: - return None diff --git a/quantumclient/quantum/v2_0/router.py b/quantumclient/quantum/v2_0/router.py deleted file mode 100644 index c5b1570..0000000 --- a/quantumclient/quantum/v2_0/router.py +++ /dev/null @@ -1,230 +0,0 @@ -# Copyright 2012 OpenStack LLC. -# All Rights Reserved -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. -# -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - -import argparse -import logging - -from quantumclient.common import exceptions -from quantumclient.common import utils -from quantumclient.openstack.common.gettextutils import _ -from quantumclient.quantum import v2_0 as quantumv20 - - -def _format_external_gateway_info(router): - try: - return utils.dumps(router['external_gateway_info']) - except Exception: - return '' - - -class ListRouter(quantumv20.ListCommand): - """List routers that belong to a given tenant.""" - - resource = 'router' - log = logging.getLogger(__name__ + '.ListRouter') - _formatters = {'external_gateway_info': _format_external_gateway_info, } - list_columns = ['id', 'name', 'external_gateway_info'] - pagination_support = True - sorting_support = True - - -class ShowRouter(quantumv20.ShowCommand): - """Show information of a given router.""" - - resource = 'router' - log = logging.getLogger(__name__ + '.ShowRouter') - - -class CreateRouter(quantumv20.CreateCommand): - """Create a router for a given tenant.""" - - resource = 'router' - log = logging.getLogger(__name__ + '.CreateRouter') - _formatters = {'external_gateway_info': _format_external_gateway_info, } - - def add_known_arguments(self, parser): - parser.add_argument( - '--admin-state-down', - dest='admin_state', action='store_false', - help='Set Admin State Up to false') - parser.add_argument( - '--admin_state_down', - dest='admin_state', action='store_false', - help=argparse.SUPPRESS) - parser.add_argument( - 'name', metavar='NAME', - help='Name of router to create') - - def args2body(self, parsed_args): - body = {'router': { - 'name': parsed_args.name, - 'admin_state_up': parsed_args.admin_state, }, } - if parsed_args.tenant_id: - body['router'].update({'tenant_id': parsed_args.tenant_id}) - return body - - -class DeleteRouter(quantumv20.DeleteCommand): - """Delete a given router.""" - - log = logging.getLogger(__name__ + '.DeleteRouter') - resource = 'router' - - -class UpdateRouter(quantumv20.UpdateCommand): - """Update router's information.""" - - log = logging.getLogger(__name__ + '.UpdateRouter') - resource = 'router' - - -class RouterInterfaceCommand(quantumv20.QuantumCommand): - """Based class to Add/Remove router interface.""" - - api = 'network' - resource = 'router' - - def call_api(self, quantum_client, router_id, body): - raise NotImplementedError() - - def success_message(self, router_id, portinfo): - raise NotImplementedError() - - def get_parser(self, prog_name): - parser = super(RouterInterfaceCommand, self).get_parser(prog_name) - parser.add_argument( - 'router_id', metavar='router-id', - help='ID of the router') - parser.add_argument( - 'interface', metavar='INTERFACE', - help='The format is "SUBNET|subnet=SUBNET|port=PORT". ' - 'Either a subnet or port must be specified. ' - 'Both ID and name are accepted as SUBNET or PORT. ' - 'Note that "subnet=" can be omitted when specifying subnet.') - return parser - - def run(self, parsed_args): - self.log.debug('run(%s)' % parsed_args) - quantum_client = self.get_client() - quantum_client.format = parsed_args.request_format - - if '=' in parsed_args.interface: - resource, value = parsed_args.interface.split('=', 1) - if resource not in ['subnet', 'port']: - exceptions.CommandError('You must specify either subnet or ' - 'port for INTERFACE parameter.') - else: - resource = 'subnet' - value = parsed_args.interface - - _router_id = quantumv20.find_resourceid_by_name_or_id( - quantum_client, self.resource, parsed_args.router_id) - - _interface_id = quantumv20.find_resourceid_by_name_or_id( - quantum_client, resource, value) - body = {'%s_id' % resource: _interface_id} - - portinfo = self.call_api(quantum_client, _router_id, body) - print >>self.app.stdout, self.success_message(parsed_args.router_id, - portinfo) - - -class AddInterfaceRouter(RouterInterfaceCommand): - """Add an internal network interface to a router.""" - - log = logging.getLogger(__name__ + '.AddInterfaceRouter') - - def call_api(self, quantum_client, router_id, body): - return quantum_client.add_interface_router(router_id, body) - - def success_message(self, router_id, portinfo): - return (_('Added interface %(port)s to router %(router)s.') % - {'router': router_id, 'port': portinfo['port_id']}) - - -class RemoveInterfaceRouter(RouterInterfaceCommand): - """Remove an internal network interface from a router.""" - - log = logging.getLogger(__name__ + '.RemoveInterfaceRouter') - - def call_api(self, quantum_client, router_id, body): - return quantum_client.remove_interface_router(router_id, body) - - def success_message(self, router_id, portinfo): - # portinfo is not used since it is None for router-interface-delete. - return _('Removed interface from router %s.') % router_id - - -class SetGatewayRouter(quantumv20.QuantumCommand): - """Set the external network gateway for a router.""" - - log = logging.getLogger(__name__ + '.SetGatewayRouter') - api = 'network' - resource = 'router' - - def get_parser(self, prog_name): - parser = super(SetGatewayRouter, self).get_parser(prog_name) - parser.add_argument( - 'router_id', metavar='router-id', - help='ID of the router') - parser.add_argument( - 'external_network_id', metavar='external-network-id', - help='ID of the external network for the gateway') - parser.add_argument( - '--disable-snat', action='store_false', dest='enable_snat', - help='Disable Source NAT on the router gateway') - return parser - - def run(self, parsed_args): - self.log.debug('run(%s)' % parsed_args) - quantum_client = self.get_client() - quantum_client.format = parsed_args.request_format - _router_id = quantumv20.find_resourceid_by_name_or_id( - quantum_client, self.resource, parsed_args.router_id) - _ext_net_id = quantumv20.find_resourceid_by_name_or_id( - quantum_client, 'network', parsed_args.external_network_id) - quantum_client.add_gateway_router( - _router_id, - {'network_id': _ext_net_id, - 'enable_snat': parsed_args.enable_snat}) - print >>self.app.stdout, ( - _('Set gateway for router %s') % parsed_args.router_id) - - -class RemoveGatewayRouter(quantumv20.QuantumCommand): - """Remove an external network gateway from a router.""" - - log = logging.getLogger(__name__ + '.RemoveGatewayRouter') - api = 'network' - resource = 'router' - - def get_parser(self, prog_name): - parser = super(RemoveGatewayRouter, self).get_parser(prog_name) - parser.add_argument( - 'router_id', metavar='router-id', - help='ID of the router') - return parser - - def run(self, parsed_args): - self.log.debug('run(%s)' % parsed_args) - quantum_client = self.get_client() - quantum_client.format = parsed_args.request_format - _router_id = quantumv20.find_resourceid_by_name_or_id( - quantum_client, self.resource, parsed_args.router_id) - quantum_client.remove_gateway_router(_router_id) - print >>self.app.stdout, ( - _('Removed gateway from router %s') % parsed_args.router_id) diff --git a/quantumclient/quantum/v2_0/securitygroup.py b/quantumclient/quantum/v2_0/securitygroup.py deleted file mode 100644 index 5fa899c..0000000 --- a/quantumclient/quantum/v2_0/securitygroup.py +++ /dev/null @@ -1,259 +0,0 @@ -# Copyright 2012 OpenStack LLC. -# All Rights Reserved -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. -# -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - -import argparse -import logging - -from quantumclient.quantum import v2_0 as quantumv20 - - -class ListSecurityGroup(quantumv20.ListCommand): - """List security groups that belong to a given tenant.""" - - resource = 'security_group' - log = logging.getLogger(__name__ + '.ListSecurityGroup') - list_columns = ['id', 'name', 'description'] - pagination_support = True - sorting_support = True - - -class ShowSecurityGroup(quantumv20.ShowCommand): - """Show information of a given security group.""" - - resource = 'security_group' - log = logging.getLogger(__name__ + '.ShowSecurityGroup') - allow_names = True - - -class CreateSecurityGroup(quantumv20.CreateCommand): - """Create a security group.""" - - resource = 'security_group' - log = logging.getLogger(__name__ + '.CreateSecurityGroup') - - def add_known_arguments(self, parser): - parser.add_argument( - 'name', metavar='NAME', - help='Name of security group') - parser.add_argument( - '--description', - help='description of security group') - - def args2body(self, parsed_args): - body = {'security_group': { - 'name': parsed_args.name}} - if parsed_args.description: - body['security_group'].update( - {'description': parsed_args.description}) - if parsed_args.tenant_id: - body['security_group'].update({'tenant_id': parsed_args.tenant_id}) - return body - - -class DeleteSecurityGroup(quantumv20.DeleteCommand): - """Delete a given security group.""" - - log = logging.getLogger(__name__ + '.DeleteSecurityGroup') - resource = 'security_group' - allow_names = True - - -class UpdateSecurityGroup(quantumv20.UpdateCommand): - """Update a given security group.""" - - log = logging.getLogger(__name__ + '.UpdateSecurityGroup') - resource = 'security_group' - - def add_known_arguments(self, parser): - parser.add_argument( - '--name', - help='Name of security group') - parser.add_argument( - '--description', - help='description of security group') - - def args2body(self, parsed_args): - body = {'security_group': {}} - if parsed_args.name: - body['security_group'].update( - {'name': parsed_args.name}) - if parsed_args.description: - body['security_group'].update( - {'description': parsed_args.description}) - return body - - -class ListSecurityGroupRule(quantumv20.ListCommand): - """List security group rules that belong to a given tenant.""" - - resource = 'security_group_rule' - log = logging.getLogger(__name__ + '.ListSecurityGroupRule') - list_columns = ['id', 'security_group_id', 'direction', 'protocol', - 'remote_ip_prefix', 'remote_group_id'] - replace_rules = {'security_group_id': 'security_group', - 'remote_group_id': 'remote_group'} - pagination_support = True - sorting_support = True - - def get_parser(self, prog_name): - parser = super(ListSecurityGroupRule, self).get_parser(prog_name) - parser.add_argument( - '--no-nameconv', action='store_true', - help='Do not convert security group ID to its name') - return parser - - @staticmethod - def replace_columns(cols, rules, reverse=False): - if reverse: - rules = dict((rules[k], k) for k in rules.keys()) - return [rules.get(col, col) for col in cols] - - def retrieve_list(self, parsed_args): - parsed_args.fields = self.replace_columns(parsed_args.fields, - self.replace_rules, - reverse=True) - return super(ListSecurityGroupRule, self).retrieve_list(parsed_args) - - def extend_list(self, data, parsed_args): - if parsed_args.no_nameconv: - return - quantum_client = self.get_client() - search_opts = {'fields': ['id', 'name']} - if self.pagination_support: - page_size = parsed_args.page_size - if page_size: - search_opts.update({'limit': page_size}) - sec_group_ids = set() - for rule in data: - for key in self.replace_rules: - sec_group_ids.add(rule[key]) - search_opts.update({"id": sec_group_ids}) - secgroups = quantum_client.list_security_groups(**search_opts) - secgroups = secgroups.get('security_groups', []) - sg_dict = dict([(sg['id'], sg['name']) - for sg in secgroups if sg['name']]) - for rule in data: - for key in self.replace_rules: - rule[key] = sg_dict.get(rule[key], rule[key]) - - def setup_columns(self, info, parsed_args): - parsed_args.columns = self.replace_columns(parsed_args.columns, - self.replace_rules, - reverse=True) - # NOTE(amotoki): 2nd element of the tuple returned by setup_columns() - # is a generator, so if you need to create a look using the generator - # object, you need to recreate a generator to show a list expectedly. - info = super(ListSecurityGroupRule, self).setup_columns(info, - parsed_args) - cols = info[0] - if not parsed_args.no_nameconv: - cols = self.replace_columns(info[0], self.replace_rules) - parsed_args.columns = cols - return (cols, info[1]) - - -class ShowSecurityGroupRule(quantumv20.ShowCommand): - """Show information of a given security group rule.""" - - resource = 'security_group_rule' - log = logging.getLogger(__name__ + '.ShowSecurityGroupRule') - allow_names = False - - -class CreateSecurityGroupRule(quantumv20.CreateCommand): - """Create a security group rule.""" - - resource = 'security_group_rule' - log = logging.getLogger(__name__ + '.CreateSecurityGroupRule') - - def add_known_arguments(self, parser): - parser.add_argument( - 'security_group_id', metavar='SECURITY_GROUP', - help='Security group name or id to add rule.') - parser.add_argument( - '--direction', - default='ingress', choices=['ingress', 'egress'], - help='direction of traffic: ingress/egress') - parser.add_argument( - '--ethertype', - default='IPv4', - help='IPv4/IPv6') - parser.add_argument( - '--protocol', - help='protocol of packet') - parser.add_argument( - '--port-range-min', - help='starting port range') - parser.add_argument( - '--port_range_min', - help=argparse.SUPPRESS) - parser.add_argument( - '--port-range-max', - help='ending port range') - parser.add_argument( - '--port_range_max', - help=argparse.SUPPRESS) - parser.add_argument( - '--remote-ip-prefix', - help='cidr to match on') - parser.add_argument( - '--remote_ip_prefix', - help=argparse.SUPPRESS) - parser.add_argument( - '--remote-group-id', metavar='REMOTE_GROUP', - help='remote security group name or id to apply rule') - parser.add_argument( - '--remote_group_id', - help=argparse.SUPPRESS) - - def args2body(self, parsed_args): - _security_group_id = quantumv20.find_resourceid_by_name_or_id( - self.get_client(), 'security_group', parsed_args.security_group_id) - body = {'security_group_rule': { - 'security_group_id': _security_group_id, - 'direction': parsed_args.direction, - 'ethertype': parsed_args.ethertype}} - if parsed_args.protocol: - body['security_group_rule'].update( - {'protocol': parsed_args.protocol}) - if parsed_args.port_range_min: - body['security_group_rule'].update( - {'port_range_min': parsed_args.port_range_min}) - if parsed_args.port_range_max: - body['security_group_rule'].update( - {'port_range_max': parsed_args.port_range_max}) - if parsed_args.remote_ip_prefix: - body['security_group_rule'].update( - {'remote_ip_prefix': parsed_args.remote_ip_prefix}) - if parsed_args.remote_group_id: - _remote_group_id = quantumv20.find_resourceid_by_name_or_id( - self.get_client(), 'security_group', - parsed_args.remote_group_id) - body['security_group_rule'].update( - {'remote_group_id': _remote_group_id}) - if parsed_args.tenant_id: - body['security_group_rule'].update( - {'tenant_id': parsed_args.tenant_id}) - return body - - -class DeleteSecurityGroupRule(quantumv20.DeleteCommand): - """Delete a given security group rule.""" - - log = logging.getLogger(__name__ + '.DeleteSecurityGroupRule') - resource = 'security_group_rule' - allow_names = False diff --git a/quantumclient/quantum/v2_0/subnet.py b/quantumclient/quantum/v2_0/subnet.py deleted file mode 100644 index e79cdc0..0000000 --- a/quantumclient/quantum/v2_0/subnet.py +++ /dev/null @@ -1,168 +0,0 @@ -# Copyright 2012 OpenStack LLC. -# All Rights Reserved -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. -# -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - -import argparse -import logging - -from quantumclient.common import exceptions -from quantumclient.common import utils -from quantumclient.quantum import v2_0 as quantumv20 - - -def _format_allocation_pools(subnet): - try: - return '\n'.join([utils.dumps(pool) for pool in - subnet['allocation_pools']]) - except Exception: - return '' - - -def _format_dns_nameservers(subnet): - try: - return '\n'.join([utils.dumps(server) for server in - subnet['dns_nameservers']]) - except Exception: - return '' - - -def _format_host_routes(subnet): - try: - return '\n'.join([utils.dumps(route) for route in - subnet['host_routes']]) - except Exception: - return '' - - -class ListSubnet(quantumv20.ListCommand): - """List networks that belong to a given tenant.""" - - resource = 'subnet' - log = logging.getLogger(__name__ + '.ListSubnet') - _formatters = {'allocation_pools': _format_allocation_pools, - 'dns_nameservers': _format_dns_nameservers, - 'host_routes': _format_host_routes, } - list_columns = ['id', 'name', 'cidr', 'allocation_pools'] - pagination_support = True - sorting_support = True - - -class ShowSubnet(quantumv20.ShowCommand): - """Show information of a given subnet.""" - - resource = 'subnet' - log = logging.getLogger(__name__ + '.ShowSubnet') - - -class CreateSubnet(quantumv20.CreateCommand): - """Create a subnet for a given tenant.""" - - resource = 'subnet' - log = logging.getLogger(__name__ + '.CreateSubnet') - - def add_known_arguments(self, parser): - parser.add_argument( - '--name', - help='name of this subnet') - parser.add_argument( - '--ip-version', - type=int, - default=4, choices=[4, 6], - help='IP version with default 4') - parser.add_argument( - '--ip_version', - type=int, - choices=[4, 6], - help=argparse.SUPPRESS) - parser.add_argument( - '--gateway', metavar='GATEWAY_IP', - help='gateway ip of this subnet') - parser.add_argument( - '--no-gateway', - action='store_true', - help='No distribution of gateway') - parser.add_argument( - '--allocation-pool', metavar='start=IP_ADDR,end=IP_ADDR', - action='append', dest='allocation_pools', type=utils.str2dict, - help='Allocation pool IP addresses for this subnet ' - '(This option can be repeated)') - parser.add_argument( - '--allocation_pool', - action='append', dest='allocation_pools', type=utils.str2dict, - help=argparse.SUPPRESS) - parser.add_argument( - '--host-route', metavar='destination=CIDR,nexthop=IP_ADDR', - action='append', dest='host_routes', type=utils.str2dict, - help='Additional route (This option can be repeated)') - parser.add_argument( - '--dns-nameserver', metavar='DNS_NAMESERVER', - action='append', dest='dns_nameservers', - help='DNS name server for this subnet ' - '(This option can be repeated)') - parser.add_argument( - '--disable-dhcp', - action='store_true', - help='Disable DHCP for this subnet') - parser.add_argument( - 'network_id', metavar='NETWORK', - help='network id or name this subnet belongs to') - parser.add_argument( - 'cidr', metavar='CIDR', - help='cidr of subnet to create') - - def args2body(self, parsed_args): - _network_id = quantumv20.find_resourceid_by_name_or_id( - self.get_client(), 'network', parsed_args.network_id) - body = {'subnet': {'cidr': parsed_args.cidr, - 'network_id': _network_id, - 'ip_version': parsed_args.ip_version, }, } - - if parsed_args.gateway and parsed_args.no_gateway: - raise exceptions.CommandError("--gateway option and " - "--no-gateway option can " - "not be used same time") - if parsed_args.no_gateway: - body['subnet'].update({'gateway_ip': None}) - if parsed_args.gateway: - body['subnet'].update({'gateway_ip': parsed_args.gateway}) - if parsed_args.tenant_id: - body['subnet'].update({'tenant_id': parsed_args.tenant_id}) - if parsed_args.name: - body['subnet'].update({'name': parsed_args.name}) - if parsed_args.disable_dhcp: - body['subnet'].update({'enable_dhcp': False}) - if parsed_args.allocation_pools: - body['subnet']['allocation_pools'] = parsed_args.allocation_pools - if parsed_args.host_routes: - body['subnet']['host_routes'] = parsed_args.host_routes - if parsed_args.dns_nameservers: - body['subnet']['dns_nameservers'] = parsed_args.dns_nameservers - - return body - - -class DeleteSubnet(quantumv20.DeleteCommand): - """Delete a given subnet.""" - - resource = 'subnet' - log = logging.getLogger(__name__ + '.DeleteSubnet') - - -class UpdateSubnet(quantumv20.UpdateCommand): - """Update subnet's information.""" - - resource = 'subnet' - log = logging.getLogger(__name__ + '.UpdateSubnet') |
