Rename quantumclient to neutronclient

Implements Blueprint: remove-use-of-quantum

Change-Id: Idebe92d56d277435ffd23f292984f9b8b8fdb2df
This commit is contained in:
Mark McClain 2013-07-02 18:44:42 -04:00
parent 8ed38707b1
commit 93ac15bfeb
71 changed files with 658 additions and 737 deletions

6
.gitignore vendored
View File

@ -8,9 +8,9 @@ build-stamp
cover/* cover/*
doc/build/ doc/build/
doc/source/api/ doc/source/api/
python_quantumclient.egg-info/* python_neutronclient.egg-info/*
quantum/vcsversion.py neutron/vcsversion.py
quantumclient/versioninfo neutronclient/versioninfo
run_tests.err.log run_tests.err.log
run_tests.log run_tests.log
.autogenerated .autogenerated

View File

@ -1,4 +1,4 @@
QuantumClient Style Commandments Neutron Style Commandments
================================ ================================
- Step 1: Read http://www.python.org/dev/peps/pep-0008/ - Step 1: Read http://www.python.org/dev/peps/pep-0008/
@ -39,7 +39,7 @@ Example::
\n \n
{{third-party lib imports in human alphabetical order}} {{third-party lib imports in human alphabetical order}}
\n \n
{{quantum imports in human alphabetical order}} {{neutron imports in human alphabetical order}}
\n \n
\n \n
{{begin your code}} {{begin your code}}
@ -59,12 +59,12 @@ Example::
import eventlet import eventlet
import webob.exc import webob.exc
import quantum.api.networks import neutron.api.networks
from quantum.api import ports from neutron.api import ports
from quantum.db import models from neutron.db import models
from quantum.extensions import multiport from neutron.extensions import multiport
import quantum.manager import neutron.manager
from quantum import service from neutron import service
Docstrings Docstrings

View File

@ -1 +1 @@
This is the client API library for Quantum. This is the client API library for Neutron.

View File

@ -4,7 +4,7 @@
import sys import sys
import os import os
project = 'python-quantumclient' project = 'python-neutronclient'
# -- General configuration --------------------------------------------- # -- General configuration ---------------------------------------------

View File

@ -1,19 +1,19 @@
Python bindings to the OpenStack Network API Python bindings to the OpenStack Network API
============================================ ============================================
In order to use the python quantum client directly, you must first obtain an auth token and identify which endpoint you wish to speak to. Once you have done so, you can use the API like so:: In order to use the python neutron client directly, you must first obtain an auth token and identify which endpoint you wish to speak to. Once you have done so, you can use the API like so::
>>> import logging >>> import logging
>>> from quantumclient.quantum import client >>> from neutronclient.neutron import client
>>> logging.basicConfig(level=logging.DEBUG) >>> logging.basicConfig(level=logging.DEBUG)
>>> quantum = client.Client('2.0', endpoint_url=OS_URL, token=OS_TOKEN) >>> neutron = client.Client('2.0', endpoint_url=OS_URL, token=OS_TOKEN)
>>> quantum.format = 'json' >>> neutron.format = 'json'
>>> network = {'name': 'mynetwork', 'admin_state_up': True} >>> network = {'name': 'mynetwork', 'admin_state_up': True}
>>> quantum.create_network({'network':network}) >>> neutron.create_network({'network':network})
>>> networks = quantum.list_networks(name='mynetwork') >>> networks = neutron.list_networks(name='mynetwork')
>>> print networks >>> print networks
>>> network_id = networks['networks'][0]['id'] >>> network_id = networks['networks'][0]['id']
>>> quantum.delete_network(network_id) >>> neutron.delete_network(network_id)
Command-line Tool Command-line Tool
@ -27,21 +27,21 @@ In order to use the CLI, you must provide your OpenStack username, password, ten
The command line tool will attempt to reauthenticate using your provided credentials for every request. You can override this behavior by manually supplying an auth token using ``--os-url`` and ``--os-auth-token``. You can alternatively set these environment variables:: The command line tool will attempt to reauthenticate using your provided credentials for every request. You can override this behavior by manually supplying an auth token using ``--os-url`` and ``--os-auth-token``. You can alternatively set these environment variables::
export OS_URL=http://quantum.example.org:9696/ export OS_URL=http://neutron.example.org:9696/
export OS_TOKEN=3bcc3d3a03f44e3d8377f9247b0ad155 export OS_TOKEN=3bcc3d3a03f44e3d8377f9247b0ad155
If quantum server does not require authentication, besides these two arguments or environment variables (We can use any value as token.), we need manually supply ``--os-auth-strategy`` or set the environment variable:: If neutron server does not require authentication, besides these two arguments or environment variables (We can use any value as token.), we need manually supply ``--os-auth-strategy`` or set the environment variable::
export OS_AUTH_STRATEGY=noauth export OS_AUTH_STRATEGY=noauth
Once you've configured your authentication parameters, you can run ``quantum -h`` to see a complete listing of available commands. Once you've configured your authentication parameters, you can run ``neutron -h`` to see a complete listing of available commands.
Release Notes Release Notes
============= =============
2.0 2.0
----- -----
* support Quantum API 2.0 * support Neutron API 2.0
2.2.0 2.2.0
----- -----

View File

@ -18,111 +18,111 @@ FORMAT=" --request-format xml"
# test the CRUD of network # test the CRUD of network
network=mynet1 network=mynet1
quantum net-create $FORMAT $NOAUTH $network || die "fail to create network $network" neutron net-create $FORMAT $NOAUTH $network || die "fail to create network $network"
temp=`quantum net-list $FORMAT -- --name $network --fields id | wc -l` temp=`neutron net-list $FORMAT -- --name $network --fields id | wc -l`
echo $temp echo $temp
if [ $temp -ne 5 ]; then if [ $temp -ne 5 ]; then
die "networks with name $network is not unique or found" die "networks with name $network is not unique or found"
fi fi
network_id=`quantum net-list -- --name $network --fields id | tail -n 2 | head -n 1 | cut -d' ' -f 2` network_id=`neutron net-list -- --name $network --fields id | tail -n 2 | head -n 1 | cut -d' ' -f 2`
echo "ID of network with name $network is $network_id" echo "ID of network with name $network is $network_id"
quantum net-show $FORMAT $network || die "fail to show network $network" neutron net-show $FORMAT $network || die "fail to show network $network"
quantum net-show $FORMAT $network_id || die "fail to show network $network_id" neutron net-show $FORMAT $network_id || die "fail to show network $network_id"
quantum net-update $FORMAT $network --admin_state_up False || die "fail to update network $network" neutron net-update $FORMAT $network --admin_state_up False || die "fail to update network $network"
quantum net-update $FORMAT $network_id --admin_state_up True || die "fail to update network $network_id" neutron net-update $FORMAT $network_id --admin_state_up True || die "fail to update network $network_id"
quantum net-list $FORMAT -c id -- --id fakeid || die "fail to list networks with column selection on empty list" neutron net-list $FORMAT -c id -- --id fakeid || die "fail to list networks with column selection on empty list"
# test the CRUD of subnet # test the CRUD of subnet
subnet=mysubnet1 subnet=mysubnet1
cidr=10.0.1.3/24 cidr=10.0.1.3/24
quantum subnet-create $FORMAT $NOAUTH $network $cidr --name $subnet || die "fail to create subnet $subnet" neutron subnet-create $FORMAT $NOAUTH $network $cidr --name $subnet || die "fail to create subnet $subnet"
tempsubnet=`quantum subnet-list $FORMAT -- --name $subnet --fields id | wc -l` tempsubnet=`neutron subnet-list $FORMAT -- --name $subnet --fields id | wc -l`
echo $tempsubnet echo $tempsubnet
if [ $tempsubnet -ne 5 ]; then if [ $tempsubnet -ne 5 ]; then
die "subnets with name $subnet is not unique or found" die "subnets with name $subnet is not unique or found"
fi fi
subnet_id=`quantum subnet-list $FORMAT -- --name $subnet --fields id | tail -n 2 | head -n 1 | cut -d' ' -f 2` subnet_id=`neutron subnet-list $FORMAT -- --name $subnet --fields id | tail -n 2 | head -n 1 | cut -d' ' -f 2`
echo "ID of subnet with name $subnet is $subnet_id" echo "ID of subnet with name $subnet is $subnet_id"
quantum subnet-show $FORMAT $subnet || die "fail to show subnet $subnet" neutron subnet-show $FORMAT $subnet || die "fail to show subnet $subnet"
quantum subnet-show $FORMAT $subnet_id || die "fail to show subnet $subnet_id" neutron subnet-show $FORMAT $subnet_id || die "fail to show subnet $subnet_id"
quantum subnet-update $FORMAT $subnet --dns_namesevers host1 || die "fail to update subnet $subnet" neutron subnet-update $FORMAT $subnet --dns_namesevers host1 || die "fail to update subnet $subnet"
quantum subnet-update $FORMAT $subnet_id --dns_namesevers host2 || die "fail to update subnet $subnet_id" neutron subnet-update $FORMAT $subnet_id --dns_namesevers host2 || die "fail to update subnet $subnet_id"
# test the crud of ports # test the crud of ports
port=myport1 port=myport1
quantum port-create $FORMAT $NOAUTH $network --name $port || die "fail to create port $port" neutron port-create $FORMAT $NOAUTH $network --name $port || die "fail to create port $port"
tempport=`quantum port-list $FORMAT -- --name $port --fields id | wc -l` tempport=`neutron port-list $FORMAT -- --name $port --fields id | wc -l`
echo $tempport echo $tempport
if [ $tempport -ne 5 ]; then if [ $tempport -ne 5 ]; then
die "ports with name $port is not unique or found" die "ports with name $port is not unique or found"
fi fi
port_id=`quantum port-list $FORMAT -- --name $port --fields id | tail -n 2 | head -n 1 | cut -d' ' -f 2` port_id=`neutron port-list $FORMAT -- --name $port --fields id | tail -n 2 | head -n 1 | cut -d' ' -f 2`
echo "ID of port with name $port is $port_id" echo "ID of port with name $port is $port_id"
quantum port-show $FORMAT $port || die "fail to show port $port" neutron port-show $FORMAT $port || die "fail to show port $port"
quantum port-show $FORMAT $port_id || die "fail to show port $port_id" neutron port-show $FORMAT $port_id || die "fail to show port $port_id"
quantum port-update $FORMAT $port --device_id deviceid1 || die "fail to update port $port" neutron port-update $FORMAT $port --device_id deviceid1 || die "fail to update port $port"
quantum port-update $FORMAT $port_id --device_id deviceid2 || die "fail to update port $port_id" neutron port-update $FORMAT $port_id --device_id deviceid2 || die "fail to update port $port_id"
# test quota commands RUD # test quota commands RUD
DEFAULT_NETWORKS=10 DEFAULT_NETWORKS=10
DEFAULT_PORTS=50 DEFAULT_PORTS=50
tenant_id=tenant_a tenant_id=tenant_a
tenant_id_b=tenant_b tenant_id_b=tenant_b
quantum quota-update $FORMAT --tenant_id $tenant_id --network 30 || die "fail to update quota for tenant $tenant_id" neutron quota-update $FORMAT --tenant_id $tenant_id --network 30 || die "fail to update quota for tenant $tenant_id"
quantum quota-update $FORMAT --tenant_id $tenant_id_b --network 20 || die "fail to update quota for tenant $tenant_id" neutron quota-update $FORMAT --tenant_id $tenant_id_b --network 20 || die "fail to update quota for tenant $tenant_id"
networks=`quantum quota-list $FORMAT -c network -c tenant_id | grep $tenant_id | awk '{print $2}'` networks=`neutron quota-list $FORMAT -c network -c tenant_id | grep $tenant_id | awk '{print $2}'`
if [ $networks -ne 30 ]; then if [ $networks -ne 30 ]; then
die "networks quota should be 30" die "networks quota should be 30"
fi fi
networks=`quantum quota-list $FORMAT -c network -c tenant_id | grep $tenant_id_b | awk '{print $2}'` networks=`neutron quota-list $FORMAT -c network -c tenant_id | grep $tenant_id_b | awk '{print $2}'`
if [ $networks -ne 20 ]; then if [ $networks -ne 20 ]; then
die "networks quota should be 20" die "networks quota should be 20"
fi fi
networks=`quantum quota-show $FORMAT --tenant_id $tenant_id | grep network | awk -F'|' '{print $3}'` networks=`neutron quota-show $FORMAT --tenant_id $tenant_id | grep network | awk -F'|' '{print $3}'`
if [ $networks -ne 30 ]; then if [ $networks -ne 30 ]; then
die "networks quota should be 30" die "networks quota should be 30"
fi fi
quantum quota-delete $FORMAT --tenant_id $tenant_id || die "fail to delete quota for tenant $tenant_id" neutron quota-delete $FORMAT --tenant_id $tenant_id || die "fail to delete quota for tenant $tenant_id"
networks=`quantum quota-show $FORMAT --tenant_id $tenant_id | grep network | awk -F'|' '{print $3}'` networks=`neutron quota-show $FORMAT --tenant_id $tenant_id | grep network | awk -F'|' '{print $3}'`
if [ $networks -ne $DEFAULT_NETWORKS ]; then if [ $networks -ne $DEFAULT_NETWORKS ]; then
die "networks quota should be $DEFAULT_NETWORKS" die "networks quota should be $DEFAULT_NETWORKS"
fi fi
# update self # update self
if [ "t$NOAUTH" = "t" ]; then if [ "t$NOAUTH" = "t" ]; then
# with auth # with auth
quantum quota-update $FORMAT --port 99 || die "fail to update quota for self" neutron quota-update $FORMAT --port 99 || die "fail to update quota for self"
ports=`quantum quota-show $FORMAT | grep port | awk -F'|' '{print $3}'` ports=`neutron quota-show $FORMAT | grep port | awk -F'|' '{print $3}'`
if [ $ports -ne 99 ]; then if [ $ports -ne 99 ]; then
die "ports quota should be 99" die "ports quota should be 99"
fi fi
ports=`quantum quota-list $FORMAT -c port | grep 99 | awk '{print $2}'` ports=`neutron quota-list $FORMAT -c port | grep 99 | awk '{print $2}'`
if [ $ports -ne 99 ]; then if [ $ports -ne 99 ]; then
die "ports quota should be 99" die "ports quota should be 99"
fi fi
quantum quota-delete $FORMAT || die "fail to delete quota for tenant self" neutron quota-delete $FORMAT || die "fail to delete quota for tenant self"
ports=`quantum quota-show $FORMAT | grep port | awk -F'|' '{print $3}'` ports=`neutron quota-show $FORMAT | grep port | awk -F'|' '{print $3}'`
if [ $ports -ne $DEFAULT_PORTS ]; then if [ $ports -ne $DEFAULT_PORTS ]; then
die "ports quota should be $DEFAULT_PORTS" die "ports quota should be $DEFAULT_PORTS"
fi fi
else else
# without auth # without auth
quantum quota-update $FORMAT --port 100 neutron quota-update $FORMAT --port 100
if [ $? -eq 0 ]; then if [ $? -eq 0 ]; then
die "without valid context on server, quota update command should fail." die "without valid context on server, quota update command should fail."
fi fi
quantum quota-show $FORMAT neutron quota-show $FORMAT
if [ $? -eq 0 ]; then if [ $? -eq 0 ]; then
die "without valid context on server, quota show command should fail." die "without valid context on server, quota show command should fail."
fi fi
quantum quota-delete $FORMAT neutron quota-delete $FORMAT
if [ $? -eq 0 ]; then if [ $? -eq 0 ]; then
die "without valid context on server, quota delete command should fail." die "without valid context on server, quota delete command should fail."
fi fi
quantum quota-list $FORMAT || die "fail to update quota for self" neutron quota-list $FORMAT || die "fail to update quota for self"
fi fi

View File

@ -29,12 +29,13 @@ if not hasattr(urlparse, 'parse_qsl'):
import httplib2 import httplib2
from quantumclient.common import exceptions from neutronclient.common import exceptions
from quantumclient.common import utils from neutronclient.common import utils
_logger = logging.getLogger(__name__) _logger = logging.getLogger(__name__)
if 'QUANTUMCLIENT_DEBUG' in os.environ and os.environ['QUANTUMCLIENT_DEBUG']:
if os.environ.get('NEUTRONCLIENT_DEBUG'):
ch = logging.StreamHandler() ch = logging.StreamHandler()
_logger.setLevel(logging.DEBUG) _logger.setLevel(logging.DEBUG)
_logger.addHandler(ch) _logger.addHandler(ch)
@ -61,7 +62,7 @@ class ServiceCatalog(object):
def url_for(self, attr=None, filter_value=None, def url_for(self, attr=None, filter_value=None,
service_type='network', endpoint_type='publicURL'): service_type='network', endpoint_type='publicURL'):
"""Fetch the URL from the Quantum service for """Fetch the URL from the Neutron service for
a particular endpoint type. If none given, return a particular endpoint type. If none given, return
publicURL. publicURL.
""" """
@ -91,7 +92,7 @@ class ServiceCatalog(object):
class HTTPClient(httplib2.Http): class HTTPClient(httplib2.Http):
"""Handles the REST calls and responses, include authn.""" """Handles the REST calls and responses, include authn."""
USER_AGENT = 'python-quantumclient' USER_AGENT = 'python-neutronclient'
def __init__(self, username=None, tenant_name=None, def __init__(self, username=None, tenant_name=None,
password=None, auth_url=None, password=None, auth_url=None,
@ -215,7 +216,7 @@ class HTTPClient(httplib2.Http):
try: try:
resp, body = self._cs_request(url, "GET") resp, body = self._cs_request(url, "GET")
except exceptions.Unauthorized: except exceptions.Unauthorized:
# rollback to authenticate() to handle case when quantum client # rollback to authenticate() to handle case when neutron client
# is initialized just before the token is expired # is initialized just before the token is expired
self.authenticate() self.authenticate()
return self.endpoint_url return self.endpoint_url

View File

@ -17,7 +17,7 @@
import gettext import gettext
t = gettext.translation('quantumclient', fallback=True) t = gettext.translation('neutronclient', fallback=True)
def _(msg): def _(msg):

View File

@ -20,8 +20,8 @@
import logging import logging
from quantumclient import client from neutronclient import client
from quantumclient.quantum import client as quantum_client from neutronclient.neutron import client as neutron_client
LOG = logging.getLogger(__name__) LOG = logging.getLogger(__name__)
@ -45,7 +45,7 @@ class ClientCache(object):
class ClientManager(object): class ClientManager(object):
"""Manages access to API clients, including authentication. """Manages access to API clients, including authentication.
""" """
quantum = ClientCache(quantum_client.make_client) neutron = ClientCache(neutron_client.make_client)
def __init__(self, token=None, url=None, def __init__(self, token=None, url=None,
auth_url=None, auth_url=None,

View File

@ -15,15 +15,15 @@
# License for the specific language governing permissions and limitations # License for the specific language governing permissions and limitations
# under the License. # under the License.
from quantumclient.common import _ from neutronclient.common import _
""" """
Quantum base exception handling. Neutron base exception handling.
""" """
class QuantumException(Exception): class NeutronException(Exception):
"""Base Quantum Exception """Base Neutron Exception
Taken from nova.exception.NovaException Taken from nova.exception.NovaException
To correctly use this class, inherit from it and define To correctly use this class, inherit from it and define
@ -45,66 +45,66 @@ class QuantumException(Exception):
return self._error_string return self._error_string
class NotFound(QuantumException): class NotFound(NeutronException):
pass pass
class QuantumClientException(QuantumException): class NeutronClientException(NeutronException):
def __init__(self, **kwargs): def __init__(self, **kwargs):
message = kwargs.get('message') message = kwargs.get('message')
self.status_code = kwargs.get('status_code', 0) self.status_code = kwargs.get('status_code', 0)
if message: if message:
self.message = message self.message = message
super(QuantumClientException, self).__init__(**kwargs) super(NeutronClientException, self).__init__(**kwargs)
# NOTE: on the client side, we use different exception types in order # NOTE: on the client side, we use different exception types in order
# to allow client library users to handle server exceptions in try...except # to allow client library users to handle server exceptions in try...except
# blocks. The actual error message is the one generated on the server side # blocks. The actual error message is the one generated on the server side
class NetworkNotFoundClient(QuantumClientException): class NetworkNotFoundClient(NeutronClientException):
pass pass
class PortNotFoundClient(QuantumClientException): class PortNotFoundClient(NeutronClientException):
pass pass
class MalformedResponseBody(QuantumException): class MalformedResponseBody(NeutronException):
message = _("Malformed response body: %(reason)s") message = _("Malformed response body: %(reason)s")
class StateInvalidClient(QuantumClientException): class StateInvalidClient(NeutronClientException):
pass pass
class NetworkInUseClient(QuantumClientException): class NetworkInUseClient(NeutronClientException):
pass pass
class PortInUseClient(QuantumClientException): class PortInUseClient(NeutronClientException):
pass pass
class AlreadyAttachedClient(QuantumClientException): class AlreadyAttachedClient(NeutronClientException):
pass pass
class Unauthorized(QuantumClientException): class Unauthorized(NeutronClientException):
message = _("Unauthorized: bad credentials.") message = _("Unauthorized: bad credentials.")
class Forbidden(QuantumClientException): class Forbidden(NeutronClientException):
message = _("Forbidden: your credentials don't give you access to this " message = _("Forbidden: your credentials don't give you access to this "
"resource.") "resource.")
class EndpointNotFound(QuantumClientException): class EndpointNotFound(NeutronClientException):
"""Could not find Service or Region in Service Catalog.""" """Could not find Service or Region in Service Catalog."""
message = _("Could not find Service or Region in Service Catalog.") message = _("Could not find Service or Region in Service Catalog.")
class EndpointTypeNotFound(QuantumClientException): class EndpointTypeNotFound(NeutronClientException):
"""Could not find endpoint type in Service Catalog.""" """Could not find endpoint type in Service Catalog."""
def __str__(self): def __str__(self):
@ -112,19 +112,19 @@ class EndpointTypeNotFound(QuantumClientException):
return msg % repr(self.message) return msg % repr(self.message)
class AmbiguousEndpoints(QuantumClientException): class AmbiguousEndpoints(NeutronClientException):
"""Found more than one matching endpoint in Service Catalog.""" """Found more than one matching endpoint in Service Catalog."""
def __str__(self): def __str__(self):
return "AmbiguousEndpoints: %s" % repr(self.message) return "AmbiguousEndpoints: %s" % repr(self.message)
class QuantumCLIError(QuantumClientException): class NeutronCLIError(NeutronClientException):
"""Exception raised when command line parsing fails.""" """Exception raised when command line parsing fails."""
pass pass
class RequestURITooLong(QuantumClientException): class RequestURITooLong(NeutronClientException):
"""Raised when a request fails with HTTP error 414.""" """Raised when a request fails with HTTP error 414."""
def __init__(self, **kwargs): def __init__(self, **kwargs):
@ -132,8 +132,8 @@ class RequestURITooLong(QuantumClientException):
super(RequestURITooLong, self).__init__(**kwargs) super(RequestURITooLong, self).__init__(**kwargs)
class ConnectionFailed(QuantumClientException): class ConnectionFailed(NeutronClientException):
message = _("Connection to quantum failed: %(reason)s") message = _("Connection to neutron failed: %(reason)s")
class BadInputError(Exception): class BadInputError(Exception):
@ -146,7 +146,7 @@ class Error(Exception):
super(Error, self).__init__(message) super(Error, self).__init__(message)
class MalformedRequestBody(QuantumException): class MalformedRequestBody(NeutronException):
message = _("Malformed request body: %(reason)s") message = _("Malformed request body: %(reason)s")

View File

@ -16,7 +16,7 @@
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # vim: tabstop=4 shiftwidth=4 softtabstop=4
### ###
### Codes from quantum wsgi ### Codes from neutron wsgi
### ###
import logging import logging
@ -24,10 +24,10 @@ import logging
from xml.etree import ElementTree as etree from xml.etree import ElementTree as etree
from xml.parsers import expat from xml.parsers import expat
from quantumclient.common import constants from neutronclient.common import constants
from quantumclient.common import exceptions as exception from neutronclient.common import exceptions as exception
from quantumclient.openstack.common.gettextutils import _ from neutronclient.openstack.common.gettextutils import _
from quantumclient.openstack.common import jsonutils from neutronclient.openstack.common import jsonutils
LOG = logging.getLogger(__name__) LOG = logging.getLogger(__name__)
@ -360,7 +360,7 @@ class XMLDeserializer(TextDeserializer):
return self.default(datastring) return self.default(datastring)
# NOTE(maru): this class is duplicated from quantum.wsgi # NOTE(maru): this class is duplicated from neutron.wsgi
class Serializer(object): class Serializer(object):
"""Serializes and deserializes dictionaries to certain MIME types.""" """Serializes and deserializes dictionaries to certain MIME types."""

View File

@ -26,8 +26,8 @@ import logging
import os import os
import sys import sys
from quantumclient.common import exceptions from neutronclient.common import exceptions
from quantumclient.openstack.common import strutils from neutronclient.openstack.common import strutils
def env(*vars, **kwargs): def env(*vars, **kwargs):

View File

@ -15,20 +15,20 @@
# #
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # vim: tabstop=4 shiftwidth=4 softtabstop=4
from quantumclient.common import exceptions from neutronclient.common import exceptions
from quantumclient.common import utils from neutronclient.common import utils
API_NAME = 'network' API_NAME = 'network'
API_VERSIONS = { API_VERSIONS = {
'2.0': 'quantumclient.v2_0.client.Client', '2.0': 'neutronclient.v2_0.client.Client',
} }
def make_client(instance): def make_client(instance):
"""Returns an quantum client. """Returns an neutron client.
""" """
quantum_client = utils.get_client_class( neutron_client = utils.get_client_class(
API_NAME, API_NAME,
instance._api_version[API_NAME], instance._api_version[API_NAME],
API_VERSIONS, API_VERSIONS,
@ -37,7 +37,7 @@ def make_client(instance):
url = instance._url url = instance._url
url = url.rstrip("/") url = url.rstrip("/")
if '2.0' == instance._api_version[API_NAME]: if '2.0' == instance._api_version[API_NAME]:
client = quantum_client(username=instance._username, client = neutron_client(username=instance._username,
tenant_name=instance._tenant_name, tenant_name=instance._tenant_name,
password=instance._password, password=instance._password,
region_name=instance._region_name, region_name=instance._region_name,
@ -53,12 +53,12 @@ def make_client(instance):
def Client(api_version, *args, **kwargs): def Client(api_version, *args, **kwargs):
"""Return an quantum client. """Return an neutron client.
@param api_version: only 2.0 is supported now @param api_version: only 2.0 is supported now
""" """
quantum_client = utils.get_client_class( neutron_client = utils.get_client_class(
API_NAME, API_NAME,
api_version, api_version,
API_VERSIONS, API_VERSIONS,
) )
return quantum_client(*args, **kwargs) return neutron_client(*args, **kwargs)

View File

@ -23,10 +23,10 @@ from cliff.formatters import table
from cliff import lister from cliff import lister
from cliff import show from cliff import show
from quantumclient.common import command from neutronclient.common import command
from quantumclient.common import exceptions from neutronclient.common import exceptions
from quantumclient.common import utils from neutronclient.common import utils
from quantumclient.openstack.common.gettextutils import _ from neutronclient.openstack.common.gettextutils import _
HEX_ELEM = '[0-9A-Fa-f]' HEX_ELEM = '[0-9A-Fa-f]'
UUID_PATTERN = '-'.join([HEX_ELEM + '{8}', HEX_ELEM + '{4}', UUID_PATTERN = '-'.join([HEX_ELEM + '{8}', HEX_ELEM + '{4}',
@ -55,14 +55,14 @@ def _find_resourceid_by_name(client, resource, name):
msg = (_("Multiple %(resource)s matches found for name '%(name)s'," msg = (_("Multiple %(resource)s matches found for name '%(name)s',"
" use an ID to be more specific.") % " use an ID to be more specific.") %
{'resource': resource, 'name': name}) {'resource': resource, 'name': name})
raise exceptions.QuantumClientException( raise exceptions.NeutronClientException(
message=msg) message=msg)
elif len(info) == 0: elif len(info) == 0:
not_found_message = (_("Unable to find %(resource)s with name " not_found_message = (_("Unable to find %(resource)s with name "
"'%(name)s'") % "'%(name)s'") %
{'resource': resource, 'name': name}) {'resource': resource, 'name': name})
# 404 is used to simulate server side behavior # 404 is used to simulate server side behavior
raise exceptions.QuantumClientException( raise exceptions.NeutronClientException(
message=not_found_message, status_code=404) message=not_found_message, status_code=404)
else: else:
return info[0]['id'] return info[0]['id']
@ -257,7 +257,7 @@ def update_dict(obj, dict, attributes):
class TableFormater(table.TableFormatter): class TableFormater(table.TableFormatter):
"""This class is used to keep consistency with prettytable 0.6. """This class is used to keep consistency with prettytable 0.6.
https://bugs.launchpad.net/python-quantumclient/+bug/1165962 https://bugs.launchpad.net/python-neutronclient/+bug/1165962
""" """
def emit_list(self, column_names, data, stdout, parsed_args): def emit_list(self, column_names, data, stdout, parsed_args):
if column_names: if column_names:
@ -267,22 +267,22 @@ class TableFormater(table.TableFormatter):
stdout.write('\n') stdout.write('\n')
class QuantumCommand(command.OpenStackCommand): class NeutronCommand(command.OpenStackCommand):
api = 'network' api = 'network'
log = logging.getLogger(__name__ + '.QuantumCommand') log = logging.getLogger(__name__ + '.NeutronCommand')
values_specs = [] values_specs = []
json_indent = None json_indent = None
def __init__(self, app, app_args): def __init__(self, app, app_args):
super(QuantumCommand, self).__init__(app, app_args) super(NeutronCommand, self).__init__(app, app_args)
if hasattr(self, 'formatters'): if hasattr(self, 'formatters'):
self.formatters['table'] = TableFormater() self.formatters['table'] = TableFormater()
def get_client(self): def get_client(self):
return self.app.client_manager.quantum return self.app.client_manager.neutron
def get_parser(self, prog_name): def get_parser(self, prog_name):
parser = super(QuantumCommand, self).get_parser(prog_name) parser = super(NeutronCommand, self).get_parser(prog_name)
parser.add_argument( parser.add_argument(
'--request-format', '--request-format',
help=_('the xml or json request format'), help=_('the xml or json request format'),
@ -317,7 +317,7 @@ class QuantumCommand(command.OpenStackCommand):
return {} return {}
class CreateCommand(QuantumCommand, show.ShowOne): class CreateCommand(NeutronCommand, show.ShowOne):
"""Create a resource for a given tenant """Create a resource for a given tenant
""" """
@ -339,14 +339,14 @@ class CreateCommand(QuantumCommand, show.ShowOne):
def get_data(self, parsed_args): def get_data(self, parsed_args):
self.log.debug('get_data(%s)' % parsed_args) self.log.debug('get_data(%s)' % parsed_args)
quantum_client = self.get_client() neutron_client = self.get_client()
quantum_client.format = parsed_args.request_format neutron_client.format = parsed_args.request_format
_extra_values = parse_args_to_dict(self.values_specs) _extra_values = parse_args_to_dict(self.values_specs)
_merge_args(self, parsed_args, _extra_values, _merge_args(self, parsed_args, _extra_values,
self.values_specs) self.values_specs)
body = self.args2body(parsed_args) body = self.args2body(parsed_args)
body[self.resource].update(_extra_values) body[self.resource].update(_extra_values)
obj_creator = getattr(quantum_client, obj_creator = getattr(neutron_client,
"create_%s" % self.resource) "create_%s" % self.resource)
data = obj_creator(body) data = obj_creator(body)
self.format_output_data(data) self.format_output_data(data)
@ -359,7 +359,7 @@ class CreateCommand(QuantumCommand, show.ShowOne):
return zip(*sorted(info.iteritems())) return zip(*sorted(info.iteritems()))
class UpdateCommand(QuantumCommand): class UpdateCommand(NeutronCommand):
"""Update resource's information """Update resource's information
""" """
@ -377,8 +377,8 @@ class UpdateCommand(QuantumCommand):
def run(self, parsed_args): def run(self, parsed_args):
self.log.debug('run(%s)' % parsed_args) self.log.debug('run(%s)' % parsed_args)
quantum_client = self.get_client() neutron_client = self.get_client()
quantum_client.format = parsed_args.request_format neutron_client.format = parsed_args.request_format
_extra_values = parse_args_to_dict(self.values_specs) _extra_values = parse_args_to_dict(self.values_specs)
_merge_args(self, parsed_args, _extra_values, _merge_args(self, parsed_args, _extra_values,
self.values_specs) self.values_specs)
@ -390,10 +390,10 @@ class UpdateCommand(QuantumCommand):
if not body[self.resource]: if not body[self.resource]:
raise exceptions.CommandError( raise exceptions.CommandError(
"Must specify new values to update %s" % self.resource) "Must specify new values to update %s" % self.resource)
_id = find_resourceid_by_name_or_id(quantum_client, _id = find_resourceid_by_name_or_id(neutron_client,
self.resource, self.resource,
parsed_args.id) parsed_args.id)
obj_updator = getattr(quantum_client, obj_updator = getattr(neutron_client,
"update_%s" % self.resource) "update_%s" % self.resource)
obj_updator(_id, body) obj_updator(_id, body)
print >>self.app.stdout, ( print >>self.app.stdout, (
@ -402,7 +402,7 @@ class UpdateCommand(QuantumCommand):
return return
class DeleteCommand(QuantumCommand): class DeleteCommand(NeutronCommand):
"""Delete a given resource """Delete a given resource
""" """
@ -425,12 +425,12 @@ class DeleteCommand(QuantumCommand):
def run(self, parsed_args): def run(self, parsed_args):
self.log.debug('run(%s)' % parsed_args) self.log.debug('run(%s)' % parsed_args)
quantum_client = self.get_client() neutron_client = self.get_client()
quantum_client.format = parsed_args.request_format neutron_client.format = parsed_args.request_format
obj_deleter = getattr(quantum_client, obj_deleter = getattr(neutron_client,
"delete_%s" % self.resource) "delete_%s" % self.resource)
if self.allow_names: if self.allow_names:
_id = find_resourceid_by_name_or_id(quantum_client, self.resource, _id = find_resourceid_by_name_or_id(neutron_client, self.resource,
parsed_args.id) parsed_args.id)
else: else:
_id = parsed_args.id _id = parsed_args.id
@ -441,7 +441,7 @@ class DeleteCommand(QuantumCommand):
return return
class ListCommand(QuantumCommand, lister.Lister): class ListCommand(NeutronCommand, lister.Lister):
"""List resources that belong to a given tenant """List resources that belong to a given tenant
""" """
@ -473,16 +473,16 @@ class ListCommand(QuantumCommand, lister.Lister):
search_opts.update({'verbose': 'True'}) search_opts.update({'verbose': 'True'})
return search_opts return search_opts
def call_server(self, quantum_client, search_opts, parsed_args): def call_server(self, neutron_client, search_opts, parsed_args):
obj_lister = getattr(quantum_client, obj_lister = getattr(neutron_client,
"list_%ss" % self.resource) "list_%ss" % self.resource)
data = obj_lister(**search_opts) data = obj_lister(**search_opts)
return data return data
def retrieve_list(self, parsed_args): def retrieve_list(self, parsed_args):
"""Retrieve a list of resources from Quantum server""" """Retrieve a list of resources from Neutron server"""
quantum_client = self.get_client() neutron_client = self.get_client()
quantum_client.format = parsed_args.request_format neutron_client.format = parsed_args.request_format
_extra_values = parse_args_to_dict(self.values_specs) _extra_values = parse_args_to_dict(self.values_specs)
_merge_args(self, parsed_args, _extra_values, _merge_args(self, parsed_args, _extra_values,
self.values_specs) self.values_specs)
@ -504,7 +504,7 @@ class ListCommand(QuantumCommand, lister.Lister):
dirs = dirs[:len(keys)] dirs = dirs[:len(keys)]
if dirs: if dirs:
search_opts.update({'sort_dir': dirs}) search_opts.update({'sort_dir': dirs})
data = self.call_server(quantum_client, search_opts, parsed_args) data = self.call_server(neutron_client, search_opts, parsed_args)
collection = self.resource + "s" collection = self.resource + "s"
return data.get(collection, []) return data.get(collection, [])
@ -512,7 +512,7 @@ class ListCommand(QuantumCommand, lister.Lister):
"""Update a retrieved list. """Update a retrieved list.
This method provides a way to modify a original list returned from This method provides a way to modify a original list returned from
the quantum server. For example, you can add subnet cidr information the neutron server. For example, you can add subnet cidr information
to a list network. to a list network.
""" """
pass pass
@ -540,7 +540,7 @@ class ListCommand(QuantumCommand, lister.Lister):
return self.setup_columns(data, parsed_args) return self.setup_columns(data, parsed_args)
class ShowCommand(QuantumCommand, show.ShowOne): class ShowCommand(NeutronCommand, show.ShowOne):
"""Show information of a given resource """Show information of a given resource
""" """
@ -564,8 +564,8 @@ class ShowCommand(QuantumCommand, show.ShowOne):
def get_data(self, parsed_args): def get_data(self, parsed_args):
self.log.debug('get_data(%s)' % parsed_args) self.log.debug('get_data(%s)' % parsed_args)
quantum_client = self.get_client() neutron_client = self.get_client()
quantum_client.format = parsed_args.request_format neutron_client.format = parsed_args.request_format
params = {} params = {}
if parsed_args.show_details: if parsed_args.show_details:
@ -573,12 +573,12 @@ class ShowCommand(QuantumCommand, show.ShowOne):
if parsed_args.fields: if parsed_args.fields:
params = {'fields': parsed_args.fields} params = {'fields': parsed_args.fields}
if self.allow_names: if self.allow_names:
_id = find_resourceid_by_name_or_id(quantum_client, self.resource, _id = find_resourceid_by_name_or_id(neutron_client, self.resource,
parsed_args.id) parsed_args.id)
else: else:
_id = parsed_args.id _id = parsed_args.id
obj_shower = getattr(quantum_client, "show_%s" % self.resource) obj_shower = getattr(neutron_client, "show_%s" % self.resource)
data = obj_shower(_id, **params) data = obj_shower(_id, **params)
self.format_output_data(data) self.format_output_data(data)
resource = data[self.resource] resource = data[self.resource]

View File

@ -17,7 +17,7 @@
import logging import logging
from quantumclient.quantum import v2_0 as quantumV20 from neutronclient.neutron import v2_0 as neutronV20
def _format_timestamp(component): def _format_timestamp(component):
@ -27,7 +27,7 @@ def _format_timestamp(component):
return '' return ''
class ListAgent(quantumV20.ListCommand): class ListAgent(neutronV20.ListCommand):
"""List agents.""" """List agents."""
resource = 'agent' resource = 'agent'
@ -40,7 +40,7 @@ class ListAgent(quantumV20.ListCommand):
agent['alive'] = ":-)" if agent['alive'] else 'xxx' agent['alive'] = ":-)" if agent['alive'] else 'xxx'
class ShowAgent(quantumV20.ShowCommand): class ShowAgent(neutronV20.ShowCommand):
"""Show information of a given agent.""" """Show information of a given agent."""
resource = 'agent' resource = 'agent'
@ -49,7 +49,7 @@ class ShowAgent(quantumV20.ShowCommand):
json_indent = 5 json_indent = 5
class DeleteAgent(quantumV20.DeleteCommand): class DeleteAgent(neutronV20.DeleteCommand):
"""Delete a given agent.""" """Delete a given agent."""
log = logging.getLogger(__name__ + '.DeleteAgent') log = logging.getLogger(__name__ + '.DeleteAgent')
@ -57,7 +57,7 @@ class DeleteAgent(quantumV20.DeleteCommand):
allow_names = False allow_names = False
class UpdateAgent(quantumV20.UpdateCommand): class UpdateAgent(neutronV20.UpdateCommand):
"""Update a given agent.""" """Update a given agent."""
log = logging.getLogger(__name__ + '.UpdateAgent') log = logging.getLogger(__name__ + '.UpdateAgent')

View File

@ -17,14 +17,14 @@
import logging import logging
from quantumclient.openstack.common.gettextutils import _ from neutronclient.neutron import v2_0 as neutronV20
from quantumclient.quantum import v2_0 as quantumV20 from neutronclient.neutron.v2_0 import network
from quantumclient.quantum.v2_0 import network from neutronclient.neutron.v2_0 import router
from quantumclient.quantum.v2_0 import router from neutronclient.openstack.common.gettextutils import _
PERFECT_TIME_FORMAT = "%Y-%m-%dT%H:%M:%S.%f" PERFECT_TIME_FORMAT = "%Y-%m-%dT%H:%M:%S.%f"
class AddNetworkToDhcpAgent(quantumV20.QuantumCommand): class AddNetworkToDhcpAgent(neutronV20.NeutronCommand):
"""Add a network to a DHCP agent.""" """Add a network to a DHCP agent."""
log = logging.getLogger(__name__ + '.AddNetworkToDhcpAgent') log = logging.getLogger(__name__ + '.AddNetworkToDhcpAgent')
@ -41,17 +41,17 @@ class AddNetworkToDhcpAgent(quantumV20.QuantumCommand):
def run(self, parsed_args): def run(self, parsed_args):
self.log.debug('run(%s)' % parsed_args) self.log.debug('run(%s)' % parsed_args)
quantum_client = self.get_client() neutron_client = self.get_client()
quantum_client.format = parsed_args.request_format neutron_client.format = parsed_args.request_format
_net_id = quantumV20.find_resourceid_by_name_or_id( _net_id = neutronV20.find_resourceid_by_name_or_id(
quantum_client, 'network', parsed_args.network) neutron_client, 'network', parsed_args.network)
quantum_client.add_network_to_dhcp_agent(parsed_args.dhcp_agent, neutron_client.add_network_to_dhcp_agent(parsed_args.dhcp_agent,
{'network_id': _net_id}) {'network_id': _net_id})
print >>self.app.stdout, ( print >>self.app.stdout, (
_('Added network %s to DHCP agent') % parsed_args.network) _('Added network %s to DHCP agent') % parsed_args.network)
class RemoveNetworkFromDhcpAgent(quantumV20.QuantumCommand): class RemoveNetworkFromDhcpAgent(neutronV20.NeutronCommand):
"""Remove a network from a DHCP agent.""" """Remove a network from a DHCP agent."""
log = logging.getLogger(__name__ + '.RemoveNetworkFromDhcpAgent') log = logging.getLogger(__name__ + '.RemoveNetworkFromDhcpAgent')
@ -67,11 +67,11 @@ class RemoveNetworkFromDhcpAgent(quantumV20.QuantumCommand):
def run(self, parsed_args): def run(self, parsed_args):
self.log.debug('run(%s)' % parsed_args) self.log.debug('run(%s)' % parsed_args)
quantum_client = self.get_client() neutron_client = self.get_client()
quantum_client.format = parsed_args.request_format neutron_client.format = parsed_args.request_format
_net_id = quantumV20.find_resourceid_by_name_or_id( _net_id = neutronV20.find_resourceid_by_name_or_id(
quantum_client, 'network', parsed_args.network) neutron_client, 'network', parsed_args.network)
quantum_client.remove_network_from_dhcp_agent( neutron_client.remove_network_from_dhcp_agent(
parsed_args.dhcp_agent, _net_id) parsed_args.dhcp_agent, _net_id)
print >>self.app.stdout, ( print >>self.app.stdout, (
_('Removed network %s to DHCP agent') % parsed_args.network) _('Removed network %s to DHCP agent') % parsed_args.network)
@ -91,13 +91,13 @@ class ListNetworksOnDhcpAgent(network.ListNetwork):
help='ID of the DHCP agent') help='ID of the DHCP agent')
return parser return parser
def call_server(self, quantum_client, search_opts, parsed_args): def call_server(self, neutron_client, search_opts, parsed_args):
data = quantum_client.list_networks_on_dhcp_agent( data = neutron_client.list_networks_on_dhcp_agent(
parsed_args.dhcp_agent, **search_opts) parsed_args.dhcp_agent, **search_opts)
return data return data
class ListDhcpAgentsHostingNetwork(quantumV20.ListCommand): class ListDhcpAgentsHostingNetwork(neutronV20.ListCommand):
"""List DHCP agents hosting a network.""" """List DHCP agents hosting a network."""
resource = 'agent' resource = 'agent'
@ -118,16 +118,16 @@ class ListDhcpAgentsHostingNetwork(quantumV20.ListCommand):
for agent in data: for agent in data:
agent['alive'] = ":-)" if agent['alive'] else 'xxx' agent['alive'] = ":-)" if agent['alive'] else 'xxx'
def call_server(self, quantum_client, search_opts, parsed_args): def call_server(self, neutron_client, search_opts, parsed_args):
_id = quantumV20.find_resourceid_by_name_or_id(quantum_client, _id = neutronV20.find_resourceid_by_name_or_id(neutron_client,
'network', 'network',
parsed_args.network) parsed_args.network)
search_opts['network'] = _id search_opts['network'] = _id
data = quantum_client.list_dhcp_agent_hosting_networks(**search_opts) data = neutron_client.list_dhcp_agent_hosting_networks(**search_opts)
return data return data
class AddRouterToL3Agent(quantumV20.QuantumCommand): class AddRouterToL3Agent(neutronV20.NeutronCommand):
"""Add a router to a L3 agent.""" """Add a router to a L3 agent."""
log = logging.getLogger(__name__ + '.AddRouterToL3Agent') log = logging.getLogger(__name__ + '.AddRouterToL3Agent')
@ -144,17 +144,17 @@ class AddRouterToL3Agent(quantumV20.QuantumCommand):
def run(self, parsed_args): def run(self, parsed_args):
self.log.debug('run(%s)' % parsed_args) self.log.debug('run(%s)' % parsed_args)
quantum_client = self.get_client() neutron_client = self.get_client()
quantum_client.format = parsed_args.request_format neutron_client.format = parsed_args.request_format
_id = quantumV20.find_resourceid_by_name_or_id( _id = neutronV20.find_resourceid_by_name_or_id(
quantum_client, 'router', parsed_args.router) neutron_client, 'router', parsed_args.router)
quantum_client.add_router_to_l3_agent(parsed_args.l3_agent, neutron_client.add_router_to_l3_agent(parsed_args.l3_agent,
{'router_id': _id}) {'router_id': _id})
print >>self.app.stdout, ( print >>self.app.stdout, (
_('Added router %s to L3 agent') % parsed_args.router) _('Added router %s to L3 agent') % parsed_args.router)
class RemoveRouterFromL3Agent(quantumV20.QuantumCommand): class RemoveRouterFromL3Agent(neutronV20.NeutronCommand):
"""Remove a router from a L3 agent.""" """Remove a router from a L3 agent."""
log = logging.getLogger(__name__ + '.RemoveRouterFromL3Agent') log = logging.getLogger(__name__ + '.RemoveRouterFromL3Agent')
@ -171,17 +171,17 @@ class RemoveRouterFromL3Agent(quantumV20.QuantumCommand):
def run(self, parsed_args): def run(self, parsed_args):
self.log.debug('run(%s)' % parsed_args) self.log.debug('run(%s)' % parsed_args)
quantum_client = self.get_client() neutron_client = self.get_client()
quantum_client.format = parsed_args.request_format neutron_client.format = parsed_args.request_format
_id = quantumV20.find_resourceid_by_name_or_id( _id = neutronV20.find_resourceid_by_name_or_id(
quantum_client, 'router', parsed_args.router) neutron_client, 'router', parsed_args.router)
quantum_client.remove_router_from_l3_agent( neutron_client.remove_router_from_l3_agent(
parsed_args.l3_agent, _id) parsed_args.l3_agent, _id)
print >>self.app.stdout, ( print >>self.app.stdout, (
_('Removed Router %s to L3 agent') % parsed_args.router) _('Removed Router %s to L3 agent') % parsed_args.router)
class ListRoutersOnL3Agent(quantumV20.ListCommand): class ListRoutersOnL3Agent(neutronV20.ListCommand):
"""List the routers on a L3 agent.""" """List the routers on a L3 agent."""
log = logging.getLogger(__name__ + '.ListRoutersOnL3Agent') log = logging.getLogger(__name__ + '.ListRoutersOnL3Agent')
@ -199,13 +199,13 @@ class ListRoutersOnL3Agent(quantumV20.ListCommand):
help='ID of the L3 agent to query') help='ID of the L3 agent to query')
return parser return parser
def call_server(self, quantum_client, search_opts, parsed_args): def call_server(self, neutron_client, search_opts, parsed_args):
data = quantum_client.list_routers_on_l3_agent( data = neutron_client.list_routers_on_l3_agent(
parsed_args.l3_agent, **search_opts) parsed_args.l3_agent, **search_opts)
return data return data
class ListL3AgentsHostingRouter(quantumV20.ListCommand): class ListL3AgentsHostingRouter(neutronV20.ListCommand):
"""List L3 agents hosting a router.""" """List L3 agents hosting a router."""
resource = 'agent' resource = 'agent'
@ -225,10 +225,10 @@ class ListL3AgentsHostingRouter(quantumV20.ListCommand):
for agent in data: for agent in data:
agent['alive'] = ":-)" if agent['alive'] else 'xxx' agent['alive'] = ":-)" if agent['alive'] else 'xxx'
def call_server(self, quantum_client, search_opts, parsed_args): def call_server(self, neutron_client, search_opts, parsed_args):
_id = quantumV20.find_resourceid_by_name_or_id(quantum_client, _id = neutronV20.find_resourceid_by_name_or_id(neutron_client,
'router', 'router',
parsed_args.router) parsed_args.router)
search_opts['router'] = _id search_opts['router'] = _id
data = quantum_client.list_l3_agent_hosting_routers(**search_opts) data = neutron_client.list_l3_agent_hosting_routers(**search_opts)
return data return data

View File

@ -17,7 +17,7 @@
import logging import logging
from quantumclient.quantum import v2_0 as cmd_base from neutronclient.neutron import v2_0 as cmd_base
class ListExt(cmd_base.ListCommand): class ListExt(cmd_base.ListCommand):

View File

@ -18,11 +18,11 @@
import argparse import argparse
import logging import logging
from quantumclient.openstack.common.gettextutils import _ from neutronclient.neutron import v2_0 as neutronV20
from quantumclient.quantum import v2_0 as quantumv20 from neutronclient.openstack.common.gettextutils import _
class ListFloatingIP(quantumv20.ListCommand): class ListFloatingIP(neutronV20.ListCommand):
"""List floating ips that belong to a given tenant.""" """List floating ips that belong to a given tenant."""
resource = 'floatingip' resource = 'floatingip'
@ -33,7 +33,7 @@ class ListFloatingIP(quantumv20.ListCommand):
sorting_support = True sorting_support = True
class ShowFloatingIP(quantumv20.ShowCommand): class ShowFloatingIP(neutronV20.ShowCommand):
"""Show information of a given floating ip.""" """Show information of a given floating ip."""
resource = 'floatingip' resource = 'floatingip'
@ -41,7 +41,7 @@ class ShowFloatingIP(quantumv20.ShowCommand):
allow_names = False allow_names = False
class CreateFloatingIP(quantumv20.CreateCommand): class CreateFloatingIP(neutronV20.CreateCommand):
"""Create a floating ip for a given tenant.""" """Create a floating ip for a given tenant."""
resource = 'floatingip' resource = 'floatingip'
@ -66,7 +66,7 @@ class CreateFloatingIP(quantumv20.CreateCommand):
help=argparse.SUPPRESS) help=argparse.SUPPRESS)
def args2body(self, parsed_args): def args2body(self, parsed_args):
_network_id = quantumv20.find_resourceid_by_name_or_id( _network_id = neutronV20.find_resourceid_by_name_or_id(
self.get_client(), 'network', parsed_args.floating_network_id) self.get_client(), 'network', parsed_args.floating_network_id)
body = {self.resource: {'floating_network_id': _network_id}} body = {self.resource: {'floating_network_id': _network_id}}
if parsed_args.port_id: if parsed_args.port_id:
@ -79,7 +79,7 @@ class CreateFloatingIP(quantumv20.CreateCommand):
return body return body
class DeleteFloatingIP(quantumv20.DeleteCommand): class DeleteFloatingIP(neutronV20.DeleteCommand):
"""Delete a given floating ip.""" """Delete a given floating ip."""
log = logging.getLogger(__name__ + '.DeleteFloatingIP') log = logging.getLogger(__name__ + '.DeleteFloatingIP')
@ -87,7 +87,7 @@ class DeleteFloatingIP(quantumv20.DeleteCommand):
allow_names = False allow_names = False
class AssociateFloatingIP(quantumv20.QuantumCommand): class AssociateFloatingIP(neutronV20.NeutronCommand):
"""Create a mapping between a floating ip and a fixed ip.""" """Create a mapping between a floating ip and a fixed ip."""
api = 'network' api = 'network'
@ -113,20 +113,20 @@ class AssociateFloatingIP(quantumv20.QuantumCommand):
def run(self, parsed_args): def run(self, parsed_args):
self.log.debug('run(%s)' % parsed_args) self.log.debug('run(%s)' % parsed_args)
quantum_client = self.get_client() neutron_client = self.get_client()
quantum_client.format = parsed_args.request_format neutron_client.format = parsed_args.request_format
update_dict = {} update_dict = {}
if parsed_args.port_id: if parsed_args.port_id:
update_dict['port_id'] = parsed_args.port_id update_dict['port_id'] = parsed_args.port_id
if parsed_args.fixed_ip_address: if parsed_args.fixed_ip_address:
update_dict['fixed_ip_address'] = parsed_args.fixed_ip_address update_dict['fixed_ip_address'] = parsed_args.fixed_ip_address
quantum_client.update_floatingip(parsed_args.floatingip_id, neutron_client.update_floatingip(parsed_args.floatingip_id,
{'floatingip': update_dict}) {'floatingip': update_dict})
print >>self.app.stdout, ( print >>self.app.stdout, (
_('Associated floatingip %s') % parsed_args.floatingip_id) _('Associated floatingip %s') % parsed_args.floatingip_id)
class DisassociateFloatingIP(quantumv20.QuantumCommand): class DisassociateFloatingIP(neutronV20.NeutronCommand):
"""Remove a mapping from a floating ip to a fixed ip. """Remove a mapping from a floating ip to a fixed ip.
""" """
@ -143,9 +143,9 @@ class DisassociateFloatingIP(quantumv20.QuantumCommand):
def run(self, parsed_args): def run(self, parsed_args):
self.log.debug('run(%s)' % parsed_args) self.log.debug('run(%s)' % parsed_args)
quantum_client = self.get_client() neutron_client = self.get_client()
quantum_client.format = parsed_args.request_format neutron_client.format = parsed_args.request_format
quantum_client.update_floatingip(parsed_args.floatingip_id, neutron_client.update_floatingip(parsed_args.floatingip_id,
{'floatingip': {'port_id': None}}) {'floatingip': {'port_id': None}})
print >>self.app.stdout, ( print >>self.app.stdout, (
_('Disassociated floatingip %s') % parsed_args.floatingip_id) _('Disassociated floatingip %s') % parsed_args.floatingip_id)

View File

@ -19,11 +19,11 @@
import logging import logging
from quantumclient.openstack.common.gettextutils import _ from neutronclient.neutron import v2_0 as neutronV20
from quantumclient.quantum import v2_0 as quantumv20 from neutronclient.openstack.common.gettextutils import _
class ListHealthMonitor(quantumv20.ListCommand): class ListHealthMonitor(neutronV20.ListCommand):
"""List healthmonitors that belong to a given tenant.""" """List healthmonitors that belong to a given tenant."""
resource = 'health_monitor' resource = 'health_monitor'
@ -33,14 +33,14 @@ class ListHealthMonitor(quantumv20.ListCommand):
sorting_support = True sorting_support = True
class ShowHealthMonitor(quantumv20.ShowCommand): class ShowHealthMonitor(neutronV20.ShowCommand):
"""Show information of a given healthmonitor.""" """Show information of a given healthmonitor."""
resource = 'health_monitor' resource = 'health_monitor'
log = logging.getLogger(__name__ + '.ShowHealthMonitor') log = logging.getLogger(__name__ + '.ShowHealthMonitor')
class CreateHealthMonitor(quantumv20.CreateCommand): class CreateHealthMonitor(neutronV20.CreateCommand):
"""Create a healthmonitor.""" """Create a healthmonitor."""
resource = 'health_monitor' resource = 'health_monitor'
@ -99,27 +99,27 @@ class CreateHealthMonitor(quantumv20.CreateCommand):
'type': parsed_args.type, 'type': parsed_args.type,
}, },
} }
quantumv20.update_dict(parsed_args, body[self.resource], neutronV20.update_dict(parsed_args, body[self.resource],
['expected_codes', 'http_method', 'url_path', ['expected_codes', 'http_method', 'url_path',
'tenant_id']) 'tenant_id'])
return body return body
class UpdateHealthMonitor(quantumv20.UpdateCommand): class UpdateHealthMonitor(neutronV20.UpdateCommand):
"""Update a given healthmonitor.""" """Update a given healthmonitor."""
resource = 'health_monitor' resource = 'health_monitor'
log = logging.getLogger(__name__ + '.UpdateHealthMonitor') log = logging.getLogger(__name__ + '.UpdateHealthMonitor')
class DeleteHealthMonitor(quantumv20.DeleteCommand): class DeleteHealthMonitor(neutronV20.DeleteCommand):
"""Delete a given healthmonitor.""" """Delete a given healthmonitor."""
resource = 'health_monitor' resource = 'health_monitor'
log = logging.getLogger(__name__ + '.DeleteHealthMonitor') log = logging.getLogger(__name__ + '.DeleteHealthMonitor')
class AssociateHealthMonitor(quantumv20.QuantumCommand): class AssociateHealthMonitor(neutronV20.NeutronCommand):
"""Create a mapping between a health monitor and a pool.""" """Create a mapping between a health monitor and a pool."""
log = logging.getLogger(__name__ + '.AssociateHealthMonitor') log = logging.getLogger(__name__ + '.AssociateHealthMonitor')
@ -136,17 +136,17 @@ class AssociateHealthMonitor(quantumv20.QuantumCommand):
return parser return parser
def run(self, parsed_args): def run(self, parsed_args):
quantum_client = self.get_client() neutron_client = self.get_client()
quantum_client.format = parsed_args.request_format neutron_client.format = parsed_args.request_format
body = {'health_monitor': {'id': parsed_args.health_monitor_id}} body = {'health_monitor': {'id': parsed_args.health_monitor_id}}
pool_id = quantumv20.find_resourceid_by_name_or_id( pool_id = neutronV20.find_resourceid_by_name_or_id(
quantum_client, 'pool', parsed_args.pool_id) neutron_client, 'pool', parsed_args.pool_id)
quantum_client.associate_health_monitor(pool_id, body) neutron_client.associate_health_monitor(pool_id, body)
print >>self.app.stdout, (_('Associated health monitor ' print >>self.app.stdout, (_('Associated health monitor '
'%s') % parsed_args.health_monitor_id) '%s') % parsed_args.health_monitor_id)
class DisassociateHealthMonitor(quantumv20.QuantumCommand): class DisassociateHealthMonitor(neutronV20.NeutronCommand):
"""Remove a mapping from a health monitor to a pool.""" """Remove a mapping from a health monitor to a pool."""
log = logging.getLogger(__name__ + '.DisassociateHealthMonitor') log = logging.getLogger(__name__ + '.DisassociateHealthMonitor')
@ -163,11 +163,11 @@ class DisassociateHealthMonitor(quantumv20.QuantumCommand):
return parser return parser
def run(self, parsed_args): def run(self, parsed_args):
quantum_client = self.get_client() neutron_client = self.get_client()
quantum_client.format = parsed_args.request_format neutron_client.format = parsed_args.request_format
pool_id = quantumv20.find_resourceid_by_name_or_id( pool_id = neutronV20.find_resourceid_by_name_or_id(
quantum_client, 'pool', parsed_args.pool_id) neutron_client, 'pool', parsed_args.pool_id)
quantum_client.disassociate_health_monitor(pool_id, neutron_client.disassociate_health_monitor(pool_id,
parsed_args parsed_args
.health_monitor_id) .health_monitor_id)
print >>self.app.stdout, (_('Disassociated health monitor ' print >>self.app.stdout, (_('Disassociated health monitor '

View File

@ -19,10 +19,10 @@
import logging import logging
from quantumclient.quantum import v2_0 as quantumv20 from neutronclient.neutron import v2_0 as neutronV20
class ListMember(quantumv20.ListCommand): class ListMember(neutronV20.ListCommand):
"""List members that belong to a given tenant.""" """List members that belong to a given tenant."""
resource = 'member' resource = 'member'
@ -34,14 +34,14 @@ class ListMember(quantumv20.ListCommand):
sorting_support = True sorting_support = True
class ShowMember(quantumv20.ShowCommand): class ShowMember(neutronV20.ShowCommand):
"""Show information of a given member.""" """Show information of a given member."""
resource = 'member' resource = 'member'
log = logging.getLogger(__name__ + '.ShowMember') log = logging.getLogger(__name__ + '.ShowMember')
class CreateMember(quantumv20.CreateCommand): class CreateMember(neutronV20.CreateCommand):
"""Create a member.""" """Create a member."""
resource = 'member' resource = 'member'
@ -69,7 +69,7 @@ class CreateMember(quantumv20.CreateCommand):
'connections. ') 'connections. ')
def args2body(self, parsed_args): def args2body(self, parsed_args):
_pool_id = quantumv20.find_resourceid_by_name_or_id( _pool_id = neutronV20.find_resourceid_by_name_or_id(
self.get_client(), 'pool', parsed_args.pool_id) self.get_client(), 'pool', parsed_args.pool_id)
body = { body = {
self.resource: { self.resource: {
@ -77,7 +77,7 @@ class CreateMember(quantumv20.CreateCommand):
'admin_state_up': parsed_args.admin_state, 'admin_state_up': parsed_args.admin_state,
}, },
} }
quantumv20.update_dict( neutronV20.update_dict(
parsed_args, parsed_args,
body[self.resource], body[self.resource],
['address', 'protocol_port', 'weight', 'tenant_id'] ['address', 'protocol_port', 'weight', 'tenant_id']
@ -85,14 +85,14 @@ class CreateMember(quantumv20.CreateCommand):
return body return body
class UpdateMember(quantumv20.UpdateCommand): class UpdateMember(neutronV20.UpdateCommand):
"""Update a given member.""" """Update a given member."""
resource = 'member' resource = 'member'
log = logging.getLogger(__name__ + '.UpdateMember') log = logging.getLogger(__name__ + '.UpdateMember')
class DeleteMember(quantumv20.DeleteCommand): class DeleteMember(neutronV20.DeleteCommand):
"""Delete a given member.""" """Delete a given member."""
resource = 'member' resource = 'member'

View File

@ -19,10 +19,10 @@
import logging import logging
from quantumclient.quantum import v2_0 as quantumv20 from neutronclient.neutron import v2_0 as neutronV20
class ListPool(quantumv20.ListCommand): class ListPool(neutronV20.ListCommand):
"""List pools that belong to a given tenant.""" """List pools that belong to a given tenant."""
resource = 'pool' resource = 'pool'
@ -33,14 +33,14 @@ class ListPool(quantumv20.ListCommand):
sorting_support = True sorting_support = True
class ShowPool(quantumv20.ShowCommand): class ShowPool(neutronV20.ShowCommand):
"""Show information of a given pool.""" """Show information of a given pool."""
resource = 'pool' resource = 'pool'
log = logging.getLogger(__name__ + '.ShowPool') log = logging.getLogger(__name__ + '.ShowPool')
class CreatePool(quantumv20.CreateCommand): class CreatePool(neutronV20.CreateCommand):
"""Create a pool.""" """Create a pool."""
resource = 'pool' resource = 'pool'
@ -73,7 +73,7 @@ class CreatePool(quantumv20.CreateCommand):
help='the subnet on which the members of the pool will be located') help='the subnet on which the members of the pool will be located')
def args2body(self, parsed_args): def args2body(self, parsed_args):
_subnet_id = quantumv20.find_resourceid_by_name_or_id( _subnet_id = neutronV20.find_resourceid_by_name_or_id(
self.get_client(), 'subnet', parsed_args.subnet_id) self.get_client(), 'subnet', parsed_args.subnet_id)
body = { body = {
self.resource: { self.resource: {
@ -81,27 +81,27 @@ class CreatePool(quantumv20.CreateCommand):
'subnet_id': _subnet_id, 'subnet_id': _subnet_id,
}, },
} }
quantumv20.update_dict(parsed_args, body[self.resource], neutronV20.update_dict(parsed_args, body[self.resource],
['description', 'lb_method', 'name', ['description', 'lb_method', 'name',
'protocol', 'tenant_id']) 'protocol', 'tenant_id'])
return body return body
class UpdatePool(quantumv20.UpdateCommand): class UpdatePool(neutronV20.UpdateCommand):
"""Update a given pool.""" """Update a given pool."""
resource = 'pool' resource = 'pool'
log = logging.getLogger(__name__ + '.UpdatePool') log = logging.getLogger(__name__ + '.UpdatePool')
class DeletePool(quantumv20.DeleteCommand): class DeletePool(neutronV20.DeleteCommand):
"""Delete a given pool.""" """Delete a given pool."""
resource = 'pool' resource = 'pool'
log = logging.getLogger(__name__ + '.DeletePool') log = logging.getLogger(__name__ + '.DeletePool')
class RetrievePoolStats(quantumv20.ShowCommand): class RetrievePoolStats(neutronV20.ShowCommand):
"""Retrieve stats for a given pool.""" """Retrieve stats for a given pool."""
resource = 'pool' resource = 'pool'
@ -109,13 +109,13 @@ class RetrievePoolStats(quantumv20.ShowCommand):
def get_data(self, parsed_args): def get_data(self, parsed_args):
self.log.debug('run(%s)' % parsed_args) self.log.debug('run(%s)' % parsed_args)
quantum_client = self.get_client() neutron_client = self.get_client()
quantum_client.format = parsed_args.request_format neutron_client.format = parsed_args.request_format
params = {} params = {}
if parsed_args.fields: if parsed_args.fields:
params = {'fields': parsed_args.fields} params = {'fields': parsed_args.fields}
data = quantum_client.retrieve_pool_stats(parsed_args.id, **params) data = neutron_client.retrieve_pool_stats(parsed_args.id, **params)
self.format_output_data(data) self.format_output_data(data)
stats = data['stats'] stats = data['stats']
if 'stats' in data: if 'stats' in data:

View File

@ -19,10 +19,10 @@
import logging import logging
from quantumclient.quantum import v2_0 as quantumv20 from neutronclient.neutron import v2_0 as neutronV20
class ListVip(quantumv20.ListCommand): class ListVip(neutronV20.ListCommand):
"""List vips that belong to a given tenant.""" """List vips that belong to a given tenant."""
resource = 'vip' resource = 'vip'
@ -33,14 +33,14 @@ class ListVip(quantumv20.ListCommand):
sorting_support = True sorting_support = True
class ShowVip(quantumv20.ShowCommand): class ShowVip(neutronV20.ShowCommand):
"""Show information of a given vip.""" """Show information of a given vip."""
resource = 'vip' resource = 'vip'
log = logging.getLogger(__name__ + '.ShowVip') log = logging.getLogger(__name__ + '.ShowVip')
class CreateVip(quantumv20.CreateCommand): class CreateVip(neutronV20.CreateCommand):
"""Create a vip.""" """Create a vip."""
resource = 'vip' resource = 'vip'
@ -83,9 +83,9 @@ class CreateVip(quantumv20.CreateCommand):
help='the subnet on which to allocate the vip address') help='the subnet on which to allocate the vip address')
def args2body(self, parsed_args): def args2body(self, parsed_args):
_pool_id = quantumv20.find_resourceid_by_name_or_id( _pool_id = neutronV20.find_resourceid_by_name_or_id(
self.get_client(), 'pool', parsed_args.pool_id) self.get_client(), 'pool', parsed_args.pool_id)
_subnet_id = quantumv20.find_resourceid_by_name_or_id( _subnet_id = neutronV20.find_resourceid_by_name_or_id(
self.get_client(), 'subnet', parsed_args.subnet_id) self.get_client(), 'subnet', parsed_args.subnet_id)
body = { body = {
self.resource: { self.resource: {
@ -94,21 +94,21 @@ class CreateVip(quantumv20.CreateCommand):
'subnet_id': _subnet_id, 'subnet_id': _subnet_id,
}, },
} }
quantumv20.update_dict(parsed_args, body[self.resource], neutronV20.update_dict(parsed_args, body[self.resource],
['address', 'connection_limit', 'description', ['address', 'connection_limit', 'description',
'name', 'protocol_port', 'protocol', 'name', 'protocol_port', 'protocol',
'tenant_id']) 'tenant_id'])
return body return body
class UpdateVip(quantumv20.UpdateCommand): class UpdateVip(neutronV20.UpdateCommand):
"""Update a given vip.""" """Update a given vip."""
resource = 'vip' resource = 'vip'
log = logging.getLogger(__name__ + '.UpdateVip') log = logging.getLogger(__name__ + '.UpdateVip')
class DeleteVip(quantumv20.DeleteCommand): class DeleteVip(neutronV20.DeleteCommand):
"""Delete a given vip.""" """Delete a given vip."""
resource = 'vip' resource = 'vip'

View File

@ -18,8 +18,8 @@
import argparse import argparse
import logging import logging
from quantumclient.common import exceptions from neutronclient.common import exceptions
from quantumclient.quantum import v2_0 as quantumv20 from neutronclient.neutron import v2_0 as neutronV20
def _format_subnets(network): def _format_subnets(network):
@ -30,7 +30,7 @@ def _format_subnets(network):
return '' return ''
class ListNetwork(quantumv20.ListCommand): class ListNetwork(neutronV20.ListCommand):
"""List networks that belong to a given tenant.""" """List networks that belong to a given tenant."""
# Length of a query filter on subnet id # Length of a query filter on subnet id
@ -45,7 +45,7 @@ class ListNetwork(quantumv20.ListCommand):
def extend_list(self, data, parsed_args): def extend_list(self, data, parsed_args):
"""Add subnet information to a network list.""" """Add subnet information to a network list."""
quantum_client = self.get_client() neutron_client = self.get_client()
search_opts = {'fields': ['id', 'cidr']} search_opts = {'fields': ['id', 'cidr']}
if self.pagination_support: if self.pagination_support:
page_size = parsed_args.page_size page_size = parsed_args.page_size
@ -58,7 +58,7 @@ class ListNetwork(quantumv20.ListCommand):
def _get_subnet_list(sub_ids): def _get_subnet_list(sub_ids):
search_opts['id'] = sub_ids search_opts['id'] = sub_ids
return quantum_client.list_subnets( return neutron_client.list_subnets(
**search_opts).get('subnets', []) **search_opts).get('subnets', [])
try: try:
@ -97,14 +97,14 @@ class ListExternalNetwork(ListNetwork):
return super(ListExternalNetwork, self).retrieve_list(parsed_args) return super(ListExternalNetwork, self).retrieve_list(parsed_args)
class ShowNetwork(quantumv20.ShowCommand): class ShowNetwork(neutronV20.ShowCommand):
"""Show information of a given network.""" """Show information of a given network."""
resource = 'network' resource = 'network'
log = logging.getLogger(__name__ + '.ShowNetwork') log = logging.getLogger(__name__ + '.ShowNetwork')
class CreateNetwork(quantumv20.CreateCommand): class CreateNetwork(neutronV20.CreateCommand):
"""Create a network for a given tenant.""" """Create a network for a given tenant."""
resource = 'network' resource = 'network'
@ -138,14 +138,14 @@ class CreateNetwork(quantumv20.CreateCommand):
return body return body
class DeleteNetwork(quantumv20.DeleteCommand): class DeleteNetwork(neutronV20.DeleteCommand):
"""Delete a given network.""" """Delete a given network."""
log = logging.getLogger(__name__ + '.DeleteNetwork') log = logging.getLogger(__name__ + '.DeleteNetwork')
resource = 'network' resource = 'network'
class UpdateNetwork(quantumv20.UpdateCommand): class UpdateNetwork(neutronV20.UpdateCommand):
"""Update network's information.""" """Update network's information."""
log = logging.getLogger(__name__ + '.UpdateNetwork') log = logging.getLogger(__name__ + '.UpdateNetwork')

View File

@ -17,10 +17,10 @@
import logging import logging
from quantumclient.quantum import v2_0 as quantumv20 from neutronclient.neutron import v2_0 as neutronV20
class ListQoSQueue(quantumv20.ListCommand): class ListQoSQueue(neutronV20.ListCommand):
"""List queues that belong to a given tenant.""" """List queues that belong to a given tenant."""
resource = 'qos_queue' resource = 'qos_queue'
@ -29,7 +29,7 @@ class ListQoSQueue(quantumv20.ListCommand):
'qos_marking', 'dscp', 'default'] 'qos_marking', 'dscp', 'default']
class ShowQoSQueue(quantumv20.ShowCommand): class ShowQoSQueue(neutronV20.ShowCommand):
"""Show information of a given queue.""" """Show information of a given queue."""
resource = 'qos_queue' resource = 'qos_queue'
@ -37,7 +37,7 @@ class ShowQoSQueue(quantumv20.ShowCommand):
allow_names = True allow_names = True
class CreateQoSQueue(quantumv20.CreateCommand): class CreateQoSQueue(neutronV20.CreateCommand):
"""Create a queue.""" """Create a queue."""
resource = 'qos_queue' resource = 'qos_queue'
@ -81,7 +81,7 @@ class CreateQoSQueue(quantumv20.CreateCommand):
return {'qos_queue': params} return {'qos_queue': params}
class DeleteQoSQueue(quantumv20.DeleteCommand): class DeleteQoSQueue(neutronV20.DeleteCommand):
"""Delete a given queue.""" """Delete a given queue."""
log = logging.getLogger(__name__ + '.DeleteQoSQueue') log = logging.getLogger(__name__ + '.DeleteQoSQueue')

View File

@ -17,14 +17,14 @@
import logging import logging
from quantumclient.common import utils from neutronclient.common import utils
from quantumclient.openstack.common.gettextutils import _ from neutronclient.neutron import v2_0 as neutronV20
from quantumclient.quantum import v2_0 as quantumv20 from neutronclient.openstack.common.gettextutils import _
RESOURCE = 'network_gateway' RESOURCE = 'network_gateway'
class ListNetworkGateway(quantumv20.ListCommand): class ListNetworkGateway(neutronV20.ListCommand):
"""List network gateways for a given tenant.""" """List network gateways for a given tenant."""
resource = RESOURCE resource = RESOURCE
@ -32,14 +32,14 @@ class ListNetworkGateway(quantumv20.ListCommand):
list_columns = ['id', 'name'] list_columns = ['id', 'name']
class ShowNetworkGateway(quantumv20.ShowCommand): class ShowNetworkGateway(neutronV20.ShowCommand):
"""Show information of a given network gateway.""" """Show information of a given network gateway."""
resource = RESOURCE resource = RESOURCE
log = logging.getLogger(__name__ + '.ShowNetworkGateway') log = logging.getLogger(__name__ + '.ShowNetworkGateway')
class CreateNetworkGateway(quantumv20.CreateCommand): class CreateNetworkGateway(neutronV20.CreateCommand):
"""Create a network gateway.""" """Create a network gateway."""
resource = RESOURCE resource = RESOURCE
@ -71,21 +71,21 @@ class CreateNetworkGateway(quantumv20.CreateCommand):
return body return body
class DeleteNetworkGateway(quantumv20.DeleteCommand): class DeleteNetworkGateway(neutronV20.DeleteCommand):
"""Delete a given network gateway.""" """Delete a given network gateway."""
resource = RESOURCE resource = RESOURCE
log = logging.getLogger(__name__ + '.DeleteNetworkGateway') log = logging.getLogger(__name__ + '.DeleteNetworkGateway')
class UpdateNetworkGateway(quantumv20.UpdateCommand): class UpdateNetworkGateway(neutronV20.UpdateCommand):
"""Update the name for a network gateway.""" """Update the name for a network gateway."""
resource = RESOURCE resource = RESOURCE
log = logging.getLogger(__name__ + '.UpdateNetworkGateway') log = logging.getLogger(__name__ + '.UpdateNetworkGateway')
class NetworkGatewayInterfaceCommand(quantumv20.QuantumCommand): class NetworkGatewayInterfaceCommand(neutronV20.NeutronCommand):
"""Base class for connecting/disconnecting networks to/from a gateway.""" """Base class for connecting/disconnecting networks to/from a gateway."""
resource = RESOURCE resource = RESOURCE
@ -110,9 +110,9 @@ class NetworkGatewayInterfaceCommand(quantumv20.QuantumCommand):
return parser return parser
def retrieve_ids(self, client, args): def retrieve_ids(self, client, args):
gateway_id = quantumv20.find_resourceid_by_name_or_id( gateway_id = neutronV20.find_resourceid_by_name_or_id(
client, self.resource, args.net_gateway_id) client, self.resource, args.net_gateway_id)
network_id = quantumv20.find_resourceid_by_name_or_id( network_id = neutronV20.find_resourceid_by_name_or_id(
client, 'network', args.network_id) client, 'network', args.network_id)
return (gateway_id, network_id) return (gateway_id, network_id)
@ -124,11 +124,11 @@ class ConnectNetworkGateway(NetworkGatewayInterfaceCommand):
def run(self, parsed_args): def run(self, parsed_args):
self.log.debug('run(%s)' % parsed_args) self.log.debug('run(%s)' % parsed_args)
quantum_client = self.get_client() neutron_client = self.get_client()
quantum_client.format = parsed_args.request_format neutron_client.format = parsed_args.request_format
(gateway_id, network_id) = self.retrieve_ids(quantum_client, (gateway_id, network_id) = self.retrieve_ids(neutron_client,
parsed_args) parsed_args)
quantum_client.connect_network_gateway( neutron_client.connect_network_gateway(
gateway_id, {'network_id': network_id, gateway_id, {'network_id': network_id,
'segmentation_type': parsed_args.segmentation_type, 'segmentation_type': parsed_args.segmentation_type,
'segmentation_id': parsed_args.segmentation_id}) 'segmentation_id': parsed_args.segmentation_id})
@ -145,11 +145,11 @@ class DisconnectNetworkGateway(NetworkGatewayInterfaceCommand):
def run(self, parsed_args): def run(self, parsed_args):
self.log.debug('run(%s)' % parsed_args) self.log.debug('run(%s)' % parsed_args)
quantum_client = self.get_client() neutron_client = self.get_client()
quantum_client.format = parsed_args.request_format neutron_client.format = parsed_args.request_format
(gateway_id, network_id) = self.retrieve_ids(quantum_client, (gateway_id, network_id) = self.retrieve_ids(neutron_client,
parsed_args) parsed_args)
quantum_client.disconnect_network_gateway( neutron_client.disconnect_network_gateway(
gateway_id, {'network_id': network_id, gateway_id, {'network_id': network_id,
'segmentation_type': parsed_args.segmentation_type, 'segmentation_type': parsed_args.segmentation_type,
'segmentation_id': parsed_args.segmentation_id}) 'segmentation_id': parsed_args.segmentation_id})

View File

@ -18,8 +18,8 @@
import argparse import argparse
import logging import logging
from quantumclient.common import utils from neutronclient.common import utils
from quantumclient.quantum import v2_0 as quantumv20 from neutronclient.neutron import v2_0 as neutronV20
def _format_fixed_ips(port): def _format_fixed_ips(port):
@ -29,7 +29,7 @@ def _format_fixed_ips(port):
return '' return ''
class ListPort(quantumv20.ListCommand): class ListPort(neutronV20.ListCommand):
"""List ports that belong to a given tenant.""" """List ports that belong to a given tenant."""
resource = 'port' resource = 'port'
@ -40,7 +40,7 @@ class ListPort(quantumv20.ListCommand):
sorting_support = True sorting_support = True
class ListRouterPort(quantumv20.ListCommand): class ListRouterPort(neutronV20.ListCommand):
"""List ports that belong to a given tenant, with specified router.""" """List ports that belong to a given tenant, with specified router."""
resource = 'port' resource = 'port'
@ -58,22 +58,22 @@ class ListRouterPort(quantumv20.ListCommand):
return parser return parser
def get_data(self, parsed_args): def get_data(self, parsed_args):
quantum_client = self.get_client() neutron_client = self.get_client()
quantum_client.format = parsed_args.request_format neutron_client.format = parsed_args.request_format
_id = quantumv20.find_resourceid_by_name_or_id( _id = neutronV20.find_resourceid_by_name_or_id(
quantum_client, 'router', parsed_args.id) neutron_client, 'router', parsed_args.id)
self.values_specs.append('--device_id=%s' % _id) self.values_specs.append('--device_id=%s' % _id)
return super(ListRouterPort, self).get_data(parsed_args) return super(ListRouterPort, self).get_data(parsed_args)
class ShowPort(quantumv20.ShowCommand): class ShowPort(neutronV20.ShowCommand):
"""Show information of a given port.""" """Show information of a given port."""
resource = 'port' resource = 'port'
log = logging.getLogger(__name__ + '.ShowPort') log = logging.getLogger(__name__ + '.ShowPort')
class CreatePort(quantumv20.CreateCommand): class CreatePort(neutronV20.CreateCommand):
"""Create a port for a given tenant.""" """Create a port for a given tenant."""
resource = 'port' resource = 'port'
@ -123,7 +123,7 @@ class CreatePort(quantumv20.CreateCommand):
help='Network id or name this port belongs to') help='Network id or name this port belongs to')
def args2body(self, parsed_args): def args2body(self, parsed_args):
_network_id = quantumv20.find_resourceid_by_name_or_id( _network_id = neutronV20.find_resourceid_by_name_or_id(
self.get_client(), 'network', parsed_args.network_id) self.get_client(), 'network', parsed_args.network_id)
body = {'port': {'admin_state_up': parsed_args.admin_state, body = {'port': {'admin_state_up': parsed_args.admin_state,
'network_id': _network_id, }, } 'network_id': _network_id, }, }
@ -141,7 +141,7 @@ class CreatePort(quantumv20.CreateCommand):
ip_dict = utils.str2dict(ip_spec) ip_dict = utils.str2dict(ip_spec)
if 'subnet_id' in ip_dict: if 'subnet_id' in ip_dict:
subnet_name_id = ip_dict['subnet_id'] subnet_name_id = ip_dict['subnet_id']
_subnet_id = quantumv20.find_resourceid_by_name_or_id( _subnet_id = neutronV20.find_resourceid_by_name_or_id(
self.get_client(), 'subnet', subnet_name_id) self.get_client(), 'subnet', subnet_name_id)
ip_dict['subnet_id'] = _subnet_id ip_dict['subnet_id'] = _subnet_id
ips.append(ip_dict) ips.append(ip_dict)
@ -150,7 +150,7 @@ class CreatePort(quantumv20.CreateCommand):
_sgids = [] _sgids = []
for sg in parsed_args.security_groups: for sg in parsed_args.security_groups:
_sgids.append(quantumv20.find_resourceid_by_name_or_id( _sgids.append(neutronV20.find_resourceid_by_name_or_id(
self.get_client(), 'security_group', sg)) self.get_client(), 'security_group', sg))
if _sgids: if _sgids:
body['port']['security_groups'] = _sgids body['port']['security_groups'] = _sgids
@ -158,14 +158,14 @@ class CreatePort(quantumv20.CreateCommand):
return body return body
class DeletePort(quantumv20.DeleteCommand): class DeletePort(neutronV20.DeleteCommand):
"""Delete a given port.""" """Delete a given port."""
resource = 'port' resource = 'port'
log = logging.getLogger(__name__ + '.DeletePort') log = logging.getLogger(__name__ + '.DeletePort')
class UpdatePort(quantumv20.UpdateCommand): class UpdatePort(neutronV20.UpdateCommand):
"""Update port's information.""" """Update port's information."""
resource = 'port' resource = 'port'

View File

@ -21,10 +21,10 @@ import logging
from cliff import lister from cliff import lister
from cliff import show from cliff import show
from quantumclient.common import exceptions from neutronclient.common import exceptions
from quantumclient.common import utils from neutronclient.common import utils
from quantumclient.openstack.common.gettextutils import _ from neutronclient.neutron import v2_0 as neutronV20
from quantumclient.quantum import v2_0 as quantumv20 from neutronclient.openstack.common.gettextutils import _
def get_tenant_id(tenant_id, client): def get_tenant_id(tenant_id, client):
@ -32,7 +32,7 @@ def get_tenant_id(tenant_id, client):
client.get_quotas_tenant()['tenant']['tenant_id']) client.get_quotas_tenant()['tenant']['tenant_id'])
class DeleteQuota(quantumv20.QuantumCommand): class DeleteQuota(neutronV20.NeutronCommand):
"""Delete defined quotas of a given tenant.""" """Delete defined quotas of a given tenant."""
api = 'network' api = 'network'
@ -51,11 +51,11 @@ class DeleteQuota(quantumv20.QuantumCommand):
def run(self, parsed_args): def run(self, parsed_args):
self.log.debug('run(%s)' % parsed_args) self.log.debug('run(%s)' % parsed_args)
quantum_client = self.get_client() neutron_client = self.get_client()
quantum_client.format = parsed_args.request_format neutron_client.format = parsed_args.request_format
tenant_id = get_tenant_id(parsed_args.tenant_id, tenant_id = get_tenant_id(parsed_args.tenant_id,
quantum_client) neutron_client)
obj_deleter = getattr(quantum_client, obj_deleter = getattr(neutron_client,
"delete_%s" % self.resource) "delete_%s" % self.resource)
obj_deleter(tenant_id) obj_deleter(tenant_id)
print >>self.app.stdout, (_('Deleted %(resource)s: %(tenant_id)s') print >>self.app.stdout, (_('Deleted %(resource)s: %(tenant_id)s')
@ -64,7 +64,7 @@ class DeleteQuota(quantumv20.QuantumCommand):
return return
class ListQuota(quantumv20.QuantumCommand, lister.Lister): class ListQuota(neutronV20.NeutronCommand, lister.Lister):
"""List defined quotas of all tenants.""" """List defined quotas of all tenants."""
api = 'network' api = 'network'
@ -77,11 +77,11 @@ class ListQuota(quantumv20.QuantumCommand, lister.Lister):
def get_data(self, parsed_args): def get_data(self, parsed_args):
self.log.debug('get_data(%s)' % parsed_args) self.log.debug('get_data(%s)' % parsed_args)
quantum_client = self.get_client() neutron_client = self.get_client()
search_opts = {} search_opts = {}
self.log.debug('search options: %s', search_opts) self.log.debug('search options: %s', search_opts)
quantum_client.format = parsed_args.request_format neutron_client.format = parsed_args.request_format
obj_lister = getattr(quantum_client, obj_lister = getattr(neutron_client,
"list_%ss" % self.resource) "list_%ss" % self.resource)
data = obj_lister(**search_opts) data = obj_lister(**search_opts)
info = [] info = []
@ -93,7 +93,7 @@ class ListQuota(quantumv20.QuantumCommand, lister.Lister):
for s in info)) for s in info))
class ShowQuota(quantumv20.QuantumCommand, show.ShowOne): class ShowQuota(neutronV20.NeutronCommand, show.ShowOne):
"""Show quotas of a given tenant """Show quotas of a given tenant
""" """
@ -113,12 +113,12 @@ class ShowQuota(quantumv20.QuantumCommand, show.ShowOne):
def get_data(self, parsed_args): def get_data(self, parsed_args):
self.log.debug('get_data(%s)' % parsed_args) self.log.debug('get_data(%s)' % parsed_args)
quantum_client = self.get_client() neutron_client = self.get_client()
quantum_client.format = parsed_args.request_format neutron_client.format = parsed_args.request_format
tenant_id = get_tenant_id(parsed_args.tenant_id, tenant_id = get_tenant_id(parsed_args.tenant_id,
quantum_client) neutron_client)
params = {} params = {}
obj_shower = getattr(quantum_client, obj_shower = getattr(neutron_client,
"show_%s" % self.resource) "show_%s" % self.resource)
data = obj_shower(tenant_id, **params) data = obj_shower(tenant_id, **params)
if self.resource in data: if self.resource in data:
@ -140,7 +140,7 @@ class ShowQuota(quantumv20.QuantumCommand, show.ShowOne):
return None return None
class UpdateQuota(quantumv20.QuantumCommand, show.ShowOne): class UpdateQuota(neutronV20.NeutronCommand, show.ShowOne):
"""Define tenant's quotas not to use defaults.""" """Define tenant's quotas not to use defaults."""
resource = 'quota' resource = 'quota'
@ -183,7 +183,7 @@ class UpdateQuota(quantumv20.QuantumCommand, show.ShowOne):
except Exception: except Exception:
message = (_('quota limit for %(name)s must be an integer') % message = (_('quota limit for %(name)s must be an integer') %
{'name': name}) {'name': name})
raise exceptions.QuantumClientException(message=message) raise exceptions.NeutronClientException(message=message)
return return_value return return_value
def args2body(self, parsed_args): def args2body(self, parsed_args):
@ -198,20 +198,20 @@ class UpdateQuota(quantumv20.QuantumCommand, show.ShowOne):
def get_data(self, parsed_args): def get_data(self, parsed_args):
self.log.debug('run(%s)' % parsed_args) self.log.debug('run(%s)' % parsed_args)
quantum_client = self.get_client() neutron_client = self.get_client()
quantum_client.format = parsed_args.request_format neutron_client.format = parsed_args.request_format
_extra_values = quantumv20.parse_args_to_dict(self.values_specs) _extra_values = neutronV20.parse_args_to_dict(self.values_specs)
quantumv20._merge_args(self, parsed_args, _extra_values, neutronV20._merge_args(self, parsed_args, _extra_values,
self.values_specs) self.values_specs)
body = self.args2body(parsed_args) body = self.args2body(parsed_args)
if self.resource in body: if self.resource in body:
body[self.resource].update(_extra_values) body[self.resource].update(_extra_values)
else: else:
body[self.resource] = _extra_values body[self.resource] = _extra_values
obj_updator = getattr(quantum_client, obj_updator = getattr(neutron_client,
"update_%s" % self.resource) "update_%s" % self.resource)
tenant_id = get_tenant_id(parsed_args.tenant_id, tenant_id = get_tenant_id(parsed_args.tenant_id,
quantum_client) neutron_client)
data = obj_updator(tenant_id, body) data = obj_updator(tenant_id, body)
if self.resource in data: if self.resource in data:
for k, v in data[self.resource].iteritems(): for k, v in data[self.resource].iteritems():

View File

@ -18,10 +18,10 @@
import argparse import argparse
import logging import logging
from quantumclient.common import exceptions from neutronclient.common import exceptions
from quantumclient.common import utils from neutronclient.common import utils
from quantumclient.openstack.common.gettextutils import _ from neutronclient.neutron import v2_0 as neutronV20
from quantumclient.quantum import v2_0 as quantumv20 from neutronclient.openstack.common.gettextutils import _
def _format_external_gateway_info(router): def _format_external_gateway_info(router):
@ -31,7 +31,7 @@ def _format_external_gateway_info(router):
return '' return ''
class ListRouter(quantumv20.ListCommand): class ListRouter(neutronV20.ListCommand):
"""List routers that belong to a given tenant.""" """List routers that belong to a given tenant."""
resource = 'router' resource = 'router'
@ -42,14 +42,14 @@ class ListRouter(quantumv20.ListCommand):
sorting_support = True sorting_support = True
class ShowRouter(quantumv20.ShowCommand): class ShowRouter(neutronV20.ShowCommand):
"""Show information of a given router.""" """Show information of a given router."""
resource = 'router' resource = 'router'
log = logging.getLogger(__name__ + '.ShowRouter') log = logging.getLogger(__name__ + '.ShowRouter')
class CreateRouter(quantumv20.CreateCommand): class CreateRouter(neutronV20.CreateCommand):
"""Create a router for a given tenant.""" """Create a router for a given tenant."""
resource = 'router' resource = 'router'
@ -78,27 +78,27 @@ class CreateRouter(quantumv20.CreateCommand):
return body return body
class DeleteRouter(quantumv20.DeleteCommand): class DeleteRouter(neutronV20.DeleteCommand):
"""Delete a given router.""" """Delete a given router."""
log = logging.getLogger(__name__ + '.DeleteRouter') log = logging.getLogger(__name__ + '.DeleteRouter')
resource = 'router' resource = 'router'
class UpdateRouter(quantumv20.UpdateCommand): class UpdateRouter(neutronV20.UpdateCommand):
"""Update router's information.""" """Update router's information."""
log = logging.getLogger(__name__ + '.UpdateRouter') log = logging.getLogger(__name__ + '.UpdateRouter')
resource = 'router' resource = 'router'
class RouterInterfaceCommand(quantumv20.QuantumCommand): class RouterInterfaceCommand(neutronV20.NeutronCommand):
"""Based class to Add/Remove router interface.""" """Based class to Add/Remove router interface."""
api = 'network' api = 'network'
resource = 'router' resource = 'router'
def call_api(self, quantum_client, router_id, body): def call_api(self, neutron_client, router_id, body):
raise NotImplementedError() raise NotImplementedError()
def success_message(self, router_id, portinfo): def success_message(self, router_id, portinfo):
@ -119,8 +119,8 @@ class RouterInterfaceCommand(quantumv20.QuantumCommand):
def run(self, parsed_args): def run(self, parsed_args):
self.log.debug('run(%s)' % parsed_args) self.log.debug('run(%s)' % parsed_args)
quantum_client = self.get_client() neutron_client = self.get_client()
quantum_client.format = parsed_args.request_format neutron_client.format = parsed_args.request_format
if '=' in parsed_args.interface: if '=' in parsed_args.interface:
resource, value = parsed_args.interface.split('=', 1) resource, value = parsed_args.interface.split('=', 1)
@ -131,14 +131,14 @@ class RouterInterfaceCommand(quantumv20.QuantumCommand):
resource = 'subnet' resource = 'subnet'
value = parsed_args.interface value = parsed_args.interface
_router_id = quantumv20.find_resourceid_by_name_or_id( _router_id = neutronV20.find_resourceid_by_name_or_id(
quantum_client, self.resource, parsed_args.router_id) neutron_client, self.resource, parsed_args.router_id)
_interface_id = quantumv20.find_resourceid_by_name_or_id( _interface_id = neutronV20.find_resourceid_by_name_or_id(
quantum_client, resource, value) neutron_client, resource, value)
body = {'%s_id' % resource: _interface_id} body = {'%s_id' % resource: _interface_id}
portinfo = self.call_api(quantum_client, _router_id, body) portinfo = self.call_api(neutron_client, _router_id, body)
print >>self.app.stdout, self.success_message(parsed_args.router_id, print >>self.app.stdout, self.success_message(parsed_args.router_id,
portinfo) portinfo)
@ -148,8 +148,8 @@ class AddInterfaceRouter(RouterInterfaceCommand):
log = logging.getLogger(__name__ + '.AddInterfaceRouter') log = logging.getLogger(__name__ + '.AddInterfaceRouter')
def call_api(self, quantum_client, router_id, body): def call_api(self, neutron_client, router_id, body):
return quantum_client.add_interface_router(router_id, body) return neutron_client.add_interface_router(router_id, body)
def success_message(self, router_id, portinfo): def success_message(self, router_id, portinfo):
return (_('Added interface %(port)s to router %(router)s.') % return (_('Added interface %(port)s to router %(router)s.') %
@ -161,15 +161,15 @@ class RemoveInterfaceRouter(RouterInterfaceCommand):
log = logging.getLogger(__name__ + '.RemoveInterfaceRouter') log = logging.getLogger(__name__ + '.RemoveInterfaceRouter')
def call_api(self, quantum_client, router_id, body): def call_api(self, neutron_client, router_id, body):
return quantum_client.remove_interface_router(router_id, body) return neutron_client.remove_interface_router(router_id, body)
def success_message(self, router_id, portinfo): def success_message(self, router_id, portinfo):
# portinfo is not used since it is None for router-interface-delete. # portinfo is not used since it is None for router-interface-delete.
return _('Removed interface from router %s.') % router_id return _('Removed interface from router %s.') % router_id
class SetGatewayRouter(quantumv20.QuantumCommand): class SetGatewayRouter(neutronV20.NeutronCommand):
"""Set the external network gateway for a router.""" """Set the external network gateway for a router."""
log = logging.getLogger(__name__ + '.SetGatewayRouter') log = logging.getLogger(__name__ + '.SetGatewayRouter')
@ -191,13 +191,13 @@ class SetGatewayRouter(quantumv20.QuantumCommand):
def run(self, parsed_args): def run(self, parsed_args):
self.log.debug('run(%s)' % parsed_args) self.log.debug('run(%s)' % parsed_args)
quantum_client = self.get_client() neutron_client = self.get_client()
quantum_client.format = parsed_args.request_format neutron_client.format = parsed_args.request_format
_router_id = quantumv20.find_resourceid_by_name_or_id( _router_id = neutronV20.find_resourceid_by_name_or_id(
quantum_client, self.resource, parsed_args.router_id) neutron_client, self.resource, parsed_args.router_id)
_ext_net_id = quantumv20.find_resourceid_by_name_or_id( _ext_net_id = neutronV20.find_resourceid_by_name_or_id(
quantum_client, 'network', parsed_args.external_network_id) neutron_client, 'network', parsed_args.external_network_id)
quantum_client.add_gateway_router( neutron_client.add_gateway_router(
_router_id, _router_id,
{'network_id': _ext_net_id, {'network_id': _ext_net_id,
'enable_snat': parsed_args.enable_snat}) 'enable_snat': parsed_args.enable_snat})
@ -205,7 +205,7 @@ class SetGatewayRouter(quantumv20.QuantumCommand):
_('Set gateway for router %s') % parsed_args.router_id) _('Set gateway for router %s') % parsed_args.router_id)
class RemoveGatewayRouter(quantumv20.QuantumCommand): class RemoveGatewayRouter(neutronV20.NeutronCommand):
"""Remove an external network gateway from a router.""" """Remove an external network gateway from a router."""
log = logging.getLogger(__name__ + '.RemoveGatewayRouter') log = logging.getLogger(__name__ + '.RemoveGatewayRouter')
@ -221,10 +221,10 @@ class RemoveGatewayRouter(quantumv20.QuantumCommand):
def run(self, parsed_args): def run(self, parsed_args):
self.log.debug('run(%s)' % parsed_args) self.log.debug('run(%s)' % parsed_args)
quantum_client = self.get_client() neutron_client = self.get_client()
quantum_client.format = parsed_args.request_format neutron_client.format = parsed_args.request_format
_router_id = quantumv20.find_resourceid_by_name_or_id( _router_id = neutronV20.find_resourceid_by_name_or_id(
quantum_client, self.resource, parsed_args.router_id) neutron_client, self.resource, parsed_args.router_id)
quantum_client.remove_gateway_router(_router_id) neutron_client.remove_gateway_router(_router_id)
print >>self.app.stdout, ( print >>self.app.stdout, (
_('Removed gateway from router %s') % parsed_args.router_id) _('Removed gateway from router %s') % parsed_args.router_id)

View File

@ -18,10 +18,10 @@
import argparse import argparse
import logging import logging
from quantumclient.quantum import v2_0 as quantumv20 from neutronclient.neutron import v2_0 as neutronV20
class ListSecurityGroup(quantumv20.ListCommand): class ListSecurityGroup(neutronV20.ListCommand):
"""List security groups that belong to a given tenant.""" """List security groups that belong to a given tenant."""
resource = 'security_group' resource = 'security_group'
@ -31,7 +31,7 @@ class ListSecurityGroup(quantumv20.ListCommand):
sorting_support = True sorting_support = True
class ShowSecurityGroup(quantumv20.ShowCommand): class ShowSecurityGroup(neutronV20.ShowCommand):
"""Show information of a given security group.""" """Show information of a given security group."""
resource = 'security_group' resource = 'security_group'
@ -39,7 +39,7 @@ class ShowSecurityGroup(quantumv20.ShowCommand):
allow_names = True allow_names = True
class CreateSecurityGroup(quantumv20.CreateCommand): class CreateSecurityGroup(neutronV20.CreateCommand):
"""Create a security group.""" """Create a security group."""
resource = 'security_group' resource = 'security_group'
@ -64,7 +64,7 @@ class CreateSecurityGroup(quantumv20.CreateCommand):
return body return body
class DeleteSecurityGroup(quantumv20.DeleteCommand): class DeleteSecurityGroup(neutronV20.DeleteCommand):
"""Delete a given security group.""" """Delete a given security group."""
log = logging.getLogger(__name__ + '.DeleteSecurityGroup') log = logging.getLogger(__name__ + '.DeleteSecurityGroup')
@ -72,7 +72,7 @@ class DeleteSecurityGroup(quantumv20.DeleteCommand):
allow_names = True allow_names = True
class UpdateSecurityGroup(quantumv20.UpdateCommand): class UpdateSecurityGroup(neutronV20.UpdateCommand):
"""Update a given security group.""" """Update a given security group."""
log = logging.getLogger(__name__ + '.UpdateSecurityGroup') log = logging.getLogger(__name__ + '.UpdateSecurityGroup')
@ -97,7 +97,7 @@ class UpdateSecurityGroup(quantumv20.UpdateCommand):
return body return body
class ListSecurityGroupRule(quantumv20.ListCommand): class ListSecurityGroupRule(neutronV20.ListCommand):
"""List security group rules that belong to a given tenant.""" """List security group rules that belong to a given tenant."""
resource = 'security_group_rule' resource = 'security_group_rule'
@ -131,7 +131,7 @@ class ListSecurityGroupRule(quantumv20.ListCommand):
def extend_list(self, data, parsed_args): def extend_list(self, data, parsed_args):
if parsed_args.no_nameconv: if parsed_args.no_nameconv:
return return
quantum_client = self.get_client() neutron_client = self.get_client()
search_opts = {'fields': ['id', 'name']} search_opts = {'fields': ['id', 'name']}
if self.pagination_support: if self.pagination_support:
page_size = parsed_args.page_size page_size = parsed_args.page_size
@ -142,7 +142,7 @@ class ListSecurityGroupRule(quantumv20.ListCommand):
for key in self.replace_rules: for key in self.replace_rules:
sec_group_ids.add(rule[key]) sec_group_ids.add(rule[key])
search_opts.update({"id": sec_group_ids}) search_opts.update({"id": sec_group_ids})
secgroups = quantum_client.list_security_groups(**search_opts) secgroups = neutron_client.list_security_groups(**search_opts)
secgroups = secgroups.get('security_groups', []) secgroups = secgroups.get('security_groups', [])
sg_dict = dict([(sg['id'], sg['name']) sg_dict = dict([(sg['id'], sg['name'])
for sg in secgroups if sg['name']]) for sg in secgroups if sg['name']])
@ -166,7 +166,7 @@ class ListSecurityGroupRule(quantumv20.ListCommand):
return (cols, info[1]) return (cols, info[1])
class ShowSecurityGroupRule(quantumv20.ShowCommand): class ShowSecurityGroupRule(neutronV20.ShowCommand):
"""Show information of a given security group rule.""" """Show information of a given security group rule."""
resource = 'security_group_rule' resource = 'security_group_rule'
@ -174,7 +174,7 @@ class ShowSecurityGroupRule(quantumv20.ShowCommand):
allow_names = False allow_names = False
class CreateSecurityGroupRule(quantumv20.CreateCommand): class CreateSecurityGroupRule(neutronV20.CreateCommand):
"""Create a security group rule.""" """Create a security group rule."""
resource = 'security_group_rule' resource = 'security_group_rule'
@ -221,7 +221,7 @@ class CreateSecurityGroupRule(quantumv20.CreateCommand):
help=argparse.SUPPRESS) help=argparse.SUPPRESS)
def args2body(self, parsed_args): def args2body(self, parsed_args):
_security_group_id = quantumv20.find_resourceid_by_name_or_id( _security_group_id = neutronV20.find_resourceid_by_name_or_id(
self.get_client(), 'security_group', parsed_args.security_group_id) self.get_client(), 'security_group', parsed_args.security_group_id)
body = {'security_group_rule': { body = {'security_group_rule': {
'security_group_id': _security_group_id, 'security_group_id': _security_group_id,
@ -240,7 +240,7 @@ class CreateSecurityGroupRule(quantumv20.CreateCommand):
body['security_group_rule'].update( body['security_group_rule'].update(
{'remote_ip_prefix': parsed_args.remote_ip_prefix}) {'remote_ip_prefix': parsed_args.remote_ip_prefix})
if parsed_args.remote_group_id: if parsed_args.remote_group_id:
_remote_group_id = quantumv20.find_resourceid_by_name_or_id( _remote_group_id = neutronV20.find_resourceid_by_name_or_id(
self.get_client(), 'security_group', self.get_client(), 'security_group',
parsed_args.remote_group_id) parsed_args.remote_group_id)
body['security_group_rule'].update( body['security_group_rule'].update(
@ -251,7 +251,7 @@ class CreateSecurityGroupRule(quantumv20.CreateCommand):
return body return body
class DeleteSecurityGroupRule(quantumv20.DeleteCommand): class DeleteSecurityGroupRule(neutronV20.DeleteCommand):
"""Delete a given security group rule.""" """Delete a given security group rule."""
log = logging.getLogger(__name__ + '.DeleteSecurityGroupRule') log = logging.getLogger(__name__ + '.DeleteSecurityGroupRule')

View File

@ -18,9 +18,9 @@
import argparse import argparse
import logging import logging
from quantumclient.common import exceptions from neutronclient.common import exceptions
from quantumclient.common import utils from neutronclient.common import utils
from quantumclient.quantum import v2_0 as quantumv20 from neutronclient.neutron import v2_0 as neutronV20
def _format_allocation_pools(subnet): def _format_allocation_pools(subnet):
@ -47,7 +47,7 @@ def _format_host_routes(subnet):
return '' return ''
class ListSubnet(quantumv20.ListCommand): class ListSubnet(neutronV20.ListCommand):
"""List networks that belong to a given tenant.""" """List networks that belong to a given tenant."""
resource = 'subnet' resource = 'subnet'
@ -60,14 +60,14 @@ class ListSubnet(quantumv20.ListCommand):
sorting_support = True sorting_support = True
class ShowSubnet(quantumv20.ShowCommand): class ShowSubnet(neutronV20.ShowCommand):
"""Show information of a given subnet.""" """Show information of a given subnet."""
resource = 'subnet' resource = 'subnet'
log = logging.getLogger(__name__ + '.ShowSubnet') log = logging.getLogger(__name__ + '.ShowSubnet')
class CreateSubnet(quantumv20.CreateCommand): class CreateSubnet(neutronV20.CreateCommand):
"""Create a subnet for a given tenant.""" """Create a subnet for a given tenant."""
resource = 'subnet' resource = 'subnet'
@ -124,7 +124,7 @@ class CreateSubnet(quantumv20.CreateCommand):
help='cidr of subnet to create') help='cidr of subnet to create')
def args2body(self, parsed_args): def args2body(self, parsed_args):
_network_id = quantumv20.find_resourceid_by_name_or_id( _network_id = neutronV20.find_resourceid_by_name_or_id(
self.get_client(), 'network', parsed_args.network_id) self.get_client(), 'network', parsed_args.network_id)
body = {'subnet': {'cidr': parsed_args.cidr, body = {'subnet': {'cidr': parsed_args.cidr,
'network_id': _network_id, 'network_id': _network_id,
@ -154,14 +154,14 @@ class CreateSubnet(quantumv20.CreateCommand):
return body return body
class DeleteSubnet(quantumv20.DeleteCommand): class DeleteSubnet(neutronV20.DeleteCommand):
"""Delete a given subnet.""" """Delete a given subnet."""
resource = 'subnet' resource = 'subnet'
log = logging.getLogger(__name__ + '.DeleteSubnet') log = logging.getLogger(__name__ + '.DeleteSubnet')
class UpdateSubnet(quantumv20.UpdateCommand): class UpdateSubnet(neutronV20.UpdateCommand):
"""Update subnet's information.""" """Update subnet's information."""
resource = 'subnet' resource = 'subnet'

View File

@ -21,7 +21,7 @@ Exceptions common to OpenStack projects
import logging import logging
from quantumclient.openstack.common.gettextutils import _ from neutronclient.openstack.common.gettextutils import _
_FATAL_EXCEPTION_FORMAT_ERRORS = False _FATAL_EXCEPTION_FORMAT_ERRORS = False

View File

@ -20,7 +20,7 @@ gettext for openstack-common modules.
Usual usage in an openstack.common module: Usual usage in an openstack.common module:
from quantumclient.openstack.common.gettextutils import _ from neutronclient.openstack.common.gettextutils import _
""" """
import gettext import gettext

View File

@ -39,7 +39,7 @@ import itertools
import json import json
import xmlrpclib import xmlrpclib
from quantumclient.openstack.common import timeutils from neutronclient.openstack.common import timeutils
def to_primitive(value, convert_instances=False, level=0): def to_primitive(value, convert_instances=False, level=0):

View File

@ -16,7 +16,7 @@
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # vim: tabstop=4 shiftwidth=4 softtabstop=4
""" """
Command-line interface to the Quantum APIs Command-line interface to the Neutron APIs
""" """
import argparse import argparse
@ -27,15 +27,31 @@ import sys
from cliff import app from cliff import app
from cliff import commandmanager from cliff import commandmanager
from quantumclient.common import clientmanager from neutronclient.common import clientmanager
from quantumclient.common import exceptions as exc from neutronclient.common import exceptions as exc
from quantumclient.common import utils from neutronclient.common import utils
from quantumclient.openstack.common import strutils from neutronclient.neutron.v2_0 import agent
from quantumclient.version import __version__ from neutronclient.neutron.v2_0 import agentscheduler
from neutronclient.neutron.v2_0 import extension
from neutronclient.neutron.v2_0 import floatingip
from neutronclient.neutron.v2_0.lb import healthmonitor as lb_healthmonitor
from neutronclient.neutron.v2_0.lb import member as lb_member
from neutronclient.neutron.v2_0.lb import pool as lb_pool
from neutronclient.neutron.v2_0.lb import vip as lb_vip
from neutronclient.neutron.v2_0 import network
from neutronclient.neutron.v2_0 import nvp_qos_queue
from neutronclient.neutron.v2_0 import nvpnetworkgateway
from neutronclient.neutron.v2_0 import port
from neutronclient.neutron.v2_0 import quota
from neutronclient.neutron.v2_0 import router
from neutronclient.neutron.v2_0 import securitygroup
from neutronclient.neutron.v2_0 import subnet
from neutronclient.openstack.common import strutils
from neutronclient.version import __version__
VERSION = '2.0' VERSION = '2.0'
QUANTUM_API_VERSION = '2.0' NEUTRON_API_VERSION = '2.0'
def run_command(cmd, cmd_parser, sub_argv): def run_command(cmd, cmd_parser, sub_argv):
@ -66,197 +82,101 @@ def env(*_vars, **kwargs):
COMMAND_V2 = { COMMAND_V2 = {
'net-list': utils.import_class( 'net-list': network.ListNetwork,
'quantumclient.quantum.v2_0.network.ListNetwork'), 'net-external-list': network.ListExternalNetwork,
'net-external-list': utils.import_class( 'net-show': network.ShowNetwork,
'quantumclient.quantum.v2_0.network.ListExternalNetwork'), 'net-create': network.CreateNetwork,
'net-show': utils.import_class( 'net-delete': network.DeleteNetwork,
'quantumclient.quantum.v2_0.network.ShowNetwork'), 'net-update': network.UpdateNetwork,
'net-create': utils.import_class( 'subnet-list': subnet.ListSubnet,
'quantumclient.quantum.v2_0.network.CreateNetwork'), 'subnet-show': subnet.ShowSubnet,
'net-delete': utils.import_class( 'subnet-create': subnet.CreateSubnet,
'quantumclient.quantum.v2_0.network.DeleteNetwork'), 'subnet-delete': subnet.DeleteSubnet,
'net-update': utils.import_class( 'subnet-update': subnet.UpdateSubnet,
'quantumclient.quantum.v2_0.network.UpdateNetwork'), 'port-list': port.ListPort,
'subnet-list': utils.import_class( 'port-show': port.ShowPort,
'quantumclient.quantum.v2_0.subnet.ListSubnet'), 'port-create': port.CreatePort,
'subnet-show': utils.import_class( 'port-delete': port.DeletePort,
'quantumclient.quantum.v2_0.subnet.ShowSubnet'), 'port-update': port.UpdatePort,
'subnet-create': utils.import_class( 'quota-list': quota.ListQuota,
'quantumclient.quantum.v2_0.subnet.CreateSubnet'), 'quota-show': quota.ShowQuota,
'subnet-delete': utils.import_class( 'quota-delete': quota.DeleteQuota,
'quantumclient.quantum.v2_0.subnet.DeleteSubnet'), 'quota-update': quota.UpdateQuota,
'subnet-update': utils.import_class( 'ext-list': extension.ListExt,
'quantumclient.quantum.v2_0.subnet.UpdateSubnet'), 'ext-show': extension.ShowExt,
'port-list': utils.import_class( 'router-list': router.ListRouter,
'quantumclient.quantum.v2_0.port.ListPort'), 'router-port-list': port.ListRouterPort,
'port-show': utils.import_class( 'router-show': router.ShowRouter,
'quantumclient.quantum.v2_0.port.ShowPort'), 'router-create': router.CreateRouter,
'port-create': utils.import_class( 'router-delete': router.DeleteRouter,
'quantumclient.quantum.v2_0.port.CreatePort'), 'router-update': router.UpdateRouter,
'port-delete': utils.import_class( 'router-interface-add': router.AddInterfaceRouter,
'quantumclient.quantum.v2_0.port.DeletePort'), 'router-interface-delete': router.RemoveInterfaceRouter,
'port-update': utils.import_class( 'router-gateway-set': router.SetGatewayRouter,
'quantumclient.quantum.v2_0.port.UpdatePort'), 'router-gateway-clear': router.RemoveGatewayRouter,
'quota-list': utils.import_class( 'floatingip-list': floatingip.ListFloatingIP,
'quantumclient.quantum.v2_0.quota.ListQuota'), 'floatingip-show': floatingip.ShowFloatingIP,
'quota-show': utils.import_class( 'floatingip-create': floatingip.CreateFloatingIP,
'quantumclient.quantum.v2_0.quota.ShowQuota'), 'floatingip-delete': floatingip.DeleteFloatingIP,
'quota-delete': utils.import_class( 'floatingip-associate': floatingip.AssociateFloatingIP,
'quantumclient.quantum.v2_0.quota.DeleteQuota'), 'floatingip-disassociate': floatingip.DisassociateFloatingIP,
'quota-update': utils.import_class( 'security-group-list': securitygroup.ListSecurityGroup,
'quantumclient.quantum.v2_0.quota.UpdateQuota'), 'security-group-show': securitygroup.ShowSecurityGroup,
'ext-list': utils.import_class( 'security-group-create': securitygroup.CreateSecurityGroup,
'quantumclient.quantum.v2_0.extension.ListExt'), 'security-group-delete': securitygroup.DeleteSecurityGroup,
'ext-show': utils.import_class( 'security-group-update': securitygroup.UpdateSecurityGroup,
'quantumclient.quantum.v2_0.extension.ShowExt'), 'security-group-rule-list': securitygroup.ListSecurityGroupRule,
'router-list': utils.import_class( 'security-group-rule-show': securitygroup.ShowSecurityGroupRule,
'quantumclient.quantum.v2_0.router.ListRouter'), 'security-group-rule-create': securitygroup.CreateSecurityGroupRule,
'router-port-list': utils.import_class( 'security-group-rule-delete': securitygroup.DeleteSecurityGroupRule,
'quantumclient.quantum.v2_0.port.ListRouterPort'), 'lb-vip-list': lb_vip.ListVip,
'router-show': utils.import_class( 'lb-vip-show': lb_vip.ShowVip,
'quantumclient.quantum.v2_0.router.ShowRouter'), 'lb-vip-create': lb_vip.CreateVip,
'router-create': utils.import_class( 'lb-vip-update': lb_vip.UpdateVip,
'quantumclient.quantum.v2_0.router.CreateRouter'), 'lb-vip-delete': lb_vip.DeleteVip,
'router-delete': utils.import_class( 'lb-pool-list': lb_pool.ListPool,
'quantumclient.quantum.v2_0.router.DeleteRouter'), 'lb-pool-show': lb_pool.ShowPool,
'router-update': utils.import_class( 'lb-pool-create': lb_pool.CreatePool,
'quantumclient.quantum.v2_0.router.UpdateRouter'), 'lb-pool-update': lb_pool.UpdatePool,
'router-interface-add': utils.import_class( 'lb-pool-delete': lb_pool.DeletePool,
'quantumclient.quantum.v2_0.router.AddInterfaceRouter'), 'lb-pool-stats': lb_pool.RetrievePoolStats,
'router-interface-delete': utils.import_class( 'lb-member-list': lb_member.ListMember,
'quantumclient.quantum.v2_0.router.RemoveInterfaceRouter'), 'lb-member-show': lb_member.ShowMember,
'router-gateway-set': utils.import_class( 'lb-member-create': lb_member.CreateMember,
'quantumclient.quantum.v2_0.router.SetGatewayRouter'), 'lb-member-update': lb_member.UpdateMember,
'router-gateway-clear': utils.import_class( 'lb-member-delete': lb_member.DeleteMember,
'quantumclient.quantum.v2_0.router.RemoveGatewayRouter'), 'lb-healthmonitor-list': lb_healthmonitor.ListHealthMonitor,
'floatingip-list': utils.import_class( 'lb-healthmonitor-show': lb_healthmonitor.ShowHealthMonitor,
'quantumclient.quantum.v2_0.floatingip.ListFloatingIP'), 'lb-healthmonitor-create': lb_healthmonitor.CreateHealthMonitor,
'floatingip-show': utils.import_class( 'lb-healthmonitor-update': lb_healthmonitor.UpdateHealthMonitor,
'quantumclient.quantum.v2_0.floatingip.ShowFloatingIP'), 'lb-healthmonitor-delete': lb_healthmonitor.DeleteHealthMonitor,
'floatingip-create': utils.import_class( 'lb-healthmonitor-associate': lb_healthmonitor.AssociateHealthMonitor,
'quantumclient.quantum.v2_0.floatingip.CreateFloatingIP'), 'lb-healthmonitor-disassociate': (
'floatingip-delete': utils.import_class( lb_healthmonitor.DisassociateHealthMonitor
'quantumclient.quantum.v2_0.floatingip.DeleteFloatingIP'), ),
'floatingip-associate': utils.import_class( 'queue-create': nvp_qos_queue.CreateQoSQueue,
'quantumclient.quantum.v2_0.floatingip.AssociateFloatingIP'), 'queue-delete': nvp_qos_queue.DeleteQoSQueue,
'floatingip-disassociate': utils.import_class( 'queue-show': nvp_qos_queue.ShowQoSQueue,
'quantumclient.quantum.v2_0.floatingip.DisassociateFloatingIP'), 'queue-list': nvp_qos_queue.ListQoSQueue,
'security-group-list': utils.import_class( 'agent-list': agent.ListAgent,
'quantumclient.quantum.v2_0.securitygroup.ListSecurityGroup'), 'agent-show': agent.ShowAgent,
'security-group-show': utils.import_class( 'agent-delete': agent.DeleteAgent,
'quantumclient.quantum.v2_0.securitygroup.ShowSecurityGroup'), 'agent-update': agent.UpdateAgent,
'security-group-create': utils.import_class( 'net-gateway-create': nvpnetworkgateway.CreateNetworkGateway,
'quantumclient.quantum.v2_0.securitygroup.CreateSecurityGroup'), 'net-gateway-update': nvpnetworkgateway.UpdateNetworkGateway,
'security-group-delete': utils.import_class( 'net-gateway-delete': nvpnetworkgateway.DeleteNetworkGateway,
'quantumclient.quantum.v2_0.securitygroup.DeleteSecurityGroup'), 'net-gateway-show': nvpnetworkgateway.ShowNetworkGateway,
'security-group-update': utils.import_class( 'net-gateway-list': nvpnetworkgateway.ListNetworkGateway,
'quantumclient.quantum.v2_0.securitygroup.UpdateSecurityGroup'), 'net-gateway-connect': nvpnetworkgateway.ConnectNetworkGateway,
'security-group-rule-list': utils.import_class( 'net-gateway-disconnect': nvpnetworkgateway.DisconnectNetworkGateway,
'quantumclient.quantum.v2_0.securitygroup.ListSecurityGroupRule'), 'dhcp-agent-network-add': agentscheduler.AddNetworkToDhcpAgent,
'security-group-rule-show': utils.import_class( 'dhcp-agent-network-remove': agentscheduler.RemoveNetworkFromDhcpAgent,
'quantumclient.quantum.v2_0.securitygroup.ShowSecurityGroupRule'), 'net-list-on-dhcp-agent': agentscheduler.ListNetworksOnDhcpAgent,
'security-group-rule-create': utils.import_class( 'dhcp-agent-list-hosting-net': agentscheduler.ListDhcpAgentsHostingNetwork,
'quantumclient.quantum.v2_0.securitygroup.CreateSecurityGroupRule'), 'l3-agent-router-add': agentscheduler.AddRouterToL3Agent,
'security-group-rule-delete': utils.import_class( 'l3-agent-router-remove': agentscheduler.RemoveRouterFromL3Agent,
'quantumclient.quantum.v2_0.securitygroup.DeleteSecurityGroupRule'), 'router-list-on-l3-agent': agentscheduler.ListRoutersOnL3Agent,
'lb-vip-list': utils.import_class( 'l3-agent-list-hosting-router': agentscheduler.ListL3AgentsHostingRouter,
'quantumclient.quantum.v2_0.lb.vip.ListVip'),
'lb-vip-show': utils.import_class(
'quantumclient.quantum.v2_0.lb.vip.ShowVip'),
'lb-vip-create': utils.import_class(
'quantumclient.quantum.v2_0.lb.vip.CreateVip'),
'lb-vip-update': utils.import_class(
'quantumclient.quantum.v2_0.lb.vip.UpdateVip'),
'lb-vip-delete': utils.import_class(
'quantumclient.quantum.v2_0.lb.vip.DeleteVip'),
'lb-pool-list': utils.import_class(
'quantumclient.quantum.v2_0.lb.pool.ListPool'),
'lb-pool-show': utils.import_class(
'quantumclient.quantum.v2_0.lb.pool.ShowPool'),
'lb-pool-create': utils.import_class(
'quantumclient.quantum.v2_0.lb.pool.CreatePool'),
'lb-pool-update': utils.import_class(
'quantumclient.quantum.v2_0.lb.pool.UpdatePool'),
'lb-pool-delete': utils.import_class(
'quantumclient.quantum.v2_0.lb.pool.DeletePool'),
'lb-pool-stats': utils.import_class(
'quantumclient.quantum.v2_0.lb.pool.RetrievePoolStats'),
'lb-member-list': utils.import_class(
'quantumclient.quantum.v2_0.lb.member.ListMember'),
'lb-member-show': utils.import_class(
'quantumclient.quantum.v2_0.lb.member.ShowMember'),
'lb-member-create': utils.import_class(
'quantumclient.quantum.v2_0.lb.member.CreateMember'),
'lb-member-update': utils.import_class(
'quantumclient.quantum.v2_0.lb.member.UpdateMember'),
'lb-member-delete': utils.import_class(
'quantumclient.quantum.v2_0.lb.member.DeleteMember'),
'lb-healthmonitor-list': utils.import_class(
'quantumclient.quantum.v2_0.lb.healthmonitor.ListHealthMonitor'),
'lb-healthmonitor-show': utils.import_class(
'quantumclient.quantum.v2_0.lb.healthmonitor.ShowHealthMonitor'),
'lb-healthmonitor-create': utils.import_class(
'quantumclient.quantum.v2_0.lb.healthmonitor.CreateHealthMonitor'),
'lb-healthmonitor-update': utils.import_class(
'quantumclient.quantum.v2_0.lb.healthmonitor.UpdateHealthMonitor'),
'lb-healthmonitor-delete': utils.import_class(
'quantumclient.quantum.v2_0.lb.healthmonitor.DeleteHealthMonitor'),
'lb-healthmonitor-associate': utils.import_class(
'quantumclient.quantum.v2_0.lb.healthmonitor.AssociateHealthMonitor'),
'lb-healthmonitor-disassociate': utils.import_class(
'quantumclient.quantum.v2_0.lb.healthmonitor'
'.DisassociateHealthMonitor'),
'queue-create': utils.import_class(
'quantumclient.quantum.v2_0.nvp_qos_queue.CreateQoSQueue'),
'queue-delete': utils.import_class(
'quantumclient.quantum.v2_0.nvp_qos_queue.DeleteQoSQueue'),
'queue-show': utils.import_class(
'quantumclient.quantum.v2_0.nvp_qos_queue.ShowQoSQueue'),
'queue-list': utils.import_class(
'quantumclient.quantum.v2_0.nvp_qos_queue.ListQoSQueue'),
'agent-list': utils.import_class(
'quantumclient.quantum.v2_0.agent.ListAgent'),
'agent-show': utils.import_class(
'quantumclient.quantum.v2_0.agent.ShowAgent'),
'agent-delete': utils.import_class(
'quantumclient.quantum.v2_0.agent.DeleteAgent'),
'agent-update': utils.import_class(
'quantumclient.quantum.v2_0.agent.UpdateAgent'),
'net-gateway-create': utils.import_class(
'quantumclient.quantum.v2_0.nvpnetworkgateway.CreateNetworkGateway'),
'net-gateway-update': utils.import_class(
'quantumclient.quantum.v2_0.nvpnetworkgateway.UpdateNetworkGateway'),
'net-gateway-delete': utils.import_class(
'quantumclient.quantum.v2_0.nvpnetworkgateway.DeleteNetworkGateway'),
'net-gateway-show': utils.import_class(
'quantumclient.quantum.v2_0.nvpnetworkgateway.ShowNetworkGateway'),
'net-gateway-list': utils.import_class(
'quantumclient.quantum.v2_0.nvpnetworkgateway.ListNetworkGateway'),
'net-gateway-connect': utils.import_class(
'quantumclient.quantum.v2_0.nvpnetworkgateway.ConnectNetworkGateway'),
'net-gateway-disconnect': utils.import_class(
'quantumclient.quantum.v2_0.nvpnetworkgateway.'
'DisconnectNetworkGateway'),
'dhcp-agent-network-add': utils.import_class(
'quantumclient.quantum.v2_0.agentscheduler.AddNetworkToDhcpAgent'),
'dhcp-agent-network-remove': utils.import_class(
'quantumclient.quantum.v2_0.agentscheduler.'
'RemoveNetworkFromDhcpAgent'),
'net-list-on-dhcp-agent': utils.import_class(
'quantumclient.quantum.v2_0.agentscheduler.'
'ListNetworksOnDhcpAgent'),
'dhcp-agent-list-hosting-net': utils.import_class(
'quantumclient.quantum.v2_0.agentscheduler.'
'ListDhcpAgentsHostingNetwork'),
'l3-agent-router-add': utils.import_class(
'quantumclient.quantum.v2_0.agentscheduler.AddRouterToL3Agent'),
'l3-agent-router-remove': utils.import_class(
'quantumclient.quantum.v2_0.agentscheduler.RemoveRouterFromL3Agent'),
'router-list-on-l3-agent': utils.import_class(
'quantumclient.quantum.v2_0.agentscheduler.ListRoutersOnL3Agent'),
'l3-agent-list-hosting-router': utils.import_class(
'quantumclient.quantum.v2_0.agentscheduler.ListL3AgentsHostingRouter'),
} }
COMMANDS = {'2.0': COMMAND_V2} COMMANDS = {'2.0': COMMAND_V2}
@ -287,17 +207,17 @@ class HelpAction(argparse.Action):
sys.exit(0) sys.exit(0)
class QuantumShell(app.App): class NeutronShell(app.App):
CONSOLE_MESSAGE_FORMAT = '%(message)s' CONSOLE_MESSAGE_FORMAT = '%(message)s'
DEBUG_MESSAGE_FORMAT = '%(levelname)s: %(name)s %(message)s' DEBUG_MESSAGE_FORMAT = '%(levelname)s: %(name)s %(message)s'
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
def __init__(self, apiversion): def __init__(self, apiversion):
super(QuantumShell, self).__init__( super(NeutronShell, self).__init__(
description=__doc__.strip(), description=__doc__.strip(),
version=VERSION, version=VERSION,
command_manager=commandmanager.CommandManager('quantum.cli'), ) command_manager=commandmanager.CommandManager('neutron.cli'), )
self.commands = COMMANDS self.commands = COMMANDS
for k, v in self.commands[apiversion].items(): for k, v in self.commands[apiversion].items():
self.command_manager.add_command(k, v) self.command_manager.add_command(k, v)
@ -423,8 +343,8 @@ class QuantumShell(app.App):
parser.add_argument( parser.add_argument(
'--insecure', '--insecure',
action='store_true', action='store_true',
default=env('QUANTUMCLIENT_INSECURE', default=False), default=env('NEUTRONCLIENT_INSECURE', default=False),
help="Explicitly allow quantumclient to perform \"insecure\" " help="Explicitly allow neutronclient to perform \"insecure\" "
"SSL (https) requests. The server's certificate will " "SSL (https) requests. The server's certificate will "
"not be verified against any certificate authorities. " "not be verified against any certificate authorities. "
"This option should be used with caution.") "This option should be used with caution.")
@ -598,7 +518,7 @@ class QuantumShell(app.App):
* validate authentication info * validate authentication info
""" """
super(QuantumShell, self).initialize_app(argv) super(NeutronShell, self).initialize_app(argv)
self.api_version = {'network': self.api_version} self.api_version = {'network': self.api_version}
@ -642,9 +562,9 @@ class QuantumShell(app.App):
def main(argv=sys.argv[1:]): def main(argv=sys.argv[1:]):
try: try:
return QuantumShell(QUANTUM_API_VERSION).run(map(strutils.safe_decode, return NeutronShell(NEUTRON_API_VERSION).run(map(strutils.safe_decode,
argv)) argv))
except exc.QuantumClientException: except exc.NeutronClientException:
return 1 return 1
except Exception as e: except Exception as e:
print unicode(e) print unicode(e)

View File

@ -17,7 +17,7 @@
import testtools import testtools
from quantumclient.common import utils from neutronclient.common import utils
class UtilsTest(testtools.TestCase): class UtilsTest(testtools.TestCase):

View File

@ -21,12 +21,12 @@ import time
import urllib import urllib
import urlparse import urlparse
from quantumclient import client from neutronclient import client
from quantumclient.common import _ from neutronclient.common import _
from quantumclient.common import constants from neutronclient.common import constants
from quantumclient.common import exceptions from neutronclient.common import exceptions
from quantumclient.common import serializer from neutronclient.common import serializer
from quantumclient.common import utils from neutronclient.common import utils
_logger = logging.getLogger(__name__) _logger = logging.getLogger(__name__)
@ -36,14 +36,14 @@ def exception_handler_v20(status_code, error_content):
"""Exception handler for API v2.0 client """Exception handler for API v2.0 client
This routine generates the appropriate This routine generates the appropriate
Quantum exception according to the contents of the Neutron exception according to the contents of the
response body response body
:param status_code: HTTP error status code :param status_code: HTTP error status code
:param error_content: deserialized body of error response :param error_content: deserialized body of error response
""" """
quantum_errors = { neutron_errors = {
'NetworkNotFound': exceptions.NetworkNotFoundClient, 'NetworkNotFound': exceptions.NetworkNotFoundClient,
'NetworkInUse': exceptions.NetworkInUseClient, 'NetworkInUse': exceptions.NetworkInUseClient,
'PortNotFound': exceptions.PortNotFoundClient, 'PortNotFound': exceptions.PortNotFoundClient,
@ -53,23 +53,23 @@ def exception_handler_v20(status_code, error_content):
error_dict = None error_dict = None
if isinstance(error_content, dict): if isinstance(error_content, dict):
error_dict = error_content.get('QuantumError') error_dict = error_content.get('NeutronError')
# Find real error type # Find real error type
bad_quantum_error_flag = False bad_neutron_error_flag = False
if error_dict: if error_dict:
# If QuantumError key is found, it will definitely contain # If Neutron key is found, it will definitely contain
# a 'message' and 'type' keys? # a 'message' and 'type' keys?
try: try:
error_type = error_dict['type'] error_type = error_dict['type']
error_message = (error_dict['message'] + "\n" + error_message = (error_dict['message'] + "\n" +
error_dict['detail']) error_dict['detail'])
except Exception: except Exception:
bad_quantum_error_flag = True bad_neutron_error_flag = True
if not bad_quantum_error_flag: if not bad_neutron_error_flag:
ex = None ex = None
try: try:
# raise the appropriate error! # raise the appropriate error!
ex = quantum_errors[error_type](message=error_message) ex = neutron_errors[error_type](message=error_message)
ex.args = ([dict(status_code=status_code, ex.args = ([dict(status_code=status_code,
message=error_message)], ) message=error_message)], )
except Exception: except Exception:
@ -77,19 +77,19 @@ def exception_handler_v20(status_code, error_content):
if ex: if ex:
raise ex raise ex
else: else:
raise exceptions.QuantumClientException(status_code=status_code, raise exceptions.NeutronClientException(status_code=status_code,
message=error_dict) message=error_dict)
else: else:
message = None message = None
if isinstance(error_content, dict): if isinstance(error_content, dict):
message = error_content.get('message', None) message = error_content.get('message', None)
if message: if message:
raise exceptions.QuantumClientException(status_code=status_code, raise exceptions.NeutronClientException(status_code=status_code,
message=message) message=message)
# If we end up here the exception was not a quantum error # If we end up here the exception was not a neutron error
msg = "%s-%s" % (status_code, error_content) msg = "%s-%s" % (status_code, error_content)
raise exceptions.QuantumClientException(status_code=status_code, raise exceptions.NeutronClientException(status_code=status_code,
message=msg) message=msg)
@ -112,7 +112,7 @@ class APIParamsCall(object):
class Client(object): class Client(object):
"""Client for the OpenStack Quantum v2.0 API. """Client for the OpenStack Neutron v2.0 API.
:param string username: Username for authentication. (optional) :param string username: Username for authentication. (optional)
:param string password: Password for authentication. (optional) :param string password: Password for authentication. (optional)
@ -124,7 +124,7 @@ class Client(object):
'internalURL', or 'adminURL') (optional) 'internalURL', or 'adminURL') (optional)
:param string region_name: Name of a region to select when choosing an :param string region_name: Name of a region to select when choosing an
endpoint from the service catalog. endpoint from the service catalog.
:param string endpoint_url: A user-supplied endpoint URL for the quantum :param string endpoint_url: A user-supplied endpoint URL for the neutron
service. Lazy-authentication is possible for API service. Lazy-authentication is possible for API
service calls if endpoint is set at service calls if endpoint is set at
instantiation.(optional) instantiation.(optional)
@ -134,13 +134,13 @@ class Client(object):
Example:: Example::
from quantumclient.v2_0 import client from neutronclient.v2_0 import client
quantum = client.Client(username=USER, neutron = client.Client(username=USER,
password=PASS, password=PASS,
tenant_name=TENANT_NAME, tenant_name=TENANT_NAME,
auth_url=KEYSTONE_URL) auth_url=KEYSTONE_URL)
nets = quantum.list_networks() nets = neutron.list_networks()
... ...
""" """
@ -717,7 +717,7 @@ class Client(object):
l3_agent, router_id)) l3_agent, router_id))
def __init__(self, **kwargs): def __init__(self, **kwargs):
"""Initialize a new client for the Quantum v2.0 API.""" """Initialize a new client for the Neutron v2.0 API."""
super(Client, self).__init__() super(Client, self).__init__()
self.httpclient = client.HTTPClient(**kwargs) self.httpclient = client.HTTPClient(**kwargs)
self.version = '2.0' self.version = '2.0'
@ -734,7 +734,7 @@ class Client(object):
des_error_body = self.deserialize(response_body, status_code) des_error_body = self.deserialize(response_body, status_code)
except Exception: except Exception:
# If unable to deserialized body it is probably not a # If unable to deserialized body it is probably not a
# Quantum error # Neutron error
des_error_body = {'message': response_body} des_error_body = {'message': response_body}
# Raise the appropriate exception # Raise the appropriate exception
exception_handler_v20(status_code, des_error_body) exception_handler_v20(status_code, des_error_body)
@ -828,7 +828,7 @@ class Client(object):
except exceptions.ConnectionFailed: except exceptions.ConnectionFailed:
# Exception has already been logged by do_request() # Exception has already been logged by do_request()
if i < self.retries: if i < self.retries:
_logger.debug(_('Retrying connection to quantum service')) _logger.debug(_('Retrying connection to Neutron service'))
time.sleep(self.retry_interval) time.sleep(self.retry_interval)
raise exceptions.ConnectionFailed(reason=_("Maximum attempts reached")) raise exceptions.ConnectionFailed(reason=_("Maximum attempts reached"))

View File

@ -19,4 +19,4 @@
import pbr.version import pbr.version
__version__ = pbr.version.VersionInfo('python-quantumclient').version_string() __version__ = pbr.version.VersionInfo('python-neutronclient').version_string()

View File

@ -4,4 +4,4 @@
modules=exception,gettextutils,jsonutils,strutils,timeutils modules=exception,gettextutils,jsonutils,strutils,timeutils
# The base module to hold the copy of openstack.common # The base module to hold the copy of openstack.common
base=quantumclient base=neutronclient

View File

@ -1,5 +1,5 @@
[metadata] [metadata]
name = python-quantumclient name = python-neutronclient
summary = CLI and Client Library for OpenStack Networking summary = CLI and Client Library for OpenStack Networking
description-file = description-file =
README.rst README.rst
@ -20,7 +20,7 @@ classifier =
[files] [files]
packages = packages =
quantumclient neutronclient
[global] [global]
setup-hooks = setup-hooks =
@ -28,7 +28,7 @@ setup-hooks =
[entry_points] [entry_points]
console_scripts = console_scripts =
quantum = quantumclient.shell:main neutron = neutronclient.shell:main
[build_sphinx] [build_sphinx]
all_files = 1 all_files = 1

View File

@ -21,7 +21,7 @@ import sys
import mox import mox
from quantumclient.quantum.v2_0.lb import healthmonitor from neutronclient.neutron.v2_0.lb import healthmonitor
from tests.unit import test_cli20 from tests.unit import test_cli20

View File

@ -19,7 +19,7 @@
import sys import sys
from quantumclient.quantum.v2_0.lb import member from neutronclient.neutron.v2_0.lb import member
from tests.unit import test_cli20 from tests.unit import test_cli20

View File

@ -21,7 +21,7 @@ import sys
import mox import mox
from quantumclient.quantum.v2_0.lb import pool from neutronclient.neutron.v2_0.lb import pool
from tests.unit import test_cli20 from tests.unit import test_cli20

View File

@ -19,7 +19,7 @@
import sys import sys
from quantumclient.quantum.v2_0.lb import vip from neutronclient.neutron.v2_0.lb import vip
from tests.unit import test_cli20 from tests.unit import test_cli20

View File

@ -23,8 +23,8 @@ import uuid
import mox import mox
import testtools import testtools
from quantumclient import client from neutronclient import client
from quantumclient.common import exceptions from neutronclient.common import exceptions
USERNAME = 'testuser' USERNAME = 'testuser'
@ -48,7 +48,7 @@ KS_TOKEN_RESULT = {
'publicURL': ENDPOINT_URL, 'publicURL': ENDPOINT_URL,
'region': REGION}], 'region': REGION}],
'type': 'network', 'type': 'network',
'name': 'Quantum Service'} 'name': 'Neutron Service'}
] ]
} }
} }
@ -56,7 +56,7 @@ KS_TOKEN_RESULT = {
ENDPOINTS_RESULT = { ENDPOINTS_RESULT = {
'endpoints': [{ 'endpoints': [{
'type': 'network', 'type': 'network',
'name': 'Quantum Service', 'name': 'Neutron Service',
'region': REGION, 'region': REGION,
'adminURL': ENDPOINT_URL, 'adminURL': ENDPOINT_URL,
'internalURL': ENDPOINT_URL, 'internalURL': ENDPOINT_URL,
@ -110,7 +110,7 @@ class CLITestAuthKeystone(testtools.TestCase):
res401 = self.mox.CreateMock(httplib2.Response) res401 = self.mox.CreateMock(httplib2.Response)
res401.status = 401 res401.status = 401
# If a token is expired, quantum server retruns 401 # If a token is expired, neutron server retruns 401
self.client.request( self.client.request(
mox.StrContains(ENDPOINT_URL + '/resource'), 'GET', mox.StrContains(ENDPOINT_URL + '/resource'), 'GET',
headers=mox.ContainsKeyValue('X-Auth-Token', TOKEN) headers=mox.ContainsKeyValue('X-Auth-Token', TOKEN)

View File

@ -17,83 +17,83 @@
import testtools import testtools
from quantumclient.common import exceptions from neutronclient.common import exceptions
from quantumclient.quantum import v2_0 as quantumV20 from neutronclient.neutron import v2_0 as neutronV20
class CLITestArgs(testtools.TestCase): class CLITestArgs(testtools.TestCase):
def test_empty(self): def test_empty(self):
_mydict = quantumV20.parse_args_to_dict([]) _mydict = neutronV20.parse_args_to_dict([])
self.assertEqual({}, _mydict) self.assertEqual({}, _mydict)
def test_default_bool(self): def test_default_bool(self):
_specs = ['--my_bool', '--arg1', 'value1'] _specs = ['--my_bool', '--arg1', 'value1']
_mydict = quantumV20.parse_args_to_dict(_specs) _mydict = neutronV20.parse_args_to_dict(_specs)
self.assertTrue(_mydict['my_bool']) self.assertTrue(_mydict['my_bool'])
def test_bool_true(self): def test_bool_true(self):
_specs = ['--my-bool', 'type=bool', 'true', '--arg1', 'value1'] _specs = ['--my-bool', 'type=bool', 'true', '--arg1', 'value1']
_mydict = quantumV20.parse_args_to_dict(_specs) _mydict = neutronV20.parse_args_to_dict(_specs)
self.assertTrue(_mydict['my_bool']) self.assertTrue(_mydict['my_bool'])
def test_bool_false(self): def test_bool_false(self):
_specs = ['--my_bool', 'type=bool', 'false', '--arg1', 'value1'] _specs = ['--my_bool', 'type=bool', 'false', '--arg1', 'value1']
_mydict = quantumV20.parse_args_to_dict(_specs) _mydict = neutronV20.parse_args_to_dict(_specs)
self.assertFalse(_mydict['my_bool']) self.assertFalse(_mydict['my_bool'])
def test_nargs(self): def test_nargs(self):
_specs = ['--tag', 'x', 'y', '--arg1', 'value1'] _specs = ['--tag', 'x', 'y', '--arg1', 'value1']
_mydict = quantumV20.parse_args_to_dict(_specs) _mydict = neutronV20.parse_args_to_dict(_specs)
self.assertTrue('x' in _mydict['tag']) self.assertTrue('x' in _mydict['tag'])
self.assertTrue('y' in _mydict['tag']) self.assertTrue('y' in _mydict['tag'])
def test_badarg(self): def test_badarg(self):
_specs = ['--tag=t', 'x', 'y', '--arg1', 'value1'] _specs = ['--tag=t', 'x', 'y', '--arg1', 'value1']
self.assertRaises(exceptions.CommandError, self.assertRaises(exceptions.CommandError,
quantumV20.parse_args_to_dict, _specs) neutronV20.parse_args_to_dict, _specs)
def test_badarg_with_minus(self): def test_badarg_with_minus(self):
_specs = ['--arg1', 'value1', '-D'] _specs = ['--arg1', 'value1', '-D']
self.assertRaises(exceptions.CommandError, self.assertRaises(exceptions.CommandError,
quantumV20.parse_args_to_dict, _specs) neutronV20.parse_args_to_dict, _specs)
def test_goodarg_with_minus_number(self): def test_goodarg_with_minus_number(self):
_specs = ['--arg1', 'value1', '-1', '-1.0'] _specs = ['--arg1', 'value1', '-1', '-1.0']
_mydict = quantumV20.parse_args_to_dict(_specs) _mydict = neutronV20.parse_args_to_dict(_specs)
self.assertEqual(['value1', '-1', '-1.0'], self.assertEqual(['value1', '-1', '-1.0'],
_mydict['arg1']) _mydict['arg1'])
def test_badarg_duplicate(self): def test_badarg_duplicate(self):
_specs = ['--tag=t', '--arg1', 'value1', '--arg1', 'value1'] _specs = ['--tag=t', '--arg1', 'value1', '--arg1', 'value1']
self.assertRaises(exceptions.CommandError, self.assertRaises(exceptions.CommandError,
quantumV20.parse_args_to_dict, _specs) neutronV20.parse_args_to_dict, _specs)
def test_badarg_early_type_specification(self): def test_badarg_early_type_specification(self):
_specs = ['type=dict', 'key=value'] _specs = ['type=dict', 'key=value']
self.assertRaises(exceptions.CommandError, self.assertRaises(exceptions.CommandError,
quantumV20.parse_args_to_dict, _specs) neutronV20.parse_args_to_dict, _specs)
def test_arg(self): def test_arg(self):
_specs = ['--tag=t', '--arg1', 'value1'] _specs = ['--tag=t', '--arg1', 'value1']
self.assertEqual('value1', self.assertEqual('value1',
quantumV20.parse_args_to_dict(_specs)['arg1']) neutronV20.parse_args_to_dict(_specs)['arg1'])
def test_dict_arg(self): def test_dict_arg(self):
_specs = ['--tag=t', '--arg1', 'type=dict', 'key1=value1,key2=value2'] _specs = ['--tag=t', '--arg1', 'type=dict', 'key1=value1,key2=value2']
arg1 = quantumV20.parse_args_to_dict(_specs)['arg1'] arg1 = neutronV20.parse_args_to_dict(_specs)['arg1']
self.assertEqual('value1', arg1['key1']) self.assertEqual('value1', arg1['key1'])
self.assertEqual('value2', arg1['key2']) self.assertEqual('value2', arg1['key2'])
def test_dict_arg_with_attribute_named_type(self): def test_dict_arg_with_attribute_named_type(self):
_specs = ['--tag=t', '--arg1', 'type=dict', 'type=value1,key2=value2'] _specs = ['--tag=t', '--arg1', 'type=dict', 'type=value1,key2=value2']
arg1 = quantumV20.parse_args_to_dict(_specs)['arg1'] arg1 = neutronV20.parse_args_to_dict(_specs)['arg1']
self.assertEqual('value1', arg1['type']) self.assertEqual('value1', arg1['type'])
self.assertEqual('value2', arg1['key2']) self.assertEqual('value2', arg1['key2'])
def test_list_of_dict_arg(self): def test_list_of_dict_arg(self):
_specs = ['--tag=t', '--arg1', 'type=dict', _specs = ['--tag=t', '--arg1', 'type=dict',
'list=true', 'key1=value1,key2=value2'] 'list=true', 'key1=value1,key2=value2']
arg1 = quantumV20.parse_args_to_dict(_specs)['arg1'] arg1 = neutronV20.parse_args_to_dict(_specs)['arg1']
self.assertEqual('value1', arg1[0]['key1']) self.assertEqual('value1', arg1[0]['key1'])
self.assertEqual('value2', arg1[0]['key2']) self.assertEqual('value2', arg1[0]['key2'])

View File

@ -21,9 +21,9 @@ import fixtures
import mox import mox
import testtools import testtools
from quantumclient.common import constants from neutronclient.common import constants
from quantumclient import shell from neutronclient import shell
from quantumclient.v2_0 import client from neutronclient.v2_0 import client
API_VERSION = "2.0" API_VERSION = "2.0"
@ -170,10 +170,10 @@ class CLITestV20Base(testtools.TestCase):
self.fake_stdout = FakeStdout() self.fake_stdout = FakeStdout()
self.useFixture(fixtures.MonkeyPatch('sys.stdout', self.fake_stdout)) self.useFixture(fixtures.MonkeyPatch('sys.stdout', self.fake_stdout))
self.useFixture(fixtures.MonkeyPatch( self.useFixture(fixtures.MonkeyPatch(
'quantumclient.quantum.v2_0.find_resourceid_by_name_or_id', 'neutronclient.neutron.v2_0.find_resourceid_by_name_or_id',
self._find_resourceid)) self._find_resourceid))
self.useFixture(fixtures.MonkeyPatch( self.useFixture(fixtures.MonkeyPatch(
'quantumclient.v2_0.client.Client.get_attr_metadata', 'neutronclient.v2_0.client.Client.get_attr_metadata',
self._get_attr_metadata)) self._get_attr_metadata))
self.client = client.Client(token=TOKEN, endpoint_url=self.endurl) self.client = client.Client(token=TOKEN, endpoint_url=self.endurl)

View File

@ -17,8 +17,8 @@
import sys import sys
from quantumclient.quantum.v2_0.extension import ListExt from neutronclient.neutron.v2_0.extension import ListExt
from quantumclient.quantum.v2_0.extension import ShowExt from neutronclient.neutron.v2_0.extension import ShowExt
from tests.unit.test_cli20 import CLITestV20Base from tests.unit.test_cli20 import CLITestV20Base
from tests.unit.test_cli20 import MyApp from tests.unit.test_cli20 import MyApp

View File

@ -18,7 +18,7 @@
import sys import sys
from quantumclient.quantum.v2_0 import floatingip as fip from neutronclient.neutron.v2_0 import floatingip as fip
from tests.unit import test_cli20 from tests.unit import test_cli20

View File

@ -18,10 +18,10 @@ import sys
import mox import mox
from quantumclient.common import exceptions from neutronclient.common import exceptions
from quantumclient.common import utils from neutronclient.common import utils
from quantumclient.quantum.v2_0 import network from neutronclient.neutron.v2_0 import network
from quantumclient import shell from neutronclient import shell
from tests.unit import test_cli20 from tests.unit import test_cli20

View File

@ -18,7 +18,7 @@
import sys import sys
from quantumclient.quantum.v2_0 import nvp_qos_queue as qos from neutronclient.neutron.v2_0 import nvp_qos_queue as qos
from tests.unit import test_cli20 from tests.unit import test_cli20

View File

@ -17,7 +17,7 @@
import sys import sys
from quantumclient.quantum.v2_0 import nvpnetworkgateway as nwgw from neutronclient.neutron.v2_0 import nvpnetworkgateway as nwgw
from tests.unit import test_cli20 from tests.unit import test_cli20

View File

@ -19,8 +19,8 @@ import sys
import mox import mox
from quantumclient.quantum.v2_0 import port from neutronclient.neutron.v2_0 import port
from quantumclient import shell from neutronclient import shell
from tests.unit import test_cli20 from tests.unit import test_cli20

View File

@ -17,8 +17,8 @@
import sys import sys
from quantumclient.common import exceptions from neutronclient.common import exceptions
from quantumclient.quantum.v2_0 import router from neutronclient.neutron.v2_0 import router
from tests.unit import test_cli20 from tests.unit import test_cli20

View File

@ -20,7 +20,7 @@ import sys
import mox import mox
from quantumclient.quantum.v2_0 import securitygroup from neutronclient.neutron.v2_0 import securitygroup
from tests.unit import test_cli20 from tests.unit import test_cli20

View File

@ -17,7 +17,7 @@
import sys import sys
from quantumclient.quantum.v2_0 import subnet from neutronclient.neutron.v2_0 import subnet
from tests.unit import test_cli20 from tests.unit import test_cli20

View File

@ -20,9 +20,9 @@ import uuid
import mox import mox
import testtools import testtools
from quantumclient.common import exceptions from neutronclient.common import exceptions
from quantumclient.quantum import v2_0 as quantumv20 from neutronclient.neutron import v2_0 as neutronV20
from quantumclient.v2_0 import client from neutronclient.v2_0 import client
from tests.unit import test_cli20 from tests.unit import test_cli20
@ -50,7 +50,7 @@ class CLITestNameorID(testtools.TestCase):
headers=mox.ContainsKeyValue('X-Auth-Token', test_cli20.TOKEN) headers=mox.ContainsKeyValue('X-Auth-Token', test_cli20.TOKEN)
).AndReturn((test_cli20.MyResp(200), resstr)) ).AndReturn((test_cli20.MyResp(200), resstr))
self.mox.ReplayAll() self.mox.ReplayAll()
returned_id = quantumv20.find_resourceid_by_name_or_id( returned_id = neutronV20.find_resourceid_by_name_or_id(
self.client, 'network', _id) self.client, 'network', _id)
self.assertEqual(_id, returned_id) self.assertEqual(_id, returned_id)
@ -72,7 +72,7 @@ class CLITestNameorID(testtools.TestCase):
headers=mox.ContainsKeyValue('X-Auth-Token', test_cli20.TOKEN) headers=mox.ContainsKeyValue('X-Auth-Token', test_cli20.TOKEN)
).AndReturn((test_cli20.MyResp(200), resstr)) ).AndReturn((test_cli20.MyResp(200), resstr))
self.mox.ReplayAll() self.mox.ReplayAll()
returned_id = quantumv20.find_resourceid_by_name_or_id( returned_id = neutronV20.find_resourceid_by_name_or_id(
self.client, 'network', _id) self.client, 'network', _id)
self.assertEqual(_id, returned_id) self.assertEqual(_id, returned_id)
@ -89,7 +89,7 @@ class CLITestNameorID(testtools.TestCase):
headers=mox.ContainsKeyValue('X-Auth-Token', test_cli20.TOKEN) headers=mox.ContainsKeyValue('X-Auth-Token', test_cli20.TOKEN)
).AndReturn((test_cli20.MyResp(200), resstr)) ).AndReturn((test_cli20.MyResp(200), resstr))
self.mox.ReplayAll() self.mox.ReplayAll()
returned_id = quantumv20.find_resourceid_by_name_or_id( returned_id = neutronV20.find_resourceid_by_name_or_id(
self.client, 'network', name) self.client, 'network', name)
self.assertEqual(_id, returned_id) self.assertEqual(_id, returned_id)
@ -107,9 +107,9 @@ class CLITestNameorID(testtools.TestCase):
).AndReturn((test_cli20.MyResp(200), resstr)) ).AndReturn((test_cli20.MyResp(200), resstr))
self.mox.ReplayAll() self.mox.ReplayAll()
try: try:
quantumv20.find_resourceid_by_name_or_id( neutronV20.find_resourceid_by_name_or_id(
self.client, 'network', name) self.client, 'network', name)
except exceptions.QuantumClientException as ex: except exceptions.NeutronClientException as ex:
self.assertTrue('Multiple' in ex.message) self.assertTrue('Multiple' in ex.message)
def test_get_id_from_name_notfound(self): def test_get_id_from_name_notfound(self):
@ -125,8 +125,8 @@ class CLITestNameorID(testtools.TestCase):
).AndReturn((test_cli20.MyResp(200), resstr)) ).AndReturn((test_cli20.MyResp(200), resstr))
self.mox.ReplayAll() self.mox.ReplayAll()
try: try:
quantumv20.find_resourceid_by_name_or_id( neutronV20.find_resourceid_by_name_or_id(
self.client, 'network', name) self.client, 'network', name)
except exceptions.QuantumClientException as ex: except exceptions.NeutronClientException as ex:
self.assertTrue('Unable to find' in ex.message) self.assertTrue('Unable to find' in ex.message)
self.assertEqual(404, ex.status_code) self.assertEqual(404, ex.status_code)

View File

@ -17,8 +17,8 @@
import sys import sys
from quantumclient.common import exceptions from neutronclient.common import exceptions
from quantumclient.quantum.v2_0 import quota as test_quota from neutronclient.neutron.v2_0 import quota as test_quota
from tests.unit import test_cli20 from tests.unit import test_cli20
@ -36,7 +36,7 @@ class CLITestV20Quota(test_cli20.CLITestV20Base):
test_cli20.MyApp(sys.stdout), None) test_cli20.MyApp(sys.stdout), None)
args = ['--tenant-id', self.test_id, '--network', 'test'] args = ['--tenant-id', self.test_id, '--network', 'test']
self.assertRaises( self.assertRaises(
exceptions.QuantumClientException, self._test_update_resource, exceptions.NeutronClientException, self._test_update_resource,
resource, cmd, self.test_id, args=args, resource, cmd, self.test_id, args=args,
extrafields={'network': 'new'}) extrafields={'network': 'new'})

View File

@ -25,8 +25,8 @@ import mox
import testtools import testtools
from testtools import matchers from testtools import matchers
from quantumclient.common import exceptions from neutronclient.common import exceptions
from quantumclient import shell as openstack_shell from neutronclient import shell as openstack_shell
DEFAULT_USERNAME = 'username' DEFAULT_USERNAME = 'username'
@ -53,7 +53,7 @@ class ShellTest(testtools.TestCase):
'OS_AUTH_URL': DEFAULT_AUTH_URL} 'OS_AUTH_URL': DEFAULT_AUTH_URL}
def _tolerant_shell(self, cmd): def _tolerant_shell(self, cmd):
t_shell = openstack_shell.QuantumShell('2.0') t_shell = openstack_shell.NeutronShell('2.0')
t_shell.run(cmd.split()) t_shell.run(cmd.split())
# Patch os.environ to avoid required auth info. # Patch os.environ to avoid required auth info.
@ -68,7 +68,7 @@ class ShellTest(testtools.TestCase):
# Make a fake shell object, a helping wrapper to call it, and a quick # Make a fake shell object, a helping wrapper to call it, and a quick
# way of asserting that certain API calls were made. # way of asserting that certain API calls were made.
global shell, _shell, assert_called, assert_called_anytime global shell, _shell, assert_called, assert_called_anytime
_shell = openstack_shell.QuantumShell('2.0') _shell = openstack_shell.NeutronShell('2.0')
shell = lambda cmd: _shell.run(cmd.split()) shell = lambda cmd: _shell.run(cmd.split())
def shell(self, argstr): def shell(self, argstr):
@ -77,7 +77,7 @@ class ShellTest(testtools.TestCase):
_old_env, os.environ = os.environ, clean_env.copy() _old_env, os.environ = os.environ, clean_env.copy()
try: try:
sys.stdout = cStringIO.StringIO() sys.stdout = cStringIO.StringIO()
_shell = openstack_shell.QuantumShell('2.0') _shell = openstack_shell.NeutronShell('2.0')
_shell.run(argstr.split()) _shell.run(argstr.split())
except SystemExit: except SystemExit:
exc_type, exc_value, exc_traceback = sys.exc_info() exc_type, exc_value, exc_traceback = sys.exc_info()
@ -90,7 +90,7 @@ class ShellTest(testtools.TestCase):
return out return out
def test_run_unknown_command(self): def test_run_unknown_command(self):
openstack_shell.QuantumShell('2.0').run('fake') openstack_shell.NeutronShell('2.0').run('fake')
def test_help(self): def test_help(self):
required = 'usage:' required = 'usage:'
@ -126,13 +126,13 @@ class ShellTest(testtools.TestCase):
' --os-auth-strategy keystone quota-list') ' --os-auth-strategy keystone quota-list')
def test_build_option_parser(self): def test_build_option_parser(self):
quant_shell = openstack_shell.QuantumShell('2.0') neutron_shell = openstack_shell.NeutronShell('2.0')
result = quant_shell.build_option_parser('descr', '2.0') result = neutron_shell.build_option_parser('descr', '2.0')
self.assertEqual(True, isinstance(result, argparse.ArgumentParser)) self.assertEqual(True, isinstance(result, argparse.ArgumentParser))
def test_main_with_unicode(self): def test_main_with_unicode(self):
self.mox.StubOutClassWithMocks(openstack_shell, 'QuantumShell') self.mox.StubOutClassWithMocks(openstack_shell, 'NeutronShell')
qshell_mock = openstack_shell.QuantumShell('2.0') qshell_mock = openstack_shell.NeutronShell('2.0')
#self.mox.StubOutWithMock(qshell_mock, 'run') #self.mox.StubOutWithMock(qshell_mock, 'run')
unicode_text = u'\u7f51\u7edc' unicode_text = u'\u7f51\u7edc'
argv = ['net-list', unicode_text, unicode_text.encode('utf-8')] argv = ['net-list', unicode_text, unicode_text.encode('utf-8')]
@ -145,7 +145,7 @@ class ShellTest(testtools.TestCase):
self.assertEqual(ret, 0) self.assertEqual(ret, 0)
def test_endpoint_option(self): def test_endpoint_option(self):
shell = openstack_shell.QuantumShell('2.0') shell = openstack_shell.NeutronShell('2.0')
parser = shell.build_option_parser('descr', '2.0') parser = shell.build_option_parser('descr', '2.0')
# Neither $OS_ENDPOINT_TYPE nor --endpoint-type # Neither $OS_ENDPOINT_TYPE nor --endpoint-type
@ -161,7 +161,7 @@ class ShellTest(testtools.TestCase):
"public") "public")
self.useFixture(fixture) self.useFixture(fixture)
shell = openstack_shell.QuantumShell('2.0') shell = openstack_shell.NeutronShell('2.0')
parser = shell.build_option_parser('descr', '2.0') parser = shell.build_option_parser('descr', '2.0')
# $OS_ENDPOINT_TYPE but not --endpoint-type # $OS_ENDPOINT_TYPE but not --endpoint-type

View File

@ -19,8 +19,8 @@ import sys
import testtools import testtools
from quantumclient.common import exceptions from neutronclient.common import exceptions
from quantumclient.common import utils from neutronclient.common import utils
class TestUtils(testtools.TestCase): class TestUtils(testtools.TestCase):

View File

@ -0,0 +1,27 @@
_neutron_opts="" # lazy init
_neutron_flags="" # lazy init
_neutron_opts_exp="" # lazy init
_neutron()
{
local cur prev nbc cflags
COMPREPLY=()
cur="${COMP_WORDS[COMP_CWORD]}"
prev="${COMP_WORDS[COMP_CWORD-1]}"
if [ "x$_neutron_opts" == "x" ] ; then
nbc="`neutron bash-completion`"
_neutron_opts="`echo "$nbc" | sed -e "s/--[a-z0-9_-]*//g" -e "s/\s\s*/ /g"`"
_neutron_flags="`echo " $nbc" | sed -e "s/ [^-][^-][a-z0-9_-]*//g" -e "s/\s\s*/ /g"`"
_neutron_opts_exp="`echo "$_neutron_opts" | sed -e "s/\s/|/g"`"
fi
if [[ " ${COMP_WORDS[@]} " =~ " "($_neutron_opts_exp)" " && "$prev" != "help" ]] ; then
COMPLETION_CACHE=~/.neutronclient/*/*-cache
cflags="$_neutron_flags "$(cat $COMPLETION_CACHE 2> /dev/null | tr '\n' ' ')
COMPREPLY=($(compgen -W "${cflags}" -- ${cur}))
else
COMPREPLY=($(compgen -W "${_neutron_opts}" -- ${cur}))
fi
return 0
}
complete -F _neutron neutron

View File

@ -1,27 +0,0 @@
_quantum_opts="" # lazy init
_quantum_flags="" # lazy init
_quantum_opts_exp="" # lazy init
_quantum()
{
local cur prev nbc cflags
COMPREPLY=()
cur="${COMP_WORDS[COMP_CWORD]}"
prev="${COMP_WORDS[COMP_CWORD-1]}"
if [ "x$_quantum_opts" == "x" ] ; then
nbc="`quantum bash-completion`"
_quantum_opts="`echo "$nbc" | sed -e "s/--[a-z0-9_-]*//g" -e "s/\s\s*/ /g"`"
_quantum_flags="`echo " $nbc" | sed -e "s/ [^-][^-][a-z0-9_-]*//g" -e "s/\s\s*/ /g"`"
_quantum_opts_exp="`echo "$_quantum_opts" | sed -e "s/\s/|/g"`"
fi
if [[ " ${COMP_WORDS[@]} " =~ " "($_quantum_opts_exp)" " && "$prev" != "help" ]] ; then
COMPLETION_CACHE=~/.quantumclient/*/*-cache
cflags="$_quantum_flags "$(cat $COMPLETION_CACHE 2> /dev/null | tr '\n' ' ')
COMPREPLY=($(compgen -W "${cflags}" -- ${cur}))
else
COMPREPLY=($(compgen -W "${_quantum_opts}" -- ${cur}))
fi
return 0
}
complete -F _quantum quantum