diff --git a/.gitignore b/.gitignore
index 3e20723ad..abdf7b022 100644
--- a/.gitignore
+++ b/.gitignore
@@ -17,6 +17,6 @@ run_tests.err.log
run_tests.log
.autogenerated
.coverage
-.testrepository/
+.stestr/
.tox/
.venv/
diff --git a/.gitreview b/.gitreview
index 994b07a43..faf5d1f5b 100644
--- a/.gitreview
+++ b/.gitreview
@@ -1,4 +1,4 @@
[gerrit]
-host=review.openstack.org
+host=review.opendev.org
port=29418
project=openstack/python-neutronclient.git
diff --git a/.pylintrc b/.pylintrc
index bd677fd6a..7e4a0716c 100644
--- a/.pylintrc
+++ b/.pylintrc
@@ -20,7 +20,7 @@ variable-rgx=[a-z_][a-z0-9_]{0,30}$
argument-rgx=[a-z_][a-z0-9_]{1,30}$
# Method names should be at least 3 characters long
-# and be lowecased with underscores
+# and be lowercased with underscores
method-rgx=([a-z_][a-z0-9_]{2,50}|setUp|tearDown)$
# Module names matching quantum-* are ok (files in bin/)
diff --git a/.stestr.conf b/.stestr.conf
new file mode 100644
index 000000000..875bb1461
--- /dev/null
+++ b/.stestr.conf
@@ -0,0 +1,3 @@
+[DEFAULT]
+test_path=${OS_TEST_PATH:-./neutronclient/tests/unit}
+top_dir=./
diff --git a/.testr.conf b/.testr.conf
deleted file mode 100644
index 01dee7036..000000000
--- a/.testr.conf
+++ /dev/null
@@ -1,4 +0,0 @@
-[DEFAULT]
-test_command=OS_STDOUT_CAPTURE=1 OS_STDERR_CAPTURE=1 ${PYTHON:-python} -m subunit.run discover -t ./ ${OS_TEST_PATH:-./neutronclient/tests/unit} $LISTOPT $IDOPTION
-test_id_option=--load-list $IDFILE
-test_list_option=--list
diff --git a/.zuul.yaml b/.zuul.yaml
new file mode 100644
index 000000000..7c8822186
--- /dev/null
+++ b/.zuul.yaml
@@ -0,0 +1,39 @@
+- project:
+ templates:
+ - openstack-cover-jobs
+ - openstack-python3-jobs
+ - publish-openstack-docs-pti
+ - check-requirements
+ - lib-forward-testing-python3
+ - release-notes-jobs-python3
+ - openstackclient-plugin-jobs
+ experimental:
+ jobs:
+ - neutronclient-grenade-neutron-lib:
+ irrelevant-files:
+ - ^(test-|)requirements.txt$
+ - ^setup.cfg$
+
+- job:
+ name: neutronclient-grenade-neutron-lib
+ parent: grenade
+ description: |
+ neutron-lib grenade job.
+ The version of this job on the current branch is py3 based,
+ while any branch before ussuri needs to use the py2 version,
+ which is defined in openstack-zuul-jobs with the old name
+ (legacy-grenade-dsvm-neutron-libs).
+ Users of this job needs to pay attention of the version used.
+ Former names for this job were:
+ * legacy-grenade-dsvm-neutron-libs
+ * neutron-lib-grenade-dsvm
+ required-projects:
+ - openstack/keystoneauth
+ - openstack/neutron
+ - openstack/neutron-lib
+ - openstack/python-cinderclient
+ - openstack/python-glanceclient
+ - openstack/python-ironicclient
+ - openstack/python-keystoneclient
+ - openstack/python-neutronclient
+ - openstack/python-novaclient
diff --git a/HACKING.rst b/HACKING.rst
index b8b3ff96c..7230971af 100644
--- a/HACKING.rst
+++ b/HACKING.rst
@@ -2,7 +2,7 @@ Neutron Style Commandments
================================
- Step 1: Read the OpenStack Style Commandments
- http://docs.openstack.org/developer/hacking/
+ https://docs.openstack.org/hacking/latest/
- Step 2: Read on
diff --git a/MANIFEST.in b/MANIFEST.in
deleted file mode 100644
index c0f014e74..000000000
--- a/MANIFEST.in
+++ /dev/null
@@ -1,6 +0,0 @@
-include tox.ini
-include LICENSE README.rst HACKING.rst
-include AUTHORS
-include ChangeLog
-include tools/*
-recursive-include tests *
diff --git a/README.rst b/README.rst
index cceea78f5..eaac15c2c 100644
--- a/README.rst
+++ b/README.rst
@@ -1,17 +1,28 @@
+========================
+Team and repository tags
+========================
+
+.. image:: https://governance.openstack.org/tc/badges/python-neutronclient.svg
+ :target: https://governance.openstack.org/tc/reference/tags/index.html
+
+.. Change things from this point on
+
Python bindings to the Neutron API
==================================
.. image:: https://img.shields.io/pypi/v/python-neutronclient.svg
- :target: https://pypi.python.org/pypi/python-neutronclient/
+ :target: https://pypi.org/project/python-neutronclient/
:alt: Latest Version
-.. image:: https://img.shields.io/pypi/dm/python-neutronclient.svg
- :target: https://pypi.python.org/pypi/python-neutronclient/
- :alt: Downloads
-
This is a client library for Neutron built on the Neutron API. It
-provides a Python API (the ``neutronclient`` module) and a command-line tool
-(``neutron``).
+provides a Python API (the ``neutronclient`` module).
+
+.. note:: This project has been deprecated. The CLI code has been deleted
+ and is not accessible anymore. The Python bindings are still in use by
+ other projects but no new features will be added to this project.
+ All projects under Openstack governance migrating to use OpenstackSDK.
+ Any new feature should be proposed to OpenStack SDK and OpenStack
+ Client.
* License: Apache License, Version 2.0
* `PyPi`_ - package installation
@@ -22,10 +33,11 @@ provides a Python API (the ``neutronclient`` module) and a command-line tool
* `Source`_
* `Developer's Guide`_
-.. _PyPi: https://pypi.python.org/pypi/python-neutronclient
-.. _Online Documentation: http://docs.openstack.org/developer/python-neutronclient
+.. _PyPi: https://pypi.org/project/python-neutronclient
+.. _Online Documentation: https://docs.openstack.org/python-neutronclient/latest/
.. _Launchpad project: https://launchpad.net/python-neutronclient
.. _Blueprints: https://blueprints.launchpad.net/python-neutronclient
.. _Bugs: https://bugs.launchpad.net/python-neutronclient
-.. _Source: https://git.openstack.org/cgit/openstack/python-neutronclient
+.. _Source: https://opendev.org/openstack/python-neutronclient
.. _Developer's Guide: http://docs.openstack.org/infra/manual/developers.html
+.. _Release Notes: https://docs.openstack.org/releasenotes/python-neutronclient
diff --git a/babel.cfg b/babel.cfg
deleted file mode 100644
index 15cd6cb76..000000000
--- a/babel.cfg
+++ /dev/null
@@ -1,2 +0,0 @@
-[python: **.py]
-
diff --git a/doc/requirements.txt b/doc/requirements.txt
new file mode 100644
index 000000000..718a2395a
--- /dev/null
+++ b/doc/requirements.txt
@@ -0,0 +1,7 @@
+# The order of packages is significant, because pip processes them in the order
+# of appearance. Changing the order has an impact on the overall integration
+# process, which may cause wedges in the gate later.
+openstackdocstheme>=2.2.0 # Apache-2.0
+reno>=3.1.0 # Apache-2.0
+sphinx>=2.0.0,!=2.1.0 # BSD
+cliff>=3.4.0 # Apache-2.0
diff --git a/doc/source/cli/index.rst b/doc/source/cli/index.rst
new file mode 100644
index 000000000..4b1f4720a
--- /dev/null
+++ b/doc/source/cli/index.rst
@@ -0,0 +1,55 @@
+..
+ Licensed under the Apache License, Version 2.0 (the "License"); you may
+ not use this file except in compliance with the License. You may obtain
+ a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ License for the specific language governing permissions and limitations
+ under the License.
+
+
+ Convention for heading levels in Neutron devref:
+ ======= Heading 0 (reserved for the title in a document)
+ ------- Heading 1
+ ~~~~~~~ Heading 2
+ +++++++ Heading 3
+ ''''''' Heading 4
+ (Avoid deeper levels because they do not render well.)
+
+=========
+Using CLI
+=========
+
+There is `OpenStackClient (OSC)
+`__
+which support the Networking API
+
+OpenStackClient
+---------------
+
+OpenStackClient provides
+`the basic network commands `__
+and python-neutronclient provides :doc:`extensions `
+(aka OSC plugins) for advanced networking services.
+
+.. toctree::
+ :maxdepth: 1
+
+ Basic network commands
+ Network commands for advanced networking services
+ Mapping Guide from neutron CLI
+
+neutron CLI
+-----------
+
+.. warning::
+
+ neutron CLI is removed. Use openstack CLI instead. See `openstack CLI command list
+ `__
+ and :doc:`its extensions for advanced networking services `.
+ The command mapping from neutron CLI to openstack CLI is available
+ `here `__.
diff --git a/doc/source/cli/osc/v2/bgp-dynamic-routing.rst b/doc/source/cli/osc/v2/bgp-dynamic-routing.rst
new file mode 100644
index 000000000..c86bb45ee
--- /dev/null
+++ b/doc/source/cli/osc/v2/bgp-dynamic-routing.rst
@@ -0,0 +1,47 @@
+===================
+BGP Dynamic Routing
+===================
+
+BGP dynamic routing enables announcement of project subnet prefixes
+via BGP. Admins create BGP speakers and BGP peers. BGP peers can be
+associated with BGP speakers, thereby enabling peering sessions with
+operator infrastructure. BGP speakers can be associated with networks,
+which controls which routes are announced to peers.
+
+Network v2
+
+.. autoprogram-cliff:: openstack.neutronclient.v2
+ :command: bgp speaker create
+
+.. autoprogram-cliff:: openstack.neutronclient.v2
+ :command: bgp speaker delete
+
+.. autoprogram-cliff:: openstack.neutronclient.v2
+ :command: bgp speaker list
+
+.. autoprogram-cliff:: openstack.neutronclient.v2
+ :command: bgp speaker set
+
+.. autoprogram-cliff:: openstack.neutronclient.v2
+ :command: bgp speaker show
+
+.. autoprogram-cliff:: openstack.neutronclient.v2
+ :command: bgp speaker add network
+
+.. autoprogram-cliff:: openstack.neutronclient.v2
+ :command: bgp speaker remove network
+
+.. autoprogram-cliff:: openstack.neutronclient.v2
+ :command: bgp speaker add peer
+
+.. autoprogram-cliff:: openstack.neutronclient.v2
+ :command: bgp speaker remove peer
+
+.. autoprogram-cliff:: openstack.neutronclient.v2
+ :command: bgp speaker list advertised routes
+
+.. autoprogram-cliff:: openstack.neutronclient.v2
+ :command: bgp peer *
+
+.. autoprogram-cliff:: openstack.neutronclient.v2
+ :command: bgp dragent *
diff --git a/doc/source/cli/osc/v2/network-log.rst b/doc/source/cli/osc/v2/network-log.rst
new file mode 100644
index 000000000..df3a32729
--- /dev/null
+++ b/doc/source/cli/osc/v2/network-log.rst
@@ -0,0 +1,15 @@
+===========
+network log
+===========
+
+A **network log** is a container to group security groups or ports for logging.
+Specified resources can be logged via these event (``ALL``, ``ACCEPT`` or
+``DROP``).
+
+Network v2
+
+.. autoprogram-cliff:: openstack.neutronclient.v2
+ :command: network loggable resources list
+
+.. autoprogram-cliff:: openstack.neutronclient.v2
+ :command: network log *
diff --git a/doc/source/cli/osc/v2/networking-sfc.rst b/doc/source/cli/osc/v2/networking-sfc.rst
new file mode 100644
index 000000000..4f4242d74
--- /dev/null
+++ b/doc/source/cli/osc/v2/networking-sfc.rst
@@ -0,0 +1,39 @@
+==============
+networking sfc
+==============
+
+**Service Function Chaining** is a mechanism for overriding the basic destination based forwarding
+that is typical of IP networks. Service Function Chains consist of an ordered sequence of
+Service Functions (SFs). SFs are virtual machines (or potentially physical devices) that perform a
+network function such as firewall, content cache, packet inspection, or any other function that
+requires processing of packets in a flow from point A to point B even though the SFs are not
+literally between point A and B from a routing table perspective.
+
+Network v2
+
+.. autoprogram-cliff:: openstack.neutronclient.v2
+ :command: sfc flow classifier *
+
+.. autoprogram-cliff:: openstack.neutronclient.v2
+ :command: sfc port chain *
+
+.. autoprogram-cliff:: openstack.neutronclient.v2
+ :command: sfc port pair create
+
+.. autoprogram-cliff:: openstack.neutronclient.v2
+ :command: sfc port pair delete
+
+.. autoprogram-cliff:: openstack.neutronclient.v2
+ :command: sfc port pair list
+
+.. autoprogram-cliff:: openstack.neutronclient.v2
+ :command: sfc port pair set
+
+.. autoprogram-cliff:: openstack.neutronclient.v2
+ :command: sfc port pair show
+
+.. autoprogram-cliff:: openstack.neutronclient.v2
+ :command: sfc port pair group *
+
+.. autoprogram-cliff:: openstack.neutronclient.v2
+ :command: sfc service graph *
diff --git a/doc/source/cli/osc/v2/subnet-onboard.rst b/doc/source/cli/osc/v2/subnet-onboard.rst
new file mode 100644
index 000000000..006970372
--- /dev/null
+++ b/doc/source/cli/osc/v2/subnet-onboard.rst
@@ -0,0 +1,17 @@
+=======================
+network onboard subnets
+=======================
+
+**network onboard subnets** enables a subnet to be adopted or
+"onboarded" into an existing subnet pool. The CIDR of the subnet
+is checked for uniqueness across any applicable address scopes
+and all subnets allocated from the target subnet pool. Once
+onboarded, the subnet CIDR is added to the prefix list of the
+subnet pool and the subnet appears as though it has been allocated
+from the subnet pool. The subnet also begins participating in the
+applicable address scope if the subnet pool belongs to one.
+
+Network v2
+
+.. autoprogram-cliff:: openstack.neutronclient.v2
+ :command: network onboard subnets
diff --git a/doc/source/cli/osc/v2/vpn-endpoint-group.rst b/doc/source/cli/osc/v2/vpn-endpoint-group.rst
new file mode 100644
index 000000000..9581d8b4a
--- /dev/null
+++ b/doc/source/cli/osc/v2/vpn-endpoint-group.rst
@@ -0,0 +1,11 @@
+==================
+VPN Endpoint Group
+==================
+
+The **Endpoint Group** is used to configure multiple local and remote subnets
+in vpnservice object.
+
+Network v2
+
+.. autoprogram-cliff:: openstack.neutronclient.v2
+ :command: vpn endpoint group *
diff --git a/doc/source/cli/osc/v2/vpn-ike-policy.rst b/doc/source/cli/osc/v2/vpn-ike-policy.rst
new file mode 100644
index 000000000..3e38a5c7c
--- /dev/null
+++ b/doc/source/cli/osc/v2/vpn-ike-policy.rst
@@ -0,0 +1,12 @@
+==============
+VPN IKE Policy
+==============
+
+The **IKE Policy** is used for phases one and two negotiation of the
+VPN connection. You can specify both the authentication and encryption
+algorithms for connections.
+
+Network v2
+
+.. autoprogram-cliff:: openstack.neutronclient.v2
+ :command: vpn ike policy *
diff --git a/doc/source/cli/osc/v2/vpn-ipsec-policy.rst b/doc/source/cli/osc/v2/vpn-ipsec-policy.rst
new file mode 100644
index 000000000..c8a5f3beb
--- /dev/null
+++ b/doc/source/cli/osc/v2/vpn-ipsec-policy.rst
@@ -0,0 +1,11 @@
+================
+VPN IPsec Policy
+================
+
+The **IPsec Policy** specifies the authentication and encryption algorithms
+and encapsulation mode to use for the established VPN connection.
+
+Network v2
+
+.. autoprogram-cliff:: openstack.neutronclient.v2
+ :command: vpn ipsec policy *
diff --git a/doc/source/cli/osc/v2/vpn-ipsec-site-connection.rst b/doc/source/cli/osc/v2/vpn-ipsec-site-connection.rst
new file mode 100644
index 000000000..0244e73ee
--- /dev/null
+++ b/doc/source/cli/osc/v2/vpn-ipsec-site-connection.rst
@@ -0,0 +1,10 @@
+=========================
+VPN IPsec Site Connection
+=========================
+
+Creates a site-to-site **IPsec Site Connection** for a VPN service.
+
+Network v2
+
+.. autoprogram-cliff:: openstack.neutronclient.v2
+ :command: vpn ipsec site connection *
diff --git a/doc/source/cli/osc/v2/vpn-service.rst b/doc/source/cli/osc/v2/vpn-service.rst
new file mode 100644
index 000000000..b412555c8
--- /dev/null
+++ b/doc/source/cli/osc/v2/vpn-service.rst
@@ -0,0 +1,11 @@
+===========
+VPN Service
+===========
+
+The **VPN Service** is associated with a router. After you
+create the service, it can contain multiple VPN connections.
+
+Network v2
+
+.. autoprogram-cliff:: openstack.neutronclient.v2
+ :command: vpn service *
diff --git a/doc/source/cli/osc_plugins.rst b/doc/source/cli/osc_plugins.rst
new file mode 100644
index 000000000..0cd7e26ba
--- /dev/null
+++ b/doc/source/cli/osc_plugins.rst
@@ -0,0 +1,37 @@
+..
+ Licensed under the Apache License, Version 2.0 (the "License"); you may
+ not use this file except in compliance with the License. You may obtain
+ a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ License for the specific language governing permissions and limitations
+ under the License.
+
+
+ Convention for heading levels in Neutron devref:
+ ======= Heading 0 (reserved for the title in a document)
+ ------- Heading 1
+ ~~~~~~~ Heading 2
+ +++++++ Heading 3
+ ''''''' Heading 4
+ (Avoid deeper levels because they do not render well.)
+
+Advanced Network Commands in OpenStack Client
+=============================================
+
+The following list covers the extended commands for advanced network
+services available in ``openstack`` command.
+
+These commands can be referenced by doing ``openstack help`` and
+the detail of individual command can be referred by
+``openstack help ``.
+
+.. toctree::
+ :glob:
+ :maxdepth: 2
+
+ osc/v2/*
diff --git a/doc/source/conf.py b/doc/source/conf.py
index bc6dad770..70fd0de2f 100644
--- a/doc/source/conf.py
+++ b/doc/source/conf.py
@@ -1,17 +1,23 @@
# -*- coding: utf-8 -*-
#
-project = 'python-neutronclient'
-
# -- General configuration ---------------------------------------------
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
-extensions = ['sphinx.ext.autodoc',
- 'oslosphinx',
- 'reno.sphinxext',
+extensions = [
+ 'sphinx.ext.autodoc',
+ 'reno.sphinxext',
+ 'openstackdocstheme',
+ 'cliff.sphinxext',
]
+# openstackdocstheme options
+openstackdocs_repo_name = 'openstack/python-neutronclient'
+openstackdocs_pdf_link = True
+openstackdocs_bug_project = 'python-neutronclient'
+openstackdocs_bug_tag = 'doc'
+
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
@@ -22,7 +28,7 @@
master_doc = 'index'
# General information about the project.
-copyright = u'OpenStack Foundation'
+copyright = 'OpenStack Foundation'
# If true, '()' will be appended to :func: etc. cross-reference text.
add_function_parentheses = True
@@ -38,18 +44,30 @@
# The theme to use for HTML and HTML Help pages. Major themes that come with
# Sphinx are currently 'default' and 'sphinxdoc'.
-# html_theme = 'nature'
+html_theme = 'openstackdocs'
# Output file base name for HTML help builder.
-htmlhelp_basename = '%sdoc' % project
+htmlhelp_basename = 'neutronclientdoc'
+# -- Options for LaTeX output ------------------------------------------------
-# Grouping the document tree into LaTeX files. List of tuples
-# (source start file, target name, title, author,
-# documentclass [howto/manual]).
latex_documents = [
- ('index',
- '%s.tex' % project,
- u'%s Documentation' % project,
- u'OpenStack Foundation', 'manual'),
+ ('index', 'doc-python-neutronclient.tex',
+ 'python-neutronclient Documentation',
+ 'Neutron Contributors', 'manual'),
]
+
+# Disable usage of xindy https://bugzilla.redhat.com/show_bug.cgi?id=1643664
+latex_use_xindy = False
+
+latex_domain_indices = False
+
+latex_elements = {
+ 'makeindex': '',
+ 'printindex': '',
+ 'preamble': r'\setcounter{tocdepth}{5}',
+}
+
+# -- Options for cliff.sphinxext plugin ---------------------------------------
+
+autoprogram_cliff_application = 'openstack'
diff --git a/doc/source/usage/osc_cli_plugins.rst b/doc/source/contributor/index.rst
similarity index 78%
rename from doc/source/usage/osc_cli_plugins.rst
rename to doc/source/contributor/index.rst
index 343c3a9d3..fae3f6b82 100644
--- a/doc/source/usage/osc_cli_plugins.rst
+++ b/doc/source/contributor/index.rst
@@ -20,14 +20,15 @@
''''''' Heading 4
(Avoid deeper levels because they do not render well.)
-Using Network CLI extensions to OpenStack Client
-================================================
+=================
+Contributor Guide
+=================
-List of released CLI commands available in openstack client. These commands
-can be referenced by doing ``openstack help network``.
+In the Contributor Guide, you will find information on neutronclient's
+lower level programming details or APIs as well as the transition to
+OpenStack client.
.. toctree::
- :glob:
:maxdepth: 2
- osc/v2/*
+ transition_to_osc
diff --git a/doc/source/devref/transition_to_osc.rst b/doc/source/contributor/transition_to_osc.rst
similarity index 53%
rename from doc/source/devref/transition_to_osc.rst
rename to doc/source/contributor/transition_to_osc.rst
index 92fa92600..9bb952902 100644
--- a/doc/source/devref/transition_to_osc.rst
+++ b/doc/source/contributor/transition_to_osc.rst
@@ -27,9 +27,9 @@ This document details the transition roadmap for moving the neutron client's
OpenStack Networking API support, both the Python library and the ``neutron``
command-line interface (CLI), to the
`OpenStack Client (OSC) `_
-and the `OpenStack Python SDK `_.
+and the `OpenStack Python SDK `_.
This transition is being guided by the
-`Deprecate individual CLIs in favour of OSC `_
+`Deprecate individual CLIs in favour of OSC `_
OpenStack spec. See the `Neutron RFE `_,
`OSC neutron support etherpad `_ and
details below for the overall progress of this transition.
@@ -47,7 +47,7 @@ It will be available along side the networking support provided by the
OpenStack Python SDK.
Users of the neutron client's command extensions will need to transition to the
-`OSC plugin system `_
+`OSC plugin system `_
before the ``neutron`` CLI is removed. Such users will maintain their OSC plugin
commands within their own project and will be responsible for deprecating and
removing their ``neutron`` CLI extension.
@@ -56,27 +56,28 @@ Transition Steps
----------------
1. **Done:** OSC adds OpenStack Python SDK as a dependency. See the following
- patch set: https://review.openstack.org/#/c/138745/
+ patch set: https://review.opendev.org/#/c/138745/
2. **Done:** OSC switches its networking support for the
- `network `_
+ `network `_
command object to use the OpenStack Python SDK instead of the neutron
client's Python library. See the following patch set:
- https://review.openstack.org/#/c/253348/
+ https://review.opendev.org/#/c/253348/
3. **Done:** OSC removes its python-neutronclient dependency.
- See the following patch set: https://review.openstack.org/#/c/255545/
+ See the following patch set: https://review.opendev.org/#/c/255545/
4. **In Progress:** OpenStack Python SDK releases version 1.0 to guarantee
backwards compatibility of its networking support and OSC updates
its dependencies to include OpenStack Python SDK version 1.0 or later.
+ See the following blueprint: https://blueprints.launchpad.net/python-openstackclient/+spec/network-command-sdk-support
5. **Done:** OSC switches its networking support for the
- `ip floating `_,
- `ip floating pool `_,
- `ip fixed `_,
- `security group `_, and
- `security group rule `_
+ `ip floating `_,
+ `ip floating pool `_,
+ `ip fixed `_,
+ `security group `_, and
+ `security group rule `_
command objects to use the OpenStack Python SDK instead of the nova
client's Python library when neutron is enabled. When nova network
is enabled, then the nova client's Python library will continue to
@@ -90,100 +91,94 @@ Transition Steps
* **Done** `Security Group Rule CRUD `_
-6. **In Progress:** OSC continues enhancing its networking support.
+6. **Done** OSC continues enhancing its networking support.
At this point and when applicable, enhancements to the ``neutron``
- CLI must also be made to the ``openstack`` CLI and the OpenStack Python SDK.
- Enhancements to the networking support in the OpenStack Python SDK will be
- handled via bugs. Users of the neutron client's command extensions should
- start their transition to the OSC plugin system.
- See the developer guide section below for more information on this step.
-
-7. **Not Started:** Deprecate the ``neutron`` CLI once the criteria below have
- been meet. Running the CLI after it has been deprecated will issue a warning
- messages such as the following:
- ``DeprecationWarning: The neutron CLI is deprecated in favor of python-openstackclient.``
- In addition, only security fixes will be made to the CLI after it has been
- deprecated.
+ CLI must also be made to the ``openstack`` CLI and possibly the
+ OpenStack Python SDK. Users of the neutron client's command extensions
+ should start their transition to the OSC plugin system. See the
+ developer guide section below for more information on this step.
+
+7. **Done** Deprecate the ``neutron`` CLI. Running the CLI after
+ it has been `deprecated `_
+ will issue a warning message:
+ ``neutron CLI is deprecated and will be removed in the Z cycle. Use openstack CLI instead.``
+ In addition, no new features will be added to the CLI, though fixes to
+ the CLI will be assessed on a case by case basis.
+
+8. **Done** Remove the ``neutron`` CLI after two deprecation cycles
+ once the criteria below have been met.
* The networking support provide by the ``openstack`` CLI is functionally
equivalent to the ``neutron`` CLI and it contains sufficient functional
and unit test coverage.
- * `Neutron Stadium `_
- projects, Neutron documentation and `DevStack `_
+ * `Neutron Stadium `_
+ projects, Neutron documentation and `DevStack `_
use ``openstack`` CLI instead of ``neutron`` CLI.
* Most users of the neutron client's command extensions have transitioned
to the OSC plugin system and use the ``openstack`` CLI instead of the
``neutron`` CLI.
-8. **Not Started:** Remove the ``neutron`` CLI after two deprecation cycles.
-
Developer Guide
---------------
-The ``neutron`` CLI version 4.x, without extensions, supports over 200
-commands while the ``openstack`` CLI version 2.6.0 supports over 50
-networking commands. Of the 50 commands, some do not have all of the options
-or arguments of their ``neutron`` CLI equivalent. With this large functional
-gap, a couple critical questions for developers during this transition are "Which
-CLI do I change?" and "Where does my CLI belong?" The answer depends on the
-state of a command and the state of the overall transition. Details are
-outlined in the tables below. Early stages of the transition will require dual
-maintenance. Eventually, dual maintenance will be reduced to critical bug fixes
-only with feature requests only being made to the ``openstack`` CLI.
-
-**Which CLI do I change?**
-
-+----------------------+------------------------+-------------------------------------------------+
-| ``neutron`` Command | ``openstack`` Command | CLI to Change |
-+======================+========================+=================================================+
-| Exists | Doesn't Exist | ``neutron`` |
-+----------------------+------------------------+-------------------------------------------------+
-| Exists | In Progress | ``neutron`` and ``openstack`` |
-| | | (update related blueprint or bug) |
-+----------------------+------------------------+-------------------------------------------------+
-| Exists | Exists | ``openstack`` |
-| | | (assumes command parity resulting in |
-| | | ``neutron`` being deprecated) |
-+----------------------+------------------------+-------------------------------------------------+
-| Doesn't Exist | Doesn't Exist | ``openstack`` |
-+----------------------+------------------------+-------------------------------------------------+
+The ``neutron`` CLI tool is now removed and all new CLI changes should be done
+in the ``OpenStackClient (OSC)`` and, if needed, also in the ``OpenStack SDK``.
**Where does my CLI belong?**
+If you are developing an API in any of the `neutron repos `_
+the client-side support must be generally located in either the openstackclient or neutronclient
+repos. Whether the actual code goes into one or the other repo it depends on the nature of the
+feature, its maturity level, and/or the depth of feedback required during the development.
+
+The table below provides an idea of what goes where. Generally speaking, we consider Core anything
+that is L2 and L3 related or that it has been located in the neutron repo for quite sometime, e.g.
+QoS or Metering, or that it is available in each neutron deployment irrespective of its configuration
+(e.g. auto-allocated-topology). Any client feature that falls into this categorization will need to
+be contributed in OSC. Any other that does not, will need to go into neutronclient, assuming that
+its server-side is located in a neutron controlled repo. This is a general guideline, when in doubt,
+please reach out to a member of the neutron core team for clarifications.
+
+---------------------------+-------------------+-------------------------------------------------+
| Networking Commands | OSC Plugin | OpenStack Project for ``openstack`` Commands |
+===========================+===================+=================================================+
| Core | No | python-openstackclient |
+---------------------------+-------------------+-------------------------------------------------+
-| Dynamic Routing | Yes | python-neutronclient |
-| | | (``neutronclient/osc/v2/dynamic_routing``) |
-+---------------------------+-------------------+-------------------------------------------------+
-| FWaaS v1 | N/A | None (deprecated) |
-+---------------------------+-------------------+-------------------------------------------------+
-| FWaaS v2 | Yes | python-neutronclient |
-| | | (``neutronclient/osc/v2/fwaas``) |
-+---------------------------+-------------------+-------------------------------------------------+
-| LBaaS v1 | N/A | None (deprecated) |
-+---------------------------+-------------------+-------------------------------------------------+
-| LBaaS v2 | Yes | python-neutronclient |
-| | | (``neutronclient/osc/v2/lbaas``) |
+| Extension | Yes | python-neutronclient |
+| (i.e. neutron stadium) | | (``neutronclient/osc/v2/``) |
+---------------------------+-------------------+-------------------------------------------------+
| Other | Yes | Applicable project owning networking resource |
+---------------------------+-------------------+-------------------------------------------------+
-| VPNaaS | Yes | python-neutronclient |
-| | | (``neutronclient/osc/v2/vpnaas``) |
-+---------------------------+-------------------+-------------------------------------------------+
+
+When a repo stops being under neutron governance, its client-side counterpart will have to go through
+deprecation. Bear in mind that for grandfathered extensions like FWaaS v1, VPNaaS, and LBaaS v1, this
+is not required as the neutronclient is already deprecated on its own.
+
+**Which Python library do I change?**
+
++-------------------------------------------------+-----------------------------------------------+
+| OpenStack Project for ``openstack`` Commands | Python Library to Change |
++=================================================+===============================================+
+| python-openstackclient | openstacksdk |
++-------------------------------------------------+-----------------------------------------------+
+| Other | Applicable project owning network resource |
++-------------------------------------------------+-----------------------------------------------+
**Important:** The actual name of the command object and/or action in OSC may differ
from those used by neutron in order to follow the OSC command structure and to avoid
-name conflicts. Developers should get new command objects and actions approved by
-the OSC team before proceeding with the implementation.
-
-The "Core" group includes network resources that provide ``neutron`` project features
-(i.e. not advanced service or other features). Examples in the "Core" group include:
-network, subnet, port, etc.
+name conflicts. The `network` prefix must be used to avoid name conflicts if the
+command object name is highly likely to have an ambiguous meaning. Developers should
+get new command objects and actions approved by the OSC team before proceeding with the
+implementation.
+
+The "Core" group includes network resources that provide core ``neutron`` project
+features (e.g. network, subnet, port, etc.) and not advanced features in the
+``neutron`` project (e.g. trunk, etc.) or advanced services in separate projects
+(FWaaS, LBaaS, VPNaaS, dynamic routing, etc.).
+The "Other" group applies projects other than the core ``neutron`` project.
+Contact the neutron PTL or core team with questions on network resource classification.
When adding or updating an ``openstack`` networking command to
python-openstackclient, changes may first be required to the
@@ -192,16 +187,15 @@ properties and/or actions. Once the OpenStack Python SDK changes are merged,
the related OSC changes can be merged. The OSC changes may require an update
to the OSC openstacksdk version in the
`requirements.txt `_
-file. ``openstack`` networking commands outside python-openstackclient
-are encouraged but not required to use the OpenStack Python SDK.
+file.
When adding an ``openstack`` networking command to python-openstackclient,
you can optionally propose an
-`OSC command spec `_
+`OSC command spec `_
which documents the new command interface before proceeding with the implementation.
Users of the neutron client's command extensions must adopt the
-`OSC plugin `_
+`OSC plugin `_
system for this transition. Such users will maintain their OSC plugin within their
own project and should follow the guidance in the table above to determine
which command to change.
@@ -211,17 +205,17 @@ Developer References
* See `OSC neutron support etherpad `_
to determine if an ``openstack`` command is in progress.
-* See `OSC command list `_
+* See `OSC command list `_
to determine if an ``openstack`` command exists.
-* See `OSC command spec list `_
+* See `OSC command spec list `_
to determine if an ``openstack`` command spec exists.
-* See `OSC plugin command list `_
+* See `OSC plugin command list `_
to determine if an ``openstack`` plugin command exists.
-* See `OSC command structure `_
+* See `OSC command structure `_
to determine the current ``openstack`` command objects, plugin objects and actions.
-* See `OSC human interface guide `_
+* See `OSC human interface guide `_
for guidance on creating new OSC command interfaces.
-* See `OSC plugin `_
+* See `OSC plugin `_
for information on the OSC plugin system to be used for ``neutron`` CLI extensions.
* Create an OSC blueprint: https://blueprints.launchpad.net/python-openstackclient/
* Report an OSC bug: https://bugs.launchpad.net/python-openstackclient/+filebug
diff --git a/doc/source/devref/cli_option_guideline.rst b/doc/source/devref/cli_option_guideline.rst
deleted file mode 100644
index 49a840525..000000000
--- a/doc/source/devref/cli_option_guideline.rst
+++ /dev/null
@@ -1,263 +0,0 @@
-..
- Licensed under the Apache License, Version 2.0 (the "License"); you may
- not use this file except in compliance with the License. You may obtain
- a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- License for the specific language governing permissions and limitations
- under the License.
-
-
- Convention for heading levels in Neutron devref:
- ======= Heading 0 (reserved for the title in a document)
- ------- Heading 1
- ~~~~~~~ Heading 2
- +++++++ Heading 3
- ''''''' Heading 4
- (Avoid deeper levels because they do not render well.)
-
-CLI Option Guideline
-====================
-
-This document describes the conventions of neutron CLI options.
-
-General conventions
--------------------
-
-#. Option names should be delimited by a hyphen instead of a underscore.
- This is the common guidelines across all OpenStack CLIs.
-
- * Good: ``--ip-version``
- * Not Good: ``--ip_version``
-
-#. Use at least one required option for ``*-create`` command. If all options
- are optional, we typically use ``name`` field as a required option.
-
-#. When you need to specify an ID of a resource, it is better to provide
- another way to specify the resource like ``name`` or other reasonable field.
-
-#. If an attribute name in API is ``foo_id``, the corresponding option
- should be ``--foo`` instead of ``--foo-id``.
-
- * It is because we usually support ID and ``name`` to specify a resource.
-
-#. Do not use ``nargs='?'`` without a special reason.
-
- * The behavior of ``nargs='?'`` option for python argparse is
- bit tricky and may lead to unexpected option parsing different
- from the help message. The detail is described in the
- :ref:`Background section ` below.
-
-#. (option) Avoid using positional options as much as possible.
-
- * Positional arguments should be limited to attributes which will
- be required in the long future.
-
-#. We honor existing options and should keep compatibilities when adding or
- changing options.
-
-Options for boolean value
--------------------------
-
-Use the form of ``--option-name {True|False}``.
-
-* For a new option, it is recommended.
-* It is suggested to use ``common.utils.add_boolean_argument`` in an
- implementation. It allows ``true``/``false`` in addition to ``True``/``False``.
-* For existing options, migration to the recommended form is not necessarily
- required. All backward-compatibility should be kept without reasonable
- reasons.
-
-Options for dict value
-----------------------
-
-Some API attributes take a dictionary.
-
-``--foo key1=val1,key2=val2`` is usually used.
-
-This means ``{"key1": "val1", "key2": "val2"}`` is passed in the API layer.
-
-Examples:
-
-* ``--host-route destination=CIDR,nexthop=IP_ADDR`` for a subnet
-* ``--fixed-ip subnet_id=SUBNET,ip_address=IP_ADDR`` for a port.
-
-Options for list value
-----------------------
-
-Some attributes take a list.
-
-In this case, we usually use:
-
-* Define an option per element (Use a singular form as an option name)
-* Allow to specify the option multiple times
-
-For Example, **port-create** has ``--security-group`` option.
-``--security-group SG1 --security-group SG2`` generates
-``{"security_groups: ["SG1", "SG2"]}`` in the API layer.
-
-This convention applies to a case of a list of dict.
-``--allocation-pool`` and ``--host-route`` for a subnet are examples.
-
-Compatibility with extra arguments
-----------------------------------
-
-*extra arguments* supports various types of option specifications.
-At least the following patterns needs to be considered when defining
-a new option. For more detail, see :ref:`cli_extra_arguments`.
-
-* Normal options with value
-* Boolean options : ``--foo True``, ``--bar=False``
-* List options : ``--bars list=true val1 val2``, ``--bars val1 val2``
-* Dict options : ``--foo type=dict key1=va1,key2=val2``
-* List of Dict options : ``--bars list=true type=dict key1=val1,key2=val2 key3=val3,key4=val4``
-* ``action=clear``
-
-For normal options with value, there are four patterns to specify an option
-as extra arguments.
-
-* ``--admin-state-up True`` (a space between option name and value)
-* ``--admin-state-up=True`` (= between option name and value)
-* ``--admin_state_up True`` (underscore is used as delimiter)
-* ``--admin_state_up=True`` (underscore is used as delimiter)
-
-.. _background:
-
-Background
-----------
-
-There are a lot of opinions on which form of options are better or not.
-This section tries to capture the reason of the current choice.
-
-Use at least one required option
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-As a convention, **neutron** CLI requires one required argument.
-
-If all options are optional in the API level and we have ``name`` field,
-we usually use ``name`` as a required parameter.
-Requiring at least one argument has the following benefits:
-
-* If we run ``neutron *-create`` without a required argument, we will have a
- brief help message without detail option help. It is convenient.
-* We can avoid miss operation by just hitting ``neutron *-create``.
- Requiring at least one parameter is a good balance.
-
-Even though we can change this convention to allow to create a resource
-without ``name`` field, it will bring confusions to existing users.
-
-There may be opinion that it is inconsistent with API level requirement
-or Horizon behavior, but even if neutron CLI requires ``name`` field
-there is no bad impact on regular users. Considering possible confusion
-if we change it, it looks better to keep it as-is.
-
-Options for Boolean value
-~~~~~~~~~~~~~~~~~~~~~~~~~
-
-* ``--enable-foo``/``--disable-foo`` or similar patterns (including
- ``--admin-state-down``) is not suggested because we need two exclusive
- options for one attribute in REST API. It is meaningless.
-
-* It is not recommended to have an option only to specify non-default value.
- For example, we have ``--shared`` or ``--admin-state-down`` options for
- net-create. This form only works for ``*-create`` and does not work for
- ``*-update``. It leads to having different options for ``*-create`` and
- ``*-update``.
-
-* A flag option like ``--enable-dhcp`` (without value) also has a problem when
- considering the compatibility with *extra argument*. We can specify
- ``-enable-dhcp True/False`` or ``--enable-dhcp=True/False`` in the *extra
- argument* mechanism. If we introduce ``--enable-dhcp`` (without value),
- the form of ``-enable-dhcp True/False`` cannot be used now.
- This is another reason we don't use a flag style option for a boolean parameter.
-
-.. _background-nargs:
-
-Avoid using nargs in positional or optional arguments
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-The behavior of ``nargs='?'`` option for python argparse is bit tricky.
-When we use ``nargs='?'`` and if the order of command-line options is
-changed then the command-line parser may fail to parse the arguments
-correctly. Two examples of such failures are provided below.
-
-Example 1:
-This example shows how the actual behavior can differ from the provided
-help message. In the below block, help message at ``[5]`` says ``--bb CC``
-is a valid format but the argument parsing for the same format fails at ``[7]``.
-
-.. code-block:: console
-
- In [1]: import argparse
- In [2]: parser = argparse.ArgumentParser()
- In [3]: parser.add_argument('--bb', nargs='?')
- In [4]: parser.add_argument('cc')
-
- In [5]: parser.print_help()
- usage: ipython [-h] [--bb [BB]] cc
-
- positional arguments:
- cc
-
- optional arguments:
- -h, --help show this help message and exit
- --bb [BB]
-
- In [6]: parser.parse_args('--bb 1 X'.split())
- Out[6]: Namespace(bb='1', cc='X')
-
- In [7]: parser.parse_args('--bb X'.split())
- usage: ipython [-h] [--bb [BB]] cc
- ipython: error: too few arguments
- An exception has occurred, use %tb to see the full traceback.
-
- SystemExit: 2
-
-
-Example 2:
-This example shows how fragile ``nargs='?'`` can be when user specifies
-options in different order from the help message.
-
-.. code-block:: console
-
- In [1]: import argparse
- In [2]: parser = argparse.ArgumentParser()
- In [3]: parser.add_argument('--a', help='option a')
- In [4]: parser.add_argument('--b', help='option b')
- In [5]: parser.add_argument('x', help='positional arg X')
- In [6]: parser.add_argument('y', nargs='?', help='positional arg Y')
- In [7]: parser.print_help()
- usage: ipython [-h] [--a A] [--b B] x [y]
-
- positional arguments:
- x positional arg X
- y positional arg Y
-
- optional arguments:
- -h, --help show this help message and exit
- --a A option a
- --b B option b
-
- In [8]: parser.parse_args('--a 1 --b 2 X Y'.split())
- Out[8]: Namespace(a='1', b='2', x='X', y='Y')
-
- In [9]: parser.parse_args('X Y --a 1 --b 2'.split())
- Out[9]: Namespace(a='1', b='2', x='X', y='Y')
-
- In [10]: parser.parse_args('X --a 1 --b 2 Y'.split())
- usage: ipython [-h] [--a A] [--b B] x [y]
- ipython: error: unrecognized arguments: Y
- An exception has occurred, use %tb to see the full traceback.
-
- SystemExit: 2
-
- To exit: use 'exit', 'quit', or Ctrl-D.
- To exit: use 'exit', 'quit', or Ctrl-D.
-
-Note: Most CLI users don't care about the order of the command-line
-options. Hence, such fragile behavior should be avoided.
-
diff --git a/doc/source/devref/client_command_extensions.rst b/doc/source/devref/client_command_extensions.rst
deleted file mode 100644
index 4b74cdf77..000000000
--- a/doc/source/devref/client_command_extensions.rst
+++ /dev/null
@@ -1,97 +0,0 @@
-..
- Licensed under the Apache License, Version 2.0 (the "License"); you may
- not use this file except in compliance with the License. You may obtain
- a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- License for the specific language governing permissions and limitations
- under the License.
-
-
- Convention for heading levels in Neutron devref:
- ======= Heading 0 (reserved for the title in a document)
- ------- Heading 1
- ~~~~~~~ Heading 2
- +++++++ Heading 3
- ''''''' Heading 4
- (Avoid deeper levels because they do not render well.)
-
-Client command extension support
-=================================
-
-The client command extension adds support for extending the neutron client while
-considering ease of creation.
-Extensions strongly conform to preexisting neutron commands (/neutron/v2_0/).
-
-A sample extension can be seen at:
-neutronclient/neutron/v2_0/contrib/_fox_sockets.py
-
-Minimum requirements from an extension
---------------------------------------
-
-* NeutronClientExtension subclasses must have a shell_command class variable
- if the command is to be available to the CLI (shell.py)
-
- Example: neutronclient.neutron.v2_0.contrib._fox_sockets.FoxInSocketsList
-
-Minimum requirements to use canonical neutron CRUD commands framework
-----------------------------------------------------------------------
-
-Neutron commands are cliff commands, commands in extension can use their
-own way to finish their tasks. But if they want to make use of the canonical
-neutron CRUD commands framework, the extension should:
-
-* have a class that subclasses NeutronClientExtension to provide the
- requisite resource name, version support, and resource collection and
- object paths for a resource the commands will process.
-
- Example: neutronclient.neutron.v2_0.contrib._fox_sockets.FoxInSocket
-
-* have a class that subclasses from the ClientExtensionList to provide
- resource object list function. This is because most commands
- need the list function to get object ID via
- neutronclient.neutron.v2_0.__init__.find_resource_by_id.
-
- Example: neutronclient.neutron.v2_0.contrib._fox_sockets.FoxInSocketsList
-
-* if needed, subclass ClientExtensionUpdate to implement update of the resource
- object.
-
- Example: neutronclient.neutron.v2_0.contrib._fox_sockets.FoxInSocketsUpdate
-
-* if needed, subclass ClientExtensionDelete to implement deletion of the resource
- object.
-
- Example: neutronclient.neutron.v2_0.contrib._fox_sockets.FoxInSocketsDelete
-
-* if needed, subclass ClientExtensionShow to get the detail of the resource
- object.
-
- Example: neutronclient.neutron.v2_0.contrib._fox_sockets.FoxInSocketsShow
-
-Precedence of command loading
-------------------------------
-
-* hard coded commands are loaded first
-* external commands (installed in the environment) are loaded then
-
-Commands that have the same name will be overwritten by commands that are
-loaded later. To change the execution of a command for your particular
-extension you only need to override the execute method.
-
-Currently this extension support is limited to top-level resources.
-Parent/child relationships may be added if desired.
-
-neutronclient.extension entry_point
------------------------------------
-
-To activate the commands in a specific extension module, add an entry in
-setup.cfg under neutronclient.extension. For example::
-
- [entry_points]
- neutronclient.extension =
- fox_sockets = neutronclient.neutron.v2_0.contrib._fox_sockets
diff --git a/doc/source/index.rst b/doc/source/index.rst
index be4c77057..c36d482ed 100644
--- a/doc/source/index.rst
+++ b/doc/source/index.rst
@@ -19,37 +19,44 @@
''''''' Heading 4
(Avoid deeper levels because they do not render well.)
-Python bindings to the OpenStack Networking API
-===============================================
+==================================
+python-neutronclient documentation
+==================================
-This is a client for OpenStack Networking API. There is a :doc:`Python API
-` (the neutronclient module), and a :doc:`command-line script
-` (installed as **neutron**). Each implements the entire OpenStack
-Networking API.
+This is a client for OpenStack Networking API. It provides
+:doc:`Python API bindings ` (the neutronclient module).
-Using neutronclient
--------------------
+There is
+`OpenStack Client (OSC) `__.
+CLI which support the Networking API.
+
+User Documentation
+------------------
.. toctree::
:maxdepth: 2
- usage/cli
- usage/library
- usage/osc_cli_plugins
+ cli/index
+ reference/index
-Developer Guide
----------------
+Contributor Guide
+-----------------
-In the Developer Guide, you will find information on Neutron’s client
-lower level programming details or APIs as well as the transition to
-OpenStack client.
+In the :doc:`Contributor Guide `, you will find
+information on neutronclient's lower level programming details or APIs
+as well as the transition to OpenStack client.
.. toctree::
:maxdepth: 2
- devref/client_command_extensions
- devref/cli_option_guideline
- devref/transition_to_osc
+ contributor/index
+
+.. note::
+
+ neutron CLI has been deprecated from Ocata release.
+ We do not add, change and drop any existing commands any more.
+ We only accept changes on OSC plugin, neutronclient python bindings
+ and bug fixes on the deprecated CLI (``neutron`` command).
History
-------
diff --git a/doc/source/reference/index.rst b/doc/source/reference/index.rst
new file mode 100644
index 000000000..5678d6578
--- /dev/null
+++ b/doc/source/reference/index.rst
@@ -0,0 +1,95 @@
+..
+ Licensed under the Apache License, Version 2.0 (the "License"); you may
+ not use this file except in compliance with the License. You may obtain
+ a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ License for the specific language governing permissions and limitations
+ under the License.
+
+
+ Convention for heading levels in Neutron devref:
+ ======= Heading 0 (reserved for the title in a document)
+ ------- Heading 1
+ ~~~~~~~ Heading 2
+ +++++++ Heading 3
+ ''''''' Heading 4
+ (Avoid deeper levels because they do not render well.)
+
+neutronclient Python API
+========================
+
+Basic Usage
+-----------
+
+First create a client instance using a keystoneauth Session. For more
+information on this keystoneauth API, see `Using Sessions`_.
+
+.. _Using Sessions: https://docs.openstack.org/keystoneauth/latest/using-sessions.html
+
+.. code-block:: python
+
+ from keystoneauth1 import identity
+ from keystoneauth1 import session
+ from neutronclient.v2_0 import client
+ username='username'
+ password='password'
+ project_name='demo'
+ project_domain_id='default'
+ user_domain_id='default'
+ auth_url='http://auth.example.com:5000/v3'
+ auth = identity.Password(auth_url=auth_url,
+ username=username,
+ password=password,
+ project_name=project_name,
+ project_domain_id=project_domain_id,
+ user_domain_id=user_domain_id)
+ sess = session.Session(auth=auth)
+ neutron = client.Client(session=sess)
+
+If you are using Identity v2.0 API (DEPRECATED), create an auth plugin using
+the appropriate parameters and `keystoneauth1.identity` will handle Identity
+API version discovery. Then you can create a Session and a Neutronclient just
+like the previous example.
+
+.. code-block:: python
+
+ auth = identity.Password(auth_url=auth_url,
+ username=username,
+ password=password,
+ project_name=project_name)
+ # create a Session and a Neutronclient
+
+Now you can call various methods on the client instance.
+
+.. code-block:: python
+
+ network = {'name': 'mynetwork', 'admin_state_up': True}
+ neutron.create_network({'network':network})
+ networks = neutron.list_networks(name='mynetwork')
+ print networks
+ network_id = networks['networks'][0]['id']
+ neutron.delete_network(network_id)
+
+Alternatively, you can create a client instance using an auth token
+and a service endpoint URL directly.
+
+.. code-block:: python
+
+ from neutronclient.v2_0 import client
+ neutron = client.Client(endpoint_url='http://192.168.206.130:9696/',
+ token='d3f9226f27774f338019aa2611112ef6')
+
+You can get ``X-Openstack-Request-Id`` as ``request_ids`` from the result.
+
+.. code-block:: python
+
+ network = {'name': 'mynetwork', 'admin_state_up': True}
+ neutron.create_network({'network':network})
+ networks = neutron.list_networks(name='mynetwork')
+ print networks.request_ids
+ # -> ['req-978a0160-7ab0-44f0-8a93-08e9a4e785fa']
diff --git a/doc/source/usage/cli.rst b/doc/source/usage/cli.rst
deleted file mode 100644
index 93a5e6675..000000000
--- a/doc/source/usage/cli.rst
+++ /dev/null
@@ -1,390 +0,0 @@
-..
- Licensed under the Apache License, Version 2.0 (the "License"); you may
- not use this file except in compliance with the License. You may obtain
- a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- License for the specific language governing permissions and limitations
- under the License.
-
-
- Convention for heading levels in Neutron devref:
- ======= Heading 0 (reserved for the title in a document)
- ------- Heading 1
- ~~~~~~~ Heading 2
- +++++++ Heading 3
- ''''''' Heading 4
- (Avoid deeper levels because they do not render well.)
-
-Command-line Interface
-======================
-
-The **neutron** shell utility interacts with OpenStack Networking API from the
-command-line. It supports the entire features of OpenStack Networking API.
-
-Basic Usage
------------
-
-In order to use the CLI, you must provide your OpenStack username, password,
-tenant, and auth endpoint. Use the corresponding configuration options
-(``--os-username``, ``--os-password``, ``--os-tenant-name``, and
-``--os-auth-url``), but it is easier to set them in environment variables.
-
-.. code-block:: shell
-
- export OS_USERNAME=user
- export OS_PASSWORD=pass
- export OS_TENANT_NAME=tenant
- export OS_AUTH_URL=http://auth.example.com:5000/v2.0
-
-Once you've configured your authentication parameters, you can run **neutron**
-commands. All commands take the form of:
-
-.. code-block:: none
-
- neutron [arguments...]
-
-Run **neutron help** to get a full list of all possible commands, and run
-**neutron help ** to get detailed help for that command.
-
-Using with os-client-config
-~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-`os-client-config `_
-provides more convenient way to manage a collection of client configurations
-and you can easily switch multiple OpenStack-based configurations.
-
-To use os-client-config, you first need to prepare
-``~/.config/openstack/clouds.yaml`` like the following.
-
-.. code-block:: yaml
-
- clouds:
- devstack:
- auth:
- auth_url: http://auth.example.com:5000
- password: your-secret
- project_domain_id: default
- project_name: demo
- user_domain_id: default
- username: demo
- identity_api_version: '3'
- region_name: RegionOne
- devstack-admin:
- auth:
- auth_url: http://auth.example.com:35357
- password: another-secret
- project_domain_id: default
- project_name: admin
- user_domain_id: default
- username: admin
- identity_api_version: '3'
- region_name: RegionOne
-
-Then, you need to specify a configuration name defined in the above clouds.yaml.
-
-.. code-block:: shell
-
- export OS_CLOUD=devstack
-
-For more detail information, see the
-`os-client-config `_
-documentation.
-
-Using with keystone token
-~~~~~~~~~~~~~~~~~~~~~~~~~
-
-The command-line tool will attempt to re-authenticate 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.
-
-.. code-block:: shell
-
- export OS_URL=http://neutron.example.org:9696/
- export OS_TOKEN=3bcc3d3a03f44e3d8377f9247b0ad155
-
-Using noauth mode
-~~~~~~~~~~~~~~~~~
-
-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.
-
-.. code-block:: shell
-
- export OS_AUTH_STRATEGY=noauth
-
-Display options
----------------
-
-Filtering
-~~~~~~~~~
-
-Neutron API supports filtering in the listing operation.
-**neutron** CLI supports this feature too.
-
-To specify a filter in ``*-list`` command, you need to pass a pair of an
-attribute name and an expected value with the format of ``-- ``.
-The example below retrieves ports owned by compute instances.
-
-.. code-block:: console
-
- $ neutron port-list --device_owner network:dhcp
- +--------------------------------------+------+-------------------+-------------------------------------------------------------------------------------------------------------+
- | id | name | mac_address | fixed_ips |
- +--------------------------------------+------+-------------------+-------------------------------------------------------------------------------------------------------------+
- | 8953d683-29ad-4be3-b73f-060727c7849b | | fa:16:3e:4b:9e:0a | {"subnet_id": "6b832dfe-f271-443c-abad-629961414a73", "ip_address": "10.0.0.2"} |
- | | | | {"subnet_id": "cdcc616b-0cff-482f-96f5-06fc63d21247", "ip_address": "fd12:877c:1d66:0:f816:3eff:fe4b:9e0a"} |
- +--------------------------------------+------+-------------------+-------------------------------------------------------------------------------------------------------------+
-
-You can also specify multiple filters.
-The example below retrieves security group rules applied to IPv4 traffic
-which belongs to a security group bfa493f9-2b03-46d2-8399-b9b038a53bc1.
-
-.. code-block:: console
-
- $ neutron security-group-rule-list --security-group-id bfa493f9-2b03-46d2-8399-b9b038a53bc1 --ethertype IPv4
- +--------------------------------------+----------------+-----------+-----------+---------------+-----------------+
- | id | security_group | direction | ethertype | protocol/port | remote |
- +--------------------------------------+----------------+-----------+-----------+---------------+-----------------+
- | 65489805-0400-4bce-9bd9-16a81952263c | default | egress | IPv4 | any | any |
- | 9429f336-4947-4643-bbd9-24528cc65648 | default | ingress | IPv4 | any | default (group) |
- +--------------------------------------+----------------+-----------+-----------+---------------+-----------------+
-
-.. note::
-
- Looking up UUID from name is not supported when specifying a filter.
- You need to use UUID to specify a specific resource.
-
-.. note::
-
- Filtering for dictionary or list attributes is not supported.
-
-Changing displayed columns
-~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-If you want displayed columns in a list operation, ``-c`` option can be used.
-``-c`` can be specified multiple times and the column order will be same as
-the order of ``-c`` options.
-
-.. code-block:: console
-
- $ neutron port-list -c id -c device_owner -c fixed_ips
- +--------------------------------------+--------------------------+-------------------------------------------------------------------------------------------------------------+
- | id | device_owner | fixed_ips |
- +--------------------------------------+--------------------------+-------------------------------------------------------------------------------------------------------------+
- | 41ca1b9b-4bbd-4aa8-bcaa-31d3d5704205 | network:router_interface | {"subnet_id": "6b832dfe-f271-443c-abad-629961414a73", "ip_address": "10.0.0.1"} |
- | 8953d683-29ad-4be3-b73f-060727c7849b | network:dhcp | {"subnet_id": "6b832dfe-f271-443c-abad-629961414a73", "ip_address": "10.0.0.2"} |
- | | | {"subnet_id": "cdcc616b-0cff-482f-96f5-06fc63d21247", "ip_address": "fd12:877c:1d66:0:f816:3eff:fe4b:9e0a"} |
- | a9da29f8-4504-4526-a5ce-cd3624fbd173 | neutron:LOADBALANCER | {"subnet_id": "6b832dfe-f271-443c-abad-629961414a73", "ip_address": "10.0.0.3"} |
- | | | {"subnet_id": "cdcc616b-0cff-482f-96f5-06fc63d21247", "ip_address": "fd12:877c:1d66:0:f816:3eff:feb1:ab71"} |
- | d6a1ff96-0a99-416f-a4d6-65d9614cf64e | compute:nova | {"subnet_id": "6b832dfe-f271-443c-abad-629961414a73", "ip_address": "10.0.0.4"} |
- | | | {"subnet_id": "cdcc616b-0cff-482f-96f5-06fc63d21247", "ip_address": "fd12:877c:1d66:0:f816:3eff:fe2c:348e"} |
- | f4789225-26d0-409f-8047-82d2c7a87a95 | network:router_interface | {"subnet_id": "cdcc616b-0cff-482f-96f5-06fc63d21247", "ip_address": "fd12:877c:1d66::1"} |
- +--------------------------------------+--------------------------+-------------------------------------------------------------------------------------------------------------+
-
-.. _cli_extra_arguments:
-
-Extra arguments for create/update operation
--------------------------------------------
-
-**neutron** CLI has a mechanism called the *extra arguments* for ``*-create``
-and ``*-update`` commands. It allows users to specify a set of *unknown
-options* which are not defined as options and not shown in the help text.
-**Unknown options MUST be placed at the end of the command line.**
-*unknown options* will be directly passed to the API layer. By this mechanism,
-you can pass an attribute which is not defined in the upstream **neutron**
-CLI. For example, when you are developing a new feature which add a new
-attribute to an existing resource, it is useful because we can test your
-feature without changing the existing neutron CLI.
-
-For example, if you run the following command::
-
- neutron resource-update --key1 value1 --key2 value2
-
-where ``resource`` is some resource name and ``--key1`` and ``--key2`` are
-unknown options, then the following JSON will be sent to the neutron API::
-
- PUT /v2.0/resources/
-
- {
- "resource": {
- "key2": "value2",
- "key1": "value1"
- }
- }
-
-Key interpretation
-~~~~~~~~~~~~~~~~~~
-
-This means an option name (``--key1`` in this case) must be one of valid
-resources of a corresponding resource. An option name ``--foo_bar`` is
-recognized as an attribute name ``foo_bar``. ``--foo-bar`` is also interpreted
-as an attribute name ``foo_bar``.
-
-Value interpretation
-~~~~~~~~~~~~~~~~~~~~
-
-By default, if the number of values is 1, the option value is interpreted as a
-string and is passed to the API layer as specified in a command-line.
-
-If the number of values is greater than 1, the option value is interpreted as a
-list and the result in the API layer will be same as when specifying a list as
-described below.
-
- neutron resource-update --key1 val1 val2 val3 --key2 val4
-
-In the above example, a value of ``key1`` is interpreted as
-``["val1", "val2", "val3"]`` and a value of ``key2`` is interpreted
-as ``val4``.
-
-The extra argument mechanism supports more complex value like a list or a dict.
-
-Specify a list value
-++++++++++++++++++++
-
-A command-line::
-
- neutron resource-update --key list=true val1 val2 val3
-
-will send the following in the API layer::
-
- {
- "key": [
- "val1",
- "val2",
- "val3"
- ]
- }
-
-.. note::
-
- If you want to specify a list value, it is recommended to specify
- ``list=true``. When ``list=true`` is specified, specified values are
- interpreted as a list even regardless of the number of values.
-
- If ``list=true`` is not specified, specified values are interpreted
- depends on the number of values how. If the number of values is more than 2,
- the specified values are interpreted as a list. If 1, the value
- is interpreted as a string.
-
-Specify a dict value
-++++++++++++++++++++
-
-A command-line::
-
- neutron resource-update --key type=dict key1=val1,key2=val2,key3=val3
-
-will send the following in the API layer::
-
- {
- "key": {
- "key1": "val1",
- "key2": "val2",
- "key3": "val3"
- }
- }
-
-.. note::
-
- ``type=bool True/False`` and ``type=int 10`` are also supported.
-
-Specify a list of dicts
-+++++++++++++++++++++++
-
-A command-line::
-
- neutron resource-update --key type=dict list=true key1=val1 key2=val2 key3=val3
-
-will send the following in the API layer::
-
- {
- "key": [
- {"key1": "val1"},
- {"key2": "val2"},
- {"key3": "val3"}
- ]
- }
-
-Passing None as a value
-~~~~~~~~~~~~~~~~~~~~~~~
-
-There is a case where we would like to pass ``None`` (``null`` in JSON)
-in the API layer. To do this::
-
- neutron resource-update --key action=clear
-
-The following body will be in the API layer::
-
- {"key": null}
-
-.. note::
-
- If ``action=clear`` is specified, ``list=true`` or ``type=dict`` is ignored.
- It means when ``action=clear`` is specified ``None`` is always sent.
-
-Debugging
----------
-
-Display API-level communication
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-``-v`` (or ``--verbose``, ``--debug``) option displays a detail interaction
-with your neutron server. It is useful to debug what happens in the API level.
-
-Here is an sample output of ``net-show`` command.
-
-The first line show what parameters are recognized by neutronclient.
-It is sometimes useful to check if command-line parameters you specify are recognized properly.
-
-.. code-block:: console
-
- $ neutron -v net-show mynetwork
- DEBUG: neutronclient.neutron.v2_0.network.ShowNetwork get_data(Namespace(columns=[], fields=[], formatter='table', id=u'mynetwork', max_width=0, noindent=False, prefix='', request_format='json', show_details=False, variables=[]))
-
-Next, neutronclient sends an authentication request to keystone to get a token
-which is used in further operations.
-
-.. code-block:: console
-
- DEBUG: keystoneauth.session REQ: curl -g -i -X GET http://172.16.18.47:5000 -H "Accept: application/json" -H "User-Agent: keystoneauth1"
- DEBUG: keystoneauth.session RESP: [300] Content-Length: 593 Vary: X-Auth-Token Keep-Alive: timeout=5, max=100 Server: Apache/2.4.7 (Ubuntu) Connection: Keep-Alive Date: Fri, 27 Nov 2015 20:10:54 GMT Content-Type: application/json
- RESP BODY: {"versions": {"values": [{"status": "stable", "updated": "2015-03-30T00:00:00Z", "media-types": [{"base": "application/json", "type": "application/vnd.openstack.identity-v3+json"}], "id": "v3.4", "links": [{"href": "http://172.16.18.47:5000/v3/", "rel": "self"}]}, {"status": "stable", "updated": "2014-04-17T00:00:00Z", "media-types": [{"base": "application/json", "type": "application/vnd.openstack.identity-v2.0+json"}], "id": "v2.0", "links": [{"href": "http://172.16.18.47:5000/v2.0/", "rel": "self"}, {"href": "http://docs.openstack.org/", "type": "text/html", "rel": "describedby"}]}]}}
-
- DEBUG: keystoneauth.identity.v3.base Making authentication request to http://172.16.18.47:5000/v3/auth/tokens
-
-Neutronclient looks up a network ID corresponding to a given network name.
-
-.. code-block:: console
-
- DEBUG: keystoneauth.session REQ: curl -g -i -X GET http://172.16.18.47:9696/v2.0/networks.json?fields=id&name=mynetwork -H "User-Agent: python-neutronclient" -H "Accept: application/json" -H "X-Auth-Token: {SHA1}39300e7398d53a02afd183f13cb6afaef95ec4e5"
- DEBUG: keystoneauth.session RESP: [200] Date: Fri, 27 Nov 2015 20:10:55 GMT Connection: keep-alive Content-Type: application/json; charset=UTF-8 Content-Length: 62 X-Openstack-Request-Id: req-ccebf6e4-4f52-4874-a1ab-5499abcba378
- RESP BODY: {"networks": [{"id": "3698d3c7-d581-443e-bf86-53c4e3a738f7"}]}
-
-Finally, neutronclient retrieves a detail of a given network using the resolved ID.
-
-.. code-block:: console
-
- DEBUG: keystoneauth.session REQ: curl -g -i -X GET http://172.16.18.47:9696/v2.0/networks/3698d3c7-d581-443e-bf86-53c4e3a738f7.json -H "User-Agent: python-neutronclient" -H "Accept: application/json" -H "X-Auth-Token: {SHA1}39300e7398d53a02afd183f13cb6afaef95ec4e5"
- DEBUG: keystoneauth.session RESP: [200] Date: Fri, 27 Nov 2015 20:10:55 GMT Connection: keep-alive Content-Type: application/json; charset=UTF-8 Content-Length: 272 X-Openstack-Request-Id: req-261add00-d6d3-4ea7-becc-105b60ac7369
- RESP BODY: {"network": {"status": "ACTIVE", "subnets": [], "name": "mynetwork", "admin_state_up": true, "tenant_id": "8f0ebf767043483a987736c8c684178d", "mtu": 0, "router:external": false, "shared": false, "port_security_enabled": true, "id": "3698d3c7-d581-443e-bf86-53c4e3a738f7"}}
-
- +-----------------------+--------------------------------------+
- | Field | Value |
- +-----------------------+--------------------------------------+
- | admin_state_up | True |
- | id | 3698d3c7-d581-443e-bf86-53c4e3a738f7 |
- | mtu | 0 |
- | name | mynetwork |
- | port_security_enabled | True |
- | router:external | False |
- | shared | False |
- | status | ACTIVE |
- | subnets | |
- | tenant_id | 8f0ebf767043483a987736c8c684178d |
- +-----------------------+--------------------------------------+
diff --git a/doc/source/usage/library.rst b/doc/source/usage/library.rst
deleted file mode 100644
index 481a08b45..000000000
--- a/doc/source/usage/library.rst
+++ /dev/null
@@ -1,71 +0,0 @@
-..
- Licensed under the Apache License, Version 2.0 (the "License"); you may
- not use this file except in compliance with the License. You may obtain
- a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- License for the specific language governing permissions and limitations
- under the License.
-
-
- Convention for heading levels in Neutron devref:
- ======= Heading 0 (reserved for the title in a document)
- ------- Heading 1
- ~~~~~~~ Heading 2
- +++++++ Heading 3
- ''''''' Heading 4
- (Avoid deeper levels because they do not render well.)
-
-neutronclient Python API
-========================
-
-Basic Usage
------------
-
-First create a client instance.
-
-.. code-block:: python
-
- >>> from neutronclient.v2_0 import client
- >>> username='adminUser'
- >>> password='secretword'
- >>> project_name='openstackDemo'
- >>> auth_url='http://192.168.206.130:5000/v2.0'
- >>> neutron = client.Client(username=username,
- ... password=password,
- ... project_name=project_name,
- ... auth_url=auth_url)
-
-Now you can call various methods on the client instance.
-
-.. code-block:: python
-
- >>> network = {'name': 'mynetwork', 'admin_state_up': True}
- >>> neutron.create_network({'network':network})
- >>> networks = neutron.list_networks(name='mynetwork')
- >>> print networks
- >>> network_id = networks['networks'][0]['id']
- >>> neutron.delete_network(network_id)
-
-Alternatively, you can create a client instance using an auth token
-and a service endpoint URL directly.
-
-.. code-block:: python
-
- >>> from neutronclient.v2_0 import client
- >>> neutron = client.Client(endpoint_url='http://192.168.206.130:9696/',
- ... token='d3f9226f27774f338019aa2611112ef6')
-
-You can get ``X-Openstack-Request-Id`` as ``request_ids`` from the result.
-
-.. code-block:: python
-
- >>> network = {'name': 'mynetwork', 'admin_state_up': True}
- >>> neutron.create_network({'network':network})
- >>> networks = neutron.list_networks(name='mynetwork')
- >>> print networks.request_ids
- ['req-978a0160-7ab0-44f0-8a93-08e9a4e785fa']
diff --git a/doc/source/usage/osc/v2/network-trunk.rst b/doc/source/usage/osc/v2/network-trunk.rst
deleted file mode 100644
index 5a79310a4..000000000
--- a/doc/source/usage/osc/v2/network-trunk.rst
+++ /dev/null
@@ -1,171 +0,0 @@
-=============
-network trunk
-=============
-
-A **network trunk** is a container to group logical ports from different
-networks and provide a single trunked vNIC for servers. It consists of
-one parent port which is a regular VIF and multiple subports which allow
-the server to connect to more networks.
-
-Network v2
-
-network subport list
---------------------
-
-List all subports for a given network trunk
-
-.. program:: network subport list
-.. code:: bash
-
- os network subport list
- --trunk
-
-.. option:: --trunk
-
- List subports belonging to this trunk (name or ID) (required)
-
-network trunk create
---------------------
-
-Create a network trunk for a given project
-
-.. program:: network trunk create
-.. code:: bash
-
- os network trunk create
- --parent-port
- [--subport ]
- [--enable | --disable]
- [--project [--project-domain ]]
-
-
-.. option:: --parent-port
-
- Parent port belonging to this trunk (name or ID) (required)
-
-.. option:: --subport
-
- Subport to add. Subport is of form 'port=,segmentation-type=,segmentation-ID='
- (--subport) option can be repeated
-
-.. option:: --enable
-
- Enable trunk (default)
-
-.. option:: --disable
-
- Disable trunk
-
-.. option:: --project
-
- Owner's project (name or ID)
-
-.. option:: --project-domain
-
- Domain the project belongs to (name or ID).
- This can be used in case collisions between project names exist.
-
-network trunk delete
---------------------
-
-Delete a given network trunk
-
-.. program:: network trunk delete
-.. code:: bash
-
- os network trunk delete
- [ ...]
-
-.. _network_trunk_delete-trunk:
-.. describe::
-
- Trunk(s) to delete (name or ID)
-
-network trunk list
-------------------
-
-List all network trunks
-
-.. program:: network trunk list
-.. code:: bash
-
- os network trunk list
- [--long]
-
-.. option:: --long
-
- List additional fields in output
-
-network trunk set
------------------
-
-Set network trunk properties
-
-.. program:: network trunk set
-.. code:: bash
-
- os network trunk set
- [--name ]
- [--subport ]
- [--enable | --disable]
-
-
-.. option:: --name
-
- Set trunk name
-
-.. option:: --subport
-
- Subport to add. Subport is of form 'port=,segmentation-type=,segmentation-ID='
- (--subport) option can be repeated
-
-.. option:: --enable
-
- Enable trunk
-
-.. option:: --disable
-
- Disable trunk
-
-.. _network_trunk_set-trunk:
-.. describe::
-
- Trunk to modify (name or ID)
-
-network trunk show
-------------------
-
-Show information of a given network trunk
-
-.. program:: network trunk show
-.. code:: bash
-
- os network trunk show
-
-
-.. _network_trunk_show-trunk:
-.. describe::
-
- Trunk to display (name or ID)
-
-network trunk unset
--------------------
-
-Unset subports from a given network trunk
-
-.. program:: network trunk unset
-.. code:: bash
-
- os network trunk unset
- --subport
-
-
-.. option:: --subport
-
- Subport to delete (name or ID of the port) (required)
- (--subport) option can be repeated
-
-.. _network_trunk_unset-trunk:
-.. describe::
-
- Unset subports from this trunk (name or ID)
diff --git a/neutron_test.sh b/neutron_test.sh
deleted file mode 100755
index d6dc75409..000000000
--- a/neutron_test.sh
+++ /dev/null
@@ -1,165 +0,0 @@
-#!/bin/bash
-set -x
-function die() {
- local exitcode=$?
- set +o xtrace
- echo $@
- cleanup
- exit $exitcode
-}
-
-net_name=mynet1
-subnet_name=mysubnet1
-port_name=myport1
-function cleanup() {
- echo Removing test port, subnet and net...
- neutron port-delete $port_name
- neutron subnet-delete $subnet_name
- neutron net-delete $net_name
-}
-
-noauth_tenant_id=me
-if [ "$1" == "noauth" ]; then
- NOAUTH="--tenant_id $noauth_tenant_id"
-else
- NOAUTH=
-fi
-
-echo "NOTE: User should be admin in order to perform all operations."
-sleep 3
-
-# test the CRUD of network
-network=$net_name
-neutron net-create $NOAUTH $network || die "fail to create network $network"
-temp=`neutron net-list -- --name $network --fields id | wc -l`
-echo $temp
-if [ $temp -ne 5 ]; then
- die "networks with name $network is not unique or found"
-fi
-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"
-
-neutron net-show $network || die "fail to show network $network"
-neutron net-show $network_id || die "fail to show network $network_id"
-
-neutron net-update $network --admin_state_up False || die "fail to update network $network"
-neutron net-update $network_id --admin_state_up True || die "fail to update network $network_id"
-
-neutron net-list -c id -- --id fakeid || die "fail to list networks with column selection on empty list"
-
-# test the CRUD of subnet
-subnet=$subnet_name
-cidr=10.0.1.0/24
-neutron subnet-create $NOAUTH $network $cidr --name $subnet || die "fail to create subnet $subnet"
-tempsubnet=`neutron subnet-list -- --name $subnet --fields id | wc -l`
-echo $tempsubnet
-if [ $tempsubnet -ne 5 ]; then
- die "subnets with name $subnet is not unique or found"
-fi
-subnet_id=`neutron subnet-list -- --name $subnet --fields id | tail -n 2 | head -n 1 | cut -d' ' -f 2`
-echo "ID of subnet with name $subnet is $subnet_id"
-neutron subnet-show $subnet || die "fail to show subnet $subnet"
-neutron subnet-show $subnet_id || die "fail to show subnet $subnet_id"
-
-neutron subnet-update $subnet --dns_nameservers list=true 1.1.1.11 1.1.1.12 || die "fail to update subnet $subnet"
-neutron subnet-update $subnet_id --dns_nameservers list=true 2.2.2.21 2.2.2.22 || die "fail to update subnet $subnet_id"
-
-# test the crud of ports
-port=$port_name
-neutron port-create $NOAUTH $network --name $port || die "fail to create port $port"
-tempport=`neutron port-list -- --name $port --fields id | wc -l`
-echo $tempport
-if [ $tempport -ne 5 ]; then
- die "ports with name $port is not unique or found"
-fi
-port_id=`neutron port-list -- --name $port --fields id | tail -n 2 | head -n 1 | cut -d' ' -f 2`
-echo "ID of port with name $port is $port_id"
-neutron port-show $port || die "fail to show port $port"
-neutron port-show $port_id || die "fail to show port $port_id"
-neutron port-update $port --device_id deviceid1 || die "fail to update port $port"
-neutron port-update $port_id --device_id deviceid2 || die "fail to update port $port_id"
-neutron port-update $port_id --allowed-address-pair ip_address=1.1.1.11,mac_address=10:00:00:00:00:00 --allowed-address-pair ip_address=1.1.1.12,mac_address=10:00:00:00:00:01 || die "fail to update port $port_id --allowed-address-pair"
-neutron port-show $port || die "fail to show port $port"
-neutron port-show $port_id || die "fail to show port $port_id"
-neutron port-update $port_id --no-allowed-address-pairs || die "fail to update port $port_id --no-allowed-address-pairs"
-neutron port-show $port || die "fail to show port $port"
-neutron port-show $port_id || die "fail to show port $port_id"
-neutron port-delete $port_id
-
-# test the create port with allowed-address-pairs
-port=$port_name
-neutron port-create $NOAUTH $network --name $port -- --allowed-address-pairs type=dict list=true ip_address=1.1.1.11,mac_address=10:00:00:00:00:00 ip_address=1.1.1.12,mac_address=10:00:00:00:00:01 || die "fail to create port $port"
-tempport=`neutron port-list -- --name $port --fields id | wc -l`
-echo $tempport
-if [ $tempport -ne 5 ]; then
- die "ports with name $port is not unique or found"
-fi
-port_id=`neutron port-list -- --name $port --fields id | tail -n 2 | head -n 1 | cut -d' ' -f 2`
-echo "ID of port with name $port is $port_id"
-neutron port-show $port || die "fail to show port $port"
-neutron port-show $port_id || die "fail to show port $port_id"
-neutron port-update $port_id --no-allowed-address-pairs || die "fail to update port $port_id --no-allowed-address-pairs"
-neutron port-show $port_id
-
-# test quota commands RUD
-DEFAULT_NETWORKS=10
-DEFAULT_PORTS=50
-tenant_id=tenant_a
-tenant_id_b=tenant_b
-neutron quota-update --tenant_id $tenant_id --network 30 || die "fail to update quota for tenant $tenant_id"
-neutron quota-update --tenant_id $tenant_id_b --network 20 || die "fail to update quota for tenant $tenant_id"
-networks=`neutron quota-list -c network -c tenant_id | grep $tenant_id | awk '{print $2}'`
-if [ $networks -ne 30 ]; then
- die "networks quota should be 30"
-fi
-networks=`neutron quota-list -c network -c tenant_id | grep $tenant_id_b | awk '{print $2}'`
-if [ $networks -ne 20 ]; then
- die "networks quota should be 20"
-fi
-networks=`neutron quota-show --tenant_id $tenant_id | grep network | awk -F'|' '{print $3}'`
-if [ $networks -ne 30 ]; then
- die "networks quota should be 30"
-fi
-neutron quota-delete --tenant_id $tenant_id || die "fail to delete quota for tenant $tenant_id"
-networks=`neutron quota-show --tenant_id $tenant_id | grep network | awk -F'|' '{print $3}'`
-if [ $networks -ne $DEFAULT_NETWORKS ]; then
- die "networks quota should be $DEFAULT_NETWORKS"
-fi
-# update self
-if [ "t$NOAUTH" = "t" ]; then
- # with auth
- neutron quota-update --port 99 || die "fail to update quota for self"
- ports=`neutron quota-show | grep port | awk -F'|' '{print $3}'`
- if [ $ports -ne 99 ]; then
- die "ports quota should be 99"
- fi
-
- ports=`neutron quota-list -c port | grep 99 | awk '{print $2}'`
- if [ $ports -ne 99 ]; then
- die "ports quota should be 99"
- fi
- neutron quota-delete || die "fail to delete quota for tenant self"
- ports=`neutron quota-show | grep port | awk -F'|' '{print $3}'`
- if [ $ports -ne $DEFAULT_PORTS ]; then
- die "ports quota should be $DEFAULT_PORTS"
- fi
-else
- # without auth
- neutron quota-update --port 100
- if [ $? -eq 0 ]; then
- die "without valid context on server, quota update command should fail."
- fi
- neutron quota-show
- if [ $? -eq 0 ]; then
- die "without valid context on server, quota show command should fail."
- fi
- neutron quota-delete
- if [ $? -eq 0 ]; then
- die "without valid context on server, quota delete command should fail."
- fi
- neutron quota-list || die "fail to update quota for self"
-fi
-
-cleanup
-echo "Success! :)"
-
diff --git a/neutronclient/_i18n.py b/neutronclient/_i18n.py
index f5aa76bcf..50ac3c5bf 100644
--- a/neutronclient/_i18n.py
+++ b/neutronclient/_i18n.py
@@ -17,7 +17,7 @@
_translators = oslo_i18n.TranslatorFactory(domain=DOMAIN)
-# The primary translation function using the well-known name "_"
+# The translation function using the well-known name "_"
_ = _translators.primary
# The contextual translation function using the name "_C"
@@ -26,16 +26,6 @@
# The plural translation function using the name "_P"
_P = _translators.plural_form
-# Translators for log levels.
-#
-# The abbreviated names are meant to reflect the usual use of a short
-# name like '_'. The "L" is for "log" and the other letter comes from
-# the level.
-_LI = _translators.log_info
-_LW = _translators.log_warning
-_LE = _translators.log_error
-_LC = _translators.log_critical
-
def get_available_languages():
return oslo_i18n.get_available_languages(DOMAIN)
diff --git a/neutronclient/client.py b/neutronclient/client.py
index 10a189ba0..e25f575f3 100644
--- a/neutronclient/client.py
+++ b/neutronclient/client.py
@@ -14,22 +14,22 @@
# under the License.
#
-try:
- import json
-except ImportError:
- import simplejson as json
import logging
import os
import debtcollector.renames
from keystoneauth1 import access
from keystoneauth1 import adapter
+from oslo_serialization import jsonutils
+from oslo_utils import importutils
import requests
from neutronclient._i18n import _
from neutronclient.common import exceptions
from neutronclient.common import utils
+osprofiler_web = importutils.try_import("osprofiler.web")
+
_logger = logging.getLogger(__name__)
if os.environ.get('NEUTRONCLIENT_DEBUG'):
@@ -43,6 +43,7 @@
logging.getLogger("requests").setLevel(_requests_log_level)
MAX_URI_LEN = 8192
USER_AGENT = 'python-neutronclient'
+REQ_ID_HEADER = 'X-OpenStack-Request-ID'
class HTTPClient(object):
@@ -60,9 +61,9 @@ def __init__(self, username=None, user_id=None,
token=None, region_name=None, timeout=None,
endpoint_url=None, insecure=False,
endpoint_type='publicURL',
- auth_strategy='keystone', ca_cert=None, log_credentials=False,
- service_type='network',
- **kwargs):
+ auth_strategy='keystone', ca_cert=None, cert=None,
+ log_credentials=False, service_type='network',
+ global_request_id=None, **kwargs):
self.username = username
self.user_id = user_id
@@ -80,6 +81,8 @@ def __init__(self, username=None, user_id=None,
self.endpoint_url = endpoint_url
self.auth_strategy = auth_strategy
self.log_credentials = log_credentials
+ self.global_request_id = global_request_id
+ self.cert = cert
if insecure:
self.verify_cert = False
else:
@@ -102,14 +105,25 @@ def _cs_request(self, *args, **kwargs):
try:
resp, body = self.request(*args, **kargs)
except requests.exceptions.SSLError as e:
- raise exceptions.SslCertificateValidationError(reason=e)
+ raise exceptions.SslCertificateValidationError(reason=str(e))
except Exception as e:
# Wrap the low-level connection error (socket timeout, redirect
# limit, decompression error, etc) into our custom high-level
# connection exception (it is excepted in the upper layers of code)
_logger.debug("throwing ConnectionFailed : %s", e)
- raise exceptions.ConnectionFailed(reason=e)
+ raise exceptions.ConnectionFailed(reason=str(e))
utils.http_log_resp(_logger, resp, body)
+
+ # log request-id for each api call
+ request_id = resp.headers.get('x-openstack-request-id')
+ if request_id:
+ _logger.debug('%(method)s call to neutron for '
+ '%(url)s used request id '
+ '%(response_request_id)s',
+ {'method': resp.request.method,
+ 'url': resp.url,
+ 'response_request_id': request_id})
+
if resp.status_code == 401:
raise exceptions.Unauthorized(message=body)
return resp, body
@@ -139,7 +153,14 @@ def request(self, url, method, body=None, headers=None, **kwargs):
if body:
headers.setdefault('Content-Type', content_type)
+ if self.global_request_id:
+ headers.setdefault(REQ_ID_HEADER, self.global_request_id)
+
headers['User-Agent'] = USER_AGENT
+ # NOTE(dbelova): osprofiler_web.get_trace_id_headers does not add any
+ # headers in case if osprofiler is not initialized.
+ if osprofiler_web:
+ headers.update(osprofiler_web.get_trace_id_headers())
resp = requests.request(
method,
@@ -147,6 +168,7 @@ def request(self, url, method, body=None, headers=None, **kwargs):
data=body,
headers=headers,
verify=self.verify_cert,
+ cert=self.cert,
timeout=self.timeout,
**kwargs)
@@ -167,7 +189,7 @@ def do_request(self, url, method, **kwargs):
# might be because the auth token expired, so try to
# re-authenticate and try again. If it still fails, bail.
try:
- kwargs.setdefault('headers', {})
+ kwargs['headers'] = kwargs.get('headers') or {}
if self.auth_token is None:
self.auth_token = ""
kwargs['headers']['X-Auth-Token'] = self.auth_token
@@ -176,7 +198,7 @@ def do_request(self, url, method, **kwargs):
return resp, body
except exceptions.Unauthorized:
self.authenticate()
- kwargs.setdefault('headers', {})
+ kwargs['headers'] = kwargs.get('headers') or {}
kwargs['headers']['X-Auth-Token'] = self.auth_token
resp, body = self._cs_request(
self.endpoint_url + url, method, **kwargs)
@@ -216,14 +238,14 @@ def _authenticate_keystone(self):
token_url = self.auth_url + "/tokens"
resp, resp_body = self._cs_request(token_url, "POST",
- body=json.dumps(body),
+ body=jsonutils.dumps(body),
content_type="application/json",
allow_redirects=True)
if resp.status_code != 200:
raise exceptions.Unauthorized(message=resp_body)
if resp_body:
try:
- resp_body = json.loads(resp_body)
+ resp_body = jsonutils.loads(resp_body)
except ValueError:
pass
else:
@@ -259,7 +281,7 @@ def _get_endpoint_url(self):
self.authenticate()
return self.endpoint_url
- body = json.loads(body)
+ body = jsonutils.loads(body)
for endpoint in body.get('endpoints', []):
if (endpoint['type'] == 'network' and
endpoint.get('region') == self.region_name):
@@ -276,6 +298,9 @@ def get_auth_info(self):
'auth_user_id': self.auth_user_id,
'endpoint_url': self.endpoint_url}
+ def get_auth_ref(self):
+ return getattr(self, 'auth_ref', None)
+
class SessionClient(adapter.Adapter):
@@ -285,9 +310,14 @@ def request(self, *args, **kwargs):
content_type = kwargs.pop('content_type', None) or 'application/json'
- headers = kwargs.setdefault('headers', {})
+ headers = kwargs.get('headers') or {}
headers.setdefault('Accept', content_type)
+ # NOTE(dbelova): osprofiler_web.get_trace_id_headers does not add any
+ # headers in case if osprofiler is not initialized.
+ if osprofiler_web:
+ headers.update(osprofiler_web.get_trace_id_headers())
+
try:
kwargs.setdefault('data', kwargs.pop('body'))
except KeyError:
@@ -296,6 +326,7 @@ def request(self, *args, **kwargs):
if kwargs.get('data'):
headers.setdefault('Content-Type', content_type)
+ kwargs['headers'] = headers
resp = super(SessionClient, self).request(*args, **kwargs)
return resp, resp.text
@@ -346,6 +377,9 @@ def get_auth_info(self):
return auth_info
+ def get_auth_ref(self):
+ return self.session.auth.get_auth_ref(self.session)
+
# FIXME(bklei): Should refactor this to use kwargs and only
# explicitly list arguments that are not None.
@@ -367,8 +401,10 @@ def construct_http_client(username=None,
log_credentials=None,
auth_strategy='keystone',
ca_cert=None,
+ cert=None,
service_type='network',
session=None,
+ global_request_id=None,
**kwargs):
if session:
@@ -377,6 +413,7 @@ def construct_http_client(username=None,
return SessionClient(session=session,
service_type=service_type,
region_name=region_name,
+ global_request_id=global_request_id,
**kwargs)
else:
# FIXME(bklei): username and password are now optional. Need
@@ -396,5 +433,7 @@ def construct_http_client(username=None,
endpoint_type=endpoint_type,
service_type=service_type,
ca_cert=ca_cert,
+ cert=cert,
log_credentials=log_credentials,
- auth_strategy=auth_strategy)
+ auth_strategy=auth_strategy,
+ global_request_id=global_request_id)
diff --git a/neutronclient/common/clientmanager.py b/neutronclient/common/clientmanager.py
index b79ee5b31..56d3d3c12 100644
--- a/neutronclient/common/clientmanager.py
+++ b/neutronclient/common/clientmanager.py
@@ -17,17 +17,12 @@
"""Manage access to the clients, including authenticating when needed.
"""
-import logging
-
import debtcollector.renames
from neutronclient import client
from neutronclient.neutron import client as neutron_client
-LOG = logging.getLogger(__name__)
-
-
class ClientCache(object):
"""Descriptor class for caching created client handles."""
diff --git a/neutronclient/common/exceptions.py b/neutronclient/common/exceptions.py
index d165a3bc0..443f78155 100644
--- a/neutronclient/common/exceptions.py
+++ b/neutronclient/common/exceptions.py
@@ -13,6 +13,8 @@
# License for the specific language governing permissions and limitations
# under the License.
+from oslo_utils import encodeutils
+
from neutronclient._i18n import _
"""
@@ -29,6 +31,14 @@
"""
+# NOTE: This method is defined here to avoid
+# an import loop between common.utils and this module.
+def _safe_decode_dict(kwargs):
+ for k, v in kwargs.items():
+ kwargs[k] = encodeutils.safe_decode(v)
+ return kwargs
+
+
class NeutronException(Exception):
"""Base Neutron Exception.
@@ -42,7 +52,7 @@ def __init__(self, message=None, **kwargs):
if message:
self.message = message
try:
- self._error_string = self.message % kwargs
+ self._error_string = self.message % _safe_decode_dict(kwargs)
except Exception:
# at least get the core message out if something happened
self._error_string = self.message
@@ -150,6 +160,10 @@ class IpAddressInUseClient(Conflict):
pass
+class IpAddressAlreadyAllocatedClient(Conflict):
+ pass
+
+
class InvalidIpForNetworkClient(BadRequest):
pass
diff --git a/neutronclient/common/extension.py b/neutronclient/common/extension.py
index 90f44a79b..00a035d6c 100644
--- a/neutronclient/common/extension.py
+++ b/neutronclient/common/extension.py
@@ -42,7 +42,6 @@ def execute(self, parsed_args):
class ClientExtensionList(NeutronClientExtension, neutronV20.ListCommand):
-
def take_action(self, parsed_args):
# NOTE(mdietz): Calls 'execute' to provide a consistent pattern
# for any implementers adding extensions with
diff --git a/neutronclient/common/serializer.py b/neutronclient/common/serializer.py
index 828e17f3a..d4c8bbbb6 100644
--- a/neutronclient/common/serializer.py
+++ b/neutronclient/common/serializer.py
@@ -13,19 +13,11 @@
# License for the specific language governing permissions and limitations
# under the License.
-import logging
-
from oslo_serialization import jsonutils
-import six
from neutronclient._i18n import _
from neutronclient.common import exceptions as exception
-LOG = logging.getLogger(__name__)
-
-if six.PY3:
- long = int
-
class ActionDispatcher(object):
"""Maps method name to local methods through action name."""
@@ -55,7 +47,7 @@ class JSONDictSerializer(DictSerializer):
def default(self, data):
def sanitizer(obj):
- return six.text_type(obj)
+ return str(obj)
return jsonutils.dumps(data, default=sanitizer)
diff --git a/neutronclient/common/utils.py b/neutronclient/common/utils.py
index 882eb2c5c..93f92fd19 100644
--- a/neutronclient/common/utils.py
+++ b/neutronclient/common/utils.py
@@ -21,12 +21,10 @@
import functools
import hashlib
import logging
-import netaddr
import os
from oslo_utils import encodeutils
from oslo_utils import importutils
-import six
from neutronclient._i18n import _
from neutronclient.common import exceptions
@@ -130,7 +128,18 @@ def str2dict(strdict, required_keys=None, optional_keys=None):
"""
result = {}
if strdict:
+ i = 0
+ kvlist = []
for kv in strdict.split(','):
+ if '=' in kv:
+ kvlist.append(kv)
+ i += 1
+ elif i == 0:
+ msg = _("missing value for key '%s'")
+ raise argparse.ArgumentTypeError(msg % kv)
+ else:
+ kvlist[i - 1] = "%s,%s" % (kvlist[i - 1], kv)
+ for kv in kvlist:
key, sep, value = kv.partition('=')
if not sep:
msg = _("invalid key-value '%s', expected format: key=value")
@@ -170,12 +179,12 @@ def http_log_req(_logger, args, kwargs):
else:
string_parts.append(' %s' % element)
- for (key, value) in six.iteritems(kwargs['headers']):
+ for (key, value) in kwargs['headers'].items():
if key in SENSITIVE_HEADERS:
v = value.encode('utf-8')
- h = hashlib.sha1(v)
+ h = hashlib.sha256(v)
d = h.hexdigest()
- value = "{SHA1}%s" % d
+ value = "{SHA256}%s" % d
header = ' -H "%s: %s"' % (key, value)
string_parts.append(header)
@@ -195,7 +204,7 @@ def http_log_resp(_logger, resp, body):
def _safe_encode_without_obj(data):
- if isinstance(data, six.string_types):
+ if isinstance(data, str):
return encodeutils.safe_encode(data)
return data
@@ -226,11 +235,3 @@ def add_boolean_argument(parser, name, **kwargs):
choices=['True', 'true', 'False', 'false'],
default=default,
**kwargs)
-
-
-def is_valid_cidr(cidr):
- try:
- netaddr.IPNetwork(cidr)
- return True
- except Exception:
- return False
diff --git a/neutronclient/i18n.py b/neutronclient/i18n.py
deleted file mode 100644
index 776628fc7..000000000
--- a/neutronclient/i18n.py
+++ /dev/null
@@ -1,27 +0,0 @@
-# Licensed under the Apache License, Version 2.0 (the "License"); you may
-# not use this file except in compliance with the License. You may obtain
-# a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-# License for the specific language governing permissions and limitations
-# under the License.
-
-# TODO(amotoki): Remove this file at the beginning of Nxx cycle.
-
-from debtcollector import moves
-
-from neutronclient import _i18n
-
-message = ("moved to neutronclient._i18n; please migrate to local "
- "oslo_i18n usage, as defined at "
- "http://docs.openstack.org/developer/oslo.i18n/usage.html")
-
-_ = moves.moved_function(_i18n._, '_', __name__, message=message)
-_LC = moves.moved_function(_i18n._LC, '_LC', __name__, message=message)
-_LE = moves.moved_function(_i18n._LE, '_LE', __name__, message=message)
-_LW = moves.moved_function(_i18n._LW, '_LW', __name__, message=message)
-_LI = moves.moved_function(_i18n._LI, '_LI', __name__, message=message)
diff --git a/neutronclient/neutron/client.py b/neutronclient/neutron/client.py
index 7961a4ca2..d859d815d 100644
--- a/neutronclient/neutron/client.py
+++ b/neutronclient/neutron/client.py
@@ -28,7 +28,7 @@ def make_client(instance):
"""Returns an neutron client."""
neutron_client = utils.get_client_class(
API_NAME,
- instance._api_version[API_NAME],
+ instance._api_version,
API_VERSIONS,
)
instance.initialize()
diff --git a/neutronclient/neutron/v2_0/__init__.py b/neutronclient/neutron/v2_0/__init__.py
index 4468bfb3a..849a93d9e 100644
--- a/neutronclient/neutron/v2_0/__init__.py
+++ b/neutronclient/neutron/v2_0/__init__.py
@@ -14,8 +14,6 @@
# under the License.
#
-from __future__ import print_function
-
import abc
import argparse
import functools
@@ -25,7 +23,6 @@
from cliff import lister
from cliff import show
from oslo_serialization import jsonutils
-import six
from neutronclient._i18n import _
from neutronclient.common import exceptions
@@ -132,9 +129,9 @@ def _process_previous_argument(current_arg, _value_number, current_type_str,
values_specs):
if current_arg is not None:
if _value_number == 0 and (current_type_str or _list_flag):
- # This kind of argument should have value
- raise exceptions.CommandError(
- _("Invalid values_specs %s") % ' '.join(values_specs))
+ # This kind of argument should have value
+ raise exceptions.CommandError(
+ _("Invalid values_specs %s") % ' '.join(values_specs))
if _value_number > 1 or _list_flag or current_type_str == 'list':
current_arg.update({'nargs': '+'})
elif _value_number == 0:
@@ -185,6 +182,14 @@ def parse_args_to_dict(values_specs):
current_item = None
# the str after 'type='
current_type_str = None
+ # dict of allowed types
+ allowed_type_dict = {
+ 'bool': utils.str2bool,
+ 'dict': utils.str2dict,
+ 'int': int,
+ 'str': str,
+ }
+
for _item in values_specs_copy:
if _item.startswith('--'):
# Deal with previous argument if any
@@ -215,12 +220,16 @@ def parse_args_to_dict(values_specs):
_("Invalid values_specs %s") % ' '.join(values_specs))
if 'type' not in current_arg:
current_type_str = _item.split('=', 2)[1]
- current_arg.update({'type': eval(current_type_str)})
- if current_type_str == 'bool':
- current_arg.update({'type': utils.str2bool})
- elif current_type_str == 'dict':
- current_arg.update({'type': utils.str2dict})
- continue
+ if current_type_str in allowed_type_dict:
+ current_arg['type'] = allowed_type_dict[current_type_str]
+ continue
+ else:
+ raise exceptions.CommandError(
+ _("Invalid value_specs {valspec}: type {curtypestr}"
+ " is not supported").format(
+ valspec=' '.join(values_specs),
+ curtypestr=current_type_str))
+
elif _item == 'list=true':
_list_flag = True
continue
@@ -240,7 +249,6 @@ def parse_args_to_dict(values_specs):
if _item.startswith('---'):
raise exceptions.CommandError(
_("Invalid values_specs %s") % ' '.join(values_specs))
-
_values_specs.append(_item)
# Deal with last one argument
@@ -250,12 +258,12 @@ def parse_args_to_dict(values_specs):
# Populate the parser with arguments
_parser = argparse.ArgumentParser(add_help=False)
- for opt, optspec in six.iteritems(_options):
+ for opt, optspec in _options.items():
_parser.add_argument(opt, **optspec)
_args = _parser.parse_args(_values_specs)
result_dict = {}
- for opt in six.iterkeys(_options):
+ for opt in _options.keys():
_opt = opt.split('--', 2)[1]
_opt = _opt.replace('-', '_')
_value = getattr(_args, _opt)
@@ -274,7 +282,7 @@ def _merge_args(qCmd, parsed_args, _extra_values, value_specs):
@param values_specs: the unparsed unknown parts
"""
temp_values = _extra_values.copy()
- for key, value in six.iteritems(temp_values):
+ for key, value in temp_values.items():
if hasattr(parsed_args, key):
arg_value = getattr(parsed_args, key)
if arg_value is not None and value is not None:
@@ -310,8 +318,7 @@ def __new__(cls, name, bases, cls_dict):
name, bases, cls_dict)
-@six.add_metaclass(NeutronCommandMeta)
-class NeutronCommand(command.Command):
+class NeutronCommand(command.Command, metaclass=NeutronCommandMeta):
values_specs = []
json_indent = None
@@ -336,7 +343,7 @@ def get_parser(self, prog_name):
parser = super(NeutronCommand, self).get_parser(prog_name)
parser.add_argument(
'--request-format',
- help=_('DEPRECATED! Only JSON request format is supported.'),
+ help=argparse.SUPPRESS,
default='json',
choices=['json', ], )
parser.add_argument(
@@ -350,10 +357,9 @@ def cleanup_output_data(self, data):
pass
def format_output_data(self, data):
- self.cleanup_output_data(data)
# Modify data to make it more readable
if self.resource in data:
- for k, v in six.iteritems(data[self.resource]):
+ for k, v in data[self.resource].items():
if isinstance(v, list):
value = '\n'.join(jsonutils.dumps(
i, indent=self.json_indent) if isinstance(i, dict)
@@ -405,7 +411,9 @@ def take_action(self, parsed_args):
data = obj_creator(self.parent_id, body)
else:
data = obj_creator(body)
- self.format_output_data(data)
+ self.cleanup_output_data(data)
+ if parsed_args.formatter == 'table':
+ self.format_output_data(data)
info = self.resource in data and data[self.resource] or None
if info:
if parsed_args.formatter == 'table':
@@ -413,7 +421,7 @@ def take_action(self, parsed_args):
file=self.app.stdout)
else:
info = {'': ''}
- return zip(*sorted(six.iteritems(info)))
+ return zip(*sorted(info.items()))
class UpdateCommand(NeutronCommand):
@@ -528,18 +536,20 @@ def _bulk_delete(self, obj_deleter, neutron_client, parsed_args_ids):
% {'id': ", ".join(successful_delete),
'resource': self.cmd_resource},
file=self.app.stdout)
- if non_existent:
- print((_("Unable to find %(resource)s(s) with id(s) "
- "'%(id)s'") %
- {'resource': self.cmd_resource,
- 'id': ", ".join(non_existent)}),
- file=self.app.stdout)
- if multiple_ids:
- print((_("Multiple %(resource)s(s) matches found for name(s)"
- " '%(id)s'. Please use an ID to be more specific.")) %
- {'resource': self.cmd_resource,
- 'id': ", ".join(multiple_ids)},
- file=self.app.stdout)
+ if non_existent or multiple_ids:
+ err_msgs = []
+ if non_existent:
+ err_msgs.append((_("Unable to find %(resource)s(s) with id(s) "
+ "'%(id)s'.") %
+ {'resource': self.cmd_resource,
+ 'id': ", ".join(non_existent)}))
+ if multiple_ids:
+ err_msgs.append((_("Multiple %(resource)s(s) matches found "
+ "for name(s) '%(id)s'. Please use an ID "
+ "to be more specific.") %
+ {'resource': self.cmd_resource,
+ 'id': ", ".join(multiple_ids)}))
+ raise exceptions.NeutronCLIError(message='\n'.join(err_msgs))
def delete_item(self, obj_deleter, neutron_client, item_id):
if self.allow_names:
@@ -712,16 +722,48 @@ def setup_columns(self, info, parsed_args):
# if no -c(s) by user and list_columns, we use columns in
# both list_columns and returned resource.
# Also Keep their order the same as in list_columns
- _columns = [x for x in self.list_columns if x in _columns]
+ _columns = self._setup_columns_with_tenant_id(self.list_columns,
+ _columns)
- formatters = self._formatters
- if hasattr(self, '_formatters_csv') and parsed_args.formatter == 'csv':
+ if parsed_args.formatter == 'table':
+ formatters = self._formatters
+ elif (parsed_args.formatter == 'csv' and
+ hasattr(self, '_formatters_csv')):
formatters = self._formatters_csv
+ else:
+ # For other formatters, we use raw value returned from neutron
+ formatters = {}
return (_columns, (utils.get_item_properties(
s, _columns, formatters=formatters, )
for s in info), )
+ def _setup_columns_with_tenant_id(self, display_columns, avail_columns):
+ _columns = [x for x in display_columns if x in avail_columns]
+ if 'tenant_id' in display_columns:
+ return _columns
+ if 'tenant_id' not in avail_columns:
+ return _columns
+ if not self.is_admin_role():
+ return _columns
+ try:
+ pos_id = _columns.index('id')
+ except ValueError:
+ pos_id = 0
+ try:
+ pos_name = _columns.index('name')
+ except ValueError:
+ pos_name = 0
+ _columns.insert(max(pos_id, pos_name) + 1, 'tenant_id')
+ return _columns
+
+ def is_admin_role(self):
+ client = self.get_client()
+ auth_ref = client.httpclient.get_auth_ref()
+ if not auth_ref:
+ return False
+ return 'admin' in auth_ref.role_names
+
def take_action(self, parsed_args):
self.set_extra_attrs(parsed_args)
data = self.retrieve_list(parsed_args)
@@ -774,9 +816,11 @@ def take_action(self, parsed_args):
data = obj_shower(_id, self.parent_id, **params)
else:
data = obj_shower(_id, **params)
- self.format_output_data(data)
+ self.cleanup_output_data(data)
+ if parsed_args.formatter == 'table':
+ self.format_output_data(data)
resource = data[self.resource]
if self.resource in data:
- return zip(*sorted(six.iteritems(resource)))
+ return zip(*sorted(resource.items()))
else:
return None
diff --git a/neutronclient/neutron/v2_0/agentscheduler.py b/neutronclient/neutron/v2_0/agentscheduler.py
index 4476b1dd3..e92b10be1 100644
--- a/neutronclient/neutron/v2_0/agentscheduler.py
+++ b/neutronclient/neutron/v2_0/agentscheduler.py
@@ -14,8 +14,6 @@
# under the License.
#
-from __future__ import print_function
-
from neutronclient._i18n import _
from neutronclient.neutron import v2_0 as neutronV20
from neutronclient.neutron.v2_0 import network
diff --git a/neutronclient/neutron/v2_0/auto_allocated_topology.py b/neutronclient/neutron/v2_0/auto_allocated_topology.py
index 3f0f58baf..a24959e16 100644
--- a/neutronclient/neutron/v2_0/auto_allocated_topology.py
+++ b/neutronclient/neutron/v2_0/auto_allocated_topology.py
@@ -15,6 +15,7 @@
#
import argparse
+
from cliff import show
from oslo_serialization import jsonutils
@@ -79,3 +80,33 @@ def take_action(self, parsed_args):
return zip(*sorted(data[self.resource].items()))
else:
return None
+
+
+class DeleteAutoAllocatedTopology(v2_0.NeutronCommand):
+ """Delete the auto-allocated topology of a given tenant."""
+
+ resource = 'auto_allocated_topology'
+
+ def get_parser(self, prog_name):
+ parser = super(DeleteAutoAllocatedTopology, self).get_parser(prog_name)
+ parser.add_argument(
+ '--tenant-id', metavar='tenant-id',
+ help=_('The owner tenant ID.'))
+ # Allow people to do
+ # neutron auto-allocated-topology-delete
+ # (Only useful to users who can look at other tenants' topologies.)
+ # We use a different name for this arg because the default will
+ # override whatever is in the named arg otherwise.
+ parser.add_argument(
+ 'pos_tenant_id',
+ help=argparse.SUPPRESS, nargs='?')
+ return parser
+
+ def take_action(self, parsed_args):
+ client = self.get_client()
+ tenant_id = parsed_args.tenant_id or parsed_args.pos_tenant_id
+ client.delete_auto_allocated_topology(tenant_id)
+ # It tenant is None, let's be clear on what it means.
+ tenant_id = tenant_id or 'None (i.e. yours)'
+ print(_('Deleted topology for tenant %s.') % tenant_id,
+ file=self.app.stdout)
diff --git a/neutronclient/neutron/v2_0/bgp/dragentscheduler.py b/neutronclient/neutron/v2_0/bgp/dragentscheduler.py
index 81ce8f1ec..d1e1de63f 100644
--- a/neutronclient/neutron/v2_0/bgp/dragentscheduler.py
+++ b/neutronclient/neutron/v2_0/bgp/dragentscheduler.py
@@ -14,8 +14,6 @@
# under the License.
#
-from __future__ import print_function
-
from neutronclient._i18n import _
from neutronclient.neutron import v2_0 as neutronV20
from neutronclient.neutron.v2_0.bgp import speaker as bgp_speaker
diff --git a/neutronclient/neutron/v2_0/bgp/speaker.py b/neutronclient/neutron/v2_0/bgp/speaker.py
index 1a70734e5..34ce22eb8 100644
--- a/neutronclient/neutron/v2_0/bgp/speaker.py
+++ b/neutronclient/neutron/v2_0/bgp/speaker.py
@@ -14,8 +14,6 @@
# under the License.
#
-from __future__ import print_function
-
from neutronclient._i18n import _
from neutronclient.common import utils
from neutronclient.common import validators
@@ -24,7 +22,7 @@
# Allowed BGP Autonomous number range
MIN_AS_NUM = 1
-MAX_AS_NUM = 65535
+MAX_AS_NUM = 4294967295
def get_network_id(client, id_or_name):
@@ -191,7 +189,7 @@ def take_action(self, parsed_args):
neutron_client.remove_peer_from_bgp_speaker(_speaker_id,
{'bgp_peer_id': _peer_id})
print(_('Removed BGP peer %(peer)s from BGP speaker %(speaker)s.') %
- {'peer': parsed_args.bgp_peer,
+ {'peer': parsed_args.bgp_peer,
'speaker': parsed_args.bgp_speaker},
file=self.app.stdout)
diff --git a/neutronclient/neutron/v2_0/flavor/flavor.py b/neutronclient/neutron/v2_0/flavor/flavor.py
index 3058da656..36a052ef2 100644
--- a/neutronclient/neutron/v2_0/flavor/flavor.py
+++ b/neutronclient/neutron/v2_0/flavor/flavor.py
@@ -13,8 +13,6 @@
# License for the specific language governing permissions and limitations
# under the License.
-from __future__ import print_function
-
import argparse
from neutronclient._i18n import _
diff --git a/neutronclient/neutron/v2_0/floatingip.py b/neutronclient/neutron/v2_0/floatingip.py
index 9f0ce089b..5f4ced40a 100644
--- a/neutronclient/neutron/v2_0/floatingip.py
+++ b/neutronclient/neutron/v2_0/floatingip.py
@@ -14,8 +14,6 @@
# under the License.
#
-from __future__ import print_function
-
import argparse
from neutronclient._i18n import _
diff --git a/neutronclient/neutron/v2_0/fw/firewallpolicy.py b/neutronclient/neutron/v2_0/fw/firewallpolicy.py
index 0c99948eb..3d9331cd6 100644
--- a/neutronclient/neutron/v2_0/fw/firewallpolicy.py
+++ b/neutronclient/neutron/v2_0/fw/firewallpolicy.py
@@ -14,8 +14,6 @@
# under the License.
#
-from __future__ import print_function
-
import argparse
from neutronclient._i18n import _
diff --git a/neutronclient/neutron/v2_0/lb/healthmonitor.py b/neutronclient/neutron/v2_0/lb/healthmonitor.py
index c2bd70cc9..33dfbf0bc 100644
--- a/neutronclient/neutron/v2_0/lb/healthmonitor.py
+++ b/neutronclient/neutron/v2_0/lb/healthmonitor.py
@@ -14,8 +14,6 @@
# under the License.
#
-from __future__ import print_function
-
from neutronclient._i18n import _
from neutronclient.neutron import v2_0 as neutronV20
@@ -66,8 +64,7 @@ def add_known_arguments(self, parser):
parser.add_argument(
'--delay',
required=True,
- help=_('The time in milliseconds between sending probes to '
- 'members.'))
+ help=_('The time in seconds between sending probes to members.'))
parser.add_argument(
'--max-retries',
required=True,
@@ -76,8 +73,8 @@ def add_known_arguments(self, parser):
parser.add_argument(
'--timeout',
required=True,
- help=_('Maximum number of milliseconds for a monitor to wait for '
- 'a connection to be established before it times out. The '
+ help=_('Maximum number of seconds for a monitor to wait for a '
+ 'connection to be established before it times out. The '
'value must be less than the delay value.'))
parser.add_argument(
'--type',
@@ -145,10 +142,11 @@ def get_parser(self, prog_name):
parser = super(DisassociateHealthMonitor, self).get_parser(prog_name)
parser.add_argument(
'health_monitor_id', metavar='HEALTH_MONITOR_ID',
- help=_('Health monitor to associate.'))
+ help=_('Health monitor to disassociate.'))
parser.add_argument(
'pool_id', metavar='POOL',
- help=_('ID of the pool to be associated with the health monitor.'))
+ help=_('ID of the pool to be disassociated with the health '
+ 'monitor.'))
return parser
def take_action(self, parsed_args):
diff --git a/neutronclient/neutron/v2_0/lb/pool.py b/neutronclient/neutron/v2_0/lb/pool.py
index afc0cc13e..5684e8e6a 100644
--- a/neutronclient/neutron/v2_0/lb/pool.py
+++ b/neutronclient/neutron/v2_0/lb/pool.py
@@ -14,9 +14,6 @@
# under the License.
#
-
-import six
-
from neutronclient._i18n import _
from neutronclient.neutron import v2_0 as neutronV20
@@ -119,6 +116,6 @@ def take_action(self, parsed_args):
self.format_output_data(data)
stats = data['stats']
if 'stats' in data:
- return zip(*sorted(six.iteritems(stats)))
+ return zip(*sorted(stats.items()))
else:
return None
diff --git a/neutronclient/neutron/v2_0/lb/v2/l7rule.py b/neutronclient/neutron/v2_0/lb/v2/l7rule.py
index 1286559f2..3c468cabf 100644
--- a/neutronclient/neutron/v2_0/lb/v2/l7rule.py
+++ b/neutronclient/neutron/v2_0/lb/v2/l7rule.py
@@ -39,32 +39,32 @@ def add_known_arguments(self, parser):
def _add_common_args(parser, is_create=True):
- parser.add_argument(
- '--type',
- required=is_create,
- type=utils.convert_to_uppercase,
- choices=['HOST_NAME', 'PATH', 'FILE_TYPE', 'HEADER', 'COOKIE'],
- help=_('Rule type.'))
- parser.add_argument(
- '--compare-type',
- required=is_create,
- type=utils.convert_to_uppercase,
- choices=['REGEX', 'STARTS_WITH', 'ENDS_WITH',
- 'CONTAINS', 'EQUAL_TO'],
- help=_('Rule compare type.'))
- parser.add_argument(
- '--invert-compare',
- dest='invert',
- action='store_true',
- help=_('Invert the compare type.'))
- parser.add_argument(
- '--key',
- help=_('Key to compare.'
- ' Relevant for HEADER and COOKIE types only.'))
- parser.add_argument(
- '--value',
- required=is_create,
- help=_('Value to compare.'))
+ parser.add_argument(
+ '--type',
+ required=is_create,
+ type=utils.convert_to_uppercase,
+ choices=['HOST_NAME', 'PATH', 'FILE_TYPE', 'HEADER', 'COOKIE'],
+ help=_('Rule type.'))
+ parser.add_argument(
+ '--compare-type',
+ required=is_create,
+ type=utils.convert_to_uppercase,
+ choices=['REGEX', 'STARTS_WITH', 'ENDS_WITH',
+ 'CONTAINS', 'EQUAL_TO'],
+ help=_('Rule compare type.'))
+ parser.add_argument(
+ '--invert-compare',
+ dest='invert',
+ action='store_true',
+ help=_('Invert the compare type.'))
+ parser.add_argument(
+ '--key',
+ help=_('Key to compare.'
+ ' Relevant for HEADER and COOKIE types only.'))
+ parser.add_argument(
+ '--value',
+ required=is_create,
+ help=_('Value to compare.'))
def _common_args2body(client, parsed_args, is_create=True):
diff --git a/neutronclient/neutron/v2_0/lb/v2/listener.py b/neutronclient/neutron/v2_0/lb/v2/listener.py
index 1adac9789..481943e6b 100644
--- a/neutronclient/neutron/v2_0/lb/v2/listener.py
+++ b/neutronclient/neutron/v2_0/lb/v2/listener.py
@@ -45,7 +45,8 @@ def _add_common_args(parser):
'--connection-limit',
type=int,
help=_('The maximum number of connections per second allowed for '
- 'the vip. Positive integer or -1 for unlimited (default).'))
+ 'the listener. Positive integer or -1 '
+ 'for unlimited (default).'))
parser.add_argument(
'--default-pool',
help=_('Default pool for the listener.'))
diff --git a/neutronclient/neutron/v2_0/lb/v2/loadbalancer.py b/neutronclient/neutron/v2_0/lb/v2/loadbalancer.py
index 8cc6dffb3..c40809fad 100644
--- a/neutronclient/neutron/v2_0/lb/v2/loadbalancer.py
+++ b/neutronclient/neutron/v2_0/lb/v2/loadbalancer.py
@@ -124,7 +124,6 @@ class RetrieveLoadBalancerStats(neutronV20.ShowCommand):
def take_action(self, parsed_args):
neutron_client = self.get_client()
- neutron_client.format = parsed_args.request_format
loadbalancer_id = neutronV20.find_resourceid_by_name_or_id(
self.get_client(), 'loadbalancer', parsed_args.id)
params = {}
diff --git a/neutronclient/neutron/v2_0/lb/v2/member.py b/neutronclient/neutron/v2_0/lb/v2/member.py
index aeae1cb28..ee3c090a9 100644
--- a/neutronclient/neutron/v2_0/lb/v2/member.py
+++ b/neutronclient/neutron/v2_0/lb/v2/member.py
@@ -15,8 +15,6 @@
# License for the specific language governing permissions and limitations
# under the License.
#
-import argparse
-
from neutronclient._i18n import _
from neutronclient.common import utils
from neutronclient.neutron import v2_0 as neutronV20
@@ -40,17 +38,16 @@ def add_known_arguments(self, parser):
def _add_common_args(parser):
- parser.add_argument(
- '--name',
- help=_('Name of the member.'))
- parser.add_argument(
- '--weight',
- help=_('Weight of the member in the pool (default:1, [0..256]).'))
+ parser.add_argument(
+ '--name',
+ help=_('Name of the member.'))
+ parser.add_argument(
+ '--weight',
+ help=_('Weight of the member in the pool (default:1, [0..256]).'))
def _parse_common_args(body, parsed_args):
- neutronV20.update_dict(parsed_args, body,
- ['weight', 'name'])
+ neutronV20.update_dict(parsed_args, body, ['weight', 'name'])
class ListMember(LbaasMemberMixin, neutronV20.ListCommand):
@@ -128,27 +125,20 @@ class UpdateMember(neutronV20.UpdateCommand):
shadow_resource = 'lbaas_member'
def add_known_arguments(self, parser):
- parser.add_argument(
- '--admin-state-down',
- dest='admin_state', action='store_false',
- default=argparse.SUPPRESS,
- help=_('[DEPRECATED in Mitaka] Set admin state up to false.'))
parser.add_argument(
'pool', metavar='POOL',
help=_('ID or name of the pool that this member belongs to.'))
utils.add_boolean_argument(
parser, '--admin-state-up',
- dest='admin_state',
help=_('Update the administrative state of '
'the member (True meaning "Up").'))
- # ToDo(reedip): After Mitaka, remove admin-state-down
_add_common_args(parser)
def args2body(self, parsed_args):
self.parent_id = _get_pool_id(self.get_client(), parsed_args.pool)
body = {}
- if hasattr(parsed_args, 'admin_state'):
- body['admin_state_up'] = parsed_args.admin_state
+ if hasattr(parsed_args, "admin_state_up"):
+ body['admin_state_up'] = parsed_args.admin_state_up
_parse_common_args(body, parsed_args)
return {self.resource: body}
diff --git a/neutronclient/neutron/v2_0/lb/v2/pool.py b/neutronclient/neutron/v2_0/lb/v2/pool.py
index b2bd326a9..0af383970 100644
--- a/neutronclient/neutron/v2_0/lb/v2/pool.py
+++ b/neutronclient/neutron/v2_0/lb/v2/pool.py
@@ -39,7 +39,7 @@ def _get_listener_id(client, listener_id_or_name):
client, 'listener', listener_id_or_name)
-def _add_common_args(parser):
+def _add_common_args(parser, is_create=True):
parser.add_argument(
'--description',
help=_('Description of the pool.'))
@@ -47,7 +47,7 @@ def _add_common_args(parser):
'--name', help=_('The name of the pool.'))
parser.add_argument(
'--lb-algorithm',
- required=True,
+ required=is_create,
type=utils.convert_to_uppercase,
choices=['ROUND_ROBIN', 'LEAST_CONNECTIONS', 'SOURCE_IP'],
help=_('The algorithm used to distribute load between the members '
@@ -57,8 +57,7 @@ def _add_common_args(parser):
def _parse_common_args(parsed_args):
body = {}
neutronV20.update_dict(parsed_args,
- body, ['description', 'lb_algorithm', 'name',
- 'session_persistence'])
+ body, ['description', 'lb_algorithm', 'name'])
return body
@@ -67,7 +66,7 @@ class ListPool(neutronV20.ListCommand):
resource = 'pool'
shadow_resource = 'lbaas_pool'
- list_columns = ['id', 'name', 'lb_method', 'protocol',
+ list_columns = ['id', 'name', 'lb_algorithm', 'protocol',
'admin_state_up']
pagination_support = True
sorting_support = True
@@ -142,7 +141,8 @@ def args2body(self, parsed_args):
body['loadbalancer_id'] = loadbalancer_id
body['admin_state_up'] = parsed_args.admin_state
neutronV20.update_dict(parsed_args, body,
- ['tenant_id', 'protocol'])
+ ['tenant_id', 'protocol',
+ 'session_persistence'])
return {self.resource: body}
@@ -157,17 +157,26 @@ def add_known_arguments(self, parser):
parser, '--admin-state-up',
help=_('Update the administrative state of '
'the pool (True meaning "Up").'))
- parser.add_argument(
+ session_group = parser.add_mutually_exclusive_group()
+ session_group.add_argument(
'--session-persistence',
metavar='type=TYPE[,cookie_name=COOKIE_NAME]',
type=utils.str2dict_type(required_keys=['type'],
optional_keys=['cookie_name']),
help=_('The type of session persistence to use and associated '
'cookie name.'))
- _add_common_args(parser)
+ session_group.add_argument(
+ '--no-session-persistence',
+ action='store_true',
+ help=_('Clear session persistence for the pool.'))
+ _add_common_args(parser, False)
def args2body(self, parsed_args):
body = _parse_common_args(parsed_args)
+ if parsed_args.no_session_persistence:
+ body['session_persistence'] = None
+ elif parsed_args.session_persistence:
+ body['session_persistence'] = parsed_args.session_persistence
neutronV20.update_dict(parsed_args, body,
['admin_state_up'])
return {self.resource: body}
diff --git a/neutronclient/neutron/v2_0/metering.py b/neutronclient/neutron/v2_0/metering.py
index df81724fc..8f6d2174e 100644
--- a/neutronclient/neutron/v2_0/metering.py
+++ b/neutronclient/neutron/v2_0/metering.py
@@ -13,6 +13,7 @@
# under the License.
from neutronclient._i18n import _
+from neutronclient.common import utils
from neutronclient.neutron import v2_0 as neutronv20
@@ -76,6 +77,7 @@ class ShowMeteringLabelRule(neutronv20.ShowCommand):
"""Show information of a given metering label rule."""
resource = 'metering_label_rule'
+ allow_names = False
class CreateMeteringLabelRule(neutronv20.CreateCommand):
@@ -93,6 +95,7 @@ def add_known_arguments(self, parser):
parser.add_argument(
'--direction',
default='ingress', choices=['ingress', 'egress'],
+ type=utils.convert_to_lowercase,
help=_('Direction of traffic, default: ingress.'))
parser.add_argument(
'--excluded',
@@ -115,3 +118,4 @@ class DeleteMeteringLabelRule(neutronv20.DeleteCommand):
"""Delete a given metering label."""
resource = 'metering_label_rule'
+ allow_names = False
diff --git a/neutronclient/neutron/v2_0/network.py b/neutronclient/neutron/v2_0/network.py
index 7a89f5a23..6c68b623a 100644
--- a/neutronclient/neutron/v2_0/network.py
+++ b/neutronclient/neutron/v2_0/network.py
@@ -33,12 +33,20 @@ def _format_subnets(network):
return ''
+def args2body_common(body, parsed_args):
+ neutronV20.update_dict(parsed_args, body,
+ ['name', 'description'])
+
+
class ListNetwork(neutronV20.ListCommand):
"""List networks that belong to a given tenant."""
# Length of a query filter on subnet id
# id=& (with len(uuid)=36)
subnet_id_filter_len = 40
+ # Length of a marker in pagination
+ # &marker= (with len(uuid)=36)
+ marker_len = 44
resource = 'network'
_formatters = {'subnets': _format_subnets, }
list_columns = ['id', 'name', 'subnets']
@@ -110,6 +118,8 @@ def _get_subnet_list(sub_ids):
subnet_count = len(subnet_ids)
max_size = ((self.subnet_id_filter_len * subnet_count) -
uri_len_exc.excess)
+ if self.pagination_support:
+ max_size -= self.marker_len
chunk_size = max_size // self.subnet_id_filter_len
subnets = []
for i in range(0, subnet_count, chunk_size):
@@ -193,8 +203,8 @@ def add_known_arguments(self, parser):
dns.add_dns_argument_create(parser, self.resource, 'domain')
def args2body(self, parsed_args):
- body = {'name': parsed_args.name,
- 'admin_state_up': parsed_args.admin_state}
+ body = {'admin_state_up': parsed_args.admin_state}
+ args2body_common(body, parsed_args)
neutronV20.update_dict(parsed_args, body,
['shared', 'tenant_id',
'vlan_transparent',
@@ -202,11 +212,9 @@ def args2body(self, parsed_args):
'provider:physical_network',
'provider:segmentation_id',
'description'])
-
self.args2body_qos_policy(parsed_args, body)
availability_zone.args2body_az_hint(parsed_args, body)
dns.args2body_dns_create(parsed_args, body, 'domain')
-
return {'network': body}
@@ -222,11 +230,18 @@ class UpdateNetwork(neutronV20.UpdateCommand, qos_policy.UpdateQosPolicyMixin):
resource = 'network'
def add_known_arguments(self, parser):
+ parser.add_argument(
+ '--name',
+ help=_('Name of the network.'))
+ parser.add_argument(
+ '--description',
+ help=_('Description of this network.'))
self.add_arguments_qos_policy(parser)
dns.add_dns_argument_update(parser, self.resource, 'domain')
def args2body(self, parsed_args):
body = {}
+ args2body_common(body, parsed_args)
self.args2body_qos_policy(parsed_args, body)
dns.args2body_dns_update(parsed_args, body, 'domain')
return {'network': body}
diff --git a/neutronclient/neutron/v2_0/network_ip_availability.py b/neutronclient/neutron/v2_0/network_ip_availability.py
index d1332a21c..ba7af8f80 100644
--- a/neutronclient/neutron/v2_0/network_ip_availability.py
+++ b/neutronclient/neutron/v2_0/network_ip_availability.py
@@ -12,7 +12,6 @@
#
from cliff import show
-import six
from neutronclient._i18n import _
from neutronclient.neutron import v2_0 as neutronV20
@@ -68,6 +67,6 @@ def take_action(self, parsed_args):
self.format_output_data(data)
resource = data[self.resource]
if self.resource in data:
- return zip(*sorted(six.iteritems(resource)))
+ return zip(*sorted(resource.items()))
else:
return None
diff --git a/neutronclient/neutron/v2_0/port.py b/neutronclient/neutron/v2_0/port.py
index b279cf601..3fe73544b 100644
--- a/neutronclient/neutron/v2_0/port.py
+++ b/neutronclient/neutron/v2_0/port.py
@@ -33,13 +33,6 @@ def _format_fixed_ips(port):
return ''
-def _format_fixed_ips_csv(port):
- try:
- return jsonutils.dumps(port['fixed_ips'])
- except (TypeError, KeyError):
- return ''
-
-
def _add_updatable_args(parser):
parser.add_argument(
'--name',
@@ -94,7 +87,6 @@ class ListPort(neutronV20.ListCommand):
resource = 'port'
_formatters = {'fixed_ips': _format_fixed_ips, }
- _formatters_csv = {'fixed_ips': _format_fixed_ips_csv, }
list_columns = ['id', 'name', 'mac_address', 'fixed_ips']
pagination_support = True
sorting_support = True
@@ -203,7 +195,7 @@ def add_arguments_allowedaddresspairs(self, parser):
group_aap = parser.add_mutually_exclusive_group()
group_aap.add_argument(
'--allowed-address-pair',
- metavar='ip_address=IP_ADDR[,mac_address=MAC_ADDR]',
+ metavar='ip_address=IP_ADDR|CIDR[,mac_address=MAC_ADDR]',
default=[],
action='append',
dest='allowed_address_pairs',
@@ -211,6 +203,9 @@ def add_arguments_allowedaddresspairs(self, parser):
required_keys=['ip_address'],
optional_keys=['mac_address']),
help=_('Allowed address pair associated with the port. '
+ '"ip_address" parameter is required. IP address or '
+ 'CIDR can be specified for "ip_address". '
+ '"mac_address" parameter is optional. '
'You can repeat this option.'))
group_aap.add_argument(
'--no-allowed-address-pairs',
@@ -250,14 +245,16 @@ def add_known_arguments(self, parser):
parser.add_argument(
'--vnic-type',
metavar='',
+ '| normal | baremetal | smart-nic>',
choices=['direct', 'direct-physical', 'macvtap',
- 'normal', 'baremetal'],
+ 'normal', 'baremetal', 'smart-nic'],
+ type=utils.convert_to_lowercase,
help=_('VNIC type for this port.'))
parser.add_argument(
'--vnic_type',
choices=['direct', 'direct-physical', 'macvtap',
- 'normal', 'baremetal'],
+ 'normal', 'baremetal', 'smart-nic'],
+ type=utils.convert_to_lowercase,
help=argparse.SUPPRESS)
parser.add_argument(
'--binding-profile',
diff --git a/neutronclient/neutron/v2_0/qos/bandwidth_limit_rule.py b/neutronclient/neutron/v2_0/qos/bandwidth_limit_rule.py
index 1cb36cd8e..27e7b626a 100644
--- a/neutronclient/neutron/v2_0/qos/bandwidth_limit_rule.py
+++ b/neutronclient/neutron/v2_0/qos/bandwidth_limit_rule.py
@@ -27,18 +27,18 @@
def add_bandwidth_limit_arguments(parser):
parser.add_argument(
'--max-kbps',
- help=_('max bandwidth in kbps.'))
+ help=_('Maximum bandwidth in kbps.'))
parser.add_argument(
'--max-burst-kbps',
- help=_('max burst bandwidth in kbps.'))
+ help=_('Maximum burst bandwidth in kbps.'))
def update_bandwidth_limit_args2body(parsed_args, body):
max_kbps = parsed_args.max_kbps
max_burst_kbps = parsed_args.max_burst_kbps
if not (max_kbps or max_burst_kbps):
- raise exceptions.CommandError(_("Must provide max_kbps"
- " or max_burst_kbps option."))
+ raise exceptions.CommandError(_("Must provide max-kbps"
+ " or max-burst-kbps option."))
neutronv20.update_dict(parsed_args, body,
['max_kbps', 'max_burst_kbps', 'tenant_id'])
diff --git a/neutronclient/neutron/v2_0/qos/minimum_bandwidth_rule.py b/neutronclient/neutron/v2_0/qos/minimum_bandwidth_rule.py
new file mode 100644
index 000000000..0dda0fb3d
--- /dev/null
+++ b/neutronclient/neutron/v2_0/qos/minimum_bandwidth_rule.py
@@ -0,0 +1,111 @@
+# Copyright (c) 2016 Intel Corporation.
+# All Rights Reserved
+#
+# Licensed under the Apache License, Version 2.0 (the "License"); you may
+# not use this file except in compliance with the License. You may obtain
+# a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+# License for the specific language governing permissions and limitations
+# under the License.
+#
+
+from neutronclient._i18n import _
+from neutronclient.common import utils
+from neutronclient.neutron import v2_0 as neutronv20
+from neutronclient.neutron.v2_0.qos import rule as qos_rule
+
+
+MINIMUM_BANDWIDTH_RULE_RESOURCE = 'minimum_bandwidth_rule'
+
+
+def add_minimum_bandwidth_arguments(parser):
+ parser.add_argument(
+ '--min-kbps',
+ required=True,
+ type=str,
+ help=_('QoS minimum bandwidth assurance, expressed in kilobits '
+ 'per second.'))
+ # NOTE(ralonsoh): the only direction implemented is "egress". Please,
+ # refer to the spec (https://review.opendev.org/#/c/316082/).
+ parser.add_argument(
+ '--direction',
+ # NOTE(ihrachys): though server picks the default for us (egress), it's
+ # better to require the argument to make the UI more explicit and the
+ # intentions more clear in the future when we add other values for the
+ # attribute on server side.
+ required=True,
+ type=utils.convert_to_lowercase,
+ choices=['egress'],
+ help=_('Traffic direction.'))
+
+
+def update_minimum_bandwidth_args2body(parsed_args, body):
+ neutronv20.update_dict(parsed_args, body, ['min_kbps', 'direction'])
+
+
+class CreateQoSMinimumBandwidthRule(qos_rule.QosRuleMixin,
+ neutronv20.CreateCommand):
+ """Create a qos minimum bandwidth rule."""
+
+ resource = MINIMUM_BANDWIDTH_RULE_RESOURCE
+
+ def add_known_arguments(self, parser):
+ super(CreateQoSMinimumBandwidthRule, self).add_known_arguments(
+ parser)
+ add_minimum_bandwidth_arguments(parser)
+
+ def args2body(self, parsed_args):
+ body = {}
+ update_minimum_bandwidth_args2body(parsed_args, body)
+ return {self.resource: body}
+
+
+class ListQoSMinimumBandwidthRules(qos_rule.QosRuleMixin,
+ neutronv20.ListCommand):
+ """List all qos minimum bandwidth rules belonging to the specified policy.
+
+ """
+
+ resource = MINIMUM_BANDWIDTH_RULE_RESOURCE
+ _formatters = {}
+ pagination_support = True
+ sorting_support = True
+
+
+class ShowQoSMinimumBandwidthRule(qos_rule.QosRuleMixin,
+ neutronv20.ShowCommand):
+ """Show information about the given qos minimum bandwidth rule."""
+
+ resource = MINIMUM_BANDWIDTH_RULE_RESOURCE
+ allow_names = False
+
+
+class UpdateQoSMinimumBandwidthRule(qos_rule.QosRuleMixin,
+ neutronv20.UpdateCommand):
+ """Update the given qos minimum bandwidth rule."""
+
+ resource = MINIMUM_BANDWIDTH_RULE_RESOURCE
+ allow_names = False
+
+ def add_known_arguments(self, parser):
+ super(UpdateQoSMinimumBandwidthRule, self).add_known_arguments(
+ parser)
+ add_minimum_bandwidth_arguments(parser)
+
+ def args2body(self, parsed_args):
+ body = {}
+ update_minimum_bandwidth_args2body(parsed_args, body)
+ return {self.resource: body}
+
+
+class DeleteQoSMinimumBandwidthRule(qos_rule.QosRuleMixin,
+ neutronv20.DeleteCommand):
+ """Delete a given qos minimum bandwidth rule."""
+
+ resource = MINIMUM_BANDWIDTH_RULE_RESOURCE
+ allow_names = False
diff --git a/neutronclient/neutron/v2_0/quota.py b/neutronclient/neutron/v2_0/quota.py
index 061f87371..a55e29f6d 100644
--- a/neutronclient/neutron/v2_0/quota.py
+++ b/neutronclient/neutron/v2_0/quota.py
@@ -14,15 +14,12 @@
# under the License.
#
-from __future__ import print_function
-
import abc
import argparse
from cliff import lister
from cliff import show
from oslo_serialization import jsonutils
-import six
from neutronclient._i18n import _
from neutronclient.common import exceptions
@@ -88,7 +85,7 @@ def take_action(self, parsed_args):
info = data[collection]
_columns = len(info) > 0 and sorted(info[0].keys()) or []
return (_columns, (utils.get_item_properties(s, _columns)
- for s in info))
+ for s in info))
class ShowQuotaBase(neutronV20.NeutronCommand, show.ShowOne):
@@ -121,7 +118,7 @@ def take_action(self, parsed_args):
tenant_id = get_tenant_id(parsed_args, neutron_client)
data = self.retrieve_data(tenant_id, neutron_client)
if self.resource in data:
- return zip(*sorted(six.iteritems(data[self.resource])))
+ return zip(*sorted(data[self.resource].items()))
return
@@ -140,7 +137,7 @@ def retrieve_data(self, tenant_id, neutron_client):
class UpdateQuota(neutronV20.NeutronCommand, show.ShowOne):
- """Define tenant's quotas not to use defaults."""
+ """Update a given tenant's quotas."""
resource = 'quota'
@@ -184,7 +181,17 @@ def get_parser(self, prog_name):
help=_('The limit of pool members.'))
parser.add_argument(
'--health-monitor', metavar='health_monitors',
+ dest='healthmonitor',
help=_('The limit of health monitors.'))
+ parser.add_argument(
+ '--loadbalancer', metavar='loadbalancers',
+ help=_('The limit of load balancers.'))
+ parser.add_argument(
+ '--listener', metavar='listeners',
+ help=_('The limit of listeners.'))
+ parser.add_argument(
+ '--rbac-policy', metavar='rbac_policies',
+ help=_('The limit of RBAC policies.'))
parser.add_argument(
'pos_tenant_id',
help=argparse.SUPPRESS, nargs='?')
@@ -197,18 +204,23 @@ def _validate_int(self, name, value):
except Exception:
message = (_('Quota limit for %(name)s must be an integer') %
{'name': name})
- raise exceptions.NeutronClientException(message=message)
+ raise exceptions.CommandError(message=message)
return return_value
def args2body(self, parsed_args):
quota = {}
for resource in ('network', 'subnet', 'port', 'router', 'floatingip',
'security_group', 'security_group_rule',
- 'vip', 'pool', 'member', 'health_monitor'):
+ 'vip', 'pool', 'member', 'healthmonitor',
+ 'loadbalancer', 'listener', 'rbac_policy'):
if getattr(parsed_args, resource):
quota[resource] = self._validate_int(
resource,
getattr(parsed_args, resource))
+ if not quota:
+ raise exceptions.CommandError(
+ message=_('Must specify a valid resource with new quota '
+ 'value'))
return {self.resource: quota}
def take_action(self, parsed_args):
@@ -226,7 +238,7 @@ def take_action(self, parsed_args):
tenant_id = get_tenant_id(parsed_args, neutron_client)
data = obj_updator(tenant_id, body)
if self.resource in data:
- for k, v in six.iteritems(data[self.resource]):
+ for k, v in data[self.resource].items():
if isinstance(v, list):
value = ""
for _item in v:
@@ -239,6 +251,6 @@ def take_action(self, parsed_args):
data[self.resource][k] = value
elif v is None:
data[self.resource][k] = ''
- return zip(*sorted(six.iteritems(data[self.resource])))
+ return zip(*sorted(data[self.resource].items()))
else:
return
diff --git a/neutronclient/neutron/v2_0/rbac.py b/neutronclient/neutron/v2_0/rbac.py
index 46f254af8..8b356d3ec 100644
--- a/neutronclient/neutron/v2_0/rbac.py
+++ b/neutronclient/neutron/v2_0/rbac.py
@@ -14,6 +14,7 @@
# under the License.
from neutronclient._i18n import _
+from neutronclient.common import utils
from neutronclient.neutron import v2_0 as neutronV20
# key=object_type: value={key=resource, value=cmd_resource}
@@ -66,19 +67,21 @@ def add_known_arguments(self, parser):
parser.add_argument(
'--type', choices=RBAC_OBJECTS.keys(),
required=True,
+ type=utils.convert_to_lowercase,
help=_('Type of the object that RBAC policy affects.'))
parser.add_argument(
'--target-tenant',
+ default='*',
help=_('ID of the tenant to which the RBAC '
'policy will be enforced.'))
parser.add_argument(
'--action', choices=['access_as_external', 'access_as_shared'],
+ type=utils.convert_to_lowercase,
required=True,
help=_('Action for the RBAC policy.'))
def args2body(self, parsed_args):
neutron_client = self.get_client()
- neutron_client.format = parsed_args.request_format
_object_id, _object_type = get_rbac_obj_params(neutron_client,
parsed_args.type,
parsed_args.name)
diff --git a/neutronclient/neutron/v2_0/router.py b/neutronclient/neutron/v2_0/router.py
index 200feee18..1f78cb85c 100644
--- a/neutronclient/neutron/v2_0/router.py
+++ b/neutronclient/neutron/v2_0/router.py
@@ -14,8 +14,6 @@
# under the License.
#
-from __future__ import print_function
-
import argparse
from oslo_serialization import jsonutils
@@ -71,6 +69,9 @@ def add_known_arguments(self, parser):
parser.add_argument(
'--description',
help=_('Description of router.'))
+ parser.add_argument(
+ '--flavor',
+ help=_('ID or name of flavor.'))
utils.add_boolean_argument(
parser, '--distributed', dest='distributed',
help=_('Create a distributed router.'))
@@ -82,6 +83,10 @@ def add_known_arguments(self, parser):
def args2body(self, parsed_args):
body = {'admin_state_up': parsed_args.admin_state}
+ if parsed_args.flavor:
+ _flavor_id = neutronV20.find_resourceid_by_name_or_id(
+ self.get_client(), 'flavor', parsed_args.flavor)
+ body['flavor_id'] = _flavor_id
neutronV20.update_dict(parsed_args, body,
['name', 'tenant_id', 'distributed', 'ha',
'description'])
@@ -175,7 +180,7 @@ def take_action(self, parsed_args):
resource, value = parsed_args.interface.split('=', 1)
if resource not in ['subnet', 'port']:
exceptions.CommandError(_('You must specify either subnet or '
- 'port for INTERFACE parameter.'))
+ 'port for INTERFACE parameter.'))
else:
resource = 'subnet'
value = parsed_args.interface
@@ -227,6 +232,9 @@ def get_parser(self, prog_name):
parser.add_argument(
'external_network', metavar='EXTERNAL-NETWORK',
help=_('ID or name of the external network for the gateway.'))
+ parser.add_argument(
+ '--enable-snat', action='store_true',
+ help=_('Enable source NAT on the router gateway.'))
parser.add_argument(
'--disable-snat', action='store_true',
help=_('Disable source NAT on the router gateway.'))
@@ -249,6 +257,8 @@ def take_action(self, parsed_args):
_ext_net_id = neutronV20.find_resourceid_by_name_or_id(
neutron_client, 'network', parsed_args.external_network)
router_dict = {'network_id': _ext_net_id}
+ if parsed_args.enable_snat:
+ router_dict['enable_snat'] = True
if parsed_args.disable_snat:
router_dict['enable_snat'] = False
if parsed_args.fixed_ip:
diff --git a/neutronclient/neutron/v2_0/securitygroup.py b/neutronclient/neutron/v2_0/securitygroup.py
index 8cb89ac1c..3c0bafa0e 100644
--- a/neutronclient/neutron/v2_0/securitygroup.py
+++ b/neutronclient/neutron/v2_0/securitygroup.py
@@ -18,6 +18,7 @@
from neutronclient._i18n import _
from neutronclient.common import exceptions
+from neutronclient.common import utils
from neutronclient.neutron import v2_0 as neutronV20
@@ -314,6 +315,7 @@ def add_known_arguments(self, parser):
'which the rule is added.'))
parser.add_argument(
'--direction',
+ type=utils.convert_to_lowercase,
default='ingress', choices=['ingress', 'egress'],
help=_('Direction of traffic: ingress/egress.'))
parser.add_argument(
@@ -321,6 +323,7 @@ def add_known_arguments(self, parser):
help=_('IPv4/IPv6'))
parser.add_argument(
'--protocol',
+ type=utils.convert_to_lowercase,
help=_('Protocol of packet. Allowed values are '
'[icmp, icmpv6, tcp, udp] and '
'integer representations [0-255].'))
diff --git a/neutronclient/neutron/v2_0/subnet.py b/neutronclient/neutron/v2_0/subnet.py
index 107b52543..633826422 100644
--- a/neutronclient/neutron/v2_0/subnet.py
+++ b/neutronclient/neutron/v2_0/subnet.py
@@ -184,10 +184,12 @@ def add_known_arguments(self, parser):
help=_('CIDR of subnet to create.'))
parser.add_argument(
'--ipv6-ra-mode',
+ type=utils.convert_to_lowercase,
choices=['dhcpv6-stateful', 'dhcpv6-stateless', 'slaac'],
help=_('IPv6 RA (Router Advertisement) mode.'))
parser.add_argument(
'--ipv6-address-mode',
+ type=utils.convert_to_lowercase,
choices=['dhcpv6-stateful', 'dhcpv6-stateless', 'slaac'],
help=_('IPv6 address mode.'))
parser.add_argument(
diff --git a/neutronclient/neutron/v2_0/subnetpool.py b/neutronclient/neutron/v2_0/subnetpool.py
index 7d83c1188..fdefc8a47 100644
--- a/neutronclient/neutron/v2_0/subnetpool.py
+++ b/neutronclient/neutron/v2_0/subnetpool.py
@@ -99,6 +99,7 @@ def add_known_arguments(self, parser):
def args2body(self, parsed_args):
body = {'prefixes': parsed_args.prefixes}
updatable_args2body(parsed_args, body)
+ neutronV20.update_dict(parsed_args, body, ['tenant_id'])
if parsed_args.shared:
body['shared'] = True
diff --git a/neutronclient/neutron/v2_0/tag.py b/neutronclient/neutron/v2_0/tag.py
index 774849cd8..ff59b74ec 100644
--- a/neutronclient/neutron/v2_0/tag.py
+++ b/neutronclient/neutron/v2_0/tag.py
@@ -16,7 +16,7 @@
# List of resources can be set tag
-TAG_RESOURCES = ['network']
+TAG_RESOURCES = ['network', 'subnet', 'port', 'router', 'subnetpool']
def _convert_resource_args(client, parsed_args):
@@ -50,6 +50,9 @@ def get_parser(self, prog_name):
def take_action(self, parsed_args):
client = self.get_client()
+ if not parsed_args.tag:
+ raise exceptions.CommandError(
+ _('Cannot add an empty value as tag'))
resource_type, resource_id = _convert_resource_args(client,
parsed_args)
client.add_tag(resource_type, resource_id, parsed_args.tag)
diff --git a/neutronclient/neutron/v2_0/vpn/ikepolicy.py b/neutronclient/neutron/v2_0/vpn/ikepolicy.py
index 2a5d91b3b..20a96aaea 100644
--- a/neutronclient/neutron/v2_0/vpn/ikepolicy.py
+++ b/neutronclient/neutron/v2_0/vpn/ikepolicy.py
@@ -14,12 +14,64 @@
# under the License.
#
+import argparse
+
from neutronclient._i18n import _
from neutronclient.common import utils
from neutronclient.neutron import v2_0 as neutronv20
from neutronclient.neutron.v2_0.vpn import utils as vpn_utils
+def add_common_args(parser, is_create=True):
+ parser.add_argument(
+ '--description',
+ help=_('Description of the IKE policy.'))
+ parser.add_argument(
+ '--auth-algorithm',
+ type=utils.convert_to_lowercase,
+ default='sha1' if is_create else argparse.SUPPRESS,
+ choices=['sha1', 'sha256', 'sha384', 'sha512'],
+ help=_('Authentication algorithm, default:sha1.'))
+ parser.add_argument(
+ '--encryption-algorithm',
+ default='aes-128' if is_create else argparse.SUPPRESS,
+ type=utils.convert_to_lowercase,
+ help=_('Encryption algorithm, default:aes-128.'))
+ parser.add_argument(
+ '--phase1-negotiation-mode',
+ default='main' if is_create else argparse.SUPPRESS,
+ choices=['main'],
+ type=utils.convert_to_lowercase,
+ help=_('IKE Phase1 negotiation mode, default:main.'))
+ parser.add_argument(
+ '--ike-version',
+ default='v1' if is_create else argparse.SUPPRESS,
+ choices=['v1', 'v2'],
+ type=utils.convert_to_lowercase,
+ help=_('IKE version for the policy, default:v1.'))
+ parser.add_argument(
+ '--pfs',
+ default='group5' if is_create else argparse.SUPPRESS,
+ type=utils.convert_to_lowercase,
+ help=_('Perfect Forward Secrecy, default:group5.'))
+ parser.add_argument(
+ '--lifetime',
+ metavar="units=UNITS,value=VALUE",
+ type=utils.str2dict_type(optional_keys=['units', 'value']),
+ help=vpn_utils.lifetime_help("IKE"))
+
+
+def parse_common_args2body(parsed_args, body):
+ neutronv20.update_dict(parsed_args, body,
+ ['auth_algorithm', 'encryption_algorithm',
+ 'phase1_negotiation_mode', 'ike_version',
+ 'pfs', 'name', 'description', 'tenant_id'])
+ if parsed_args.lifetime:
+ vpn_utils.validate_lifetime_dict(parsed_args.lifetime)
+ body['lifetime'] = parsed_args.lifetime
+ return body
+
+
class ListIKEPolicy(neutronv20.ListCommand):
"""List IKE policies that belong to a tenant."""
@@ -44,50 +96,13 @@ class CreateIKEPolicy(neutronv20.CreateCommand):
resource = 'ikepolicy'
def add_known_arguments(self, parser):
- parser.add_argument(
- '--description',
- help=_('Description of the IKE policy'))
- parser.add_argument(
- '--auth-algorithm',
- default='sha1', choices=['sha1', 'sha256'],
- help=_('Authentication algorithm in lowercase. '
- 'Default:sha1'))
- parser.add_argument(
- '--encryption-algorithm',
- default='aes-128',
- help=_('Encryption algorithm in lowercase, default:aes-128'))
- parser.add_argument(
- '--phase1-negotiation-mode',
- default='main', choices=['main'],
- help=_('IKE Phase1 negotiation mode in lowercase, default:main'))
- parser.add_argument(
- '--ike-version',
- default='v1', choices=['v1', 'v2'],
- help=_('IKE version in lowercase, default:v1'))
- parser.add_argument(
- '--pfs',
- default='group5', choices=['group2', 'group5', 'group14'],
- help=_('Perfect Forward Secrecy in lowercase, default:group5'))
- parser.add_argument(
- '--lifetime',
- metavar="units=UNITS,value=VALUE",
- type=utils.str2dict_type(optional_keys=['units', 'value']),
- help=vpn_utils.lifetime_help("IKE"))
parser.add_argument(
'name', metavar='NAME',
help=_('Name of the IKE policy.'))
+ add_common_args(parser)
def args2body(self, parsed_args):
-
- body = {}
- neutronv20.update_dict(parsed_args, body,
- ['auth_algorithm', 'encryption_algorithm',
- 'phase1_negotiation_mode', 'ike_version',
- 'pfs', 'name', 'description', 'tenant_id'])
- if parsed_args.lifetime:
- vpn_utils.validate_lifetime_dict(parsed_args.lifetime)
- body['lifetime'] = parsed_args.lifetime
- return {'ikepolicy': body}
+ return {'ikepolicy': parse_common_args2body(parsed_args, body={})}
class UpdateIKEPolicy(neutronv20.UpdateCommand):
@@ -98,18 +113,12 @@ class UpdateIKEPolicy(neutronv20.UpdateCommand):
def add_known_arguments(self, parser):
parser.add_argument(
- '--lifetime',
- metavar="units=UNITS,value=VALUE",
- type=utils.str2dict_type(optional_keys=['units', 'value']),
- help=vpn_utils.lifetime_help("IKE"))
+ '--name',
+ help=_('Updated name of the IKE policy.'))
+ add_common_args(parser, is_create=False)
def args2body(self, parsed_args):
-
- body = {}
- if parsed_args.lifetime:
- vpn_utils.validate_lifetime_dict(parsed_args.lifetime)
- body['lifetime'] = parsed_args.lifetime
- return {'ikepolicy': body}
+ return {'ikepolicy': parse_common_args2body(parsed_args, body={})}
class DeleteIKEPolicy(neutronv20.DeleteCommand):
diff --git a/neutronclient/neutron/v2_0/vpn/ipsec_site_connection.py b/neutronclient/neutron/v2_0/vpn/ipsec_site_connection.py
index 503d90163..03a635f6e 100644
--- a/neutronclient/neutron/v2_0/vpn/ipsec_site_connection.py
+++ b/neutronclient/neutron/v2_0/vpn/ipsec_site_connection.py
@@ -14,6 +14,8 @@
# under the License.
#
+import argparse
+
from oslo_serialization import jsonutils
from neutronclient._i18n import _
@@ -51,7 +53,13 @@ class ShowIPsecSiteConnection(neutronv20.ShowCommand):
class IPsecSiteConnectionMixin(object):
- def add_known_arguments(self, parser):
+ def add_known_arguments(self, parser, is_create=True):
+ parser.add_argument(
+ '--name',
+ help=_('Set friendly name for the connection.'))
+ parser.add_argument(
+ '--description',
+ help=_('Set a description for the connection.'))
parser.add_argument(
'--dpd',
metavar="action=ACTION,interval=INTERVAL,timeout=TIMEOUT",
@@ -61,11 +69,39 @@ def add_known_arguments(self, parser):
parser.add_argument(
'--local-ep-group',
help=_('Local endpoint group ID/name with subnet(s) for '
- 'the IPsec connection.'))
+ 'IPSec connection.'))
parser.add_argument(
'--peer-ep-group',
help=_('Peer endpoint group ID/name with CIDR(s) for '
- 'the IPsec connection.'))
+ 'IPSec connection.'))
+ parser.add_argument(
+ '--peer-cidr',
+ action='append', dest='peer_cidrs',
+ help=_('[DEPRECATED in Mitaka] Remote subnet(s) in CIDR format. '
+ 'Cannot be specified when using endpoint groups. Only '
+ 'applicable, if subnet provided for VPN service.'))
+ parser.add_argument(
+ '--peer-id',
+ required=is_create,
+ help=_('Peer router identity for authentication. Can be '
+ 'IPv4/IPv6 address, e-mail address, key id, or FQDN.'))
+ parser.add_argument(
+ '--peer-address',
+ required=is_create,
+ help=_('Peer gateway public IPv4/IPv6 address or FQDN.'))
+ parser.add_argument(
+ '--psk',
+ required=is_create,
+ help=_('Pre-shared key string.'))
+ parser.add_argument(
+ '--mtu',
+ default='1500' if is_create else argparse.SUPPRESS,
+ help=_('MTU size for the connection, default:1500.'))
+ parser.add_argument(
+ '--initiator',
+ default='bi-directional' if is_create else argparse.SUPPRESS,
+ choices=['bi-directional', 'response-only'],
+ help=_('Initiator state in lowercase, default:bi-directional'))
def args2body(self, parsed_args, body=None):
"""Add in conditional args and then return all conn info."""
@@ -85,6 +121,19 @@ def args2body(self, parsed_args, body=None):
self.get_client(), 'endpoint_group',
parsed_args.peer_ep_group)
body['peer_ep_group_id'] = _peer_epg
+ if hasattr(parsed_args, 'mtu') and int(parsed_args.mtu) < 68:
+ message = _("Invalid MTU value: MTU must be "
+ "greater than or equal to 68.")
+ raise exceptions.CommandError(message)
+ # ToDo (Reedip) : Remove below check when peer-cidr is removed
+ if parsed_args.peer_cidrs and parsed_args.local_ep_group:
+ message = _("You cannot specify both endpoint groups and peer "
+ "CIDR(s).")
+ raise exceptions.CommandError(message)
+ neutronv20.update_dict(parsed_args, body,
+ ['peer_id', 'mtu', 'initiator', 'psk',
+ 'peer_address', 'name', 'description',
+ 'peer_cidrs'])
return {self.resource: body}
@@ -98,21 +147,6 @@ def add_known_arguments(self, parser):
'--admin-state-down',
default=True, action='store_false',
help=_('Set admin state up to false.'))
- parser.add_argument(
- '--name',
- help=_('Set a name for the connection.'))
- parser.add_argument(
- '--description',
- help=_('Set a description for the connection.'))
- parser.add_argument(
- '--mtu',
- default='1500',
- help=_('MTU size for the connection, default:1500'))
- parser.add_argument(
- '--initiator',
- default='bi-directional', choices=['bi-directional',
- 'response-only'],
- help=_('Initiator state in lowercase, default:bi-directional'))
parser.add_argument(
'--vpnservice-id', metavar='VPNSERVICE',
required=True,
@@ -125,25 +159,6 @@ def add_known_arguments(self, parser):
'--ipsecpolicy-id', metavar='IPSECPOLICY',
required=True,
help=_('IPsec policy ID associated with this connection.'))
- parser.add_argument(
- '--peer-address',
- required=True,
- help=_('Peer gateway public IPv4/IPv6 address or FQDN.'))
- parser.add_argument(
- '--peer-id',
- required=True,
- help=_('Peer router identity for authentication. Can be '
- 'IPv4/IPv6 address, e-mail address, key id, or FQDN.'))
- parser.add_argument(
- '--peer-cidr',
- action='append', dest='peer_cidrs',
- help=_('[DEPRECATED in Mitaka] Remote subnet(s) in CIDR format. '
- 'Cannot be specified when using endpoint groups. Only '
- 'applicable, if subnet provided for VPN service.'))
- parser.add_argument(
- '--psk',
- required=True,
- help=_('Pre-shared key string.'))
super(CreateIPsecSiteConnection, self).add_known_arguments(parser)
def args2body(self, parsed_args):
@@ -156,39 +171,23 @@ def args2body(self, parsed_args):
_ipsecpolicy_id = neutronv20.find_resourceid_by_name_or_id(
self.get_client(), 'ipsecpolicy',
parsed_args.ipsecpolicy_id)
- if int(parsed_args.mtu) < 68:
- message = _("Invalid MTU value: MTU must be "
- "greater than or equal to 68")
- raise exceptions.CommandError(message)
- if (bool(parsed_args.local_ep_group) !=
- bool(parsed_args.peer_ep_group)):
- message = _("You must specify both local and peer endpoint "
- "groups.")
- raise exceptions.CommandError(message)
- if parsed_args.peer_cidrs and parsed_args.local_ep_group:
- message = _("You cannot specify both endpoint groups and peer "
- "CIDR(s).")
- raise exceptions.CommandError(message)
- if not parsed_args.peer_cidrs and not parsed_args.local_ep_group:
- message = _("You must specify endpoint groups or peer CIDR(s).")
- raise exceptions.CommandError(message)
body = {
'vpnservice_id': _vpnservice_id,
'ikepolicy_id': _ikepolicy_id,
'ipsecpolicy_id': _ipsecpolicy_id,
'admin_state_up': parsed_args.admin_state_down,
}
- neutronv20.update_dict(parsed_args, body,
- ['peer_id', 'mtu', 'initiator', 'psk',
- 'peer_address'])
- if parsed_args.name:
- body['name'] = parsed_args.name
- if parsed_args.description:
- body['description'] = parsed_args.description
if parsed_args.tenant_id:
body['tenant_id'] = parsed_args.tenant_id
- if parsed_args.peer_cidrs:
- body['peer_cidrs'] = parsed_args.peer_cidrs
+
+ if (bool(parsed_args.local_ep_group) !=
+ bool(parsed_args.peer_ep_group)):
+ message = _("You must specify both local and peer endpoint "
+ "groups.")
+ raise exceptions.CommandError(message)
+ if not parsed_args.peer_cidrs and not parsed_args.local_ep_group:
+ message = _("You must specify endpoint groups or peer CIDR(s).")
+ raise exceptions.CommandError(message)
return super(CreateIPsecSiteConnection, self).args2body(parsed_args,
body)
@@ -200,6 +199,19 @@ class UpdateIPsecSiteConnection(IPsecSiteConnectionMixin,
resource = 'ipsec_site_connection'
help_resource = 'IPsec site connection'
+ def add_known_arguments(self, parser):
+ utils.add_boolean_argument(
+ parser, '--admin-state-up',
+ help=_('Update the administrative state. (True meaning "Up")'))
+ super(UpdateIPsecSiteConnection, self).add_known_arguments(parser,
+ False)
+
+ def args2body(self, parsed_args):
+ body = {}
+ neutronv20.update_dict(parsed_args, body, ['admin_state_up'])
+ return super(UpdateIPsecSiteConnection, self).args2body(parsed_args,
+ body)
+
class DeleteIPsecSiteConnection(neutronv20.DeleteCommand):
"""Delete a given IPsec site connection."""
diff --git a/neutronclient/neutron/v2_0/vpn/ipsecpolicy.py b/neutronclient/neutron/v2_0/vpn/ipsecpolicy.py
index 5da45158e..ea70155b7 100644
--- a/neutronclient/neutron/v2_0/vpn/ipsecpolicy.py
+++ b/neutronclient/neutron/v2_0/vpn/ipsecpolicy.py
@@ -14,12 +14,64 @@
# under the License.
#
+import argparse
+
from neutronclient._i18n import _
from neutronclient.common import utils
from neutronclient.neutron import v2_0 as neutronv20
from neutronclient.neutron.v2_0.vpn import utils as vpn_utils
+def add_common_args(parser, is_create=True):
+ parser.add_argument(
+ '--auth-algorithm',
+ default='sha1' if is_create else argparse.SUPPRESS,
+ type=utils.convert_to_lowercase,
+ choices=['sha1', 'sha256', 'sha384', 'sha512'],
+ help=_('Authentication algorithm for IPsec policy, default:sha1.'))
+ parser.add_argument(
+ '--description',
+ help=_('Description of the IPsec policy.'))
+ parser.add_argument(
+ '--encapsulation-mode',
+ default='tunnel' if is_create else argparse.SUPPRESS,
+ choices=['tunnel', 'transport'],
+ type=utils.convert_to_lowercase,
+ help=_('Encapsulation mode for IPsec policy, default:tunnel.'))
+ parser.add_argument(
+ '--encryption-algorithm',
+ default='aes-128' if is_create else argparse.SUPPRESS,
+ type=utils.convert_to_lowercase,
+ help=_('Encryption algorithm for IPsec policy, default:aes-128.'))
+ parser.add_argument(
+ '--lifetime',
+ metavar="units=UNITS,value=VALUE",
+ type=utils.str2dict_type(optional_keys=['units', 'value']),
+ help=vpn_utils.lifetime_help("IPsec"))
+ parser.add_argument(
+ '--pfs',
+ default='group5' if is_create else argparse.SUPPRESS,
+ type=utils.convert_to_lowercase,
+ help=_('Perfect Forward Secrecy for IPsec policy, default:group5.'))
+ parser.add_argument(
+ '--transform-protocol',
+ default='esp' if is_create else argparse.SUPPRESS,
+ type=utils.convert_to_lowercase,
+ choices=['esp', 'ah', 'ah-esp'],
+ help=_('Transform protocol for IPsec policy, default:esp.'))
+
+
+def parse_common_args2body(parsed_args, body):
+ neutronv20.update_dict(parsed_args, body,
+ ['auth_algorithm', 'encryption_algorithm',
+ 'encapsulation_mode', 'transform_protocol',
+ 'pfs', 'name', 'description', 'tenant_id'])
+ if parsed_args.lifetime:
+ vpn_utils.validate_lifetime_dict(parsed_args.lifetime)
+ body['lifetime'] = parsed_args.lifetime
+ return body
+
+
class ListIPsecPolicy(neutronv20.ListCommand):
"""List IPsec policies that belong to a given tenant connection."""
@@ -42,51 +94,16 @@ class CreateIPsecPolicy(neutronv20.CreateCommand):
"""Create an IPsec policy."""
resource = 'ipsecpolicy'
+ help_resource = 'IPsec policy'
def add_known_arguments(self, parser):
- parser.add_argument(
- '--description',
- help=_('Description of the IPsec policy.'))
- parser.add_argument(
- '--transform-protocol',
- default='esp', choices=['esp', 'ah', 'ah-esp'],
- help=_('Transform protocol in lowercase, default:esp'))
- parser.add_argument(
- '--auth-algorithm',
- default='sha1', choices=['sha1', 'sha256'],
- help=_('Authentication algorithm in lowercase, default:sha1'))
- parser.add_argument(
- '--encryption-algorithm',
- default='aes-128',
- help=_('Encryption algorithm in lowercase, default:aes-128'))
- parser.add_argument(
- '--encapsulation-mode',
- default='tunnel', choices=['tunnel', 'transport'],
- help=_('Encapsulation mode in lowercase, default:tunnel'))
- parser.add_argument(
- '--pfs',
- default='group5', choices=['group2', 'group5', 'group14'],
- help=_('Perfect Forward Secrecy in lowercase, default:group5'))
- parser.add_argument(
- '--lifetime',
- metavar="units=UNITS,value=VALUE",
- type=utils.str2dict_type(optional_keys=['units', 'value']),
- help=vpn_utils.lifetime_help("IPsec"))
parser.add_argument(
'name', metavar='NAME',
help=_('Name of the IPsec policy.'))
+ add_common_args(parser)
def args2body(self, parsed_args):
-
- body = {}
- neutronv20.update_dict(parsed_args, body,
- ['auth_algorithm', 'encryption_algorithm',
- 'encapsulation_mode', 'transform_protocol',
- 'pfs', 'name', 'description', 'tenant_id'])
- if parsed_args.lifetime:
- vpn_utils.validate_lifetime_dict(parsed_args.lifetime)
- body['lifetime'] = parsed_args.lifetime
- return {'ipsecpolicy': body}
+ return {'ipsecpolicy': parse_common_args2body(parsed_args, body={})}
class UpdateIPsecPolicy(neutronv20.UpdateCommand):
@@ -97,18 +114,12 @@ class UpdateIPsecPolicy(neutronv20.UpdateCommand):
def add_known_arguments(self, parser):
parser.add_argument(
- '--lifetime',
- metavar="units=UNITS,value=VALUE",
- type=utils.str2dict_type(optional_keys=['units', 'value']),
- help=vpn_utils.lifetime_help("IPsec"))
+ '--name',
+ help=_('Updated name of the IPsec policy.'))
+ add_common_args(parser, is_create=False)
def args2body(self, parsed_args):
-
- body = {}
- if parsed_args.lifetime:
- vpn_utils.validate_lifetime_dict(parsed_args.lifetime)
- body['lifetime'] = parsed_args.lifetime
- return {'ipsecpolicy': body}
+ return {'ipsecpolicy': parse_common_args2body(parsed_args, body={})}
class DeleteIPsecPolicy(neutronv20.DeleteCommand):
diff --git a/neutronclient/neutron/v2_0/vpn/vpnservice.py b/neutronclient/neutron/v2_0/vpn/vpnservice.py
index 9e9ae1221..dae531408 100644
--- a/neutronclient/neutron/v2_0/vpn/vpnservice.py
+++ b/neutronclient/neutron/v2_0/vpn/vpnservice.py
@@ -15,9 +15,24 @@
#
from neutronclient._i18n import _
+from neutronclient.common import utils
from neutronclient.neutron import v2_0 as neutronv20
+def add_common_args(parser):
+ parser.add_argument(
+ '--name',
+ help=_('Name for the VPN service.'))
+ parser.add_argument(
+ '--description',
+ help=_('Description for the VPN service.'))
+
+
+def common_args2body(parsed_args, body):
+ neutronv20.update_dict(parsed_args, body,
+ ['name', 'description'])
+
+
class ListVPNService(neutronv20.ListCommand):
"""List VPN service configurations that belong to a given tenant."""
@@ -46,12 +61,6 @@ def add_known_arguments(self, parser):
'--admin-state-down',
dest='admin_state', action='store_false',
help=_('Set admin state up to false.'))
- parser.add_argument(
- '--name',
- help=_('Set a name for the VPN service.'))
- parser.add_argument(
- '--description',
- help=_('Set a description for the VPN service.'))
parser.add_argument(
'router', metavar='ROUTER',
help=_('Router unique identifier for the VPN service.'))
@@ -59,6 +68,7 @@ def add_known_arguments(self, parser):
'subnet', nargs='?', metavar='SUBNET',
help=_('[DEPRECATED in Mitaka] Unique identifier for the local '
'private subnet.'))
+ add_common_args(parser)
def args2body(self, parsed_args):
if parsed_args.subnet:
@@ -74,9 +84,8 @@ def args2body(self, parsed_args):
'router_id': _router_id,
'admin_state_up': parsed_args.admin_state}
neutronv20.update_dict(parsed_args, body,
- ['name', 'description',
- 'tenant_id'])
-
+ ['tenant_id'])
+ common_args2body(parsed_args, body)
return {self.resource: body}
@@ -86,6 +95,20 @@ class UpdateVPNService(neutronv20.UpdateCommand):
resource = 'vpnservice'
help_resource = 'VPN service'
+ def add_known_arguments(self, parser):
+ add_common_args(parser)
+ utils.add_boolean_argument(
+ parser, '--admin-state-up',
+ help=_('Update the admin state for the VPN Service.'
+ '(True means UP)'))
+
+ def args2body(self, parsed_args):
+ body = {}
+ common_args2body(parsed_args, body)
+ neutronv20.update_dict(parsed_args, body,
+ ['admin_state_up'])
+ return {self.resource: body}
+
class DeleteVPNService(neutronv20.DeleteCommand):
"""Delete a given VPN service."""
diff --git a/neutronclient/osc/plugin.py b/neutronclient/osc/plugin.py
index 1efb6c5f7..c98099f2a 100644
--- a/neutronclient/osc/plugin.py
+++ b/neutronclient/osc/plugin.py
@@ -11,11 +11,13 @@
# under the License.
#
+"""OpenStackClient plugin for advanced Networking service."""
+
import logging
# TODO(rtheis/amotoki): Add functional test infrastructure for OSC
# plugin commands.
-# TODO(amotoki): Add and update document on OSC pluign.
+# TODO(amotoki): Add and update document on OSC plugin.
from osc_lib import utils
@@ -46,10 +48,10 @@ def make_client(instance):
# - endpoint_type (do we need to specify it explicitly?)
# - auth (session object contains auth. Is it required?)
client = neutron_client(session=instance.session,
- region_name=instance._region_name,
- endpoint_type=instance._interface,
- insecure=instance._insecure,
- ca_cert=instance._cacert)
+ region_name=instance.region_name,
+ endpoint_type=instance.interface,
+ insecure=not instance.verify,
+ ca_cert=instance.cacert)
return client
diff --git a/neutronclient/osc/utils.py b/neutronclient/osc/utils.py
new file mode 100644
index 000000000..39b17b640
--- /dev/null
+++ b/neutronclient/osc/utils.py
@@ -0,0 +1,130 @@
+# Copyright 2016 NEC Corporation
+#
+# Licensed under the Apache License, Version 2.0 (the "License"); you may
+# not use this file except in compliance with the License. You may obtain
+# a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+# License for the specific language governing permissions and limitations
+# under the License.
+
+"""This module should contain OSC plugin generic methods.
+
+Methods in this module are candidates adopted to osc-lib.
+
+Stuffs specific to neutronclient OSC plugin should not be added
+to this module. They should go to neutronclient.osc.v2.utils.
+"""
+
+from keystoneclient import exceptions as identity_exc
+from keystoneclient.v3 import domains
+from keystoneclient.v3 import projects
+from osc_lib import utils
+
+from neutronclient._i18n import _
+
+
+# TODO(amotoki): Use osc-lib version once osc-lib provides this.
+def add_project_owner_option_to_parser(parser):
+ """Register project and project domain options.
+
+ :param parser: argparse.Argument parser object.
+
+ """
+ parser.add_argument(
+ '--project',
+ metavar='',
+ help=_("Owner's project (name or ID)")
+ )
+ # Borrowed from openstackclient.identity.common
+ # as it is not exposed officially.
+ parser.add_argument(
+ '--project-domain',
+ metavar='',
+ help=_('Domain the project belongs to (name or ID). '
+ 'This can be used in case collisions between project names '
+ 'exist.'),
+ )
+
+
+# The following methods are borrowed from openstackclient.identity.common
+# as it is not exposed officially.
+# TODO(amotoki): Use osc-lib version once osc-lib provides this.
+
+
+def find_domain(identity_client, name_or_id):
+ return _find_identity_resource(identity_client.domains, name_or_id,
+ domains.Domain)
+
+
+def find_project(identity_client, name_or_id, domain_name_or_id=None):
+ domain_id = _get_domain_id_if_requested(identity_client, domain_name_or_id)
+ if not domain_id:
+ return _find_identity_resource(identity_client.projects, name_or_id,
+ projects.Project)
+ else:
+ return _find_identity_resource(identity_client.projects, name_or_id,
+ projects.Project, domain_id=domain_id)
+
+
+def _get_domain_id_if_requested(identity_client, domain_name_or_id):
+ if not domain_name_or_id:
+ return None
+ domain = find_domain(identity_client, domain_name_or_id)
+ return domain.id
+
+
+def _find_identity_resource(identity_client_manager, name_or_id,
+ resource_type, **kwargs):
+ """Find a specific identity resource.
+
+ Using keystoneclient's manager, attempt to find a specific resource by its
+ name or ID. If Forbidden to find the resource (a common case if the user
+ does not have permission), then return the resource by creating a local
+ instance of keystoneclient's Resource.
+
+ The parameter identity_client_manager is a keystoneclient manager,
+ for example: keystoneclient.v3.users or keystoneclient.v3.projects.
+
+ The parameter resource_type is a keystoneclient resource, for example:
+ keystoneclient.v3.users.User or keystoneclient.v3.projects.Project.
+
+ :param identity_client_manager: the manager that contains the resource
+ :type identity_client_manager: `keystoneclient.base.CrudManager`
+ :param name_or_id: the resources's name or ID
+ :type name_or_id: string
+ :param resource_type: class that represents the resource type
+ :type resource_type: `keystoneclient.base.Resource`
+
+ :returns: the resource in question
+ :rtype: `keystoneclient.base.Resource`
+
+ """
+
+ try:
+ identity_resource = utils.find_resource(identity_client_manager,
+ name_or_id, **kwargs)
+ if identity_resource is not None:
+ return identity_resource
+ except identity_exc.Forbidden:
+ pass
+
+ return resource_type(None, {'id': name_or_id, 'name': name_or_id})
+
+
+# The above are borrowed from openstackclient.identity.common.
+# DO NOT ADD original methods in neutronclient repo to the above area.
+
+
+def _get_columns(item):
+ column_map = {}
+ hidden_columns = ['location', 'tenant_id']
+ return utils.get_osc_show_columns_for_sdk_resource(
+ item,
+ column_map,
+ hidden_columns
+ )
diff --git a/neutronclient/osc/v2/dynamic_routing/bgp_dragent.py b/neutronclient/osc/v2/dynamic_routing/bgp_dragent.py
new file mode 100644
index 000000000..91dc2a75b
--- /dev/null
+++ b/neutronclient/osc/v2/dynamic_routing/bgp_dragent.py
@@ -0,0 +1,112 @@
+# Licensed under the Apache License, Version 2.0 (the "License"); you may
+# not use this file except in compliance with the License. You may obtain
+# a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+# License for the specific language governing permissions and limitations
+# under the License.
+#
+
+from osc_lib.command import command
+from osc_lib import utils
+
+from neutronclient._i18n import _
+
+
+def _format_alive_state(item):
+ return ':-)' if item else 'XXX'
+
+
+_formatters = {
+ 'alive': _format_alive_state
+}
+
+
+def add_common_args(parser):
+ parser.add_argument('dragent_id',
+ metavar='',
+ help=_("ID of the dynamic routing agent"))
+ parser.add_argument('bgp_speaker',
+ metavar='',
+ help=_("ID or name of the BGP speaker"))
+
+
+class AddBgpSpeakerToDRAgent(command.Command):
+ """Add a BGP speaker to a dynamic routing agent"""
+
+ def get_parser(self, prog_name):
+ parser = super(AddBgpSpeakerToDRAgent, self).get_parser(prog_name)
+ add_common_args(parser)
+ return parser
+
+ def take_action(self, parsed_args):
+ client = self.app.client_manager.network
+ speaker_id = client.find_bgp_speaker(parsed_args.bgp_speaker).id
+ client.add_bgp_speaker_to_dragent(parsed_args.dragent_id, speaker_id)
+
+
+class RemoveBgpSpeakerFromDRAgent(command.Command):
+ """Removes a BGP speaker from a dynamic routing agent"""
+
+ def get_parser(self, prog_name):
+ parser = super(RemoveBgpSpeakerFromDRAgent, self).get_parser(
+ prog_name)
+ add_common_args(parser)
+ return parser
+
+ def take_action(self, parsed_args):
+ client = self.app.client_manager.network
+ speaker_id = client.find_bgp_speaker(parsed_args.bgp_speaker).id
+ client.remove_bgp_speaker_from_dragent(parsed_args.dragent_id,
+ speaker_id)
+
+
+class ListDRAgent(command.Lister):
+ """List dynamic routing agents"""
+
+ resource = 'agent'
+ list_columns = ['id', 'host', 'admin_state_up', 'alive']
+ unknown_parts_flag = False
+
+ def get_parser(self, prog_name):
+ parser = super(ListDRAgent,
+ self).get_parser(prog_name)
+ parser.add_argument('--bgp-speaker',
+ metavar='',
+ help=_("List dynamic routing agents hosting a "
+ "BGP speaker (name or ID)"))
+ return parser
+
+ def take_action(self, parsed_args):
+ client = self.app.client_manager.network
+ if parsed_args.bgp_speaker is not None:
+ speaker_id = client.find_bgp_speaker(parsed_args.bgp_speaker).id
+ data = client.get_bgp_dragents_hosting_speaker(speaker_id)
+ else:
+ attrs = {'agent_type': 'BGP dynamic routing agent'}
+ data = client.agents(**attrs)
+ columns = (
+ 'id',
+ 'agent_type',
+ 'host',
+ 'availability_zone',
+ 'is_alive',
+ 'is_admin_state_up',
+ 'binary'
+ )
+ column_headers = (
+ 'ID',
+ 'Agent Type',
+ 'Host',
+ 'Availability Zone',
+ 'Alive',
+ 'State',
+ 'Binary'
+ )
+ return (column_headers,
+ (utils.get_item_properties(
+ s, columns,) for s in data))
diff --git a/neutronclient/osc/v2/dynamic_routing/bgp_peer.py b/neutronclient/osc/v2/dynamic_routing/bgp_peer.py
new file mode 100644
index 000000000..0610a3ac0
--- /dev/null
+++ b/neutronclient/osc/v2/dynamic_routing/bgp_peer.py
@@ -0,0 +1,181 @@
+# Licensed under the Apache License, Version 2.0 (the "License"); you may
+# not use this file except in compliance with the License. You may obtain
+# a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+# License for the specific language governing permissions and limitations
+# under the License.
+#
+
+from osc_lib.command import command
+from osc_lib import utils
+
+from neutronclient._i18n import _
+from neutronclient.common import exceptions
+from neutronclient.common import utils as nc_utils
+from neutronclient.osc import utils as nc_osc_utils
+from neutronclient.osc.v2.dynamic_routing import constants
+
+
+def _get_attrs(client_manager, parsed_args):
+ attrs = {}
+
+ # Validate password
+ if 'auth_type' in parsed_args:
+ if parsed_args.auth_type != 'none':
+ if 'password' not in parsed_args or parsed_args.password is None:
+ raise exceptions.CommandError(_('Must provide password if '
+ 'auth-type is specified.'))
+ if (
+ parsed_args.auth_type == 'none' and
+ parsed_args.password is not None
+ ):
+ raise exceptions.CommandError(_('Must provide auth-type if '
+ 'password is specified.'))
+ attrs['auth_type'] = parsed_args.auth_type
+
+ if parsed_args.name is not None:
+ attrs['name'] = parsed_args.name
+ if 'remote_as' in parsed_args:
+ attrs['remote_as'] = parsed_args.remote_as
+ if 'peer_ip' in parsed_args:
+ attrs['peer_ip'] = parsed_args.peer_ip
+ if 'password' in parsed_args:
+ attrs['password'] = parsed_args.password
+
+ if 'project' in parsed_args and parsed_args.project is not None:
+ identity_client = client_manager.identity
+ project_id = nc_osc_utils.find_project(
+ identity_client,
+ parsed_args.project,
+ parsed_args.project_domain,
+ ).id
+ attrs['tenant_id'] = project_id
+ return attrs
+
+
+class CreateBgpPeer(command.ShowOne):
+ _description = _("Create a BGP peer")
+
+ def get_parser(self, prog_name):
+ parser = super(CreateBgpPeer, self).get_parser(prog_name)
+ parser.add_argument(
+ 'name',
+ metavar='',
+ help=_("Name of the BGP peer to create"))
+ parser.add_argument(
+ '--peer-ip',
+ metavar='',
+ required=True,
+ help=_("Peer IP address"))
+ parser.add_argument(
+ '--remote-as',
+ required=True,
+ metavar='',
+ help=_("Peer AS number. (Integer in [%(min_val)s, %(max_val)s] "
+ "is allowed)") % {'min_val': constants.MIN_AS_NUM,
+ 'max_val': constants.MAX_AS_NUM})
+ parser.add_argument(
+ '--auth-type',
+ metavar='',
+ choices=['none', 'md5'],
+ type=nc_utils.convert_to_lowercase,
+ default='none',
+ help=_("Authentication algorithm. Supported algorithms: "
+ "none (default), md5"))
+ parser.add_argument(
+ '--password',
+ metavar='',
+ help=_("Authentication password"))
+ nc_osc_utils.add_project_owner_option_to_parser(parser)
+ return parser
+
+ def take_action(self, parsed_args):
+ client = self.app.client_manager.network
+ attrs = _get_attrs(self.app.client_manager, parsed_args)
+ obj = client.create_bgp_peer(**attrs)
+ display_columns, columns = nc_osc_utils._get_columns(obj)
+ data = utils.get_dict_properties(obj, columns)
+ return display_columns, data
+
+
+class DeleteBgpPeer(command.Command):
+ _description = _("Delete a BGP peer")
+
+ def get_parser(self, prog_name):
+ parser = super(DeleteBgpPeer, self).get_parser(prog_name)
+ parser.add_argument(
+ 'bgp_peer',
+ metavar="",
+ help=_("BGP peer to delete (name or ID)")
+ )
+ return parser
+
+ def take_action(self, parsed_args):
+ client = self.app.client_manager.network
+ id = client.find_bgp_peer(parsed_args.bgp_peer)['id']
+ client.delete_bgp_peer(id)
+
+
+class ListBgpPeer(command.Lister):
+ _description = _("List BGP peers")
+
+ def take_action(self, parsed_args):
+ data = self.app.client_manager.network.bgp_peers(retrieve_all=True)
+ headers = ('ID', 'Name', 'Peer IP', 'Remote AS')
+ columns = ('id', 'name', 'peer_ip', 'remote_as')
+ return (headers,
+ (utils.get_dict_properties(s, columns,) for s in data))
+
+
+class SetBgpPeer(command.Command):
+ _description = _("Update a BGP peer")
+ resource = constants.BGP_PEER
+
+ def get_parser(self, prog_name):
+ parser = super(SetBgpPeer, self).get_parser(prog_name)
+ parser.add_argument(
+ '--name',
+ help=_("Updated name of the BGP peer"))
+ parser.add_argument(
+ '--password',
+ metavar='',
+ help=_("Updated authentication password"))
+ parser.add_argument(
+ 'bgp_peer',
+ metavar="",
+ help=_("BGP peer to update (name or ID)")
+ )
+ return parser
+
+ def take_action(self, parsed_args):
+ client = self.app.client_manager.network
+ id = client.find_bgp_peer(parsed_args.bgp_peer)['id']
+ attrs = _get_attrs(self.app.client_manager, parsed_args)
+ client.update_bgp_peer(id, **attrs)
+
+
+class ShowBgpPeer(command.ShowOne):
+ _description = _("Show information for a BGP peer")
+
+ def get_parser(self, prog_name):
+ parser = super(ShowBgpPeer, self).get_parser(prog_name)
+ parser.add_argument(
+ 'bgp_peer',
+ metavar="",
+ help=_("BGP peer to display (name or ID)")
+ )
+ return parser
+
+ def take_action(self, parsed_args):
+ client = self.app.client_manager.network
+ id = client.find_bgp_peer(parsed_args.bgp_peer,
+ ignore_missing=False).id
+ obj = client.get_bgp_peer(id)
+ display_columns, columns = nc_osc_utils._get_columns(obj)
+ data = utils.get_dict_properties(obj, columns)
+ return display_columns, data
diff --git a/neutronclient/osc/v2/dynamic_routing/bgp_speaker.py b/neutronclient/osc/v2/dynamic_routing/bgp_speaker.py
new file mode 100644
index 000000000..76d8340b9
--- /dev/null
+++ b/neutronclient/osc/v2/dynamic_routing/bgp_speaker.py
@@ -0,0 +1,305 @@
+# Licensed under the Apache License, Version 2.0 (the "License"); you may
+# not use this file except in compliance with the License. You may obtain
+# a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+# License for the specific language governing permissions and limitations
+# under the License.
+#
+
+from osc_lib.command import command
+from osc_lib import utils
+
+from neutronclient._i18n import _
+from neutronclient.osc import utils as nc_osc_utils
+from neutronclient.osc.v2.dynamic_routing import constants
+
+
+def _get_attrs(client_manager, parsed_args):
+ attrs = {}
+ if parsed_args.name is not None:
+ attrs['name'] = str(parsed_args.name)
+ if 'local_as' in parsed_args:
+ attrs['local_as'] = parsed_args.local_as
+ if 'ip_version' in parsed_args:
+ attrs['ip_version'] = parsed_args.ip_version
+ if parsed_args.advertise_tenant_networks:
+ attrs['advertise_tenant_networks'] = True
+ if parsed_args.no_advertise_tenant_networks:
+ attrs['advertise_tenant_networks'] = False
+ if parsed_args.advertise_floating_ip_host_routes:
+ attrs['advertise_floating_ip_host_routes'] = True
+ if parsed_args.no_advertise_floating_ip_host_routes:
+ attrs['advertise_floating_ip_host_routes'] = False
+
+ if 'project' in parsed_args and parsed_args.project is not None:
+ identity_client = client_manager.identity
+ project_id = nc_osc_utils.find_project(
+ identity_client,
+ parsed_args.project,
+ parsed_args.project_domain,
+ ).id
+ attrs['tenant_id'] = project_id
+ return attrs
+
+
+def add_common_arguments(parser):
+ parser.add_argument(
+ '--advertise-floating-ip-host-routes',
+ action='store_true',
+ help=_("Enable the advertisement of floating IP host routes "
+ "by the BGP speaker. (default)"))
+ parser.add_argument(
+ '--no-advertise-floating-ip-host-routes',
+ action='store_true',
+ help=_("Disable the advertisement of floating IP host routes "
+ "by the BGP speaker."))
+ parser.add_argument(
+ '--advertise-tenant-networks',
+ action='store_true',
+ help=_("Enable the advertisement of tenant network routes "
+ "by the BGP speaker. (default)"))
+ parser.add_argument(
+ '--no-advertise-tenant-networks',
+ action='store_true',
+ help=_("Disable the advertisement of tenant network routes "
+ "by the BGP speaker."))
+
+
+class AddNetworkToSpeaker(command.Command):
+ _description = _("Add a network to a BGP speaker")
+
+ def get_parser(self, prog_name):
+ parser = super(AddNetworkToSpeaker, self).get_parser(prog_name)
+ parser.add_argument(
+ 'bgp_speaker',
+ metavar='',
+ help=_("BGP speaker (name or ID)"))
+ parser.add_argument(
+ 'network',
+ metavar='',
+ help=_("Network to add (name or ID)"))
+ return parser
+
+ def take_action(self, parsed_args):
+ client = self.app.client_manager.network
+ speaker_id = client.find_bgp_speaker(parsed_args.bgp_speaker,
+ ignore_missing=False).id
+ net_id = client.find_network(parsed_args.network,
+ ignore_missing=False).id
+ client.add_gateway_network_to_speaker(speaker_id, net_id)
+
+
+class AddPeerToSpeaker(command.Command):
+ _description = _("Add a peer to a BGP speaker")
+
+ def get_parser(self, prog_name):
+ parser = super(AddPeerToSpeaker, self).get_parser(prog_name)
+ parser.add_argument(
+ 'bgp_speaker',
+ metavar='',
+ help=_("BGP speaker (name or ID)"))
+ parser.add_argument(
+ 'bgp_peer',
+ metavar='',
+ help=_("BGP Peer to add (name or ID)"))
+ return parser
+
+ def take_action(self, parsed_args):
+ client = self.app.client_manager.network
+ speaker_id = client.find_bgp_speaker(parsed_args.bgp_speaker)['id']
+ peer_id = client.find_bgp_peer(parsed_args.bgp_peer)['id']
+ client.add_bgp_peer_to_speaker(speaker_id, peer_id)
+
+
+class CreateBgpSpeaker(command.ShowOne):
+ _description = _("Create a BGP speaker")
+
+ def get_parser(self, prog_name):
+ parser = super(CreateBgpSpeaker, self).get_parser(prog_name)
+ parser.add_argument(
+ 'name',
+ metavar='',
+ help=_("Name of the BGP speaker to create"))
+ parser.add_argument(
+ '--local-as',
+ metavar='',
+ required=True,
+ help=_("Local AS number. (Integer in [%(min_val)s, %(max_val)s] "
+ "is allowed.)") % {'min_val': constants.MIN_AS_NUM,
+ 'max_val': constants.MAX_AS_NUM})
+ parser.add_argument(
+ '--ip-version',
+ type=int, choices=[4, 6],
+ default=4,
+ help=_("IP version for the BGP speaker (default is 4)"))
+ add_common_arguments(parser)
+ nc_osc_utils.add_project_owner_option_to_parser(parser)
+ return parser
+
+ def take_action(self, parsed_args):
+ client = self.app.client_manager.network
+ attrs = _get_attrs(self.app.client_manager, parsed_args)
+ obj = client.create_bgp_speaker(**attrs)
+ display_columns, columns = nc_osc_utils._get_columns(obj)
+ data = utils.get_dict_properties(obj, columns)
+ return display_columns, data
+
+
+class DeleteBgpSpeaker(command.Command):
+ _description = _("Delete a BGP speaker")
+
+ def get_parser(self, prog_name):
+ parser = super(DeleteBgpSpeaker, self).get_parser(prog_name)
+ parser.add_argument(
+ 'bgp_speaker',
+ metavar="",
+ help=_("BGP speaker to delete (name or ID)")
+ )
+ return parser
+
+ def take_action(self, parsed_args):
+ client = self.app.client_manager.network
+ id = client.find_bgp_speaker(parsed_args.bgp_speaker)['id']
+ client.delete_bgp_speaker(id)
+
+
+class ListBgpSpeaker(command.Lister):
+ _description = _("List BGP speakers")
+
+ def get_parser(self, prog_name):
+ parser = super(ListBgpSpeaker, self).get_parser(prog_name)
+ parser.add_argument(
+ '--agent',
+ metavar='',
+ help=_("List BGP speakers hosted by an agent (ID only)"))
+ return parser
+
+ def take_action(self, parsed_args):
+ client = self.app.client_manager.network
+ if parsed_args.agent is not None:
+ data = client.get_bgp_speakers_hosted_by_dragent(parsed_args.agent)
+ else:
+ data = client.bgp_speakers(retrieve_all=True)
+
+ headers = ('ID', 'Name', 'Local AS', 'IP Version')
+ columns = ('id', 'name', 'local_as', 'ip_version')
+ return (headers, (utils.get_dict_properties(s, columns)
+ for s in data))
+
+
+class ListRoutesAdvertisedBySpeaker(command.Lister):
+ _description = _("List routes advertised")
+
+ def get_parser(self, prog_name):
+ parser = super(ListRoutesAdvertisedBySpeaker,
+ self).get_parser(prog_name)
+ parser.add_argument(
+ 'bgp_speaker',
+ metavar='',
+ help=_("BGP speaker (name or ID)"))
+ return parser
+
+ def take_action(self, parsed_args):
+ client = self.app.client_manager.network
+ speaker_id = client.find_bgp_speaker(parsed_args.bgp_speaker)['id']
+ data = client.get_advertised_routes_of_speaker(speaker_id)
+ headers = ('Destination', 'Nexthop')
+ columns = ('destination', 'next_hop')
+ return (headers, (utils.get_dict_properties(s, columns)
+ for s in data['advertised_routes']))
+
+
+class RemoveNetworkFromSpeaker(command.Command):
+ _description = _("Remove a network from a BGP speaker")
+
+ def get_parser(self, prog_name):
+ parser = super(RemoveNetworkFromSpeaker, self).get_parser(prog_name)
+ parser.add_argument(
+ 'bgp_speaker',
+ metavar='',
+ help=_("BGP speaker (name or ID)"))
+ parser.add_argument(
+ 'network',
+ metavar='',
+ help=_("Network to remove (name or ID)"))
+ return parser
+
+ def take_action(self, parsed_args):
+ client = self.app.client_manager.network
+ speaker_id = client.find_bgp_speaker(parsed_args.bgp_speaker)['id']
+ net_id = client.find_network(parsed_args.network)['id']
+ client.remove_gateway_network_from_speaker(speaker_id, net_id)
+
+
+class RemovePeerFromSpeaker(command.Command):
+ _description = _("Remove a peer from a BGP speaker")
+
+ def get_parser(self, prog_name):
+ parser = super(RemovePeerFromSpeaker, self).get_parser(prog_name)
+ parser.add_argument(
+ 'bgp_speaker',
+ metavar='',
+ help=_("BGP speaker (name or ID)"))
+ parser.add_argument(
+ 'bgp_peer',
+ metavar='',
+ help=_("BGP Peer to remove (name or ID)"))
+ return parser
+
+ def take_action(self, parsed_args):
+ client = self.app.client_manager.network
+ speaker_id = client.find_bgp_speaker(parsed_args.bgp_speaker)['id']
+ peer_id = client.find_bgp_peer(parsed_args.bgp_peer)['id']
+ client.remove_bgp_peer_from_speaker(speaker_id, peer_id)
+
+
+class SetBgpSpeaker(command.Command):
+ _description = _("Set BGP speaker properties")
+
+ resource = constants.BGP_SPEAKER
+
+ def get_parser(self, prog_name):
+ parser = super(SetBgpSpeaker, self).get_parser(prog_name)
+ parser.add_argument(
+ 'bgp_speaker',
+ metavar="",
+ help=_("BGP speaker to update (name or ID)")
+ )
+ parser.add_argument(
+ '--name',
+ help=_("New name for the BGP speaker"))
+ add_common_arguments(parser)
+ return parser
+
+ def take_action(self, parsed_args):
+ client = self.app.client_manager.network
+ id = client.find_bgp_speaker(parsed_args.bgp_speaker)['id']
+ attrs = _get_attrs(self.app.client_manager, parsed_args)
+ client.update_bgp_speaker(id, **attrs)
+
+
+class ShowBgpSpeaker(command.ShowOne):
+ _description = _("Show a BGP speaker")
+
+ def get_parser(self, prog_name):
+ parser = super(ShowBgpSpeaker, self).get_parser(prog_name)
+ parser.add_argument(
+ 'bgp_speaker',
+ metavar="",
+ help=_("BGP speaker to display (name or ID)")
+ )
+ return parser
+
+ def take_action(self, parsed_args):
+ client = self.app.client_manager.network
+ id = client.find_bgp_speaker(parsed_args.bgp_speaker,
+ ignore_missing=False).id
+ obj = client.get_bgp_speaker(id)
+ display_columns, columns = nc_osc_utils._get_columns(obj)
+ data = utils.get_dict_properties(obj, columns)
+ return display_columns, data
diff --git a/neutronclient/osc/v2/dynamic_routing/constants.py b/neutronclient/osc/v2/dynamic_routing/constants.py
new file mode 100644
index 000000000..8885b42ed
--- /dev/null
+++ b/neutronclient/osc/v2/dynamic_routing/constants.py
@@ -0,0 +1,18 @@
+# Licensed under the Apache License, Version 2.0 (the "License"); you may
+# not use this file except in compliance with the License. You may obtain
+# a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+# License for the specific language governing permissions and limitations
+# under the License.
+
+BGP_SPEAKERS = 'bgp_speakers'
+BGP_SPEAKER = 'bgp_speaker'
+BGP_PEERS = 'bgp_peers'
+BGP_PEER = 'bgp_peer'
+MIN_AS_NUM = 1
+MAX_AS_NUM = 4294967295
diff --git a/neutronclient/osc/v2/fwaas/constants.py b/neutronclient/osc/v2/fwaas/constants.py
new file mode 100644
index 000000000..a5a74af73
--- /dev/null
+++ b/neutronclient/osc/v2/fwaas/constants.py
@@ -0,0 +1,28 @@
+# Copyright 2016-2017 FUJITSU LIMITED
+# All Rights Reserved
+#
+# Licensed under the Apache License, Version 2.0 (the "License"); you may
+# not use this file except in compliance with the License. You may obtain
+# a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+# License for the specific language governing permissions and limitations
+# under the License.
+#
+
+# TODO(slaweq): remove it once "logging" OSC plugin will be moved to the
+# python-openstackclient repo
+
+FWG = 'firewall_group'
+FWGS = 'firewall_groups'
+FWP = 'firewall_policy'
+FWPS = 'firewall_policies'
+FWR = 'firewall_rule'
+FWRS = 'firewall_rules'
+CMD_FWG = 'fwaas_' + FWG
+CMD_FWP = 'fwaas_' + FWP
+CMD_FWR = 'fwaas_' + FWR
diff --git a/neutronclient/osc/v2/trunk/__init__.py b/neutronclient/osc/v2/logging/__init__.py
similarity index 100%
rename from neutronclient/osc/v2/trunk/__init__.py
rename to neutronclient/osc/v2/logging/__init__.py
diff --git a/neutronclient/osc/v2/logging/network_log.py b/neutronclient/osc/v2/logging/network_log.py
new file mode 100644
index 000000000..b3b8204c3
--- /dev/null
+++ b/neutronclient/osc/v2/logging/network_log.py
@@ -0,0 +1,304 @@
+# Copyright 2017-2018 FUJTISU LIMITED.
+# All Rights Reserved
+#
+# Licensed under the Apache License, Version 2.0 (the "License"); you may
+# not use this file except in compliance with the License. You may obtain
+# a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+# License for the specific language governing permissions and limitations
+# under the License.
+#
+
+import copy
+
+from osc_lib.command import command
+from osc_lib import exceptions
+from osc_lib import utils
+from osc_lib.utils import columns as column_util
+from oslo_log import log as logging
+
+from neutronclient._i18n import _
+from neutronclient.common import utils as nc_utils
+from neutronclient.osc import utils as osc_utils
+from neutronclient.osc.v2.fwaas import constants as fwaas_const
+
+LOG = logging.getLogger(__name__)
+
+_attr_map = (
+ ('id', 'ID', column_util.LIST_BOTH),
+ ('description', 'Description', column_util.LIST_LONG_ONLY),
+ ('enabled', 'Enabled', column_util.LIST_BOTH),
+ ('name', 'Name', column_util.LIST_BOTH),
+ ('target_id', 'Target', column_util.LIST_LONG_ONLY),
+ ('project_id', 'Project', column_util.LIST_LONG_ONLY),
+ ('resource_id', 'Resource', column_util.LIST_LONG_ONLY),
+ ('resource_type', 'Type', column_util.LIST_BOTH),
+ ('event', 'Event', column_util.LIST_LONG_ONLY),
+ ('summary', 'Summary', column_util.LIST_SHORT_ONLY),
+)
+
+_attr_map_for_loggable = (
+ ('type', 'Supported types', column_util.LIST_BOTH),
+)
+
+NET_LOG = 'network_log'
+
+
+def _get_common_parser(parser):
+ parser.add_argument(
+ '--description',
+ metavar='',
+ help=_('Description of the network log'))
+ enable_group = parser.add_mutually_exclusive_group()
+ enable_group.add_argument(
+ '--enable',
+ action='store_true',
+ help=_('Enable this log'))
+ enable_group.add_argument(
+ '--disable',
+ action='store_true',
+ help=_('Disable this log (default is enabled)'))
+ return parser
+
+
+def _get_common_attrs(client_manager, parsed_args, is_create=True):
+ attrs = {}
+ client = client_manager.neutronclient
+
+ if is_create:
+ if 'project' in parsed_args and parsed_args.project is not None:
+ attrs['project_id'] = osc_utils.find_project(
+ client_manager.identity,
+ parsed_args.project,
+ parsed_args.project_domain,
+ ).id
+ resource_type = parsed_args.resource_type
+ attrs['resource_type'] = resource_type
+ if parsed_args.resource:
+ cmd_resource = None
+ if resource_type == fwaas_const.FWG:
+ cmd_resource = fwaas_const.CMD_FWG
+ attrs['resource_id'] = client.find_resource(
+ resource_type,
+ parsed_args.resource,
+ cmd_resource=cmd_resource)['id']
+
+ if parsed_args.target:
+ # NOTE(yushiro) Currently, we're supporting only port
+ attrs['target_id'] = client.find_resource(
+ 'port', parsed_args.target)['id']
+ if parsed_args.event:
+ attrs['event'] = parsed_args.event
+ if parsed_args.enable:
+ attrs['enabled'] = True
+ if parsed_args.disable:
+ attrs['enabled'] = False
+ if parsed_args.name:
+ attrs['name'] = parsed_args.name
+ if parsed_args.description:
+ attrs['description'] = parsed_args.description
+ return attrs
+
+
+class CreateNetworkLog(command.ShowOne):
+ _description = _("Create a new network log")
+
+ def get_parser(self, prog_name):
+ parser = super(CreateNetworkLog, self).get_parser(prog_name)
+ _get_common_parser(parser)
+ osc_utils.add_project_owner_option_to_parser(parser)
+ parser.add_argument(
+ 'name',
+ metavar='',
+ help=_('Name for the network log'))
+ parser.add_argument(
+ '--event',
+ metavar='{ALL,ACCEPT,DROP}',
+ choices=['ALL', 'ACCEPT', 'DROP'],
+ type=nc_utils.convert_to_uppercase,
+ help=_('An event to store with log'))
+ # NOTE(yushiro) '--resource-type' is managed by following command:
+ # "openstack network loggable resources list". Therefore, this option
+ # shouldn't have "choices" like ['security_group', 'firewall_group']
+ parser.add_argument(
+ '--resource-type',
+ metavar='',
+ required=True,
+ type=nc_utils.convert_to_lowercase,
+ help=_('Network log type(s). '
+ 'You can see supported type(s) with following command:\n'
+ '$ openstack network loggable resources list'))
+ parser.add_argument(
+ '--resource',
+ metavar='',
+ help=_('Name or ID of resource (security group or firewall group) '
+ 'that used for logging. You can control for logging target '
+ 'combination with --target option.'))
+ parser.add_argument(
+ '--target',
+ metavar='',
+ help=_('Port (name or ID) for logging. You can control '
+ 'for logging target combination with --resource option.'))
+ return parser
+
+ def take_action(self, parsed_args):
+ client = self.app.client_manager.neutronclient
+ attrs = _get_common_attrs(self.app.client_manager, parsed_args)
+ obj = client.create_network_log({'log': attrs})['log']
+ columns, display_columns = column_util.get_columns(obj, _attr_map)
+ data = utils.get_dict_properties(obj, columns)
+ return (display_columns, data)
+
+
+class DeleteNetworkLog(command.Command):
+ _description = _("Delete network log(s)")
+
+ def get_parser(self, prog_name):
+ parser = super(DeleteNetworkLog, self).get_parser(prog_name)
+ parser.add_argument(
+ 'network_log',
+ metavar='',
+ nargs='+',
+ help=_('Network log(s) to delete (name or ID)'))
+ return parser
+
+ def take_action(self, parsed_args):
+ client = self.app.client_manager.neutronclient
+ result = 0
+ for log_res in parsed_args.network_log:
+ try:
+ log_id = client.find_resource(
+ 'log', log_res, cmd_resource=NET_LOG)['id']
+ client.delete_network_log(log_id)
+ except Exception as e:
+ result += 1
+ LOG.error(_("Failed to delete network log with "
+ "name or ID '%(network_log)s': %(e)s"),
+ {'network_log': log_res, 'e': e})
+
+ if result > 0:
+ total = len(parsed_args.network_log)
+ msg = (_("%(result)s of %(total)s network log(s) "
+ "failed to delete") % {'result': result, 'total': total})
+ raise exceptions.CommandError(msg)
+
+
+class ListLoggableResource(command.Lister):
+ _description = _("List supported loggable resources")
+
+ def get_parser(self, prog_name):
+ parser = super(ListLoggableResource, self).get_parser(prog_name)
+ parser.add_argument(
+ '--long',
+ action='store_true',
+ help=_("List additional fields in output")
+ )
+ return parser
+
+ def take_action(self, parsed_args):
+ client = self.app.client_manager.neutronclient
+ obj = client.list_network_loggable_resources()['loggable_resources']
+ headers, columns = column_util.get_column_definitions(
+ _attr_map_for_loggable, long_listing=parsed_args.long)
+ return (headers, (utils.get_dict_properties(s, columns) for s in obj))
+
+
+class ListNetworkLog(command.Lister):
+ _description = _("List network logs")
+
+ def get_parser(self, prog_name):
+ parser = super(ListNetworkLog, self).get_parser(prog_name)
+ parser.add_argument(
+ '--long',
+ action='store_true',
+ help=_("List additional fields in output")
+ )
+ # TODO(yushiro): We'll support filtering in the future.
+ return parser
+
+ def _extend_list(self, data, parsed_args):
+ ext_data = copy.deepcopy(data)
+ for d in ext_data:
+ e_prefix = 'Event: '
+ if d['event']:
+ event = e_prefix + d['event'].upper()
+ port = '(port) ' + d['target_id'] if d['target_id'] else ''
+ resource_type = d['resource_type']
+ if d['resource_id']:
+ res = '(%s) %s' % (resource_type, d['resource_id'])
+ else:
+ res = ''
+ t_prefix = 'Logged: '
+ if port and res:
+ t = '%s on %s' % (res, port)
+ else:
+ # Either of res and port is empty, so concatenation works fine
+ t = res + port
+ target = t_prefix + t if t else t_prefix + '(None specified)'
+ d['summary'] = ',\n'.join([event, target])
+ return ext_data
+
+ def take_action(self, parsed_args):
+ client = self.app.client_manager.neutronclient
+ obj = client.list_network_logs()['logs']
+ obj_extend = self._extend_list(obj, parsed_args)
+ headers, columns = column_util.get_column_definitions(
+ _attr_map, long_listing=parsed_args.long)
+ return (headers, (
+ utils.get_dict_properties(s, columns) for s in obj_extend))
+
+
+class SetNetworkLog(command.Command):
+ _description = _("Set network log properties")
+
+ def get_parser(self, prog_name):
+ parser = super(SetNetworkLog, self).get_parser(prog_name)
+ _get_common_parser(parser)
+ parser.add_argument(
+ 'network_log',
+ metavar='',
+ help=_('Network log to set (name or ID)'))
+ parser.add_argument(
+ '--name',
+ metavar='',
+ help=_('Name of the network log'))
+ return parser
+
+ def take_action(self, parsed_args):
+ client = self.app.client_manager.neutronclient
+ log_id = client.find_resource(
+ 'log', parsed_args.network_log, cmd_resource=NET_LOG)['id']
+ attrs = _get_common_attrs(self.app.client_manager, parsed_args,
+ is_create=False)
+ try:
+ client.update_network_log(log_id, {'log': attrs})
+ except Exception as e:
+ msg = (_("Failed to set network log '%(logging)s': %(e)s")
+ % {'logging': parsed_args.network_log, 'e': e})
+ raise exceptions.CommandError(msg)
+
+
+class ShowNetworkLog(command.ShowOne):
+ _description = _("Display network log details")
+
+ def get_parser(self, prog_name):
+ parser = super(ShowNetworkLog, self).get_parser(prog_name)
+ parser.add_argument(
+ 'network_log',
+ metavar='',
+ help=_('Network log to show (name or ID)'))
+ return parser
+
+ def take_action(self, parsed_args):
+ client = self.app.client_manager.neutronclient
+ log_id = client.find_resource(
+ 'log', parsed_args.network_log, cmd_resource=NET_LOG)['id']
+ obj = client.show_network_log(log_id)['log']
+ columns, display_columns = column_util.get_columns(obj, _attr_map)
+ data = utils.get_dict_properties(obj, columns)
+ return (display_columns, data)
diff --git a/neutronclient/tests/functional/__init__.py b/neutronclient/osc/v2/sfc/__init__.py
similarity index 100%
rename from neutronclient/tests/functional/__init__.py
rename to neutronclient/osc/v2/sfc/__init__.py
diff --git a/neutronclient/osc/v2/sfc/sfc_flow_classifier.py b/neutronclient/osc/v2/sfc/sfc_flow_classifier.py
new file mode 100755
index 000000000..775730fc2
--- /dev/null
+++ b/neutronclient/osc/v2/sfc/sfc_flow_classifier.py
@@ -0,0 +1,346 @@
+# Copyright (c) 2017 Huawei Technologies India Pvt.Limited.
+# All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License"); you may
+# not use this file except in compliance with the License. You may obtain
+# a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+# License for the specific language governing permissions and limitations
+# under the License.
+
+import argparse
+import logging
+
+from osc_lib.command import command
+from osc_lib import exceptions
+from osc_lib import utils
+from osc_lib.utils import columns as column_util
+
+from neutronclient._i18n import _
+from neutronclient.common import exceptions as nc_exc
+
+LOG = logging.getLogger(__name__)
+
+resource = 'flow_classifier'
+
+_attr_map = (
+ ('id', 'ID', column_util.LIST_BOTH),
+ ('name', 'Name', column_util.LIST_BOTH),
+ ('summary', 'Summary', column_util.LIST_SHORT_ONLY),
+ ('protocol', 'Protocol', column_util.LIST_LONG_ONLY),
+ ('ethertype', 'Ethertype', column_util.LIST_LONG_ONLY),
+ ('source_ip_prefix', 'Source IP',
+ column_util.LIST_LONG_ONLY),
+ ('destination_ip_prefix', 'Destination IP',
+ column_util.LIST_LONG_ONLY),
+ ('logical_source_port', 'Logical Source Port',
+ column_util.LIST_LONG_ONLY),
+ ('logical_destination_port', 'Logical Destination Port',
+ column_util.LIST_LONG_ONLY),
+ ('source_port_range_min', 'Source Port Range Min',
+ column_util.LIST_LONG_ONLY),
+ ('source_port_range_max', 'Source Port Range Max',
+ column_util.LIST_LONG_ONLY),
+ ('destination_port_range_min', 'Destination Port Range Min',
+ column_util.LIST_LONG_ONLY),
+ ('destination_port_range_max', 'Destination Port Range Max',
+ column_util.LIST_LONG_ONLY),
+ ('l7_parameters', 'L7 Parameters', column_util.LIST_LONG_ONLY),
+ ('description', 'Description', column_util.LIST_LONG_ONLY),
+ ('project_id', 'Project', column_util.LIST_LONG_ONLY),
+)
+
+_attr_map_dict = {
+ 'id': 'ID',
+ 'name': 'Name',
+ 'description': 'Description',
+ 'summary': 'Summary',
+ 'protocol': 'Protocol',
+ 'ethertype': 'Ethertype',
+ 'source_ip_prefix': 'Source IP',
+ 'destination_ip_prefix': 'Destination IP',
+ 'logical_source_port': 'Logical Source Port',
+ 'logical_destination_port': 'Logical Destination Port',
+ 'source_port_range_min': 'Source Port Range Min',
+ 'source_port_range_max': 'Source Port Range Max',
+ 'destination_port_range_min': 'Destination Port Range Min',
+ 'destination_port_range_max': 'Destination Port Range Max',
+ 'l7_parameters': 'L7 Parameters',
+ 'tenant_id': 'Project',
+ 'project_id': 'Project',
+}
+
+
+class CreateSfcFlowClassifier(command.ShowOne):
+ _description = _("Create a flow classifier")
+
+ def get_parser(self, prog_name):
+ parser = super(CreateSfcFlowClassifier, self).get_parser(prog_name)
+ parser.add_argument(
+ 'name',
+ metavar='',
+ help=_('Name of the flow classifier'))
+ parser.add_argument(
+ '--description',
+ metavar='',
+ help=_('Description for the flow classifier'))
+ parser.add_argument(
+ '--protocol',
+ metavar='',
+ help=_('IP protocol name. Protocol name should be as per '
+ 'IANA standard.'))
+ parser.add_argument(
+ '--ethertype',
+ metavar='{IPv4,IPv6}',
+ default='IPv4', choices=['IPv4', 'IPv6'],
+ help=_('L2 ethertype, default is IPv4'))
+ parser.add_argument(
+ '--source-port',
+ metavar=':',
+ help=_('Source protocol port (allowed range [1,65535]. Must be '
+ 'specified as a:b, where a=min-port and b=max-port) '
+ 'in the allowed range.'))
+ parser.add_argument(
+ '--destination-port',
+ metavar=':',
+ help=_('Destination protocol port (allowed range [1,65535]. Must '
+ 'be specified as a:b, where a=min-port and b=max-port) '
+ 'in the allowed range.'))
+ parser.add_argument(
+ '--source-ip-prefix',
+ metavar='',
+ help=_('Source IP address in CIDR notation'))
+ parser.add_argument(
+ '--destination-ip-prefix',
+ metavar='',
+ help=_('Destination IP address in CIDR notation'))
+ parser.add_argument(
+ '--logical-source-port',
+ metavar='',
+ help=_('Neutron source port (name or ID)'))
+ parser.add_argument(
+ '--logical-destination-port',
+ metavar='',
+ help=_('Neutron destination port (name or ID)'))
+ parser.add_argument(
+ '--l7-parameters',
+ help=_('Dictionary of L7 parameters. Currently, no value is '
+ 'supported for this option.'))
+ return parser
+
+ def take_action(self, parsed_args):
+ client = self.app.client_manager.network
+ attrs = _get_common_attrs(self.app.client_manager, parsed_args)
+ obj = client.create_sfc_flow_classifier(**attrs)
+ display_columns, columns = utils.get_osc_show_columns_for_sdk_resource(
+ obj, _attr_map_dict, ['location', 'tenant_id', 'summary'])
+ data = utils.get_dict_properties(obj, columns)
+ return display_columns, data
+
+
+class DeleteSfcFlowClassifier(command.Command):
+ _description = _("Delete a given flow classifier")
+
+ def get_parser(self, prog_name):
+ parser = super(DeleteSfcFlowClassifier, self).get_parser(prog_name)
+ parser.add_argument(
+ 'flow_classifier',
+ metavar='',
+ nargs='+',
+ help=_("Flow classifier(s) to delete (name or ID)")
+ )
+ return parser
+
+ def take_action(self, parsed_args):
+ client = self.app.client_manager.network
+ result = 0
+ for fcl in parsed_args.flow_classifier:
+ try:
+ fc_id = client.find_sfc_flow_classifier(
+ fcl, ignore_missing=False)['id']
+ client.delete_sfc_flow_classifier(fc_id)
+ except Exception as e:
+ result += 1
+ LOG.error(_("Failed to delete flow classifier with name "
+ "or ID '%(fc)s': %(e)s"), {'fc': fcl, 'e': e})
+ if result > 0:
+ total = len(parsed_args.flow_classifier)
+ msg = (_("%(result)s of %(total)s flow classifier(s) "
+ "failed to delete.") % {'result': result, 'total': total})
+ raise exceptions.CommandError(msg)
+
+
+class ListSfcFlowClassifier(command.Lister):
+ _description = _("List flow classifiers")
+
+ def get_parser(self, prog_name):
+ parser = super(ListSfcFlowClassifier, self).get_parser(prog_name)
+ parser.add_argument(
+ '--long',
+ action='store_true',
+ help=_("List additional fields in output")
+ )
+ return parser
+
+ def extend_list(self, data, parsed_args):
+ ext_data = []
+ for d in data:
+ val = []
+ protocol = d['protocol'].upper() if d['protocol'] else 'any'
+ val.append('protocol: ' + protocol)
+ val.append(self._get_protocol_port_details(d, 'source'))
+ val.append(self._get_protocol_port_details(d, 'destination'))
+ if 'logical_source_port' in d:
+ val.append('neutron_source_port: ' +
+ str(d['logical_source_port']))
+
+ if 'logical_destination_port' in d:
+ val.append('neutron_destination_port: ' +
+ str(d['logical_destination_port']))
+
+ if 'l7_parameters' in d:
+ l7_param = 'l7_parameters: {%s}' % ','.join(d['l7_parameters'])
+ val.append(l7_param)
+ d['summary'] = ',\n'.join(val)
+ ext_data.append(d)
+ return ext_data
+
+ def _get_protocol_port_details(self, data, val):
+ type_ip_prefix = val + '_ip_prefix'
+ ip_prefix = data.get(type_ip_prefix)
+ if not ip_prefix:
+ ip_prefix = 'any'
+ min_port = data.get(val + '_port_range_min')
+ if min_port is None:
+ min_port = 'any'
+ max_port = data.get(val + '_port_range_max')
+ if max_port is None:
+ max_port = 'any'
+ return '%s[port]: %s[%s:%s]' % (
+ val, ip_prefix, min_port, max_port)
+
+ def take_action(self, parsed_args):
+ client = self.app.client_manager.network
+ obj = client.sfc_flow_classifiers()
+ obj_extend = self.extend_list(obj, parsed_args)
+ headers, columns = column_util.get_column_definitions(
+ _attr_map, long_listing=parsed_args.long)
+ return (headers, (utils.get_dict_properties(
+ s, columns) for s in obj_extend))
+
+
+class SetSfcFlowClassifier(command.Command):
+ _description = _("Set flow classifier properties")
+
+ def get_parser(self, prog_name):
+ parser = super(SetSfcFlowClassifier, self).get_parser(prog_name)
+ parser.add_argument(
+ '--name',
+ metavar='',
+ help=_('Name of the flow classifier'))
+ parser.add_argument(
+ '--description',
+ metavar='',
+ help=_('Description for the flow classifier'))
+ parser.add_argument(
+ 'flow_classifier',
+ metavar='',
+ help=_("Flow classifier to modify (name or ID)")
+ )
+ return parser
+
+ def take_action(self, parsed_args):
+ client = self.app.client_manager.network
+ fc_id = client.find_sfc_flow_classifier(parsed_args.flow_classifier,
+ ignore_missing=False)['id']
+ attrs = _get_common_attrs(self.app.client_manager, parsed_args,
+ is_create=False)
+ try:
+ client.update_sfc_flow_classifier(fc_id, **attrs)
+ except Exception as e:
+ msg = (_("Failed to update flow classifier '%(fc)s': %(e)s")
+ % {'fc': parsed_args.flow_classifier, 'e': e})
+ raise exceptions.CommandError(msg)
+
+
+class ShowSfcFlowClassifier(command.ShowOne):
+ _description = _("Display flow classifier details")
+
+ def get_parser(self, prog_name):
+ parser = super(ShowSfcFlowClassifier, self).get_parser(prog_name)
+ parser.add_argument(
+ 'flow_classifier',
+ metavar='',
+ help=_("Flow classifier to display (name or ID)")
+ )
+ return parser
+
+ def take_action(self, parsed_args):
+ client = self.app.client_manager.network
+ fc_id = client.find_sfc_flow_classifier(parsed_args.flow_classifier,
+ ignore_missing=False)['id']
+ obj = client.get_sfc_flow_classifier(fc_id)
+ display_columns, columns = utils.get_osc_show_columns_for_sdk_resource(
+ obj, _attr_map_dict, ['location', 'tenant_id', 'summary'])
+ data = utils.get_dict_properties(obj, columns)
+ return display_columns, data
+
+
+def _get_common_attrs(client_manager, parsed_args, is_create=True):
+ attrs = {}
+ if parsed_args.name is not None:
+ attrs['name'] = parsed_args.name
+ if parsed_args.description is not None:
+ attrs['description'] = parsed_args.description
+ if is_create:
+ _get_attrs(client_manager, attrs, parsed_args)
+ return attrs
+
+
+def _get_attrs(client_manager, attrs, parsed_args):
+ if parsed_args.protocol is not None:
+ attrs['protocol'] = parsed_args.protocol
+ if parsed_args.ethertype:
+ attrs['ethertype'] = parsed_args.ethertype
+ if parsed_args.source_ip_prefix is not None:
+ attrs['source_ip_prefix'] = parsed_args.source_ip_prefix
+ if parsed_args.destination_ip_prefix is not None:
+ attrs['destination_ip_prefix'] = parsed_args.destination_ip_prefix
+ if parsed_args.logical_source_port is not None:
+ attrs['logical_source_port'] = client_manager.network.find_port(
+ parsed_args.logical_source_port, ignore_missing=False
+ )['id']
+ if parsed_args.logical_destination_port is not None:
+ attrs['logical_destination_port'] = client_manager.network.find_port(
+ parsed_args.logical_destination_port, ignore_missing=False
+ )['id']
+ if parsed_args.source_port is not None:
+ _fill_protocol_port_info(attrs, 'source',
+ parsed_args.source_port)
+ if parsed_args.destination_port is not None:
+ _fill_protocol_port_info(attrs, 'destination',
+ parsed_args.destination_port)
+ if parsed_args.l7_parameters is not None:
+ attrs['l7_parameters'] = parsed_args.l7_parameters
+
+
+def _fill_protocol_port_info(attrs, port_type, port_val):
+ min_port, sep, max_port = port_val.partition(":")
+ if not min_port:
+ msg = ("Invalid port value '%s', expected format is "
+ "min-port:max-port or min-port.")
+ raise argparse.ArgumentTypeError(msg % port_val)
+ if not max_port:
+ max_port = min_port
+ try:
+ attrs[port_type + '_port_range_min'] = int(min_port)
+ attrs[port_type + '_port_range_max'] = int(max_port)
+ except ValueError:
+ message = (_("Protocol port value %s must be an integer "
+ "or integer:integer.") % port_val)
+ raise nc_exc.CommandError(message=message)
diff --git a/neutronclient/osc/v2/sfc/sfc_port_chain.py b/neutronclient/osc/v2/sfc/sfc_port_chain.py
new file mode 100755
index 000000000..d96007b85
--- /dev/null
+++ b/neutronclient/osc/v2/sfc/sfc_port_chain.py
@@ -0,0 +1,381 @@
+# Copyright (c) 2017 Huawei Technologies India Pvt.Limited.
+# All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License"); you may
+# not use this file except in compliance with the License. You may obtain
+# a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+# License for the specific language governing permissions and limitations
+# under the License.
+
+import logging
+
+from osc_lib.cli import parseractions
+from osc_lib.command import command
+from osc_lib import exceptions
+from osc_lib import utils
+from osc_lib.utils import columns as column_util
+
+from neutronclient._i18n import _
+
+LOG = logging.getLogger(__name__)
+
+resource = 'port_chain'
+
+_attr_map = (
+ ('id', 'ID', column_util.LIST_BOTH),
+ ('name', 'Name', column_util.LIST_BOTH),
+ ('port_pair_groups', 'Port Pair Groups', column_util.LIST_BOTH),
+ ('flow_classifiers', 'Flow Classifiers',
+ column_util.LIST_BOTH),
+ ('chain_parameters', 'Chain Parameters',
+ column_util.LIST_BOTH),
+ ('description', 'Description', column_util.LIST_LONG_ONLY),
+ ('project_id', 'Project', column_util.LIST_LONG_ONLY),
+)
+
+_attr_map_dict = {
+ 'id': 'ID',
+ 'name': 'Name',
+ 'port_pair_groups': 'Port Pair Groups',
+ 'flow_classifiers': 'Flow Classifiers',
+ 'chain_parameters': 'Chain Parameters',
+ 'description': 'Description',
+ 'tenant_id': 'Project',
+ 'project_id': 'Project',
+}
+
+
+class CreateSfcPortChain(command.ShowOne):
+ _description = _("Create a port chain")
+
+ def get_parser(self, prog_name):
+ parser = super(CreateSfcPortChain, self).get_parser(prog_name)
+ parser.add_argument(
+ 'name',
+ metavar='',
+ help=_('Name of the port chain'))
+ parser.add_argument(
+ '--description',
+ metavar='',
+ help=_('Description for the port chain'))
+ parser.add_argument(
+ '--flow-classifier',
+ default=[],
+ metavar='',
+ dest='flow_classifiers',
+ action='append',
+ help=_('Add flow classifier (name or ID). '
+ 'This option can be repeated.'))
+ parser.add_argument(
+ '--chain-parameters',
+ metavar='correlation=,symmetric=',
+ action=parseractions.MultiKeyValueAction,
+ optional_keys=['correlation', 'symmetric'],
+ help=_('Dictionary of chain parameters. Supports '
+ 'correlation=(mpls|nsh) (default is mpls) '
+ 'and symmetric=(true|false).'))
+ parser.add_argument(
+ '--port-pair-group',
+ metavar='',
+ dest='port_pair_groups',
+ required=True,
+ action='append',
+ help=_('Add port pair group (name or ID). '
+ 'This option can be repeated.'))
+ return parser
+
+ def take_action(self, parsed_args):
+ client = self.app.client_manager.network
+ attrs = _get_common_attrs(self.app.client_manager, parsed_args)
+ obj = client.create_sfc_port_chain(**attrs)
+ display_columns, columns = utils.get_osc_show_columns_for_sdk_resource(
+ obj, _attr_map_dict, ['location', 'tenant_id'])
+ data = utils.get_dict_properties(obj, columns)
+ return display_columns, data
+
+
+class DeleteSfcPortChain(command.Command):
+ _description = _("Delete a given port chain")
+
+ def get_parser(self, prog_name):
+ parser = super(DeleteSfcPortChain, self).get_parser(prog_name)
+ parser.add_argument(
+ 'port_chain',
+ metavar="",
+ nargs='+',
+ help=_("Port chain(s) to delete (name or ID)")
+ )
+ return parser
+
+ def take_action(self, parsed_args):
+ client = self.app.client_manager.network
+ result = 0
+ for pc in parsed_args.port_chain:
+ try:
+ pc_id = client.find_sfc_port_chain(
+ pc, ignore_missing=False)['id']
+ client.delete_sfc_port_chain(pc_id)
+ except Exception as e:
+ result += 1
+ LOG.error(_("Failed to delete port chain with name "
+ "or ID '%(pc)s': %(e)s"), {'pc': pc, 'e': e})
+ if result > 0:
+ total = len(parsed_args.port_chain)
+ msg = (_("%(result)s of %(total)s port chain(s) "
+ "failed to delete.") % {'result': result,
+ 'total': total})
+ raise exceptions.CommandError(msg)
+
+
+class ListSfcPortChain(command.Lister):
+ _description = _("List port chains")
+
+ def get_parser(self, prog_name):
+ parser = super(ListSfcPortChain, self).get_parser(prog_name)
+ parser.add_argument(
+ '--long',
+ action='store_true',
+ default=False,
+ help=_("List additional fields in output")
+ )
+ return parser
+
+ def take_action(self, parsed_args):
+ client = self.app.client_manager.network
+ data = client.sfc_port_chains()
+ headers, columns = column_util.get_column_definitions(
+ _attr_map, long_listing=parsed_args.long)
+ return (headers,
+ (utils.get_dict_properties(s, columns)
+ for s in data))
+
+
+class SetSfcPortChain(command.Command):
+ _description = _("Set port chain properties")
+
+ def get_parser(self, prog_name):
+ parser = super(SetSfcPortChain, self).get_parser(prog_name)
+ parser.add_argument(
+ '--name',
+ metavar='',
+ help=_('Name of the port chain'))
+ parser.add_argument(
+ '--description',
+ metavar='',
+ help=_('Description for the port chain'))
+ parser.add_argument(
+ '--flow-classifier',
+ metavar='',
+ dest='flow_classifiers',
+ action='append',
+ help=_('Add flow classifier (name or ID). '
+ 'This option can be repeated.'))
+ parser.add_argument(
+ '--no-flow-classifier',
+ action='store_true',
+ help=_('Remove associated flow classifiers from the port chain'))
+ parser.add_argument(
+ '--port-pair-group',
+ metavar='',
+ dest='port_pair_groups',
+ action='append',
+ help=_('Add port pair group (name or ID). '
+ 'Current port pair groups order is kept, the added port '
+ 'pair group will be placed at the end of the port chain. '
+ 'This option can be repeated.'))
+ parser.add_argument(
+ '--no-port-pair-group',
+ action='store_true',
+ help=_('Remove associated port pair groups from the port chain. '
+ 'At least one --port-pair-group must be specified '
+ 'together.'))
+ parser.add_argument(
+ 'port_chain',
+ metavar='',
+ help=_("Port chain to modify (name or ID)"))
+ return parser
+
+ def take_action(self, parsed_args):
+ client = self.app.client_manager.network
+ pc_id = client.find_sfc_port_chain(parsed_args.port_chain,
+ ignore_missing=False)['id']
+ attrs = _get_common_attrs(self.app.client_manager, parsed_args,
+ is_create=False)
+ if parsed_args.no_flow_classifier:
+ attrs['flow_classifiers'] = []
+ if parsed_args.flow_classifiers:
+ if parsed_args.no_flow_classifier:
+ fc_list = []
+ else:
+ fc_list = client.find_sfc_port_chain(
+ parsed_args.port_chain,
+ ignore_missing=False
+ )['flow_classifiers']
+ for fc in parsed_args.flow_classifiers:
+ fc_id = client.find_sfc_flow_classifier(
+ fc,
+ ignore_missing=False)['id']
+ if fc_id not in fc_list:
+ fc_list.append(fc_id)
+ attrs['flow_classifiers'] = fc_list
+ if (parsed_args.no_port_pair_group and not
+ parsed_args.port_pair_groups):
+ message = _('At least one --port-pair-group must be specified.')
+ raise exceptions.CommandError(message)
+ if parsed_args.no_port_pair_group and parsed_args.port_pair_groups:
+ ppg_list = []
+ for ppg in parsed_args.port_pair_groups:
+ ppg_id = client.find_sfc_port_pair_group(
+ ppg, ignore_missing=False)['id']
+ if ppg_id not in ppg_list:
+ ppg_list.append(ppg_id)
+ attrs['port_pair_groups'] = ppg_list
+ if (parsed_args.port_pair_groups and
+ not parsed_args.no_port_pair_group):
+ ppg_list = client.find_sfc_port_chain(
+ parsed_args.port_chain,
+ ignore_missing=False
+ )['port_pair_groups']
+ for ppg in parsed_args.port_pair_groups:
+ ppg_id = client.find_sfc_port_pair_group(
+ ppg, ignore_missing=False)['id']
+ if ppg_id not in ppg_list:
+ ppg_list.append(ppg_id)
+ attrs['port_pair_groups'] = ppg_list
+ try:
+ client.update_sfc_port_chain(pc_id, **attrs)
+ except Exception as e:
+ msg = (_("Failed to update port chain '%(pc)s': %(e)s")
+ % {'pc': parsed_args.port_chain, 'e': e})
+ raise exceptions.CommandError(msg)
+
+
+class ShowSfcPortChain(command.ShowOne):
+ _description = _("Display port chain details")
+
+ def get_parser(self, prog_name):
+ parser = super(ShowSfcPortChain, self).get_parser(prog_name)
+ parser.add_argument(
+ 'port_chain',
+ metavar="",
+ help=_("Port chain to display (name or ID)")
+ )
+ return parser
+
+ def take_action(self, parsed_args):
+ client = self.app.client_manager.network
+ pc_id = client.find_sfc_port_chain(parsed_args.port_chain,
+ ignore_missing=False)['id']
+ obj = client.get_sfc_port_chain(pc_id)
+ display_columns, columns = utils.get_osc_show_columns_for_sdk_resource(
+ obj, _attr_map_dict, ['location', 'tenant_id'])
+ data = utils.get_dict_properties(obj, columns)
+ return display_columns, data
+
+
+class UnsetSfcPortChain(command.Command):
+ _description = _("Unset port chain properties")
+
+ def get_parser(self, prog_name):
+ parser = super(UnsetSfcPortChain, self).get_parser(prog_name)
+ parser.add_argument(
+ 'port_chain',
+ metavar='',
+ help=_("Port chain to unset (name or ID)"))
+ port_chain = parser.add_mutually_exclusive_group()
+ port_chain.add_argument(
+ '--flow-classifier',
+ action='append',
+ metavar='',
+ dest='flow_classifiers',
+ help=_('Remove flow classifier(s) from the port chain '
+ '(name or ID). This option can be repeated.'))
+ port_chain.add_argument(
+ '--all-flow-classifier',
+ action='store_true',
+ help=_('Remove all flow classifiers from the port chain'))
+ parser.add_argument(
+ '--port-pair-group',
+ metavar='',
+ dest='port_pair_groups',
+ action='append',
+ help=_('Remove port pair group(s) from the port chain '
+ '(name or ID). This option can be repeated.'))
+ return parser
+
+ def take_action(self, parsed_args):
+ client = self.app.client_manager.network
+ pc_id = client.find_sfc_port_chain(parsed_args.port_chain,
+ ignore_missing=False)['id']
+ attrs = {}
+ if parsed_args.flow_classifiers:
+ fc_list = client.find_sfc_port_chain(
+ parsed_args.port_chain, ignore_missing=False
+ )['flow_classifiers']
+ for fc in parsed_args.flow_classifiers:
+ fc_id = client.find_sfc_flow_classifier(
+ fc,
+ ignore_missing=False)['id']
+ if fc_id in fc_list:
+ fc_list.remove(fc_id)
+ attrs['flow_classifiers'] = fc_list
+ if parsed_args.all_flow_classifier:
+ attrs['flow_classifiers'] = []
+ if parsed_args.port_pair_groups:
+ ppg_list = client.find_sfc_port_chain(
+ parsed_args.port_chain,
+ ignore_missing=False)['port_pair_groups']
+ for ppg in parsed_args.port_pair_groups:
+ ppg_id = client.find_sfc_port_pair_group(
+ ppg,
+ ignore_missing=False)['id']
+ if ppg_id in ppg_list:
+ ppg_list.remove(ppg_id)
+ if ppg_list == []:
+ message = _('At least one port pair group must be'
+ ' specified.')
+ raise exceptions.CommandError(message)
+ attrs['port_pair_groups'] = ppg_list
+ try:
+ client.update_sfc_port_chain(pc_id, **attrs)
+ except Exception as e:
+ msg = (_("Failed to unset port chain '%(pc)s': %(e)s")
+ % {'pc': parsed_args.port_chain, 'e': e})
+ raise exceptions.CommandError(msg)
+
+
+def _get_common_attrs(client_manager, parsed_args, is_create=True):
+ attrs = {}
+ client = client_manager.network
+ if parsed_args.name is not None:
+ attrs['name'] = parsed_args.name
+ if parsed_args.description is not None:
+ attrs['description'] = parsed_args.description
+ if parsed_args.port_pair_groups:
+ attrs['port_pair_groups'] = [client.find_sfc_port_pair_group(
+ ppg, ignore_missing=False)['id']
+ for ppg in parsed_args.port_pair_groups]
+ if parsed_args.flow_classifiers:
+ attrs['flow_classifiers'] = [client.find_sfc_flow_classifier(
+ fc, ignore_missing=False)['id']
+ for fc in parsed_args.flow_classifiers]
+ if is_create is True:
+ _get_attrs(attrs, parsed_args)
+ return attrs
+
+
+def _get_attrs(attrs, parsed_args):
+ if parsed_args.chain_parameters is not None:
+ chain_params = {}
+ for chain_param in parsed_args.chain_parameters:
+ if 'correlation' in chain_param:
+ chain_params['correlation'] = chain_param['correlation']
+ if 'symmetric' in chain_param:
+ chain_params['symmetric'] = chain_param['symmetric']
+ attrs['chain_parameters'] = chain_params
diff --git a/neutronclient/osc/v2/sfc/sfc_port_pair.py b/neutronclient/osc/v2/sfc/sfc_port_pair.py
new file mode 100755
index 000000000..11e8e7631
--- /dev/null
+++ b/neutronclient/osc/v2/sfc/sfc_port_pair.py
@@ -0,0 +1,251 @@
+# Copyright (c) 2017 Huawei Technologies India Pvt.Limited.
+# All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License"); you may
+# not use this file except in compliance with the License. You may obtain
+# a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+# License for the specific language governing permissions and limitations
+# under the License.
+
+import logging
+
+from osc_lib.cli import parseractions
+from osc_lib.command import command
+from osc_lib import exceptions
+from osc_lib import utils
+from osc_lib.utils import columns as column_util
+
+from neutronclient._i18n import _
+
+LOG = logging.getLogger(__name__)
+
+resource = 'port_pair'
+
+_attr_map = (
+ ('id', 'ID', column_util.LIST_BOTH),
+ ('name', 'Name', column_util.LIST_BOTH),
+ ('ingress', 'Ingress Logical Port', column_util.LIST_BOTH),
+ ('egress', 'Egress Logical Port', column_util.LIST_BOTH),
+ ('service_function_parameters', 'Service Function Parameters',
+ column_util.LIST_LONG_ONLY),
+ ('description', 'Description', column_util.LIST_LONG_ONLY),
+ ('project_id', 'Project', column_util.LIST_LONG_ONLY),
+)
+
+_attr_map_dict = {
+ 'id': 'ID',
+ 'name': 'Name',
+ 'description': 'Description',
+ 'ingress': 'Ingress Logical Port',
+ 'egress': 'Egress Logical Port',
+ 'service_function_parameters': 'Service Function Parameters',
+ 'tenant_id': 'Project',
+ 'project_id': 'Project',
+}
+
+
+class CreateSfcPortPair(command.ShowOne):
+ _description = _("Create a port pair")
+
+ def get_parser(self, prog_name):
+ parser = super(CreateSfcPortPair, self).get_parser(prog_name)
+ parser.add_argument(
+ 'name',
+ metavar='',
+ help=_('Name of the port pair'))
+ parser.add_argument(
+ '--description',
+ metavar='',
+ help=_('Description for the port pair'))
+ parser.add_argument(
+ '--service-function-parameters',
+ metavar='correlation=,weight=',
+ action=parseractions.MultiKeyValueAction,
+ optional_keys=['correlation', 'weight'],
+ help=_('Dictionary of service function parameters. '
+ 'Currently, correlation=(None|mpls|nsh) and weight '
+ 'are supported. Weight is an integer that influences '
+ 'the selection of a port pair within a port pair group '
+ 'for a flow. The higher the weight, the more flows will '
+ 'hash to the port pair. The default weight is 1.'))
+ parser.add_argument(
+ '--ingress',
+ metavar='',
+ required=True,
+ help=_('Ingress neutron port (name or ID)'))
+ parser.add_argument(
+ '--egress',
+ metavar='',
+ required=True,
+ help=_('Egress neutron port (name or ID)'))
+ return parser
+
+ def take_action(self, parsed_args):
+ client = self.app.client_manager.network
+ attrs = _get_common_attrs(self.app.client_manager, parsed_args)
+ obj = client.create_sfc_port_pair(**attrs)
+ display_columns, columns = utils.get_osc_show_columns_for_sdk_resource(
+ obj, _attr_map_dict, ['location', 'tenant_id'])
+ data = utils.get_dict_properties(obj, columns)
+ return display_columns, data
+
+
+class DeleteSfcPortPair(command.Command):
+ _description = _("Delete a given port pair")
+
+ def get_parser(self, prog_name):
+ parser = super(DeleteSfcPortPair, self).get_parser(prog_name)
+ parser.add_argument(
+ 'port_pair',
+ metavar="",
+ nargs='+',
+ help=_("Port pair(s) to delete (name or ID)")
+ )
+ return parser
+
+ def take_action(self, parsed_args):
+ client = self.app.client_manager.network
+ result = 0
+ for pp in parsed_args.port_pair:
+ try:
+ port_pair_id = client.find_sfc_port_pair(
+ pp, ignore_missing=False)['id']
+ client.delete_sfc_port_pair(port_pair_id)
+ except Exception as e:
+ result += 1
+ LOG.error(_("Failed to delete port pair with name "
+ "or ID '%(port_pair)s': %(e)s"),
+ {'port_pair': pp, 'e': e})
+ if result > 0:
+ total = len(parsed_args.port_pair)
+ msg = (_("%(result)s of %(total)s port pair(s) "
+ "failed to delete.") % {'result': result,
+ 'total': total})
+ raise exceptions.CommandError(msg)
+
+
+class ListSfcPortPair(command.Lister):
+ _description = _("List port pairs")
+
+ def get_parser(self, prog_name):
+ parser = super(ListSfcPortPair, self).get_parser(prog_name)
+ parser.add_argument(
+ '--long',
+ action='store_true',
+ help=_("List additional fields in output")
+ )
+ return parser
+
+ def take_action(self, parsed_args):
+ client = self.app.client_manager.network
+ data = client.sfc_port_pairs()
+ headers, columns = column_util.get_column_definitions(
+ _attr_map, long_listing=parsed_args.long)
+ return (headers,
+ (utils.get_dict_properties(
+ s, columns,
+ ) for s in data))
+
+
+class SetSfcPortPair(command.Command):
+ _description = _("Set port pair properties")
+
+ def get_parser(self, prog_name):
+ parser = super(SetSfcPortPair, self).get_parser(prog_name)
+ parser.add_argument(
+ '--name',
+ metavar='',
+ help=_('Name of the port pair'))
+ parser.add_argument(
+ '--description',
+ metavar='',
+ help=_('Description for the port pair'))
+ parser.add_argument(
+ 'port_pair',
+ metavar='',
+ help=_("Port pair to modify (name or ID)")
+ )
+ return parser
+
+ def take_action(self, parsed_args):
+ client = self.app.client_manager.network
+ port_pair_id = client.find_sfc_port_pair(
+ parsed_args.port_pair, ignore_missing=False
+ )['id']
+ attrs = _get_common_attrs(self.app.client_manager, parsed_args,
+ is_create=False)
+ try:
+ client.update_sfc_port_pair(port_pair_id, **attrs)
+ except Exception as e:
+ msg = (_("Failed to update port pair '%(port_pair)s': %(e)s")
+ % {'port_pair': parsed_args.port_pair, 'e': e})
+ raise exceptions.CommandError(msg)
+
+
+class ShowSfcPortPair(command.ShowOne):
+ _description = _("Display port pair details")
+
+ def get_parser(self, prog_name):
+ parser = super(ShowSfcPortPair, self).get_parser(prog_name)
+ parser.add_argument(
+ 'port_pair',
+ metavar='',
+ help=_("Port pair to display (name or ID)")
+ )
+ return parser
+
+ def take_action(self, parsed_args):
+ client = self.app.client_manager.network
+ port_pair_id = client.find_sfc_port_pair(
+ parsed_args.port_pair, ignore_missing=False
+ )['id']
+ obj = client.get_sfc_port_pair(port_pair_id)
+ display_columns, columns = utils.get_osc_show_columns_for_sdk_resource(
+ obj, _attr_map_dict, ['location', 'tenant_id'])
+ data = utils.get_dict_properties(obj, columns)
+ return display_columns, data
+
+
+def _get_common_attrs(client_manager, parsed_args, is_create=True):
+ attrs = {}
+ if parsed_args.name is not None:
+ attrs['name'] = parsed_args.name
+ if parsed_args.description is not None:
+ attrs['description'] = parsed_args.description
+ if is_create:
+ _get_attrs(client_manager, attrs, parsed_args)
+ return attrs
+
+
+def _get_attrs(client_manager, attrs, parsed_args):
+ client = client_manager.network
+ if parsed_args.ingress is not None:
+ attrs['ingress'] = client.find_port(
+ parsed_args.ingress, ignore_missing=False
+ )['id']
+ if parsed_args.egress is not None:
+ attrs['egress'] = client.find_port(
+ parsed_args.egress, ignore_missing=False
+ )['id']
+ if parsed_args.service_function_parameters is not None:
+ attrs['service_function_parameters'] = _get_service_function_params(
+ parsed_args.service_function_parameters)
+
+
+def _get_service_function_params(sf_params):
+ attrs = {}
+ for sf_param in sf_params:
+ if 'correlation' in sf_param:
+ if sf_param['correlation'] == 'None':
+ attrs['correlation'] = None
+ else:
+ attrs['correlation'] = sf_param['correlation']
+ if 'weight' in sf_param:
+ attrs['weight'] = sf_param['weight']
+ return attrs
diff --git a/neutronclient/osc/v2/sfc/sfc_port_pair_group.py b/neutronclient/osc/v2/sfc/sfc_port_pair_group.py
new file mode 100755
index 000000000..ec8859b42
--- /dev/null
+++ b/neutronclient/osc/v2/sfc/sfc_port_pair_group.py
@@ -0,0 +1,326 @@
+# Copyright (c) 2017 Huawei Technologies India Pvt.Limited.
+# All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License"); you may
+# not use this file except in compliance with the License. You may obtain
+# a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+# License for the specific language governing permissions and limitations
+# under the License.
+
+import logging
+
+from osc_lib.cli import parseractions
+from osc_lib.command import command
+from osc_lib import exceptions
+from osc_lib import utils
+from osc_lib.utils import columns as column_util
+
+from neutronclient._i18n import _
+
+LOG = logging.getLogger(__name__)
+
+resource = 'port_pair_group'
+
+_attr_map = (
+ ('id', 'ID', column_util.LIST_BOTH),
+ ('name', 'Name', column_util.LIST_BOTH),
+ ('port_pairs', 'Port Pair', column_util.LIST_BOTH),
+ ('port_pair_group_parameters', 'Port Pair Group Parameters',
+ column_util.LIST_BOTH),
+ ('description', 'Description', column_util.LIST_LONG_ONLY),
+ ('project_id', 'Project', column_util.LIST_LONG_ONLY),
+ ('is_tap_enabled', 'Tap Enabled', column_util.LIST_BOTH)
+)
+
+_attr_map_dict = {
+ 'id': 'ID',
+ 'name': 'Name',
+ 'description': 'Description',
+ 'port_pairs': 'Port Pair',
+ 'port_pair_group_parameters': 'Port Pair Group Parameters',
+ 'is_tap_enabled': 'Tap Enabled',
+ 'tenant_id': 'Project',
+ 'project_id': 'Project',
+}
+
+
+class CreateSfcPortPairGroup(command.ShowOne):
+ _description = _("Create a port pair group")
+
+ def get_parser(self, prog_name):
+ parser = super(CreateSfcPortPairGroup, self).get_parser(prog_name)
+ parser.add_argument(
+ 'name',
+ metavar='',
+ help=_('Name of the port pair group'))
+ parser.add_argument(
+ '--description',
+ metavar='',
+ help=_('Description for the port pair group'))
+ parser.add_argument(
+ '--port-pair',
+ metavar='',
+ dest='port_pairs',
+ default=[],
+ action='append',
+ help=_('Port pair (name or ID). '
+ 'This option can be repeated.'))
+ tap_enable = parser.add_mutually_exclusive_group()
+ tap_enable.add_argument(
+ '--enable-tap',
+ action='store_true',
+ help=_('Port pairs of this port pair group are deployed as '
+ 'passive tap service function')
+ )
+ tap_enable.add_argument(
+ '--disable-tap',
+ action='store_true',
+ help=_('Port pairs of this port pair group are deployed as l3 '
+ 'service function (default)')
+ )
+ parser.add_argument(
+ '--port-pair-group-parameters',
+ metavar='lb-fields=',
+ action=parseractions.KeyValueAction,
+ help=_('Dictionary of port pair group parameters. '
+ 'Currently only one parameter lb-fields is supported. '
+ ' is a & separated list of load-balancing '
+ 'fields.'))
+ return parser
+
+ def take_action(self, parsed_args):
+ client = self.app.client_manager.network
+ attrs = _get_common_attrs(self.app.client_manager, parsed_args)
+ obj = client.create_sfc_port_pair_group(**attrs)
+ display_columns, columns = utils.get_osc_show_columns_for_sdk_resource(
+ obj, _attr_map_dict, ['location', 'tenant_id'])
+ data = utils.get_dict_properties(obj, columns)
+ return display_columns, data
+
+
+class DeleteSfcPortPairGroup(command.Command):
+ _description = _("Delete a given port pair group")
+
+ def get_parser(self, prog_name):
+ parser = super(DeleteSfcPortPairGroup, self).get_parser(prog_name)
+ parser.add_argument(
+ 'port_pair_group',
+ metavar='',
+ nargs='+',
+ help=_("Port pair group(s) to delete (name or ID)")
+ )
+ return parser
+
+ def take_action(self, parsed_args):
+ client = self.app.client_manager.network
+ result = 0
+ for ppg in parsed_args.port_pair_group:
+ try:
+ ppg_id = client.find_sfc_port_pair_group(
+ ppg, ignore_missing=False)['id']
+ client.delete_sfc_port_pair_group(ppg_id)
+ except Exception as e:
+ result += 1
+ LOG.error(_("Failed to delete port pair group with name "
+ "or ID '%(ppg)s': %(e)s"), {'ppg': ppg, 'e': e})
+ if result > 0:
+ total = len(parsed_args.port_pair_group)
+ msg = (_("%(result)s of %(total)s port pair group(s) "
+ "failed to delete.") % {'result': result,
+ 'total': total})
+ raise exceptions.CommandError(msg)
+
+
+class ListSfcPortPairGroup(command.Lister):
+ _description = _("List port pair group")
+
+ def get_parser(self, prog_name):
+ parser = super(ListSfcPortPairGroup, self).get_parser(prog_name)
+ parser.add_argument(
+ '--long',
+ action='store_true',
+ default=False,
+ help=_("List additional fields in output")
+ )
+ return parser
+
+ def take_action(self, parsed_args):
+ client = self.app.client_manager.network
+ data = client.sfc_port_pair_groups()
+ headers, columns = column_util.get_column_definitions(
+ _attr_map, long_listing=parsed_args.long)
+ return (headers,
+ (utils.get_dict_properties(
+ s, columns,
+ ) for s in data))
+
+
+class SetSfcPortPairGroup(command.Command):
+ _description = _("Set port pair group properties")
+
+ def get_parser(self, prog_name):
+ parser = super(SetSfcPortPairGroup, self).get_parser(prog_name)
+ parser.add_argument(
+ 'port_pair_group',
+ metavar='',
+ help=_("Port pair group to modify (name or ID)"))
+ parser.add_argument(
+ '--name',
+ metavar='',
+ help=_('Name of the port pair group'))
+ parser.add_argument(
+ '--description',
+ metavar='',
+ help=_('Description for the port pair group'))
+ parser.add_argument(
+ '--port-pair',
+ metavar='',
+ dest='port_pairs',
+ default=[],
+ action='append',
+ help=_('Port pair (name or ID). '
+ 'This option can be repeated.'))
+ parser.add_argument(
+ '--no-port-pair',
+ action='store_true',
+ help=_('Remove all port pair from port pair group'))
+ return parser
+
+ def take_action(self, parsed_args):
+ client = self.app.client_manager.network
+ ppg_id = client.find_sfc_port_pair_group(
+ parsed_args.port_pair_group)['id']
+ attrs = _get_common_attrs(self.app.client_manager, parsed_args,
+ is_create=False)
+ if parsed_args.no_port_pair:
+ attrs['port_pairs'] = []
+ if parsed_args.port_pairs:
+ added = [client.find_sfc_port_pair(pp,
+ ignore_missing=False)['id']
+ for pp in parsed_args.port_pairs]
+ if parsed_args.no_port_pair:
+ existing = []
+ else:
+ existing = client.find_sfc_port_pair_group(
+ parsed_args.port_pair_group,
+ ignore_missing=False)['port_pairs']
+ attrs['port_pairs'] = sorted(list(set(existing) | set(added)))
+ try:
+ client.update_sfc_port_pair_group(ppg_id, **attrs)
+ except Exception as e:
+ msg = (_("Failed to update port pair group '%(ppg)s': %(e)s")
+ % {'ppg': parsed_args.port_pair_group, 'e': e})
+ raise exceptions.CommandError(msg)
+
+
+class ShowSfcPortPairGroup(command.ShowOne):
+ _description = _("Display port pair group details")
+
+ def get_parser(self, prog_name):
+ parser = super(ShowSfcPortPairGroup, self).get_parser(prog_name)
+ parser.add_argument(
+ 'port_pair_group',
+ metavar='',
+ help=_("Port pair group to display (name or ID)")
+ )
+ return parser
+
+ def take_action(self, parsed_args):
+ client = self.app.client_manager.network
+ ppg_id = client.find_sfc_port_pair_group(
+ parsed_args.port_pair_group, ignore_missing=False)['id']
+ obj = client.get_sfc_port_pair_group(ppg_id)
+ display_columns, columns = utils.get_osc_show_columns_for_sdk_resource(
+ obj, _attr_map_dict, ['location', 'tenant_id'])
+ data = utils.get_dict_properties(obj, columns)
+ return display_columns, data
+
+
+class UnsetSfcPortPairGroup(command.Command):
+ _description = _("Unset port pairs from port pair group")
+
+ def get_parser(self, prog_name):
+ parser = super(UnsetSfcPortPairGroup, self).get_parser(prog_name)
+ parser.add_argument(
+ 'port_pair_group',
+ metavar='',
+ help=_("Port pair group to unset (name or ID)"))
+ port_pair_group = parser.add_mutually_exclusive_group()
+ port_pair_group.add_argument(
+ '--port-pair',
+ action='append',
+ metavar='',
+ dest='port_pairs',
+ help=_('Remove port pair(s) from the port pair group '
+ '(name or ID). This option can be repeated.'))
+ port_pair_group.add_argument(
+ '--all-port-pair',
+ action='store_true',
+ help=_('Remove all port pairs from the port pair group'))
+ return parser
+
+ def take_action(self, parsed_args):
+ client = self.app.client_manager.network
+ ppg_id = client.find_sfc_port_pair_group(
+ parsed_args.port_pair_group, ignore_missing=False)['id']
+ attrs = {}
+ if parsed_args.port_pairs:
+ existing = client.find_sfc_port_pair_group(
+ parsed_args.port_pair_group,
+ ignore_missing=False)['port_pairs']
+ removed = [client.find_sfc_port_pair(pp,
+ ignore_missing=False)['id']
+ for pp in parsed_args.port_pairs]
+ attrs['port_pairs'] = list(set(existing) - set(removed))
+ if parsed_args.all_port_pair:
+ attrs['port_pairs'] = []
+ try:
+ client.update_sfc_port_pair_group(ppg_id, **attrs)
+ except Exception as e:
+ msg = (_("Failed to unset port pair group '%(ppg)s': %(e)s")
+ % {'ppg': parsed_args.port_pair_group, 'e': e})
+ raise exceptions.CommandError(msg)
+
+
+def _get_ppg_param(attrs, ppg):
+ attrs['port_pair_group_parameters'] = {}
+ for key, value in ppg.items():
+ if key == 'lb-fields':
+ attrs['port_pair_group_parameters']['lb_fields'] = ([
+ field for field in value.split('&') if field])
+ else:
+ attrs['port_pair_group_parameters'][key] = value
+ return attrs['port_pair_group_parameters']
+
+
+def _get_common_attrs(client_manager, parsed_args, is_create=True):
+ client = client_manager.network
+ attrs = {}
+ if parsed_args.name is not None:
+ attrs['name'] = parsed_args.name
+ if parsed_args.description is not None:
+ attrs['description'] = parsed_args.description
+ if parsed_args.port_pairs:
+ attrs['port_pairs'] = [client.find_sfc_port_pair(
+ pp, ignore_missing=False)['id']
+ for pp in parsed_args.port_pairs]
+
+ if is_create:
+ _get_attrs(attrs, parsed_args)
+ return attrs
+
+
+def _get_attrs(attrs, parsed_args):
+ if parsed_args.port_pair_group_parameters is not None:
+ attrs['port_pair_group_parameters'] = (
+ _get_ppg_param(attrs, parsed_args.port_pair_group_parameters))
+ if parsed_args.enable_tap:
+ attrs['tap_enabled'] = True
+ if parsed_args.disable_tap:
+ attrs['tap_enabled'] = False
diff --git a/neutronclient/osc/v2/sfc/sfc_service_graph.py b/neutronclient/osc/v2/sfc/sfc_service_graph.py
new file mode 100644
index 000000000..2edf2ccd0
--- /dev/null
+++ b/neutronclient/osc/v2/sfc/sfc_service_graph.py
@@ -0,0 +1,272 @@
+# Copyright 2017 Intel Corporation.
+#
+# Licensed under the Apache License, Version 2.0 (the "License"); you may
+# not use this file except in compliance with the License. You may obtain
+# a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+# License for the specific language governing permissions and limitations
+# under the License.
+
+import logging
+
+from osc_lib.command import command
+from osc_lib import exceptions
+from osc_lib import utils
+from osc_lib.utils import columns as column_util
+
+from neutronclient._i18n import _
+
+LOG = logging.getLogger(__name__)
+
+resource = 'service_graph'
+
+_attr_map = (
+ ('id', 'ID', column_util.LIST_BOTH),
+ ('name', 'Name', column_util.LIST_BOTH),
+ ('port_chains', 'Branching Points', column_util.LIST_BOTH),
+ ('description', 'Description', column_util.LIST_LONG_ONLY),
+ ('project_id', 'Project', column_util.LIST_LONG_ONLY),
+)
+
+_attr_map_dict = {
+ 'id': 'ID',
+ 'name': 'Name',
+ 'description': 'Description',
+ 'port_chains': 'Branching Points',
+ 'tenant_id': 'Project',
+ 'project_id': 'Project',
+}
+
+
+class CreateSfcServiceGraph(command.ShowOne):
+ """Create a service graph."""
+ def get_parser(self, prog_name):
+ parser = super(CreateSfcServiceGraph, self).get_parser(prog_name)
+ parser.add_argument(
+ 'name',
+ metavar='',
+ help=_('Name of the service graph.'))
+ parser.add_argument(
+ '--description',
+ help=_('Description for the service graph.'))
+ parser.add_argument(
+ '--branching-point',
+ metavar='SRC_CHAIN:DST_CHAIN_1,DST_CHAIN_2,DST_CHAIN_N',
+ dest='branching_points',
+ action='append',
+ default=[], required=True,
+ help=_('Service graph branching point: the key is the source '
+ 'Port Chain while the value is a list of destination '
+ 'Port Chains. This option can be repeated.'))
+ return parser
+
+ def take_action(self, parsed_args):
+ client = self.app.client_manager.network
+ attrs = _get_common_attrs(self.app.client_manager, parsed_args)
+ try:
+ obj = client.create_sfc_service_graph(**attrs)
+ display_columns, columns = \
+ utils.get_osc_show_columns_for_sdk_resource(
+ obj, _attr_map_dict, ['location', 'tenant_id'])
+ data = utils.get_dict_properties(obj, columns)
+ return display_columns, data
+ except Exception as e:
+ msg = (_("Failed to create service graph using '%(pcs)s': %(e)s")
+ % {'pcs': parsed_args.branching_points, 'e': e})
+ raise exceptions.CommandError(msg)
+
+
+class SetSfcServiceGraph(command.Command):
+ _description = _("Set service graph properties")
+
+ def get_parser(self, prog_name):
+ parser = super(SetSfcServiceGraph, self).get_parser(prog_name)
+ parser.add_argument(
+ '--name',
+ metavar='',
+ help=_('Name of the service graph'))
+ parser.add_argument(
+ '--description',
+ metavar='',
+ help=_('Description for the service graph'))
+ parser.add_argument(
+ 'service_graph',
+ metavar='',
+ help=_("Service graph to modify (name or ID)")
+ )
+ return parser
+
+ def take_action(self, parsed_args):
+ client = self.app.client_manager.network
+ service_graph_id = client.find_sfc_service_graph(
+ parsed_args.service_graph, ignore_missing=False)['id']
+ attrs = _get_common_attrs(self.app.client_manager, parsed_args,
+ is_create=False)
+ try:
+ client.update_sfc_service_graph(service_graph_id, **attrs)
+ except Exception as e:
+ msg = (_("Failed to update service graph "
+ "'%(service_graph)s': %(e)s")
+ % {'service_graph': parsed_args.service_graph, 'e': e})
+ raise exceptions.CommandError(msg)
+
+
+class DeleteSfcServiceGraph(command.Command):
+ """Delete a given service graph."""
+
+ def get_parser(self, prog_name):
+ parser = super(DeleteSfcServiceGraph, self).get_parser(prog_name)
+ parser.add_argument(
+ 'service_graph',
+ metavar="",
+ nargs='+',
+ help=_("ID or name of the service graph(s) to delete.")
+ )
+ return parser
+
+ def take_action(self, parsed_args):
+ client = self.app.client_manager.network
+ result = 0
+ for sg in parsed_args.service_graph:
+ try:
+ sg_id = client.find_sfc_service_graph(
+ sg, ignore_missing=False)['id']
+ client.delete_sfc_service_graph(sg_id)
+ except Exception as e:
+ result += 1
+ LOG.error(_("Failed to delete service graph with name "
+ "or ID '%(sg)s': %(e)s"),
+ {'sg': sg, 'e': e})
+ if result > 0:
+ total = len(parsed_args.service_graph)
+ msg = (_("%(result)s of %(total)s service graph(s) "
+ "failed to delete.") % {'result': result,
+ 'total': total})
+ raise exceptions.CommandError(msg)
+
+
+class ListSfcServiceGraph(command.Lister):
+ _description = _("List service graphs")
+
+ def get_parser(self, prog_name):
+ parser = super(ListSfcServiceGraph, self).get_parser(prog_name)
+ parser.add_argument(
+ '--long',
+ action='store_true',
+ default=False,
+ help=_("List additional fields in output")
+ )
+ return parser
+
+ def take_action(self, parsed_args):
+ client = self.app.client_manager.network
+ data = client.sfc_service_graphs()
+ headers, columns = column_util.get_column_definitions(
+ _attr_map, long_listing=parsed_args.long)
+ return (headers,
+ (utils.get_dict_properties(s, columns)
+ for s in data))
+
+
+class ShowSfcServiceGraph(command.ShowOne):
+ """Show information of a given service graph."""
+
+ def get_parser(self, prog_name):
+ parser = super(ShowSfcServiceGraph, self).get_parser(prog_name)
+ parser.add_argument(
+ 'service_graph',
+ metavar="",
+ help=_("ID or name of the service graph to display.")
+ )
+ return parser
+
+ def take_action(self, parsed_args):
+ client = self.app.client_manager.network
+ sg_id = client.find_sfc_service_graph(parsed_args.service_graph,
+ ignore_missing=False)['id']
+ obj = client.get_sfc_service_graph(sg_id)
+ display_columns, columns = utils.get_osc_show_columns_for_sdk_resource(
+ obj, _attr_map_dict, ['location', 'tenant_id'])
+ data = utils.get_dict_properties(obj, columns)
+ return display_columns, data
+
+
+def _get_common_attrs(client_manager, parsed_args, is_create=True):
+ attrs = {}
+ if parsed_args.name is not None:
+ attrs['name'] = str(parsed_args.name)
+ if parsed_args.description is not None:
+ attrs['description'] = str(parsed_args.description)
+ if is_create:
+ _get_attrs_for_create(client_manager, attrs, parsed_args)
+ return attrs
+
+
+def _validate_destination_chains(comma_split, attrs, client, sc_):
+ for e in comma_split:
+ if e != "":
+ dc_ = client.find_sfc_port_chain(e, ignore_missing=False)['id']
+ attrs['port_chains'][sc_].append(dc_)
+ if _check_cycle(attrs['port_chains'], sc_, dc_):
+ raise exceptions.CommandError(
+ "Error: Service graph contains a cycle")
+ else:
+ raise exceptions.CommandError(
+ "Error: you must specify at least one "
+ "destination chain for each source chain")
+ return attrs
+
+
+def _check_cycle(graph, new_src, new_dest):
+ for src in graph:
+ if src == new_dest:
+ if _visit(graph, src, new_dest, new_src):
+ return True
+ return False
+
+
+def _visit(graph, src, new_dest, new_src):
+ if src in graph:
+ found_cycle = False
+ for dest in graph[src]:
+ if new_src == dest or found_cycle:
+ return True
+ else:
+ found_cycle = _visit(graph, dest, new_dest, new_src)
+ return False
+
+
+def _get_attrs_for_create(client_manager, attrs, parsed_args):
+ client = client_manager.network
+ if parsed_args.branching_points:
+ attrs['port_chains'] = {}
+ src_chain = None
+ for c in parsed_args.branching_points:
+ if ':' not in c:
+ raise exceptions.CommandError(
+ "Error: You must specify at least one "
+ "destination chain for each source chain.")
+ colon_split = c.split(':')
+ src_chain = colon_split.pop(0)
+ sc_ = client.find_sfc_port_chain(src_chain,
+ ignore_missing=False)['id']
+ for i in colon_split:
+ comma_split = i.split(',')
+ unique = set(comma_split)
+ if len(unique) != len(comma_split):
+ raise exceptions.CommandError(
+ "Error: Duplicate "
+ "destination chains from "
+ "source chain {}".format(src_chain))
+ if sc_ in attrs['port_chains']:
+ raise exceptions.CommandError(
+ "Error: Source chain {} is in "
+ "use already ".format(src_chain))
+ attrs['port_chains'][sc_] = []
+ _validate_destination_chains(
+ comma_split, attrs, client, sc_)
diff --git a/neutronclient/tests/functional/adv-svcs/__init__.py b/neutronclient/osc/v2/subnet_onboard/__init__.py
similarity index 100%
rename from neutronclient/tests/functional/adv-svcs/__init__.py
rename to neutronclient/osc/v2/subnet_onboard/__init__.py
diff --git a/neutronclient/osc/v2/subnet_onboard/subnet_onboard.py b/neutronclient/osc/v2/subnet_onboard/subnet_onboard.py
new file mode 100644
index 000000000..10c6ab4c2
--- /dev/null
+++ b/neutronclient/osc/v2/subnet_onboard/subnet_onboard.py
@@ -0,0 +1,59 @@
+# Copyright (c) 2019 SUSE Linux Products GmbH
+# All Rights Reserved
+#
+# Licensed under the Apache License, Version 2.0 (the "License"); you may
+# not use this file except in compliance with the License. You may obtain
+# a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+# License for the specific language governing permissions and limitations
+# under the License.
+#
+
+"""Subnet onboard action implementation"""
+import logging
+
+from osc_lib.command import command
+from osc_lib import exceptions
+
+from neutronclient._i18n import _
+
+LOG = logging.getLogger(__name__)
+
+
+class NetworkOnboardSubnets(command.Command):
+ """Onboard network subnets into a subnet pool"""
+
+ def get_parser(self, prog_name):
+ parser = super(NetworkOnboardSubnets, self).get_parser(prog_name)
+ parser.add_argument(
+ 'network',
+ metavar="",
+ help=_("Onboard all subnets associated with this network")
+ )
+ parser.add_argument(
+ 'subnetpool',
+ metavar="",
+ help=_("Target subnet pool for onboarding subnets")
+ )
+ return parser
+
+ def take_action(self, parsed_args):
+ client = self.app.client_manager.neutronclient
+ subnetpool_id = _get_id(client, parsed_args.subnetpool, 'subnetpool')
+ network_id = _get_id(client, parsed_args.network, 'network')
+ body = {'network_id': network_id}
+ try:
+ client.onboard_network_subnets(subnetpool_id, body)
+ except Exception as e:
+ msg = (_("Failed to onboard subnets for network '%(n)s': %(e)s")
+ % {'n': parsed_args.network, 'e': e})
+ raise exceptions.CommandError(msg)
+
+
+def _get_id(client, id_or_name, resource):
+ return client.find_resource(resource, str(id_or_name))['id']
diff --git a/neutronclient/osc/v2/trunk/network_trunk.py b/neutronclient/osc/v2/trunk/network_trunk.py
deleted file mode 100644
index e3eed827a..000000000
--- a/neutronclient/osc/v2/trunk/network_trunk.py
+++ /dev/null
@@ -1,380 +0,0 @@
-# Copyright 2016 ZTE Corporation.
-# All Rights Reserved
-#
-# Licensed under the Apache License, Version 2.0 (the "License"); you may
-# not use this file except in compliance with the License. You may obtain
-# a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-# License for the specific language governing permissions and limitations
-# under the License.
-#
-
-"""Network trunk and subports action implementations"""
-import logging
-
-from osc_lib.cli import parseractions
-from osc_lib.command import command
-from osc_lib import exceptions
-from osc_lib import utils
-
-# TODO(abhiraut): Switch to neutronclients identity utils
-from openstackclient.identity import common as identity_common
-
-from neutronclient._i18n import _
-
-LOG = logging.getLogger(__name__)
-
-TRUNK = 'trunk'
-TRUNKS = 'trunks'
-SUB_PORTS = 'sub_ports'
-
-
-class CreateNetworkTrunk(command.ShowOne):
- """Create a network trunk for a given project"""
-
- def get_parser(self, prog_name):
- parser = super(CreateNetworkTrunk, self).get_parser(prog_name)
- parser.add_argument(
- 'name',
- metavar='',
- help=_("Name of the trunk to create")
- )
- parser.add_argument(
- '--parent-port',
- metavar='',
- required=True,
- help=_("Parent port belonging to this trunk (name or ID)")
- )
- parser.add_argument(
- '--subport',
- metavar='',
- action=parseractions.MultiKeyValueAction, dest='add_subports',
- help=_("Subport to add. Subport is of form "
- "\'port=,segmentation-type=,segmentation-ID=\' "
- "(--subport) option can be repeated")
- )
- admin_group = parser.add_mutually_exclusive_group()
- admin_group.add_argument(
- '--enable',
- action='store_true',
- default=True,
- help=_("Enable trunk (default)")
- )
- admin_group.add_argument(
- '--disable',
- action='store_true',
- help=_("Disable trunk")
- )
- parser.add_argument(
- '--project',
- metavar='',
- help=_("Owner's project (name or ID)")
- )
- identity_common.add_project_domain_option_to_parser(parser)
- return parser
-
- def take_action(self, parsed_args):
- client = self.app.client_manager.neutronclient
- attrs = _get_attrs_for_trunk(self.app.client_manager,
- parsed_args)
- body = {TRUNK: attrs}
- obj = client.create_trunk(body)
- columns = _get_columns(obj[TRUNK])
- data = utils.get_dict_properties(obj[TRUNK], columns,
- formatters=_formatters)
- return columns, data
-
-
-class DeleteNetworkTrunk(command.Command):
- """Delete a given network trunk"""
-
- def get_parser(self, prog_name):
- parser = super(DeleteNetworkTrunk, self).get_parser(prog_name)
- parser.add_argument(
- 'trunk',
- metavar="",
- nargs="+",
- help=_("Trunk(s) to delete (name or ID)")
- )
- return parser
-
- def take_action(self, parsed_args):
- client = self.app.client_manager.neutronclient
- result = 0
- for trunk in parsed_args.trunk:
- try:
- trunk_id = _get_id(client, trunk, TRUNK)
- client.delete_trunk(trunk_id)
- except Exception as e:
- result += 1
- LOG.error(_("Failed to delete trunk with name "
- "or ID '%(trunk)s': %(e)s")
- % {'trunk': trunk, 'e': e})
- if result > 0:
- total = len(parsed_args.trunk)
- msg = (_("%(result)s of %(total)s trunks failed "
- "to delete.") % {'result': result, 'total': total})
- raise exceptions.CommandError(msg)
-
-
-class ListNetworkTrunk(command.Lister):
- """List all network trunks"""
-
- def get_parser(self, prog_name):
- parser = super(ListNetworkTrunk, self).get_parser(prog_name)
- parser.add_argument(
- '--long',
- action='store_true',
- default=False,
- help=_("List additional fields in output")
- )
- return parser
-
- def take_action(self, parsed_args):
- client = self.app.client_manager.neutronclient
- data = client.list_trunks()
- headers = (
- 'ID',
- 'Name',
- 'Parent Port'
- )
- columns = (
- 'id',
- 'name',
- 'port_id'
- )
- if parsed_args.long:
- headers += (
- 'Status',
- 'State',
- )
- columns += (
- 'status',
- 'admin_state_up',
- )
- return (headers,
- (utils.get_dict_properties(
- s, columns,
- formatters=_formatters,
- ) for s in data[TRUNKS]))
-
-
-class SetNetworkTrunk(command.Command):
- """Set network trunk properties"""
-
- def get_parser(self, prog_name):
- parser = super(SetNetworkTrunk, self).get_parser(prog_name)
- parser.add_argument(
- 'trunk',
- metavar="",
- help=_("Trunk to modify (name or ID)")
- )
- parser.add_argument(
- '--name',
- metavar="",
- help=_("Set trunk name")
- )
- parser.add_argument(
- '--subport',
- metavar='',
- action=parseractions.MultiKeyValueAction, dest='set_subports',
- help=_("Subport to add. Subport is of form "
- "\'port=,segmentation-type=,segmentation-ID=\'"
- "(--subport) option can be repeated")
- )
- admin_group = parser.add_mutually_exclusive_group()
- admin_group.add_argument(
- '--enable',
- action='store_true',
- help=_("Enable trunk")
- )
- admin_group.add_argument(
- '--disable',
- action='store_true',
- help=_("Disable trunk")
- )
- return parser
-
- def take_action(self, parsed_args):
- client = self.app.client_manager.neutronclient
- trunk_id = _get_id(client, parsed_args.trunk, TRUNK)
- attrs = _get_attrs_for_trunk(self.app.client_manager, parsed_args)
- body = {TRUNK: attrs}
- try:
- client.update_trunk(trunk_id, body)
- except Exception as e:
- msg = (_("Failed to set trunk '%(t)s': %(e)s")
- % {'t': parsed_args.trunk, 'e': e})
- raise exceptions.CommandError(msg)
- if parsed_args.set_subports:
- subport_attrs = _get_attrs_for_subports(self.app.client_manager,
- parsed_args)
- try:
- client.trunk_add_subports(trunk_id, subport_attrs)
- except Exception as e:
- msg = (_("Failed to add subports to trunk '%(t)s': %(e)s")
- % {'t': parsed_args.trunk, 'e': e})
- raise exceptions.CommandError(msg)
-
-
-class ShowNetworkTrunk(command.ShowOne):
- """Show information of a given network trunk"""
- def get_parser(self, prog_name):
- parser = super(ShowNetworkTrunk, self).get_parser(prog_name)
- parser.add_argument(
- 'trunk',
- metavar="",
- help=_("Trunk to display (name or ID)")
- )
- return parser
-
- def take_action(self, parsed_args):
- client = self.app.client_manager.neutronclient
- trunk_id = _get_id(client, parsed_args.trunk, TRUNK)
- obj = client.show_trunk(trunk_id)
- columns = _get_columns(obj[TRUNK])
- data = utils.get_dict_properties(obj[TRUNK], columns,
- formatters=_formatters)
- return columns, data
-
-
-class ListNetworkSubport(command.Lister):
- """List all subports for a given network trunk"""
-
- def get_parser(self, prog_name):
- parser = super(ListNetworkSubport, self).get_parser(prog_name)
- parser.add_argument(
- '--trunk',
- required=True,
- metavar="",
- help=_("List subports belonging to this trunk (name or ID)")
- )
- return parser
-
- def take_action(self, parsed_args):
- client = self.app.client_manager.neutronclient
- trunk_id = _get_id(client, parsed_args.trunk, TRUNK)
- data = client.trunk_get_subports(trunk_id)
- headers = ('Port', 'Segmentation Type', 'Segmentation ID')
- columns = ('port_id', 'segmentation_type', 'segmentation_id')
- return (headers,
- (utils.get_dict_properties(
- s, columns,
- ) for s in data[SUB_PORTS]))
-
-
-class UnsetNetworkTrunk(command.Command):
- """Unset subports from a given network trunk"""
-
- def get_parser(self, prog_name):
- parser = super(UnsetNetworkTrunk, self).get_parser(prog_name)
- parser.add_argument(
- 'trunk',
- metavar="",
- help=_("Unset subports from this trunk (name or ID)")
- )
- parser.add_argument(
- '--subport',
- metavar="",
- required=True,
- action='append', dest='unset_subports',
- help=_("Subport to delete (name or ID of the port) "
- "(--subport) option can be repeated")
- )
- return parser
-
- def take_action(self, parsed_args):
- client = self.app.client_manager.neutronclient
- attrs = _get_attrs_for_subports(self.app.client_manager, parsed_args)
- trunk_id = _get_id(client, parsed_args.trunk, TRUNK)
- client.trunk_remove_subports(trunk_id, attrs)
-
-
-def _format_admin_state(item):
- return 'UP' if item else 'DOWN'
-
-
-_formatters = {
- 'admin_state_up': _format_admin_state,
- 'sub_ports': utils.format_list_of_dicts,
-}
-
-
-def _get_columns(item):
- return tuple(sorted(list(item.keys())))
-
-
-def _get_attrs_for_trunk(client_manager, parsed_args):
- attrs = {}
- if parsed_args.name is not None:
- attrs['name'] = str(parsed_args.name)
- if parsed_args.enable:
- attrs['admin_state_up'] = True
- if parsed_args.disable:
- attrs['admin_state_up'] = False
- if 'parent_port' in parsed_args and parsed_args.parent_port is not None:
- port_id = _get_id(client_manager.neutronclient,
- parsed_args.parent_port, 'port')
- attrs['port_id'] = port_id
- if 'add_subports' in parsed_args and parsed_args.add_subports is not None:
- attrs[SUB_PORTS] = _format_subports(client_manager,
- parsed_args.add_subports)
-
- # "trunk set" command doesn't support setting project.
- if 'project' in parsed_args and parsed_args.project is not None:
- identity_client = client_manager.identity
- project_id = identity_common.find_project(
- identity_client,
- parsed_args.project,
- parsed_args.project_domain,
- ).id
- attrs['tenant_id'] = project_id
-
- return attrs
-
-
-def _format_subports(client_manager, subports):
- attrs = []
- for subport in subports:
- subport_attrs = {}
- if subport.get('port'):
- port_id = _get_id(client_manager.neutronclient,
- subport['port'], 'port')
- subport_attrs['port_id'] = port_id
- if subport.get('segmentation-id'):
- try:
- subport_attrs['segmentation_id'] = int(
- subport['segmentation-id'])
- except ValueError:
- msg = (_("Segmentation-id '%s' is not an integer") %
- subport['segmentation-id'])
- raise exceptions.CommandError(msg)
- if subport.get('segmentation-type'):
- subport_attrs['segmentation_type'] = subport['segmentation-type']
- attrs.append(subport_attrs)
- return attrs
-
-
-def _get_attrs_for_subports(client_manager, parsed_args):
- attrs = {}
- if 'set_subports' in parsed_args and parsed_args.set_subports is not None:
- attrs[SUB_PORTS] = _format_subports(client_manager,
- parsed_args.set_subports)
- if ('unset_subports' in parsed_args and
- parsed_args.unset_subports is not None):
- subports_list = []
- for subport in parsed_args.unset_subports:
- port_id = _get_id(client_manager.neutronclient,
- subport, 'port')
- subports_list.append({'port_id': port_id})
- attrs[SUB_PORTS] = subports_list
- return attrs
-
-
-def _get_id(client, id_or_name, resource):
- return client.find_resource(resource, str(id_or_name))['id']
diff --git a/neutronclient/osc/v2/utils.py b/neutronclient/osc/v2/utils.py
new file mode 100644
index 000000000..b03e29c3d
--- /dev/null
+++ b/neutronclient/osc/v2/utils.py
@@ -0,0 +1,24 @@
+# Copyright 2016 NEC Corporation
+#
+# Licensed under the Apache License, Version 2.0 (the "License"); you may
+# not use this file except in compliance with the License. You may obtain
+# a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+# License for the specific language governing permissions and limitations
+# under the License.
+
+"""This module is intended to contain methods specific
+to Networking v2 API and its extensions.
+"""
+
+from cliff import columns as cliff_columns
+
+
+class AdminStateColumn(cliff_columns.FormattableColumn):
+ def human_readable(self):
+ return 'UP' if self._value else 'DOWN'
diff --git a/neutronclient/osc/v2/vpnaas/endpoint_group.py b/neutronclient/osc/v2/vpnaas/endpoint_group.py
new file mode 100644
index 000000000..e37c2cef4
--- /dev/null
+++ b/neutronclient/osc/v2/vpnaas/endpoint_group.py
@@ -0,0 +1,222 @@
+# Copyright 2017 FUJITSU LIMITED
+# All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License"); you may
+# not use this file except in compliance with the License. You may obtain
+# a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+# License for the specific language governing permissions and limitations
+# under the License.
+#
+
+from osc_lib.command import command
+from osc_lib import exceptions
+from osc_lib import utils
+from osc_lib.utils import columns as column_util
+from oslo_log import log as logging
+
+from neutronclient._i18n import _
+from neutronclient.osc import utils as osc_utils
+
+
+LOG = logging.getLogger(__name__)
+
+_attr_map = (
+ ('id', 'ID', column_util.LIST_BOTH),
+ ('name', 'Name', column_util.LIST_BOTH),
+ ('type', 'Type', column_util.LIST_BOTH),
+ ('endpoints', 'Endpoints', column_util.LIST_BOTH),
+ ('description', 'Description', column_util.LIST_LONG_ONLY),
+ ('project_id', 'Project', column_util.LIST_LONG_ONLY),
+)
+
+_attr_map_dict = {
+ 'id': 'ID',
+ 'name': 'Name',
+ 'type': 'Type',
+ 'endpoints': 'Endpoints',
+ 'description': 'Description',
+ 'tenant_id': 'Project',
+ 'project_id': 'Project',
+}
+
+
+def _get_common_parser(parser):
+ parser.add_argument(
+ '--description',
+ metavar='',
+ help=_('Description for the endpoint group'))
+ return parser
+
+
+def _get_common_attrs(client_manager, parsed_args, is_create=True):
+ attrs = {}
+ if is_create:
+ if parsed_args.project is not None:
+ attrs['tenant_id'] = osc_utils.find_project(
+ client_manager.identity,
+ parsed_args.project,
+ parsed_args.project_domain,
+ ).id
+ if parsed_args.description:
+ attrs['description'] = parsed_args.description
+ return attrs
+
+
+class CreateEndpointGroup(command.ShowOne):
+ _description = _("Create an endpoint group")
+
+ def get_parser(self, prog_name):
+ parser = super(CreateEndpointGroup, self).get_parser(prog_name)
+ _get_common_parser(parser)
+ parser.add_argument(
+ 'name',
+ metavar='',
+ help=_('Name for the endpoint group'))
+ parser.add_argument(
+ '--type',
+ required=True,
+ help=_('Type of endpoints in group (e.g. subnet, cidr)'))
+ parser.add_argument(
+ '--value',
+ action='append',
+ dest='endpoints',
+ required=True,
+ help=_('Endpoint(s) for the group. Must all be of the same type. '
+ '(--value) option can be repeated'))
+ osc_utils.add_project_owner_option_to_parser(parser)
+ return parser
+
+ def take_action(self, parsed_args):
+ client = self.app.client_manager.network
+ attrs = _get_common_attrs(self.app.client_manager, parsed_args)
+ if parsed_args.name:
+ attrs['name'] = str(parsed_args.name)
+ attrs['type'] = parsed_args.type
+ if parsed_args.type == 'subnet':
+ _subnet_ids = [client.find_subnet(
+ endpoint,
+ ignore_missing=False)['id']
+ for endpoint in parsed_args.endpoints]
+ attrs['endpoints'] = _subnet_ids
+ else:
+ attrs['endpoints'] = parsed_args.endpoints
+ obj = client.create_vpn_endpoint_group(**attrs)
+ display_columns, columns = utils.get_osc_show_columns_for_sdk_resource(
+ obj, _attr_map_dict, ['location', 'tenant_id'])
+ data = utils.get_dict_properties(obj, columns)
+ return display_columns, data
+
+
+class DeleteEndpointGroup(command.Command):
+ _description = _("Delete endpoint group(s)")
+
+ def get_parser(self, prog_name):
+ parser = super(DeleteEndpointGroup, self).get_parser(prog_name)
+ parser.add_argument(
+ 'endpoint_group',
+ metavar='',
+ nargs='+',
+ help=_('Endpoint group(s) to delete (name or ID)'))
+ return parser
+
+ def take_action(self, parsed_args):
+ client = self.app.client_manager.network
+ result = 0
+ for endpoint in parsed_args.endpoint_group:
+ try:
+ endpoint_id = client.find_vpn_endpoint_group(
+ endpoint, ignore_missing=False)['id']
+ client.delete_vpn_endpoint_group(endpoint_id)
+ except Exception as e:
+ result += 1
+ LOG.error(_("Failed to delete endpoint group with "
+ "name or ID '%(endpoint_group)s': %(e)s"),
+ {'endpoint_group': endpoint, 'e': e})
+
+ if result > 0:
+ total = len(parsed_args.endpoint_group)
+ msg = (_("%(result)s of %(total)s endpoint group failed "
+ "to delete.") % {'result': result, 'total': total})
+ raise exceptions.CommandError(msg)
+
+
+class ListEndpointGroup(command.Lister):
+ _description = _("List endpoint groups that belong to a given project")
+
+ def get_parser(self, prog_name):
+ parser = super(ListEndpointGroup, self).get_parser(prog_name)
+ parser.add_argument(
+ '--long',
+ action='store_true',
+ default=False,
+ help=_("List additional fields in output")
+ )
+ return parser
+
+ def take_action(self, parsed_args):
+ client = self.app.client_manager.network
+ obj = client.vpn_endpoint_groups()
+ headers, columns = column_util.get_column_definitions(
+ _attr_map, long_listing=parsed_args.long)
+ return (headers, (utils.get_dict_properties(s, columns) for s in obj))
+
+
+class SetEndpointGroup(command.Command):
+ _description = _("Set endpoint group properties")
+
+ def get_parser(self, prog_name):
+ parser = super(SetEndpointGroup, self).get_parser(prog_name)
+ _get_common_parser(parser)
+ parser.add_argument(
+ '--name',
+ metavar='',
+ help=_('Set a name for the endpoint group'))
+ parser.add_argument(
+ 'endpoint_group',
+ metavar='',
+ help=_('Endpoint group to set (name or ID)'))
+ return parser
+
+ def take_action(self, parsed_args):
+ client = self.app.client_manager.network
+ attrs = _get_common_attrs(self.app.client_manager,
+ parsed_args, is_create=False)
+ if parsed_args.name:
+ attrs['name'] = str(parsed_args.name)
+ endpoint_id = client.find_vpn_endpoint_group(
+ parsed_args.endpoint_group, ignore_missing=False)['id']
+ try:
+ client.update_vpn_endpoint_group(endpoint_id, **attrs)
+ except Exception as e:
+ msg = (_("Failed to set endpoint group "
+ "%(endpoint_group)s: %(e)s")
+ % {'endpoint_group': parsed_args.endpoint_group, 'e': e})
+ raise exceptions.CommandError(msg)
+
+
+class ShowEndpointGroup(command.ShowOne):
+ _description = _("Display endpoint group details")
+
+ def get_parser(self, prog_name):
+ parser = super(ShowEndpointGroup, self).get_parser(prog_name)
+ parser.add_argument(
+ 'endpoint_group',
+ metavar='',
+ help=_('Endpoint group to display (name or ID)'))
+ return parser
+
+ def take_action(self, parsed_args):
+ client = self.app.client_manager.network
+ endpoint_id = client.find_vpn_endpoint_group(
+ parsed_args.endpoint_group, ignore_missing=False)['id']
+ obj = client.get_vpn_endpoint_group(endpoint_id)
+ display_columns, columns = utils.get_osc_show_columns_for_sdk_resource(
+ obj, _attr_map_dict, ['location', 'tenant_id'])
+ data = utils.get_dict_properties(obj, columns)
+ return (display_columns, data)
diff --git a/neutronclient/osc/v2/vpnaas/ikepolicy.py b/neutronclient/osc/v2/vpnaas/ikepolicy.py
new file mode 100644
index 000000000..0a8aecb08
--- /dev/null
+++ b/neutronclient/osc/v2/vpnaas/ikepolicy.py
@@ -0,0 +1,318 @@
+# Copyright 2017 FUJITSU LIMITED
+# All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License"); you may
+# not use this file except in compliance with the License. You may obtain
+# a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+# License for the specific language governing permissions and limitations
+# under the License.
+#
+
+from osc_lib.command import command
+from osc_lib import exceptions
+from osc_lib import utils
+from osc_lib.utils import columns as column_util
+from oslo_log import log as logging
+
+from neutronclient._i18n import _
+from neutronclient.common import utils as nc_utils
+from neutronclient.osc import utils as osc_utils
+from neutronclient.osc.v2.vpnaas import utils as vpn_utils
+
+
+LOG = logging.getLogger(__name__)
+
+_attr_map = (
+ ('id', 'ID', column_util.LIST_BOTH),
+ ('name', 'Name', column_util.LIST_BOTH),
+ ('auth_algorithm', 'Authentication Algorithm', column_util.LIST_BOTH),
+ ('encryption_algorithm', 'Encryption Algorithm', column_util.LIST_BOTH),
+ ('ike_version', 'IKE Version', column_util.LIST_BOTH),
+ ('pfs', 'Perfect Forward Secrecy (PFS)', column_util.LIST_BOTH),
+ ('description', 'Description', column_util.LIST_LONG_ONLY),
+ ('phase1_negotiation_mode', 'Phase1 Negotiation Mode',
+ column_util.LIST_LONG_ONLY),
+ ('project_id', 'Project', column_util.LIST_LONG_ONLY),
+ ('lifetime', 'Lifetime', column_util.LIST_LONG_ONLY),
+)
+
+_attr_map_dict = {
+ 'id': 'ID',
+ 'name': 'Name',
+ 'auth_algorithm': 'Authentication Algorithm',
+ 'encryption_algorithm': 'Encryption Algorithm',
+ 'ike_version': 'IKE Version',
+ 'pfs': 'Perfect Forward Secrecy (PFS)',
+ 'phase1_negotiation_mode': 'Phase1 Negotiation Mode',
+ 'lifetime': 'Lifetime',
+ 'description': 'Description',
+ 'tenant_id': 'Project',
+ 'project_id': 'Project',
+}
+
+_auth_algorithms = [
+ 'sha1',
+ 'sha256',
+ 'sha384',
+ 'sha512',
+ 'aes-xcbc',
+ 'aes-cmac',
+]
+
+_encryption_algorithms = [
+ '3des',
+ 'aes-128',
+ 'aes-192',
+ 'aes-256',
+ 'aes-128-ccm-8',
+ 'aes-192-ccm-8',
+ 'aes-256-ccm-8',
+ 'aes-128-ccm-12',
+ 'aes-192-ccm-12',
+ 'aes-256-ccm-12',
+ 'aes-128-ccm-16',
+ 'aes-192-ccm-16',
+ 'aes-256-ccm-16',
+ 'aes-128-gcm-8',
+ 'aes-192-gcm-8',
+ 'aes-256-gcm-8',
+ 'aes-128-gcm-12',
+ 'aes-192-gcm-12',
+ 'aes-256-gcm-12',
+ 'aes-128-gcm-16',
+ 'aes-192-gcm-16',
+ 'aes-256-gcm-16',
+ 'aes-128-ctr',
+ 'aes-192-ctr',
+ 'aes-256-ctr',
+]
+
+_pfs_groups = [
+ 'group2',
+ 'group5',
+ 'group14',
+ 'group15',
+ 'group16',
+ 'group17',
+ 'group18',
+ 'group19',
+ 'group20',
+ 'group21',
+ 'group22',
+ 'group23',
+ 'group24',
+ 'group25',
+ 'group26',
+ 'group27',
+ 'group28',
+ 'group29',
+ 'group30',
+ 'group31',
+]
+
+
+def _convert_to_lowercase(string):
+ return string.lower()
+
+
+def _get_common_parser(parser):
+ parser.add_argument(
+ '--description',
+ metavar='',
+ help=_('Description of the IKE policy'))
+ parser.add_argument(
+ '--auth-algorithm',
+ choices=_auth_algorithms,
+ type=_convert_to_lowercase,
+ help=_('Authentication algorithm'))
+ parser.add_argument(
+ '--encryption-algorithm',
+ choices=_encryption_algorithms,
+ type=_convert_to_lowercase,
+ help=_('Encryption algorithm'))
+ parser.add_argument(
+ '--phase1-negotiation-mode',
+ choices=['main', 'aggressive'],
+ type=_convert_to_lowercase,
+ help=_('IKE Phase1 negotiation mode'))
+ parser.add_argument(
+ '--ike-version',
+ choices=['v1', 'v2'],
+ type=_convert_to_lowercase,
+ help=_('IKE version for the policy'))
+ parser.add_argument(
+ '--pfs',
+ choices=_pfs_groups,
+ type=_convert_to_lowercase,
+ help=_('Perfect Forward Secrecy'))
+ parser.add_argument(
+ '--lifetime',
+ metavar="units=UNITS,value=VALUE",
+ type=nc_utils.str2dict_type(optional_keys=['units', 'value']),
+ help=vpn_utils.lifetime_help("IKE"))
+ return parser
+
+
+def _get_common_attrs(client_manager, parsed_args, is_create=True):
+ attrs = {}
+ if is_create:
+ if 'project' in parsed_args and parsed_args.project is not None:
+ attrs['project_id'] = osc_utils.find_project(
+ client_manager.identity,
+ parsed_args.project,
+ parsed_args.project_domain,
+ ).id
+ if parsed_args.description:
+ attrs['description'] = parsed_args.description
+ if parsed_args.auth_algorithm:
+ attrs['auth_algorithm'] = parsed_args.auth_algorithm
+ if parsed_args.encryption_algorithm:
+ attrs['encryption_algorithm'] = parsed_args.encryption_algorithm
+ if parsed_args.phase1_negotiation_mode:
+ attrs['phase1_negotiation_mode'] = parsed_args.phase1_negotiation_mode
+ if parsed_args.ike_version:
+ attrs['ike_version'] = parsed_args.ike_version
+ if parsed_args.pfs:
+ attrs['pfs'] = parsed_args.pfs
+ if parsed_args.lifetime:
+ vpn_utils.validate_lifetime_dict(parsed_args.lifetime)
+ attrs['lifetime'] = parsed_args.lifetime
+ return attrs
+
+
+class CreateIKEPolicy(command.ShowOne):
+ _description = _("Create an IKE policy")
+
+ def get_parser(self, prog_name):
+ parser = super(CreateIKEPolicy, self).get_parser(prog_name)
+ _get_common_parser(parser)
+ parser.add_argument(
+ 'name',
+ metavar='',
+ help=_('Name of the IKE policy'))
+ osc_utils.add_project_owner_option_to_parser(parser)
+ return parser
+
+ def take_action(self, parsed_args):
+ client = self.app.client_manager.network
+ attrs = _get_common_attrs(self.app.client_manager, parsed_args)
+ if parsed_args.name:
+ attrs['name'] = str(parsed_args.name)
+ obj = client.create_vpn_ike_policy(**attrs)
+ display_columns, columns = utils.get_osc_show_columns_for_sdk_resource(
+ obj, _attr_map_dict, ['location', 'tenant_id', 'units', 'value'])
+ data = utils.get_dict_properties(obj, columns)
+ return display_columns, data
+
+
+class DeleteIKEPolicy(command.Command):
+ _description = _("Delete IKE policy (policies)")
+
+ def get_parser(self, prog_name):
+ parser = super(DeleteIKEPolicy, self).get_parser(prog_name)
+ parser.add_argument(
+ 'ikepolicy',
+ metavar='',
+ nargs='+',
+ help=_('IKE policy to delete (name or ID)'))
+ return parser
+
+ def take_action(self, parsed_args):
+ client = self.app.client_manager.network
+ result = 0
+ for ike in parsed_args.ikepolicy:
+ try:
+ ike_id = client.find_vpn_ike_policy(ike,
+ ignore_missing=False)['id']
+ client.delete_vpn_ike_policy(ike_id)
+ except Exception as e:
+ result += 1
+ LOG.error(_("Failed to delete IKE policy with "
+ "name or ID '%(ikepolicy)s': %(e)s"),
+ {'ikepolicy': ike, 'e': e})
+
+ if result > 0:
+ total = len(parsed_args.ikepolicy)
+ msg = (_("%(result)s of %(total)s IKE policy failed "
+ "to delete.") % {'result': result, 'total': total})
+ raise exceptions.CommandError(msg)
+
+
+class ListIKEPolicy(command.Lister):
+ _description = _("List IKE policies that belong to a given project")
+
+ def get_parser(self, prog_name):
+ parser = super(ListIKEPolicy, self).get_parser(prog_name)
+ parser.add_argument(
+ '--long',
+ action='store_true',
+ help=_("List additional fields in output")
+ )
+ return parser
+
+ def take_action(self, parsed_args):
+ client = self.app.client_manager.network
+ obj = client.vpn_ike_policies()
+ headers, columns = column_util.get_column_definitions(
+ _attr_map, long_listing=parsed_args.long)
+ return (headers, (utils.get_dict_properties(s, columns) for s in obj))
+
+
+class SetIKEPolicy(command.Command):
+ _description = _("Set IKE policy properties")
+
+ def get_parser(self, prog_name):
+ parser = super(SetIKEPolicy, self).get_parser(prog_name)
+ _get_common_parser(parser)
+ parser.add_argument(
+ '--name',
+ metavar='',
+ help=_('Name of the IKE policy'))
+ parser.add_argument(
+ 'ikepolicy',
+ metavar='',
+ help=_('IKE policy to set (name or ID)'))
+ return parser
+
+ def take_action(self, parsed_args):
+ client = self.app.client_manager.network
+ attrs = _get_common_attrs(self.app.client_manager,
+ parsed_args, is_create=False)
+ if parsed_args.name:
+ attrs['name'] = parsed_args.name
+ ike_id = client.find_vpn_ike_policy(parsed_args.ikepolicy,
+ ignore_missing=False)['id']
+ try:
+ client.update_vpn_ike_policy(ike_id, **attrs)
+ except Exception as e:
+ msg = (_("Failed to set IKE policy '%(ike)s': %(e)s")
+ % {'ike': parsed_args.ikepolicy, 'e': e})
+ raise exceptions.CommandError(msg)
+
+
+class ShowIKEPolicy(command.ShowOne):
+ _description = _("Display IKE policy details")
+
+ def get_parser(self, prog_name):
+ parser = super(ShowIKEPolicy, self).get_parser(prog_name)
+ parser.add_argument(
+ 'ikepolicy',
+ metavar='',
+ help=_('IKE policy to display (name or ID)'))
+ return parser
+
+ def take_action(self, parsed_args):
+ client = self.app.client_manager.network
+ ike_id = client.find_vpn_ike_policy(parsed_args.ikepolicy,
+ ignore_missing=False)['id']
+ obj = client.get_vpn_ike_policy(ike_id)
+ display_columns, columns = utils.get_osc_show_columns_for_sdk_resource(
+ obj, _attr_map_dict, ['location', 'tenant_id', 'units', 'value'])
+ data = utils.get_dict_properties(obj, columns)
+ return (display_columns, data)
diff --git a/neutronclient/osc/v2/vpnaas/ipsec_site_connection.py b/neutronclient/osc/v2/vpnaas/ipsec_site_connection.py
new file mode 100644
index 000000000..1497793b0
--- /dev/null
+++ b/neutronclient/osc/v2/vpnaas/ipsec_site_connection.py
@@ -0,0 +1,385 @@
+# Copyright 2017 FUJITSU LIMITED
+# All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License"); you may
+# not use this file except in compliance with the License. You may obtain
+# a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+# License for the specific language governing permissions and limitations
+# under the License.
+#
+
+from osc_lib.cli import format_columns
+from osc_lib.command import command
+from osc_lib import exceptions
+from osc_lib import utils
+from osc_lib.utils import columns as column_util
+from oslo_log import log as logging
+
+from neutronclient._i18n import _
+from neutronclient.common import utils as nc_utils
+from neutronclient.osc import utils as osc_utils
+from neutronclient.osc.v2.vpnaas import utils as vpn_utils
+
+
+LOG = logging.getLogger(__name__)
+
+
+_formatters = {
+ 'peer_cidrs': format_columns.ListColumn
+}
+
+
+_attr_map = (
+ ('id', 'ID', column_util.LIST_BOTH),
+ ('name', 'Name', column_util.LIST_BOTH),
+ ('peer_address', 'Peer Address', column_util.LIST_BOTH),
+ ('auth_mode', 'Authentication Algorithm', column_util.LIST_BOTH),
+ ('status', 'Status', column_util.LIST_BOTH),
+ ('project_id', 'Project', column_util.LIST_LONG_ONLY),
+ ('peer_cidrs', 'Peer CIDRs', column_util.LIST_LONG_ONLY),
+ ('vpnservice_id', 'VPN Service', column_util.LIST_LONG_ONLY),
+ ('ipsecpolicy_id', 'IPSec Policy', column_util.LIST_LONG_ONLY),
+ ('ikepolicy_id', 'IKE Policy', column_util.LIST_LONG_ONLY),
+ ('mtu', 'MTU', column_util.LIST_LONG_ONLY),
+ ('initiator', 'Initiator', column_util.LIST_LONG_ONLY),
+ ('is_admin_state_up', 'State', column_util.LIST_LONG_ONLY),
+ ('description', 'Description', column_util.LIST_LONG_ONLY),
+ ('psk', 'Pre-shared Key', column_util.LIST_LONG_ONLY),
+ ('route_mode', 'Route Mode', column_util.LIST_LONG_ONLY),
+ ('local_id', 'Local ID', column_util.LIST_LONG_ONLY),
+ ('peer_id', 'Peer ID', column_util.LIST_LONG_ONLY),
+ ('local_ep_group_id', 'Local Endpoint Group ID',
+ column_util.LIST_LONG_ONLY),
+ ('peer_ep_group_id', 'Peer Endpoint Group ID', column_util.LIST_LONG_ONLY),
+ ('dpd', 'DPD', column_util.LIST_LONG_ONLY),
+)
+
+_attr_map_dict = {
+ 'id': 'ID',
+ 'name': 'Name',
+ 'peer_address': 'Peer Address',
+ 'auth_mode': 'Authentication Algorithm',
+ 'status': 'Status',
+ 'peer_cidrs': 'Peer CIDRs',
+ 'vpnservice_id': 'VPN Service',
+ 'ipsecpolicy_id': 'IPSec Policy',
+ 'ikepolicy_id': 'IKE Policy',
+ 'mtu': 'MTU',
+ 'initiator': 'Initiator',
+ 'is_admin_state_up': 'State',
+ 'psk': 'Pre-shared Key',
+ 'route_mode': 'Route Mode',
+ 'local_id': 'Local ID',
+ 'peer_id': 'Peer ID',
+ 'local_ep_group_id': 'Local Endpoint Group ID',
+ 'peer_ep_group_id': 'Peer Endpoint Group ID',
+ 'description': 'Description',
+ 'project_id': 'Project',
+ 'dpd': 'DPD',
+}
+
+
+def _convert_to_lowercase(string):
+ return string.lower()
+
+
+def _get_common_parser(parser, is_create=True):
+ parser.add_argument(
+ '--description',
+ metavar='',
+ help=_('Description for the connection'))
+ parser.add_argument(
+ '--dpd',
+ metavar="action=ACTION,interval=INTERVAL,timeout=TIMEOUT",
+ type=nc_utils.str2dict_type(
+ optional_keys=['action', 'interval', 'timeout']),
+ help=vpn_utils.dpd_help("IPsec connection"))
+ parser.add_argument(
+ '--mtu',
+ help=_('MTU size for the connection'))
+ parser.add_argument(
+ '--initiator',
+ choices=['bi-directional', 'response-only'],
+ type=_convert_to_lowercase,
+ help=_('Initiator state'))
+ peer_group = parser.add_mutually_exclusive_group()
+ peer_group.add_argument(
+ '--peer-cidr',
+ dest='peer_cidrs',
+ help=_('Remote subnet(s) in CIDR format. '
+ 'Cannot be specified when using endpoint groups. Only '
+ 'applicable, if subnet provided for VPN service.')
+ )
+ peer_group.add_argument(
+ '--local-endpoint-group',
+ help=_('Local endpoint group (name or ID) with subnet(s) '
+ 'for IPsec connection')
+ )
+ parser.add_argument(
+ '--peer-endpoint-group',
+ help=_('Peer endpoint group (name or ID) with CIDR(s) for '
+ 'IPSec connection'))
+ admin_group = parser.add_mutually_exclusive_group()
+ admin_group.add_argument(
+ '--enable',
+ action='store_true',
+ help=_("Enable IPSec site connection")
+ )
+ admin_group.add_argument(
+ '--disable',
+ action='store_true',
+ help=_("Disable IPSec site connection")
+ )
+ parser.add_argument(
+ '--local-id',
+ help=_('An ID to be used instead of the external IP '
+ 'address for a virtual router'))
+ return parser
+
+
+def _get_common_attrs(client_manager, parsed_args, is_create=True):
+ attrs = {}
+ if is_create:
+ if 'project' in parsed_args and parsed_args.project is not None:
+ attrs['project_id'] = osc_utils.find_project(
+ client_manager.identity,
+ parsed_args.project,
+ parsed_args.project_domain,
+ ).id
+ if parsed_args.description:
+ attrs['description'] = str(parsed_args.description)
+ if parsed_args.mtu:
+ attrs['mtu'] = parsed_args.mtu
+ if parsed_args.enable:
+ attrs['admin_state_up'] = True
+ if parsed_args.disable:
+ attrs['admin_state_up'] = False
+ if parsed_args.initiator:
+ attrs['initiator'] = parsed_args.initiator
+ if parsed_args.dpd:
+ vpn_utils.validate_dpd_dict(parsed_args.dpd)
+ attrs['dpd'] = parsed_args.dpd
+ if parsed_args.local_endpoint_group:
+ _local_epg = client_manager.network.find_vpn_endpoint_group(
+ parsed_args.local_endpoint_group)['id']
+ attrs['local_ep_group_id'] = _local_epg
+ if parsed_args.peer_endpoint_group:
+ _peer_epg = client_manager.network.find_vpn_endpoint_group(
+ parsed_args.peer_endpoint_group)['id']
+ attrs['peer_ep_group_id'] = _peer_epg
+ if parsed_args.peer_cidrs:
+ attrs['peer_cidrs'] = parsed_args.peer_cidrs
+ if parsed_args.local_id:
+ attrs['local_id'] = parsed_args.local_id
+ return attrs
+
+
+class CreateIPsecSiteConnection(command.ShowOne):
+ _description = _("Create an IPsec site connection")
+
+ def get_parser(self, prog_name):
+ parser = super(CreateIPsecSiteConnection, self).get_parser(prog_name)
+ _get_common_parser(parser)
+ parser.add_argument(
+ '--peer-id',
+ required=True,
+ help=_('Peer router identity for authentication. Can be '
+ 'IPv4/IPv6 address, e-mail address, key id, or FQDN'))
+ parser.add_argument(
+ '--peer-address',
+ required=True,
+ help=_('Peer gateway public IPv4/IPv6 address or FQDN'))
+ parser.add_argument(
+ '--psk',
+ required=True,
+ help=_('Pre-shared key string.'))
+ parser.add_argument(
+ '--vpnservice',
+ metavar='VPNSERVICE',
+ required=True,
+ help=_('VPN service instance associated with this '
+ 'connection (name or ID)'))
+ parser.add_argument(
+ '--ikepolicy',
+ metavar='IKEPOLICY',
+ required=True,
+ help=_('IKE policy associated with this connection (name or ID)'))
+ parser.add_argument(
+ '--ipsecpolicy',
+ metavar='IPSECPOLICY',
+ required=True,
+ help=_('IPsec policy associated with this connection '
+ '(name or ID)'))
+ parser.add_argument(
+ 'name',
+ metavar='',
+ help=_('Set friendly name for the connection'))
+ osc_utils.add_project_owner_option_to_parser(parser)
+ return parser
+
+ def take_action(self, parsed_args):
+ client = self.app.client_manager.network
+ attrs = _get_common_attrs(self.app.client_manager, parsed_args)
+ if parsed_args.vpnservice:
+ _vpnservice_id = client.find_vpn_service(
+ parsed_args.vpnservice, ignore_missing=False)['id']
+ attrs['vpnservice_id'] = _vpnservice_id
+ if parsed_args.ikepolicy:
+ _ikepolicy_id = client.find_vpn_ike_policy(
+ parsed_args.ikepolicy, ignore_missing=False)['id']
+ attrs['ikepolicy_id'] = _ikepolicy_id
+ if parsed_args.ipsecpolicy:
+ _ipsecpolicy_id = client.find_vpn_ipsec_policy(
+ parsed_args.ipsecpolicy, ignore_missing=False)['id']
+ attrs['ipsecpolicy_id'] = _ipsecpolicy_id
+ if parsed_args.peer_id:
+ attrs['peer_id'] = parsed_args.peer_id
+ if parsed_args.peer_address:
+ attrs['peer_address'] = parsed_args.peer_address
+ if parsed_args.psk:
+ attrs['psk'] = parsed_args.psk
+ if parsed_args.name:
+ attrs['name'] = parsed_args.name
+ if (bool(parsed_args.local_endpoint_group) !=
+ bool(parsed_args.peer_endpoint_group)):
+ message = _("You must specify both local and peer endpoint "
+ "groups")
+ raise exceptions.CommandError(message)
+ if not parsed_args.peer_cidrs and not parsed_args.local_endpoint_group:
+ message = _("You must specify endpoint groups or peer CIDR(s)")
+ raise exceptions.CommandError(message)
+ obj = client.create_vpn_ipsec_site_connection(**attrs)
+ display_columns, columns = utils.get_osc_show_columns_for_sdk_resource(
+ obj, _attr_map_dict, ['location', 'tenant_id', 'action',
+ 'timeout', 'interval'])
+ data = utils.get_dict_properties(obj, columns, formatters=_formatters)
+ return display_columns, data
+
+
+class DeleteIPsecSiteConnection(command.Command):
+ _description = _("Delete IPsec site connection(s)")
+
+ def get_parser(self, prog_name):
+ parser = super(DeleteIPsecSiteConnection, self).get_parser(prog_name)
+ parser.add_argument(
+ 'ipsec_site_connection',
+ metavar='',
+ nargs='+',
+ help=_('IPsec site connection to delete (name or ID)'))
+ return parser
+
+ def take_action(self, parsed_args):
+ client = self.app.client_manager.network
+ result = 0
+ for ipsec_conn in parsed_args.ipsec_site_connection:
+ try:
+ ipsec_con_id = client.find_vpn_ipsec_site_connection(
+ ipsec_conn, ignore_missing=False)['id']
+ client.delete_vpn_ipsec_site_connection(ipsec_con_id)
+ except Exception as e:
+ result += 1
+ LOG.error(_("Failed to delete IPsec site connection with "
+ "name or ID '%(ipsec_site_conn)s': %(e)s"),
+ {'ipsec_site_conn': ipsec_conn, 'e': e})
+
+ if result > 0:
+ total = len(parsed_args.ipsec_site_connection)
+ msg = (_("%(result)s of %(total)s IPsec site connection failed "
+ "to delete.") % {'result': result, 'total': total})
+ raise exceptions.CommandError(msg)
+
+
+class ListIPsecSiteConnection(command.Lister):
+ _description = _("List IPsec site connections "
+ "that belong to a given project")
+
+ def get_parser(self, prog_name):
+ parser = super(ListIPsecSiteConnection, self).get_parser(prog_name)
+ parser.add_argument(
+ '--long',
+ action='store_true',
+ default=False,
+ help=_("List additional fields in output")
+ )
+ return parser
+
+ def take_action(self, parsed_args):
+ client = self.app.client_manager.network
+ obj = client.vpn_ipsec_site_connections()
+ headers, columns = column_util.get_column_definitions(
+ _attr_map, long_listing=parsed_args.long)
+ return (headers, (utils.get_dict_properties(
+ s, columns, formatters=_formatters) for s in obj))
+
+
+class SetIPsecSiteConnection(command.Command):
+ _description = _("Set IPsec site connection properties")
+
+ def get_parser(self, prog_name):
+ parser = super(SetIPsecSiteConnection, self).get_parser(prog_name)
+ _get_common_parser(parser)
+ parser.add_argument(
+ '--peer-id',
+ help=_('Peer router identity for authentication. Can be '
+ 'IPv4/IPv6 address, e-mail address, key id, or FQDN'))
+ parser.add_argument(
+ '--peer-address',
+ help=_('Peer gateway public IPv4/IPv6 address or FQDN'))
+ parser.add_argument(
+ '--name',
+ metavar='',
+ help=_('Set friendly name for the connection'))
+ parser.add_argument(
+ 'ipsec_site_connection',
+ metavar='',
+ help=_('IPsec site connection to set (name or ID)'))
+ return parser
+
+ def take_action(self, parsed_args):
+ client = self.app.client_manager.network
+ attrs = _get_common_attrs(self.app.client_manager,
+ parsed_args, is_create=False)
+ if parsed_args.peer_id:
+ attrs['peer_id'] = parsed_args.peer_id
+ if parsed_args.peer_address:
+ attrs['peer_address'] = parsed_args.peer_address
+ if parsed_args.name:
+ attrs['name'] = parsed_args.name
+ ipsec_conn_id = client.find_vpn_ipsec_site_connection(
+ parsed_args.ipsec_site_connection, ignore_missing=False)['id']
+ try:
+ client.update_vpn_ipsec_site_connection(ipsec_conn_id, **attrs)
+ except Exception as e:
+ msg = (_("Failed to set IPsec site "
+ "connection '%(ipsec_conn)s': %(e)s")
+ % {'ipsec_conn': parsed_args.ipsec_site_connection, 'e': e})
+ raise exceptions.CommandError(msg)
+
+
+class ShowIPsecSiteConnection(command.ShowOne):
+ _description = _("Show information of a given IPsec site connection")
+
+ def get_parser(self, prog_name):
+ parser = super(ShowIPsecSiteConnection, self).get_parser(prog_name)
+ parser.add_argument(
+ 'ipsec_site_connection',
+ metavar='',
+ help=_('IPsec site connection to display (name or ID)'))
+ return parser
+
+ def take_action(self, parsed_args):
+ client = self.app.client_manager.network
+ ipsec_site_id = client.find_vpn_ipsec_site_connection(
+ parsed_args.ipsec_site_connection, ignore_missing=False)['id']
+ obj = client.get_vpn_ipsec_site_connection(ipsec_site_id)
+ display_columns, columns = utils.get_osc_show_columns_for_sdk_resource(
+ obj, _attr_map_dict, ['location', 'tenant_id', 'action',
+ 'timeout', 'interval'])
+ data = utils.get_dict_properties(obj, columns, formatters=_formatters)
+ return (display_columns, data)
diff --git a/neutronclient/osc/v2/vpnaas/ipsecpolicy.py b/neutronclient/osc/v2/vpnaas/ipsecpolicy.py
new file mode 100644
index 000000000..c6e42bd06
--- /dev/null
+++ b/neutronclient/osc/v2/vpnaas/ipsecpolicy.py
@@ -0,0 +1,318 @@
+# Copyright 2017 FUJITSU LIMITED
+# All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License"); you may
+# not use this file except in compliance with the License. You may obtain
+# a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+# License for the specific language governing permissions and limitations
+# under the License.
+#
+
+from osc_lib.command import command
+from osc_lib import exceptions
+from osc_lib import utils
+from osc_lib.utils import columns as column_util
+from oslo_log import log as logging
+
+from neutronclient._i18n import _
+from neutronclient.common import utils as nc_utils
+from neutronclient.osc import utils as osc_utils
+from neutronclient.osc.v2.vpnaas import utils as vpn_utils
+
+
+LOG = logging.getLogger(__name__)
+
+_attr_map = (
+ ('id', 'ID', column_util.LIST_BOTH),
+ ('name', 'Name', column_util.LIST_BOTH),
+ ('auth_algorithm', 'Authentication Algorithm', column_util.LIST_BOTH),
+ ('encapsulation_mode', 'Encapsulation Mode', column_util.LIST_BOTH),
+ ('transform_protocol', 'Transform Protocol', column_util.LIST_BOTH),
+ ('encryption_algorithm', 'Encryption Algorithm', column_util.LIST_BOTH),
+ ('pfs', 'Perfect Forward Secrecy (PFS)', column_util.LIST_LONG_ONLY),
+ ('description', 'Description', column_util.LIST_LONG_ONLY),
+ ('project_id', 'Project', column_util.LIST_LONG_ONLY),
+ ('lifetime', 'Lifetime', column_util.LIST_LONG_ONLY),
+)
+
+_attr_map_dict = {
+ 'id': 'ID',
+ 'name': 'Name',
+ 'auth_algorithm': 'Authentication Algorithm',
+ 'encapsulation_mode': 'Encapsulation Mode',
+ 'transform_protocol': 'Transform Protocol',
+ 'encryption_algorithm': 'Encryption Algorithm',
+ 'pfs': 'Perfect Forward Secrecy (PFS)',
+ 'lifetime': 'Lifetime',
+ 'description': 'Description',
+ 'project_id': 'Project',
+}
+
+_auth_algorithms = [
+ 'sha1',
+ 'sha256',
+ 'sha384',
+ 'sha512',
+ 'aes-xcbc',
+ 'aes-cmac',
+]
+
+_encryption_algorithms = [
+ '3des',
+ 'aes-128',
+ 'aes-192',
+ 'aes-256',
+ 'aes-128-ccm-8',
+ 'aes-192-ccm-8',
+ 'aes-256-ccm-8',
+ 'aes-128-ccm-12',
+ 'aes-192-ccm-12',
+ 'aes-256-ccm-12',
+ 'aes-128-ccm-16',
+ 'aes-192-ccm-16',
+ 'aes-256-ccm-16',
+ 'aes-128-gcm-8',
+ 'aes-192-gcm-8',
+ 'aes-256-gcm-8',
+ 'aes-128-gcm-12',
+ 'aes-192-gcm-12',
+ 'aes-256-gcm-12',
+ 'aes-128-gcm-16',
+ 'aes-192-gcm-16',
+ 'aes-256-gcm-16',
+ 'aes-128-ctr',
+ 'aes-192-ctr',
+ 'aes-256-ctr',
+]
+
+_pfs_groups = [
+ 'group2',
+ 'group5',
+ 'group14',
+ 'group15',
+ 'group16',
+ 'group17',
+ 'group18',
+ 'group19',
+ 'group20',
+ 'group21',
+ 'group22',
+ 'group23',
+ 'group24',
+ 'group25',
+ 'group26',
+ 'group27',
+ 'group28',
+ 'group29',
+ 'group30',
+ 'group31',
+]
+
+
+def _convert_to_lowercase(string):
+ return string.lower()
+
+
+def _get_common_parser(parser):
+ parser.add_argument(
+ '--description',
+ metavar='',
+ help=_('Description of the IPsec policy'))
+ parser.add_argument(
+ '--auth-algorithm',
+ choices=_auth_algorithms,
+ type=_convert_to_lowercase,
+ help=_('Authentication algorithm for IPsec policy'))
+ parser.add_argument(
+ '--encapsulation-mode',
+ choices=['tunnel', 'transport'],
+ type=_convert_to_lowercase,
+ help=_('Encapsulation mode for IPsec policy'))
+ parser.add_argument(
+ '--encryption-algorithm',
+ choices=_encryption_algorithms,
+ type=_convert_to_lowercase,
+ help=_('Encryption algorithm for IPsec policy'))
+ parser.add_argument(
+ '--lifetime',
+ metavar="units=UNITS,value=VALUE",
+ type=nc_utils.str2dict_type(optional_keys=['units', 'value']),
+ help=vpn_utils.lifetime_help("IPsec"))
+ parser.add_argument(
+ '--pfs',
+ choices=_pfs_groups,
+ type=_convert_to_lowercase,
+ help=_('Perfect Forward Secrecy for IPsec policy'))
+ parser.add_argument(
+ '--transform-protocol',
+ type=_convert_to_lowercase,
+ choices=['esp', 'ah', 'ah-esp'],
+ help=_('Transform protocol for IPsec policy'))
+
+
+def _get_common_attrs(client_manager, parsed_args, is_create=True):
+ attrs = {}
+ if is_create:
+ if 'project' in parsed_args and parsed_args.project is not None:
+ attrs['project_id'] = osc_utils.find_project(
+ client_manager.identity,
+ parsed_args.project,
+ parsed_args.project_domain,
+ ).id
+ if parsed_args.description:
+ attrs['description'] = str(parsed_args.description)
+ if parsed_args.auth_algorithm:
+ attrs['auth_algorithm'] = parsed_args.auth_algorithm
+ if parsed_args.encapsulation_mode:
+ attrs['encapsulation_mode'] = parsed_args.encapsulation_mode
+ if parsed_args.transform_protocol:
+ attrs['transform_protocol'] = parsed_args.transform_protocol
+ if parsed_args.encryption_algorithm:
+ attrs['encryption_algorithm'] = parsed_args.encryption_algorithm
+ if parsed_args.pfs:
+ attrs['pfs'] = parsed_args.pfs
+ if parsed_args.lifetime:
+ vpn_utils.validate_lifetime_dict(parsed_args.lifetime)
+ attrs['lifetime'] = parsed_args.lifetime
+ return attrs
+
+
+class CreateIPsecPolicy(command.ShowOne):
+ _description = _("Create an IPsec policy")
+
+ def get_parser(self, prog_name):
+ parser = super(CreateIPsecPolicy, self).get_parser(prog_name)
+ _get_common_parser(parser)
+ parser.add_argument(
+ 'name',
+ metavar='',
+ help=_('Name of the IPsec policy'))
+ osc_utils.add_project_owner_option_to_parser(parser)
+ return parser
+
+ def take_action(self, parsed_args):
+ client = self.app.client_manager.network
+ attrs = _get_common_attrs(self.app.client_manager, parsed_args)
+ if parsed_args.name:
+ attrs['name'] = str(parsed_args.name)
+ obj = client.create_vpn_ipsec_policy(**attrs)
+ display_columns, columns = utils.get_osc_show_columns_for_sdk_resource(
+ obj, _attr_map_dict, ['location', 'tenant_id',
+ 'phase1_negotiation_mode', 'units', 'value'])
+ data = utils.get_dict_properties(obj, columns)
+ return display_columns, data
+
+
+class DeleteIPsecPolicy(command.Command):
+ _description = _("Delete IPsec policy(policies)")
+
+ def get_parser(self, prog_name):
+ parser = super(DeleteIPsecPolicy, self).get_parser(prog_name)
+ parser.add_argument(
+ 'ipsecpolicy',
+ metavar='',
+ nargs='+',
+ help=_('ipsec policy to delete (name or ID)'))
+ return parser
+
+ def take_action(self, parsed_args):
+ client = self.app.client_manager.network
+ result = 0
+ for ipsec in parsed_args.ipsecpolicy:
+ try:
+ ipsec_id = client.find_vpn_ipsec_policy(
+ ipsec, ignore_missing=False)['id']
+ client.delete_vpn_ipsec_policy(ipsec_id)
+ except Exception as e:
+ result += 1
+ LOG.error(_("Failed to delete IPsec policy with "
+ "name or ID '%(ipsecpolicy)s': %(e)s"),
+ {'ipsecpolicy': ipsec, 'e': e})
+
+ if result > 0:
+ total = len(parsed_args.ipsecpolicy)
+ msg = (_("%(result)s of %(total)s IPsec policy failed "
+ "to delete.") % {'result': result, 'total': total})
+ raise exceptions.CommandError(msg)
+
+
+class ListIPsecPolicy(command.Lister):
+ _description = _("List IPsec policies that belong to a given project")
+
+ def get_parser(self, prog_name):
+ parser = super(ListIPsecPolicy, self).get_parser(prog_name)
+ parser.add_argument(
+ '--long',
+ action='store_true',
+ default=False,
+ help=_("List additional fields in output")
+ )
+ return parser
+
+ def take_action(self, parsed_args):
+ client = self.app.client_manager.network
+ obj = client.vpn_ipsec_policies()
+ headers, columns = column_util.get_column_definitions(
+ _attr_map, long_listing=parsed_args.long)
+ return (headers, (utils.get_dict_properties(s, columns) for s in obj))
+
+
+class SetIPsecPolicy(command.Command):
+ _description = _("Set IPsec policy properties")
+
+ def get_parser(self, prog_name):
+ parser = super(SetIPsecPolicy, self).get_parser(prog_name)
+ _get_common_parser(parser)
+ parser.add_argument(
+ '--name',
+ metavar='',
+ help=_('Name of the IPsec policy'))
+ parser.add_argument(
+ 'ipsecpolicy',
+ metavar='',
+ help=_('IPsec policy to set (name or ID)'))
+ return parser
+
+ def take_action(self, parsed_args):
+ client = self.app.client_manager.network
+ attrs = _get_common_attrs(self.app.client_manager,
+ parsed_args, is_create=False)
+ if parsed_args.name:
+ attrs['name'] = str(parsed_args.name)
+ ipsec_id = client.find_vpn_ipsec_policy(
+ parsed_args.ipsecpolicy, ignore_missing=False)['id']
+ try:
+ client.update_vpn_ipsec_policy(ipsec_id, **attrs)
+ except Exception as e:
+ msg = (_("Failed to set IPsec policy '%(ipsec)s': %(e)s")
+ % {'ipsec': parsed_args.ipsecpolicy, 'e': e})
+ raise exceptions.CommandError(msg)
+
+
+class ShowIPsecPolicy(command.ShowOne):
+ _description = _("Display IPsec policy details")
+
+ def get_parser(self, prog_name):
+ parser = super(ShowIPsecPolicy, self).get_parser(prog_name)
+ parser.add_argument(
+ 'ipsecpolicy',
+ metavar='',
+ help=_('IPsec policy to display (name or ID)'))
+ return parser
+
+ def take_action(self, parsed_args):
+ client = self.app.client_manager.network
+ ipsec_id = client.find_vpn_ipsec_policy(
+ parsed_args.ipsecpolicy, ignore_missing=False)['id']
+ obj = client.get_vpn_ipsec_policy(ipsec_id)
+ display_columns, columns = utils.get_osc_show_columns_for_sdk_resource(
+ obj, _attr_map_dict, ['location', 'tenant_id',
+ 'phase1_negotiation_mode', 'units', 'value'])
+ data = utils.get_dict_properties(obj, columns)
+ return (display_columns, data)
diff --git a/neutronclient/osc/v2/vpnaas/utils.py b/neutronclient/osc/v2/vpnaas/utils.py
new file mode 100644
index 000000000..2de5cc35e
--- /dev/null
+++ b/neutronclient/osc/v2/vpnaas/utils.py
@@ -0,0 +1,112 @@
+# Copyright 2017 FUJITSU LIMITED
+# All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License"); you may
+# not use this file except in compliance with the License. You may obtain
+# a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+# License for the specific language governing permissions and limitations
+# under the License.
+#
+
+
+"""VPN Utilities and helper functions."""
+
+
+from neutronclient._i18n import _
+from neutronclient.common import exceptions
+
+DPD_SUPPORTED_ACTIONS = ['hold', 'clear', 'restart',
+ 'restart-by-peer', 'disabled']
+DPD_SUPPORTED_KEYS = ['action', 'interval', 'timeout']
+
+lifetime_keys = ['units', 'value']
+lifetime_units = ['seconds']
+
+
+def validate_dpd_dict(dpd_dict):
+ for key, value in dpd_dict.items():
+ if key not in DPD_SUPPORTED_KEYS:
+ message = _(
+ "DPD Dictionary KeyError: "
+ "Reason-Invalid DPD key : "
+ "'%(key)s' not in %(supported_key)s") % {
+ 'key': key, 'supported_key': DPD_SUPPORTED_KEYS}
+ raise exceptions.CommandError(message)
+ if key == 'action' and value not in DPD_SUPPORTED_ACTIONS:
+ message = _(
+ "DPD Dictionary ValueError: "
+ "Reason-Invalid DPD action : "
+ "'%(key_value)s' not in %(supported_action)s") % {
+ 'key_value': value,
+ 'supported_action': DPD_SUPPORTED_ACTIONS}
+ raise exceptions.CommandError(message)
+ if key in ('interval', 'timeout'):
+ try:
+ if int(value) <= 0:
+ raise ValueError()
+ except ValueError:
+ message = _(
+ "DPD Dictionary ValueError: "
+ "Reason-Invalid positive integer value: "
+ "'%(key)s' = %(value)s") % {
+ 'key': key, 'value': value}
+ raise exceptions.CommandError(message)
+ else:
+ dpd_dict[key] = int(value)
+ return
+
+
+def validate_lifetime_dict(lifetime_dict):
+
+ for key, value in lifetime_dict.items():
+ if key not in lifetime_keys:
+ message = _(
+ "Lifetime Dictionary KeyError: "
+ "Reason-Invalid unit key : "
+ "'%(key)s' not in %(supported_key)s") % {
+ 'key': key, 'supported_key': lifetime_keys}
+ raise exceptions.CommandError(message)
+ if key == 'units' and value not in lifetime_units:
+ message = _(
+ "Lifetime Dictionary ValueError: "
+ "Reason-Invalid units : "
+ "'%(key_value)s' not in %(supported_units)s") % {
+ 'key_value': key, 'supported_units': lifetime_units}
+ raise exceptions.CommandError(message)
+ if key == 'value':
+ try:
+ if int(value) < 60:
+ raise ValueError()
+ except ValueError:
+ message = _(
+ "Lifetime Dictionary ValueError: "
+ "Reason-Invalid value should be at least 60:"
+ "'%(key_value)s' = %(value)s") % {
+ 'key_value': key, 'value': value}
+ raise exceptions.CommandError(message)
+ else:
+ lifetime_dict['value'] = int(value)
+ return
+
+
+def lifetime_help(policy):
+ lifetime = _("%s lifetime attributes. "
+ "'units'-seconds, default:seconds. "
+ "'value'-non negative integer, default:3600.") % policy
+ return lifetime
+
+
+def dpd_help(policy):
+ dpd = _(" %s Dead Peer Detection attributes."
+ " 'action'-hold,clear,disabled,restart,restart-by-peer."
+ " 'interval' and 'timeout' are non negative integers. "
+ " 'interval' should be less than 'timeout' value. "
+ " 'action', default:hold 'interval', default:30, "
+ " 'timeout', default:120.") % policy.capitalize()
+ return dpd
diff --git a/neutronclient/osc/v2/vpnaas/vpnservice.py b/neutronclient/osc/v2/vpnaas/vpnservice.py
new file mode 100644
index 000000000..9e1e489ca
--- /dev/null
+++ b/neutronclient/osc/v2/vpnaas/vpnservice.py
@@ -0,0 +1,252 @@
+# Copyright 2017 FUJITSU LIMITED
+# All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License"); you may
+# not use this file except in compliance with the License. You may obtain
+# a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+# License for the specific language governing permissions and limitations
+# under the License.
+#
+
+from osc_lib.command import command
+from osc_lib import exceptions
+from osc_lib import utils
+from osc_lib.utils import columns as column_util
+from oslo_log import log as logging
+
+from neutronclient._i18n import _
+from neutronclient.osc import utils as osc_utils
+
+
+LOG = logging.getLogger(__name__)
+
+_attr_map = (
+ ('id', 'ID', column_util.LIST_BOTH),
+ ('name', 'Name', column_util.LIST_BOTH),
+ ('router_id', 'Router', column_util.LIST_BOTH),
+ ('subnet_id', 'Subnet', column_util.LIST_BOTH),
+ ('flavor_id', 'Flavor', column_util.LIST_BOTH),
+ ('is_admin_state_up', 'State', column_util.LIST_BOTH),
+ ('status', 'Status', column_util.LIST_BOTH),
+ ('description', 'Description', column_util.LIST_LONG_ONLY),
+ ('project_id', 'Project', column_util.LIST_LONG_ONLY),
+ ('external_v4_ip', 'Ext v4 IP', column_util.LIST_LONG_ONLY),
+ ('external_v6_ip', 'Ext v6 IP', column_util.LIST_LONG_ONLY),
+)
+
+_attr_map_dict = {
+ 'id': 'ID',
+ 'name': 'Name',
+ 'router_id': 'Router',
+ 'subnet_id': 'Subnet',
+ 'flavor_id': 'Flavor',
+ 'is_admin_state_up': 'State',
+ 'status': 'Status',
+ 'description': 'Description',
+ 'project_id': 'Project',
+ 'external_v4_ip': 'Ext v4 IP',
+ 'external_v6_ip': 'Ext v6 IP',
+}
+
+
+def _get_common_parser(parser):
+ parser.add_argument(
+ '--description',
+ metavar='',
+ help=_('Description for the VPN service'))
+ parser.add_argument(
+ '--subnet',
+ metavar='',
+ help=_('Local private subnet (name or ID)'))
+ parser.add_argument(
+ '--flavor',
+ metavar='',
+ help=_('Flavor for the VPN service (name or ID)'))
+ admin_group = parser.add_mutually_exclusive_group()
+ admin_group.add_argument(
+ '--enable',
+ action='store_true',
+ help=_("Enable VPN service")
+ )
+ admin_group.add_argument(
+ '--disable',
+ action='store_true',
+ help=_("Disable VPN service")
+ )
+ return parser
+
+
+def _get_common_attrs(client_manager, parsed_args, is_create=True):
+ attrs = {}
+ if is_create:
+ if 'project' in parsed_args and parsed_args.project is not None:
+ attrs['project_id'] = osc_utils.find_project(
+ client_manager.identity,
+ parsed_args.project,
+ parsed_args.project_domain,
+ ).id
+ if parsed_args.description:
+ attrs['description'] = str(parsed_args.description)
+ if parsed_args.subnet:
+ _subnet_id = client_manager.network.find_subnet(
+ parsed_args.subnet).id
+ attrs['subnet_id'] = _subnet_id
+ if parsed_args.flavor:
+ _flavor_id = client_manager.network.find_flavor(
+ parsed_args.flavor,
+ ignore_missing=False
+ ).id
+ attrs['flavor_id'] = _flavor_id
+ if parsed_args.enable:
+ attrs['admin_state_up'] = True
+ if parsed_args.disable:
+ attrs['admin_state_up'] = False
+ return attrs
+
+
+class CreateVPNService(command.ShowOne):
+ _description = _("Create an VPN service")
+
+ def get_parser(self, prog_name):
+ parser = super(CreateVPNService, self).get_parser(prog_name)
+ _get_common_parser(parser)
+ parser.add_argument(
+ 'name',
+ metavar='',
+ help=_('Name for the VPN service'))
+ parser.add_argument(
+ '--router',
+ metavar='ROUTER',
+ required=True,
+ help=_('Router for the VPN service (name or ID)'))
+ osc_utils.add_project_owner_option_to_parser(parser)
+ return parser
+
+ def take_action(self, parsed_args):
+ client = self.app.client_manager.network
+ attrs = _get_common_attrs(self.app.client_manager, parsed_args)
+ if parsed_args.name:
+ attrs['name'] = str(parsed_args.name)
+ if parsed_args.router:
+ _router_id = client.find_router(parsed_args.router,
+ ignore_missing=False).id
+ attrs['router_id'] = _router_id
+ obj = client.create_vpn_service(**attrs)
+ display_columns, columns = utils.get_osc_show_columns_for_sdk_resource(
+ obj, _attr_map_dict, ['location', 'tenant_id'])
+ data = utils.get_dict_properties(obj, columns)
+ return display_columns, data
+
+
+class DeleteVPNService(command.Command):
+ _description = _("Delete VPN service(s)")
+
+ def get_parser(self, prog_name):
+ parser = super(DeleteVPNService, self).get_parser(prog_name)
+ parser.add_argument(
+ 'vpnservice',
+ metavar='',
+ nargs='+',
+ help=_('VPN service to delete (name or ID)'))
+ return parser
+
+ def take_action(self, parsed_args):
+ client = self.app.client_manager.network
+ result = 0
+ for vpn in parsed_args.vpnservice:
+ try:
+ vpn_id = client.find_vpn_service(vpn,
+ ignore_missing=False)['id']
+ client.delete_vpn_service(vpn_id)
+ except Exception as e:
+ result += 1
+ LOG.error(_("Failed to delete VPN service with "
+ "name or ID '%(vpnservice)s': %(e)s"),
+ {'vpnservice': vpn, 'e': e})
+
+ if result > 0:
+ total = len(parsed_args.vpnservice)
+ msg = (_("%(result)s of %(total)s vpn service failed "
+ "to delete.") % {'result': result, 'total': total})
+ raise exceptions.CommandError(msg)
+
+
+class ListVPNService(command.Lister):
+ _description = _("List VPN services that belong to a given project")
+
+ def get_parser(self, prog_name):
+ parser = super(ListVPNService, self).get_parser(prog_name)
+ parser.add_argument(
+ '--long',
+ action='store_true',
+ default=False,
+ help=_("List additional fields in output")
+ )
+ return parser
+
+ def take_action(self, parsed_args):
+ client = self.app.client_manager.network
+ obj = client.vpn_services()
+ headers, columns = column_util.get_column_definitions(
+ _attr_map, long_listing=parsed_args.long)
+ return (headers, (utils.get_dict_properties(s, columns) for s in obj))
+
+
+class SetVPNSercice(command.Command):
+ _description = _("Set VPN service properties")
+
+ def get_parser(self, prog_name):
+ parser = super(SetVPNSercice, self).get_parser(prog_name)
+ _get_common_parser(parser)
+ parser.add_argument(
+ '--name',
+ metavar='',
+ help=_('Name for the VPN service'))
+ parser.add_argument(
+ 'vpnservice',
+ metavar='',
+ help=_('VPN service to modify (name or ID)'))
+ return parser
+
+ def take_action(self, parsed_args):
+ client = self.app.client_manager.network
+ attrs = _get_common_attrs(self.app.client_manager,
+ parsed_args, is_create=False)
+ if parsed_args.name:
+ attrs['name'] = str(parsed_args.name)
+ vpn_id = client.find_vpn_service(parsed_args.vpnservice,
+ ignore_missing=False)['id']
+ try:
+ client.update_vpn_service(vpn_id, **attrs)
+ except Exception as e:
+ msg = (_("Failed to set vpn service '%(vpn)s': %(e)s")
+ % {'vpn': parsed_args.vpnservice, 'e': e})
+ raise exceptions.CommandError(msg)
+
+
+class ShowVPNService(command.ShowOne):
+ _description = _("Display VPN service details")
+
+ def get_parser(self, prog_name):
+ parser = super(ShowVPNService, self).get_parser(prog_name)
+ parser.add_argument(
+ 'vpnservice',
+ metavar='',
+ help=_('VPN service to display (name or ID)'))
+ return parser
+
+ def take_action(self, parsed_args):
+ client = self.app.client_manager.network
+ vpn_id = client.find_vpn_service(parsed_args.vpnservice,
+ ignore_missing=False)['id']
+ obj = client.get_vpn_service(vpn_id)
+ display_columns, columns = utils.get_osc_show_columns_for_sdk_resource(
+ obj, _attr_map_dict, ['location', 'tenant_id'])
+ data = utils.get_dict_properties(obj, columns)
+ return (display_columns, data)
diff --git a/neutronclient/shell.py b/neutronclient/shell.py
deleted file mode 100644
index 5ddae52b2..000000000
--- a/neutronclient/shell.py
+++ /dev/null
@@ -1,1003 +0,0 @@
-# Copyright 2012 OpenStack Foundation.
-# All Rights Reserved
-#
-# Licensed under the Apache License, Version 2.0 (the "License"); you may
-# not use this file except in compliance with the License. You may obtain
-# a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-# License for the specific language governing permissions and limitations
-# under the License.
-#
-
-"""
-Command-line interface to the Neutron APIs
-"""
-
-from __future__ import print_function
-
-import argparse
-import inspect
-import itertools
-import logging
-import os
-import sys
-
-from keystoneauth1 import session
-import os_client_config
-from oslo_utils import encodeutils
-
-from cliff import app
-from cliff import command
-from cliff import commandmanager
-
-from neutronclient._i18n import _
-from neutronclient.common import clientmanager
-from neutronclient.common import exceptions as exc
-from neutronclient.common import extension as client_extension
-from neutronclient.common import utils
-from neutronclient.neutron.v2_0 import address_scope
-from neutronclient.neutron.v2_0 import agent
-from neutronclient.neutron.v2_0 import agentscheduler
-from neutronclient.neutron.v2_0 import auto_allocated_topology
-from neutronclient.neutron.v2_0 import availability_zone
-from neutronclient.neutron.v2_0.bgp import dragentscheduler as bgp_drsched
-from neutronclient.neutron.v2_0.bgp import peer as bgp_peer
-from neutronclient.neutron.v2_0.bgp import speaker as bgp_speaker
-from neutronclient.neutron.v2_0 import extension
-from neutronclient.neutron.v2_0.flavor import flavor
-from neutronclient.neutron.v2_0.flavor import flavor_profile
-from neutronclient.neutron.v2_0 import floatingip
-from neutronclient.neutron.v2_0.fw import firewall
-from neutronclient.neutron.v2_0.fw import firewallpolicy
-from neutronclient.neutron.v2_0.fw import firewallrule
-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.v2 import healthmonitor as lbaas_healthmon
-from neutronclient.neutron.v2_0.lb.v2 import l7policy as lbaas_l7policy
-from neutronclient.neutron.v2_0.lb.v2 import l7rule as lbaas_l7rule
-from neutronclient.neutron.v2_0.lb.v2 import listener as lbaas_listener
-from neutronclient.neutron.v2_0.lb.v2 import loadbalancer as lbaas_loadbalancer
-from neutronclient.neutron.v2_0.lb.v2 import member as lbaas_member
-from neutronclient.neutron.v2_0.lb.v2 import pool as lbaas_pool
-from neutronclient.neutron.v2_0.lb import vip as lb_vip
-from neutronclient.neutron.v2_0 import metering
-from neutronclient.neutron.v2_0 import network
-from neutronclient.neutron.v2_0 import network_ip_availability
-from neutronclient.neutron.v2_0 import port
-from neutronclient.neutron.v2_0 import purge
-from neutronclient.neutron.v2_0.qos import bandwidth_limit_rule
-from neutronclient.neutron.v2_0.qos import dscp_marking_rule
-from neutronclient.neutron.v2_0.qos import policy as qos_policy
-from neutronclient.neutron.v2_0.qos import rule as qos_rule
-from neutronclient.neutron.v2_0 import quota
-from neutronclient.neutron.v2_0 import rbac
-from neutronclient.neutron.v2_0 import router
-from neutronclient.neutron.v2_0 import securitygroup
-from neutronclient.neutron.v2_0 import servicetype
-from neutronclient.neutron.v2_0 import subnet
-from neutronclient.neutron.v2_0 import subnetpool
-from neutronclient.neutron.v2_0 import tag
-from neutronclient.neutron.v2_0.vpn import endpoint_group
-from neutronclient.neutron.v2_0.vpn import ikepolicy
-from neutronclient.neutron.v2_0.vpn import ipsec_site_connection
-from neutronclient.neutron.v2_0.vpn import ipsecpolicy
-from neutronclient.neutron.v2_0.vpn import vpnservice
-from neutronclient.version import __version__
-
-
-VERSION = '2.0'
-NEUTRON_API_VERSION = '2.0'
-
-
-def run_command(cmd, cmd_parser, sub_argv):
- _argv = sub_argv
- index = -1
- values_specs = []
- if '--' in sub_argv:
- index = sub_argv.index('--')
- _argv = sub_argv[:index]
- values_specs = sub_argv[index:]
- known_args, _values_specs = cmd_parser.parse_known_args(_argv)
- if(isinstance(cmd, subnet.CreateSubnet) and not known_args.cidr):
- cidr = get_first_valid_cidr(_values_specs)
- if cidr:
- known_args.cidr = cidr
- _values_specs.remove(cidr)
- cmd.values_specs = (index == -1 and _values_specs or values_specs)
- return cmd.run(known_args)
-
-
-def get_first_valid_cidr(value_specs):
- # Bug 1442771, argparse does not allow optional positional parameter
- # to be separated from previous positional parameter.
- # When cidr was separated from network, the value will not be able
- # to be parsed into known_args, but saved to _values_specs instead.
- for value in value_specs:
- if utils.is_valid_cidr(value):
- return value
-
-
-def env(*_vars, **kwargs):
- """Search for the first defined of possibly many env vars.
-
- Returns the first environment variable defined in vars, or
- returns the default defined in kwargs.
-
- """
- for v in _vars:
- value = os.environ.get(v, None)
- if value:
- return value
- return kwargs.get('default', '')
-
-
-def check_non_negative_int(value):
- try:
- value = int(value)
- except ValueError:
- raise argparse.ArgumentTypeError(_("invalid int value: %r") % value)
- if value < 0:
- raise argparse.ArgumentTypeError(_("input value %d is negative") %
- value)
- return value
-
-
-class BashCompletionCommand(command.Command):
- """Prints all of the commands and options for bash-completion."""
-
- def take_action(self, parsed_args):
- pass
-
-
-COMMAND_V2 = {
- 'bash-completion': BashCompletionCommand,
- 'net-list': network.ListNetwork,
- 'net-external-list': network.ListExternalNetwork,
- 'net-show': network.ShowNetwork,
- 'net-create': network.CreateNetwork,
- 'net-delete': network.DeleteNetwork,
- 'net-update': network.UpdateNetwork,
- 'subnet-list': subnet.ListSubnet,
- 'subnet-show': subnet.ShowSubnet,
- 'subnet-create': subnet.CreateSubnet,
- 'subnet-delete': subnet.DeleteSubnet,
- 'subnet-update': subnet.UpdateSubnet,
- 'subnetpool-list': subnetpool.ListSubnetPool,
- 'subnetpool-show': subnetpool.ShowSubnetPool,
- 'subnetpool-create': subnetpool.CreateSubnetPool,
- 'subnetpool-delete': subnetpool.DeleteSubnetPool,
- 'subnetpool-update': subnetpool.UpdateSubnetPool,
- 'port-list': port.ListPort,
- 'port-show': port.ShowPort,
- 'port-create': port.CreatePort,
- 'port-delete': port.DeletePort,
- 'port-update': port.UpdatePort,
- 'purge': purge.Purge,
- 'quota-list': quota.ListQuota,
- 'quota-show': quota.ShowQuota,
- 'quota-default-show': quota.ShowQuotaDefault,
- 'quota-delete': quota.DeleteQuota,
- 'quota-update': quota.UpdateQuota,
- 'ext-list': extension.ListExt,
- 'ext-show': extension.ShowExt,
- 'router-list': router.ListRouter,
- 'router-port-list': port.ListRouterPort,
- 'router-show': router.ShowRouter,
- 'router-create': router.CreateRouter,
- 'router-delete': router.DeleteRouter,
- 'router-update': router.UpdateRouter,
- 'router-interface-add': router.AddInterfaceRouter,
- 'router-interface-delete': router.RemoveInterfaceRouter,
- 'router-gateway-set': router.SetGatewayRouter,
- 'router-gateway-clear': router.RemoveGatewayRouter,
- 'floatingip-list': floatingip.ListFloatingIP,
- 'floatingip-show': floatingip.ShowFloatingIP,
- 'floatingip-create': floatingip.CreateFloatingIP,
- 'floatingip-delete': floatingip.DeleteFloatingIP,
- 'floatingip-associate': floatingip.AssociateFloatingIP,
- 'floatingip-disassociate': floatingip.DisassociateFloatingIP,
- 'security-group-list': securitygroup.ListSecurityGroup,
- 'security-group-show': securitygroup.ShowSecurityGroup,
- 'security-group-create': securitygroup.CreateSecurityGroup,
- 'security-group-delete': securitygroup.DeleteSecurityGroup,
- 'security-group-update': securitygroup.UpdateSecurityGroup,
- 'security-group-rule-list': securitygroup.ListSecurityGroupRule,
- 'security-group-rule-show': securitygroup.ShowSecurityGroupRule,
- 'security-group-rule-create': securitygroup.CreateSecurityGroupRule,
- 'security-group-rule-delete': securitygroup.DeleteSecurityGroupRule,
- 'lbaas-loadbalancer-list': lbaas_loadbalancer.ListLoadBalancer,
- 'lbaas-loadbalancer-show': lbaas_loadbalancer.ShowLoadBalancer,
- 'lbaas-loadbalancer-create': lbaas_loadbalancer.CreateLoadBalancer,
- 'lbaas-loadbalancer-update': lbaas_loadbalancer.UpdateLoadBalancer,
- 'lbaas-loadbalancer-delete': lbaas_loadbalancer.DeleteLoadBalancer,
- 'lbaas-loadbalancer-stats': lbaas_loadbalancer.RetrieveLoadBalancerStats,
- 'lbaas-loadbalancer-status': lbaas_loadbalancer.RetrieveLoadBalancerStatus,
- 'lbaas-listener-list': lbaas_listener.ListListener,
- 'lbaas-listener-show': lbaas_listener.ShowListener,
- 'lbaas-listener-create': lbaas_listener.CreateListener,
- 'lbaas-listener-update': lbaas_listener.UpdateListener,
- 'lbaas-listener-delete': lbaas_listener.DeleteListener,
- 'lbaas-l7policy-list': lbaas_l7policy.ListL7Policy,
- 'lbaas-l7policy-show': lbaas_l7policy.ShowL7Policy,
- 'lbaas-l7policy-create': lbaas_l7policy.CreateL7Policy,
- 'lbaas-l7policy-update': lbaas_l7policy.UpdateL7Policy,
- 'lbaas-l7policy-delete': lbaas_l7policy.DeleteL7Policy,
- 'lbaas-l7rule-list': lbaas_l7rule.ListL7Rule,
- 'lbaas-l7rule-show': lbaas_l7rule.ShowL7Rule,
- 'lbaas-l7rule-create': lbaas_l7rule.CreateL7Rule,
- 'lbaas-l7rule-update': lbaas_l7rule.UpdateL7Rule,
- 'lbaas-l7rule-delete': lbaas_l7rule.DeleteL7Rule,
- 'lbaas-pool-list': lbaas_pool.ListPool,
- 'lbaas-pool-show': lbaas_pool.ShowPool,
- 'lbaas-pool-create': lbaas_pool.CreatePool,
- 'lbaas-pool-update': lbaas_pool.UpdatePool,
- 'lbaas-pool-delete': lbaas_pool.DeletePool,
- 'lbaas-healthmonitor-list': lbaas_healthmon.ListHealthMonitor,
- 'lbaas-healthmonitor-show': lbaas_healthmon.ShowHealthMonitor,
- 'lbaas-healthmonitor-create': lbaas_healthmon.CreateHealthMonitor,
- 'lbaas-healthmonitor-update': lbaas_healthmon.UpdateHealthMonitor,
- 'lbaas-healthmonitor-delete': lbaas_healthmon.DeleteHealthMonitor,
- 'lbaas-member-list': lbaas_member.ListMember,
- 'lbaas-member-show': lbaas_member.ShowMember,
- 'lbaas-member-create': lbaas_member.CreateMember,
- 'lbaas-member-update': lbaas_member.UpdateMember,
- 'lbaas-member-delete': lbaas_member.DeleteMember,
- 'lb-vip-list': lb_vip.ListVip,
- 'lb-vip-show': lb_vip.ShowVip,
- 'lb-vip-create': lb_vip.CreateVip,
- 'lb-vip-update': lb_vip.UpdateVip,
- 'lb-vip-delete': lb_vip.DeleteVip,
- 'lb-pool-list': lb_pool.ListPool,
- 'lb-pool-show': lb_pool.ShowPool,
- 'lb-pool-create': lb_pool.CreatePool,
- 'lb-pool-update': lb_pool.UpdatePool,
- 'lb-pool-delete': lb_pool.DeletePool,
- 'lb-pool-stats': lb_pool.RetrievePoolStats,
- 'lb-member-list': lb_member.ListMember,
- 'lb-member-show': lb_member.ShowMember,
- 'lb-member-create': lb_member.CreateMember,
- 'lb-member-update': lb_member.UpdateMember,
- 'lb-member-delete': lb_member.DeleteMember,
- 'lb-healthmonitor-list': lb_healthmonitor.ListHealthMonitor,
- 'lb-healthmonitor-show': lb_healthmonitor.ShowHealthMonitor,
- 'lb-healthmonitor-create': lb_healthmonitor.CreateHealthMonitor,
- 'lb-healthmonitor-update': lb_healthmonitor.UpdateHealthMonitor,
- 'lb-healthmonitor-delete': lb_healthmonitor.DeleteHealthMonitor,
- 'lb-healthmonitor-associate': lb_healthmonitor.AssociateHealthMonitor,
- 'lb-healthmonitor-disassociate': (
- lb_healthmonitor.DisassociateHealthMonitor
- ),
- 'agent-list': agent.ListAgent,
- 'agent-show': agent.ShowAgent,
- 'agent-delete': agent.DeleteAgent,
- 'agent-update': agent.UpdateAgent,
- 'dhcp-agent-network-add': agentscheduler.AddNetworkToDhcpAgent,
- 'dhcp-agent-network-remove': agentscheduler.RemoveNetworkFromDhcpAgent,
- 'net-list-on-dhcp-agent': agentscheduler.ListNetworksOnDhcpAgent,
- 'dhcp-agent-list-hosting-net': agentscheduler.ListDhcpAgentsHostingNetwork,
- 'l3-agent-router-add': agentscheduler.AddRouterToL3Agent,
- 'l3-agent-router-remove': agentscheduler.RemoveRouterFromL3Agent,
- 'router-list-on-l3-agent': agentscheduler.ListRoutersOnL3Agent,
- 'l3-agent-list-hosting-router': agentscheduler.ListL3AgentsHostingRouter,
- 'lb-pool-list-on-agent': agentscheduler.ListPoolsOnLbaasAgent,
- 'lb-agent-hosting-pool': agentscheduler.GetLbaasAgentHostingPool,
- 'lbaas-loadbalancer-list-on-agent':
- agentscheduler.ListLoadBalancersOnLbaasAgent,
- 'lbaas-agent-hosting-loadbalancer':
- agentscheduler.GetLbaasAgentHostingLoadBalancer,
- 'service-provider-list': servicetype.ListServiceProvider,
- 'firewall-rule-list': firewallrule.ListFirewallRule,
- 'firewall-rule-show': firewallrule.ShowFirewallRule,
- 'firewall-rule-create': firewallrule.CreateFirewallRule,
- 'firewall-rule-update': firewallrule.UpdateFirewallRule,
- 'firewall-rule-delete': firewallrule.DeleteFirewallRule,
- 'firewall-policy-list': firewallpolicy.ListFirewallPolicy,
- 'firewall-policy-show': firewallpolicy.ShowFirewallPolicy,
- 'firewall-policy-create': firewallpolicy.CreateFirewallPolicy,
- 'firewall-policy-update': firewallpolicy.UpdateFirewallPolicy,
- 'firewall-policy-delete': firewallpolicy.DeleteFirewallPolicy,
- 'firewall-policy-insert-rule': firewallpolicy.FirewallPolicyInsertRule,
- 'firewall-policy-remove-rule': firewallpolicy.FirewallPolicyRemoveRule,
- 'firewall-list': firewall.ListFirewall,
- 'firewall-show': firewall.ShowFirewall,
- 'firewall-create': firewall.CreateFirewall,
- 'firewall-update': firewall.UpdateFirewall,
- 'firewall-delete': firewall.DeleteFirewall,
- 'ipsec-site-connection-list': (
- ipsec_site_connection.ListIPsecSiteConnection
- ),
- 'ipsec-site-connection-show': (
- ipsec_site_connection.ShowIPsecSiteConnection
- ),
- 'ipsec-site-connection-create': (
- ipsec_site_connection.CreateIPsecSiteConnection
- ),
- 'ipsec-site-connection-update': (
- ipsec_site_connection.UpdateIPsecSiteConnection
- ),
- 'ipsec-site-connection-delete': (
- ipsec_site_connection.DeleteIPsecSiteConnection
- ),
- 'vpn-endpoint-group-list': endpoint_group.ListEndpointGroup,
- 'vpn-endpoint-group-show': endpoint_group.ShowEndpointGroup,
- 'vpn-endpoint-group-create': endpoint_group.CreateEndpointGroup,
- 'vpn-endpoint-group-update': endpoint_group.UpdateEndpointGroup,
- 'vpn-endpoint-group-delete': endpoint_group.DeleteEndpointGroup,
- 'vpn-service-list': vpnservice.ListVPNService,
- 'vpn-service-show': vpnservice.ShowVPNService,
- 'vpn-service-create': vpnservice.CreateVPNService,
- 'vpn-service-update': vpnservice.UpdateVPNService,
- 'vpn-service-delete': vpnservice.DeleteVPNService,
- 'vpn-ipsecpolicy-list': ipsecpolicy.ListIPsecPolicy,
- 'vpn-ipsecpolicy-show': ipsecpolicy.ShowIPsecPolicy,
- 'vpn-ipsecpolicy-create': ipsecpolicy.CreateIPsecPolicy,
- 'vpn-ipsecpolicy-update': ipsecpolicy.UpdateIPsecPolicy,
- 'vpn-ipsecpolicy-delete': ipsecpolicy.DeleteIPsecPolicy,
- 'vpn-ikepolicy-list': ikepolicy.ListIKEPolicy,
- 'vpn-ikepolicy-show': ikepolicy.ShowIKEPolicy,
- 'vpn-ikepolicy-create': ikepolicy.CreateIKEPolicy,
- 'vpn-ikepolicy-update': ikepolicy.UpdateIKEPolicy,
- 'vpn-ikepolicy-delete': ikepolicy.DeleteIKEPolicy,
- 'meter-label-create': metering.CreateMeteringLabel,
- 'meter-label-list': metering.ListMeteringLabel,
- 'meter-label-show': metering.ShowMeteringLabel,
- 'meter-label-delete': metering.DeleteMeteringLabel,
- 'meter-label-rule-create': metering.CreateMeteringLabelRule,
- 'meter-label-rule-list': metering.ListMeteringLabelRule,
- 'meter-label-rule-show': metering.ShowMeteringLabelRule,
- 'meter-label-rule-delete': metering.DeleteMeteringLabelRule,
- 'rbac-create': rbac.CreateRBACPolicy,
- 'rbac-update': rbac.UpdateRBACPolicy,
- 'rbac-list': rbac.ListRBACPolicy,
- 'rbac-show': rbac.ShowRBACPolicy,
- 'rbac-delete': rbac.DeleteRBACPolicy,
- 'address-scope-list': address_scope.ListAddressScope,
- 'address-scope-show': address_scope.ShowAddressScope,
- 'address-scope-create': address_scope.CreateAddressScope,
- 'address-scope-delete': address_scope.DeleteAddressScope,
- 'address-scope-update': address_scope.UpdateAddressScope,
- 'qos-policy-list': qos_policy.ListQoSPolicy,
- 'qos-policy-show': qos_policy.ShowQoSPolicy,
- 'qos-policy-create': qos_policy.CreateQoSPolicy,
- 'qos-policy-update': qos_policy.UpdateQoSPolicy,
- 'qos-policy-delete': qos_policy.DeleteQoSPolicy,
- 'qos-bandwidth-limit-rule-create': (
- bandwidth_limit_rule.CreateQoSBandwidthLimitRule
- ),
- 'qos-bandwidth-limit-rule-show': (
- bandwidth_limit_rule.ShowQoSBandwidthLimitRule
- ),
- 'qos-bandwidth-limit-rule-list': (
- bandwidth_limit_rule.ListQoSBandwidthLimitRules
- ),
- 'qos-bandwidth-limit-rule-update': (
- bandwidth_limit_rule.UpdateQoSBandwidthLimitRule
- ),
- 'qos-bandwidth-limit-rule-delete': (
- bandwidth_limit_rule.DeleteQoSBandwidthLimitRule
- ),
- 'qos-dscp-marking-rule-create': (
- dscp_marking_rule.CreateQoSDscpMarkingRule
- ),
- 'qos-dscp-marking-rule-show': (
- dscp_marking_rule.ShowQoSDscpMarkingRule
- ),
- 'qos-dscp-marking-rule-list': (
- dscp_marking_rule.ListQoSDscpMarkingRules
- ),
- 'qos-dscp-marking-rule-update': (
- dscp_marking_rule.UpdateQoSDscpMarkingRule
- ),
- 'qos-dscp-marking-rule-delete': (
- dscp_marking_rule.DeleteQoSDscpMarkingRule
- ),
- 'qos-available-rule-types': qos_rule.ListQoSRuleTypes,
- 'flavor-list': flavor.ListFlavor,
- 'flavor-show': flavor.ShowFlavor,
- 'flavor-create': flavor.CreateFlavor,
- 'flavor-delete': flavor.DeleteFlavor,
- 'flavor-update': flavor.UpdateFlavor,
- 'flavor-associate': flavor.AssociateFlavor,
- 'flavor-disassociate': flavor.DisassociateFlavor,
- 'flavor-profile-list': flavor_profile.ListFlavorProfile,
- 'flavor-profile-show': flavor_profile.ShowFlavorProfile,
- 'flavor-profile-create': flavor_profile.CreateFlavorProfile,
- 'flavor-profile-delete': flavor_profile.DeleteFlavorProfile,
- 'flavor-profile-update': flavor_profile.UpdateFlavorProfile,
- 'availability-zone-list': availability_zone.ListAvailabilityZone,
- 'auto-allocated-topology-show': (
- auto_allocated_topology.ShowAutoAllocatedTopology),
- 'bgp-dragent-speaker-add': (
- bgp_drsched.AddBGPSpeakerToDRAgent
- ),
- 'bgp-dragent-speaker-remove': (
- bgp_drsched.RemoveBGPSpeakerFromDRAgent
- ),
- 'bgp-speaker-list-on-dragent': (
- bgp_drsched.ListBGPSpeakersOnDRAgent
- ),
- 'bgp-dragent-list-hosting-speaker': (
- bgp_drsched.ListDRAgentsHostingBGPSpeaker
- ),
- 'bgp-speaker-list': bgp_speaker.ListSpeakers,
- 'bgp-speaker-advertiseroute-list': (
- bgp_speaker.ListRoutesAdvertisedBySpeaker
- ),
- 'bgp-speaker-show': bgp_speaker.ShowSpeaker,
- 'bgp-speaker-create': bgp_speaker.CreateSpeaker,
- 'bgp-speaker-update': bgp_speaker.UpdateSpeaker,
- 'bgp-speaker-delete': bgp_speaker.DeleteSpeaker,
- 'bgp-speaker-peer-add': bgp_speaker.AddPeerToSpeaker,
- 'bgp-speaker-peer-remove': bgp_speaker.RemovePeerFromSpeaker,
- 'bgp-speaker-network-add': bgp_speaker.AddNetworkToSpeaker,
- 'bgp-speaker-network-remove': bgp_speaker.RemoveNetworkFromSpeaker,
- 'bgp-peer-list': bgp_peer.ListPeers,
- 'bgp-peer-show': bgp_peer.ShowPeer,
- 'bgp-peer-create': bgp_peer.CreatePeer,
- 'bgp-peer-update': bgp_peer.UpdatePeer,
- 'bgp-peer-delete': bgp_peer.DeletePeer,
- 'net-ip-availability-list': network_ip_availability.ListIpAvailability,
- 'net-ip-availability-show': network_ip_availability.ShowIpAvailability,
- 'tag-add': tag.AddTag,
- 'tag-replace': tag.ReplaceTag,
- 'tag-remove': tag.RemoveTag,
-}
-
-COMMANDS = {'2.0': COMMAND_V2}
-
-
-class HelpAction(argparse.Action):
- """Print help message including sub-commands
-
- Provide a custom action so the -h and --help options
- to the main app will print a list of the commands.
-
- The commands are determined by checking the CommandManager
- instance, passed in as the "default" value for the action.
- """
- def __call__(self, parser, namespace, values, option_string=None):
- outputs = []
- max_len = 0
- app = self.default
- parser.print_help(app.stdout)
- app.stdout.write(_('\nCommands for API v%s:\n') % app.api_version)
- command_manager = app.command_manager
- for name, ep in sorted(command_manager):
- factory = ep.load()
- cmd = factory(self, None)
- one_liner = cmd.get_description().split('\n')[0]
- outputs.append((name, one_liner))
- max_len = max(len(name), max_len)
- for (name, one_liner) in outputs:
- app.stdout.write(' %s %s\n' % (name.ljust(max_len), one_liner))
- sys.exit(0)
-
-
-class NeutronShell(app.App):
-
- # verbose logging levels
- WARNING_LEVEL = 0
- INFO_LEVEL = 1
- DEBUG_LEVEL = 2
- CONSOLE_MESSAGE_FORMAT = '%(message)s'
- DEBUG_MESSAGE_FORMAT = '%(levelname)s: %(name)s %(message)s'
- log = logging.getLogger(__name__)
-
- def __init__(self, apiversion):
- super(NeutronShell, self).__init__(
- description=__doc__.strip(),
- version=VERSION,
- command_manager=commandmanager.CommandManager('neutron.cli'), )
- self.commands = COMMANDS
- for k, v in self.commands[apiversion].items():
- self.command_manager.add_command(k, v)
-
- self._register_extensions(VERSION)
-
- # Pop the 'complete' to correct the outputs of 'neutron help'.
- self.command_manager.commands.pop('complete')
-
- # This is instantiated in initialize_app() only when using
- # password flow auth
- self.auth_client = None
- self.api_version = apiversion
-
- def build_option_parser(self, description, version):
- """Return an argparse option parser for this application.
-
- Subclasses may override this method to extend
- the parser with more global options.
-
- :param description: full description of the application
- :paramtype description: str
- :param version: version number for the application
- :paramtype version: str
- """
- parser = argparse.ArgumentParser(
- description=description,
- add_help=False, )
- parser.add_argument(
- '--version',
- action='version',
- version=__version__, )
- parser.add_argument(
- '-v', '--verbose', '--debug',
- action='count',
- dest='verbose_level',
- default=self.DEFAULT_VERBOSE_LEVEL,
- help=_('Increase verbosity of output and show tracebacks on'
- ' errors. You can repeat this option.'))
- parser.add_argument(
- '-q', '--quiet',
- action='store_const',
- dest='verbose_level',
- const=0,
- help=_('Suppress output except warnings and errors.'))
- parser.add_argument(
- '-h', '--help',
- action=HelpAction,
- nargs=0,
- default=self, # tricky
- help=_("Show this help message and exit."))
- parser.add_argument(
- '-r', '--retries',
- metavar="NUM",
- type=check_non_negative_int,
- default=0,
- help=_("How many times the request to the Neutron server should "
- "be retried if it fails."))
- # FIXME(bklei): this method should come from keystoneauth1
- self._append_global_identity_args(parser)
-
- return parser
-
- def _append_global_identity_args(self, parser):
- # FIXME(bklei): these are global identity (Keystone) arguments which
- # should be consistent and shared by all service clients. Therefore,
- # they should be provided by keystoneauth1. We will need to
- # refactor this code once this functionality is available in
- # keystoneauth1.
- #
- # Note: At that time we'll need to decide if we can just abandon
- # the deprecated args (--service-type and --endpoint-type).
-
- parser.add_argument(
- '--os-service-type', metavar='',
- default=env('OS_NETWORK_SERVICE_TYPE', default='network'),
- help=_('Defaults to env[OS_NETWORK_SERVICE_TYPE] or network.'))
-
- parser.add_argument(
- '--os-endpoint-type', metavar='',
- default=env('OS_ENDPOINT_TYPE', default='public'),
- help=_('Defaults to env[OS_ENDPOINT_TYPE] or public.'))
-
- # FIXME(bklei): --service-type is deprecated but kept in for
- # backward compatibility.
- parser.add_argument(
- '--service-type', metavar='',
- default=env('OS_NETWORK_SERVICE_TYPE', default='network'),
- help=_('DEPRECATED! Use --os-service-type.'))
-
- # FIXME(bklei): --endpoint-type is deprecated but kept in for
- # backward compatibility.
- parser.add_argument(
- '--endpoint-type', metavar='',
- default=env('OS_ENDPOINT_TYPE', default='public'),
- help=_('DEPRECATED! Use --os-endpoint-type.'))
-
- parser.add_argument(
- '--os-auth-strategy', metavar='',
- default=env('OS_AUTH_STRATEGY', default='keystone'),
- help=_('DEPRECATED! Only keystone is supported.'))
-
- parser.add_argument(
- '--os_auth_strategy',
- help=argparse.SUPPRESS)
-
- parser.add_argument(
- '--os-cloud', metavar='',
- default=env('OS_CLOUD', default=None),
- help=_('Defaults to env[OS_CLOUD].'))
-
- parser.add_argument(
- '--os-auth-url', metavar='',
- default=env('OS_AUTH_URL'),
- help=_('Authentication URL, defaults to env[OS_AUTH_URL].'))
- parser.add_argument(
- '--os_auth_url',
- help=argparse.SUPPRESS)
-
- project_name_group = parser.add_mutually_exclusive_group()
- project_name_group.add_argument(
- '--os-tenant-name', metavar='',
- default=env('OS_TENANT_NAME'),
- help=_('Authentication tenant name, defaults to '
- 'env[OS_TENANT_NAME].'))
- project_name_group.add_argument(
- '--os-project-name',
- metavar='