Initial commit using code imported from

  https://github.com/jaypipes/os_vif

This patch also includes the following fixes to make the import pass all
jenkins jobs:
 - add doc/source/conf.py and index.rst
 - sync with global requirements

Change-Id: Iac6a9d45ea799eaa71f895af115e966c28246a22
This commit is contained in:
Jay Pipes 2015-06-19 23:10:54 -04:00 committed by Russell Bryant
parent deb06cfe24
commit 8023f33453
32 changed files with 1419 additions and 0 deletions

4
.coveragerc Normal file
View File

@ -0,0 +1,4 @@
[run]
branch = True
source = os_vif
omit = os_vif/tests/*,os_vif/openstack/*

54
.gitignore vendored Normal file
View File

@ -0,0 +1,54 @@
covhtml
*.py[cod]
# C extensions
*.so
# Packages
*.egg
*.egg-info
dist
build
eggs
parts
bin
var
sdist
develop-eggs
.installed.cfg
lib
lib64
# Installer logs
pip-log.txt
# Unit test / coverage reports
.coverage
.tox
nosetests.xml
.testrepository
.venv
# Translations
*.mo
# Mr Developer
.mr.developer.cfg
.project
.pydevproject
# Complexity
output/*.html
output/*/index.html
# Sphinx
doc/build
# pbr generates these
AUTHORS
ChangeLog
# Editors
*~
.*.swp
.*sw?

3
.mailmap Normal file
View File

@ -0,0 +1,3 @@
# Format is:
# <preferred e-mail> <other e-mail 1>
# <preferred e-mail> <other e-mail 2>

7
.testr.conf Normal file
View File

@ -0,0 +1,7 @@
[DEFAULT]
test_command=OS_STDOUT_CAPTURE=${OS_STDOUT_CAPTURE:-1} \
OS_STDERR_CAPTURE=${OS_STDERR_CAPTURE:-1} \
OS_TEST_TIMEOUT=${OS_TEST_TIMEOUT:-60} \
${PYTHON:-python} -m subunit.run discover -t ./ . $LISTOPT $IDOPTION
test_id_option=--load-list $IDFILE
test_list_option=--list

16
CONTRIBUTING.rst Normal file
View File

@ -0,0 +1,16 @@
If you would like to contribute to the development of OpenStack,
you must follow the steps in this page:
http://docs.openstack.org/infra/manual/developers.html
Once those steps have been completed, changes to OpenStack
should be submitted for review via the Gerrit tool, following
the workflow documented at:
http://docs.openstack.org/infra/manual/developers.html#development-workflow
Pull requests submitted through GitHub will be ignored.
Bugs should be filed on Launchpad, not GitHub:
https://bugs.launchpad.net/os-vif

4
HACKING.rst Normal file
View File

@ -0,0 +1,4 @@
os_vif Style Commandments
=========================
Read the OpenStack Style Commandments http://docs.openstack.org/developer/hacking/

176
LICENSE Normal file
View File

@ -0,0 +1,176 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.

6
MANIFEST.in Normal file
View File

@ -0,0 +1,6 @@
include AUTHORS
include ChangeLog
exclude .gitignore
exclude .gitreview
global-exclude *.pyc

82
README.rst Normal file
View File

@ -0,0 +1,82 @@
======
os-vif
======
A library for plugging and unplugging virtual interfaces in OpenStack.
Features
--------
* A base VIF plugin class that supplies a plug() and unplug() interface
* Versioned objects that represent a virtual interface and its components
Usage
-----
The interface to the `os_vif` library is very simple. To begin using the
library, first call the `os_vif.initialize()` function, supplying a set of
keyword arguments for configuration options::
import os_vif
os_vif.initialize(libvirt_virt_type='kvm',
network_device_mtu=1500,
vlan_interface='eth1',
use_ipv6=False,
iptables_top_regex='',
iptables_bottom_regex='',
iptables_drop_action='DROP',
forward_bridge_interface=['all'])
Once the `os_vif` library is initialized, there are only two other library
functions: `os_vif.plug()` and `os_vif.unplug()`. Both methods accept a single
argument of type `os_vif.objects.VIF`::
import uuid
from nova import objects as nova_objects
from os_vif import exception as vif_exc
from os_vif import objects as vif_objects
from os_vif import vnic_types
instance_uuid = 'd7a730ca-3c28-49c3-8f26-4662b909fe8a'
instance = nova_objects.Instance.get_by_uuid(instance_uuid)
instance_info = vif_objects.InstanceInfo.from_nova_instance(instance)
subnet = vif_objects.Subnet(cidr='192.168.1.0/24')
subnets = vif_objects.SubnetList([subnet])
network = vif_objects.Network(label='tenantnet',
subnets=subnets,
multi_host=False,
should_provide_vlan=False,
should_provide_bridge=False)
vif_uuid = uuid.uuid4()
details = {
'ovs_hybrid_plug': True,
'vhostuser_socket': '/path/to/socket',
}
vif = vif_objects.VIF(id=vif_uuid,
address=None,
network=network,
plugin='vhostuser',
details=details,
profile=None,
vnic_type=vnic_types.NORMAL,
active=True,
preserve_on_delete=False,
instance_info=instance_info)
# Now do the actual plug operations to connect the VIF to
# the backing network interface.
try:
os_vif.plug(vif)
except vif_exc.PlugException as err:
# Handle the failure...
# If you are removing a virtual machine and its interfaces,
# you would use the unplug() operation:
try:
os_vif.unplug(vif)
except vif_exc.UnplugException as err:
# Handle the failure...

2
babel.cfg Normal file
View File

@ -0,0 +1,2 @@
[python: **.py]

75
doc/source/conf.py Executable file
View File

@ -0,0 +1,75 @@
# -*- coding: utf-8 -*-
# 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 os
import sys
sys.path.insert(0, os.path.abspath('../..'))
# -- 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',
#'sphinx.ext.intersphinx',
'oslosphinx'
]
# autodoc generation is a bit aggressive and a nuisance when doing heavy
# text edit cycles.
# execute "export SPHINX_DEBUG=1" in your terminal to disable
# The suffix of source filenames.
source_suffix = '.rst'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'os-vif'
copyright = u'2016, OpenStack Foundation'
# If true, '()' will be appended to :func: etc. cross-reference text.
add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
add_module_names = True
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# -- Options for HTML output --------------------------------------------------
# The theme to use for HTML and HTML Help pages. Major themes that come with
# Sphinx are currently 'default' and 'sphinxdoc'.
# html_theme_path = ["."]
# html_theme = '_theme'
# html_static_path = ['static']
# Output file base name for HTML help builder.
htmlhelp_basename = '%sdoc' % project
# 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'),
]
# Example configuration for intersphinx: refer to the Python standard library.
#intersphinx_mapping = {'http://docs.python.org/': None}

15
doc/source/index.rst Normal file
View File

@ -0,0 +1,15 @@
Welcome to os-vif's documentation!
========================================================
Contents:
.. toctree::
:maxdepth: 2
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`

8
openstack-common.conf Normal file
View File

@ -0,0 +1,8 @@
[DEFAULT]
# The list of modules to copy from oslo-incubator.git
# The base module to hold the copy of openstack.common
base=os_vif
module=loopingcall

133
os_vif/__init__.py Normal file
View File

@ -0,0 +1,133 @@
# 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 oslo_concurrency import processutils
from oslo_log import log as logging
from stevedore import extension
import os_vif.exception
import os_vif.i18n
import os_vif.objects
_LE = os_vif.i18n._LE
_LI = os_vif.i18n._LI
_EXT_MANAGER = None
LOG = logging.getLogger('os_vif')
def initialize(reset=False, **config):
"""
Loads all os_vif plugins and initializes them with a dictionary of
configuration options. These configuration options are passed as-is
to the individual VIF plugins that are loaded via stevedore.
:param reset: Recreate and load the VIF plugin extensions.
The following configuration options are currently known to be
used by the VIF plugins, however this list may change and you
should check the documentation of individual plugins for a complete
list of configuration options that the plugin understands or uses.
:param **config: Configuration option dictionary.
`use_ipv6`: Default: False. For plugins that configure IPv6 iptables
rules or functionality, set this option to True if you want
to support IPv6.
`disable_rootwrap`: Default: False. Set to True to force plugins to use
sudoers files instead of any `oslo.rootwrap` functionality.
`use_rootwrap_daemon`: Default: False. Set to True to use the optional
`oslo.rootwrap` daemon for better performance of root-run
commands.
`rootwrap_config`: Default: /etc/nova/rootwrap.conf. Path to the
rootwrap configuration file.
`iptables_top_regex`: Default: ''. Override top filters in iptables
rules construction.
`iptables_bottom_regex`: Default: ''. Override bottom filters in
iptables rules construction.
`iptables_drop_action`: Default: DROP. Override the name of the drop
action in iptables rules.
`forward_bridge_interface`: Default: ['all'].
`network_device_mtu`: Default: 1500. Override the MTU of network
devices created by a VIF plugin.
"""
global _EXT_MANAGER
if reset or (_EXT_MANAGER is None):
_EXT_MANAGER = extension.ExtensionManager(namespace='os_vif',
invoke_on_load=True,
invoke_args=config)
os_vif.objects.register_all()
def plug(vif, instance):
"""
Given a model of a VIF, perform operations to plug the VIF properly.
:param vif: `os_vif.objects.VIF` object.
:param instance: `nova.objects.Instance` object.
:raises `exception.LibraryNotInitialized` if the user of the library
did not call os_vif.initialize(**config) before trying to
plug a VIF.
:raises `exception.NoMatchingPlugin` if there is no plugin for the
type of VIF supplied.
:raises `exception.PlugException` if anything fails during unplug
operations.
"""
if _EXT_MANAGER is None:
raise os_vif.exception.LibraryNotInitialized()
plugin_name = vif.plugin
try:
plugin = _EXT_MANAGER[plugin_name]
except KeyError:
raise os_vif.exception.NoMatchingPlugin(plugin_name=plugin_name)
try:
LOG.debug("Plugging vif %s", vif)
plugin.plug(vif, instance)
LOG.info(_LI("Successfully plugged vif %s"), vif)
except processutils.ProcessExecutionError as err:
LOG.error(_LE("Failed to plug vif %(vif)s. Got error: %(err)s"),
vif=vif, err=err)
raise os_vif.exception.PlugException(vif=vif, err=err)
def unplug(vif):
"""
Given a model of a VIF, perform operations to unplug the VIF properly.
:param vif: `os_vif.objects.VIF` object.
:raises `exception.LibraryNotInitialized` if the user of the library
did not call os_vif.initialize(**config) before trying to
plug a VIF.
:raises `exception.NoMatchingPlugin` if there is no plugin for the
type of VIF supplied.
:raises `exception.UnplugException` if anything fails during unplug
operations.
"""
if _EXT_MANAGER is None:
raise os_vif.exception.LibraryNotInitialized()
plugin_name = vif.plugin
try:
plugin = _EXT_MANAGER[plugin_name]
except KeyError:
raise os_vif.exception.NoMatchingPlugin(plugin_name=plugin_name)
try:
LOG.debug("Unplugging vif %s", vif)
plugin.unplug(vif)
LOG.info(_LI("Successfully unplugged vif %s"), vif)
except processutils.ProcessExecutionError as err:
LOG.error(_LE("Failed to unplug vif %(vif)s. Got error: %(err)s"),
vif=vif, err=err)
raise os_vif.exception.UnplugException(vif=vif, err=err)

63
os_vif/exception.py Normal file
View File

@ -0,0 +1,63 @@
# 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 os_vif.i18n import _
class ExceptionBase(Exception):
"""Base Exception
To correctly use this class, inherit from it and define
a 'msg_fmt' property. That msg_fmt will get printf'd
with the keyword arguments provided to the constructor.
"""
msg_fmt = _("An unknown exception occurred.")
def __init__(self, message=None, **kwargs):
self.kwargs = kwargs
if not message:
try:
message = self.msg_fmt % kwargs
except Exception:
# at least get the core message out if something happened
message = self.msg_fmt
self.message = message
super(ExceptionBase, self).__init__(message)
def format_message(self):
# NOTE(mrodden): use the first argument to the python Exception object
# which should be our full NovaException message, (see __init__)
return self.args[0]
class LibraryNotInitialized(ExceptionBase):
msg_fmt = _("Before using the os_vif library, you need to call "
"os_vif.initialize()")
class NoMatchingPlugin(ExceptionBase):
msg_fmt = _("No VIF plugin was found with the name %(plugin_name)s")
class PlugException(ExceptionBase):
msg_fmt = _("Failed to plug VIF %(vif)s. Got error: %(err)s")
class UnplugException(ExceptionBase):
msg_fmt = _("Failed to unplug VIF %(vif)s. Got error: %(err)s")
class NetworkMissingPhysicalNetwork(ExceptionBase):
msg_fmt = _("Physical network is missing for network %(network_uuid)s")

46
os_vif/i18n.py Normal file
View File

@ -0,0 +1,46 @@
# Copyright 2014 IBM Corp.
#
# 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.
"""oslo.i18n integration module.
See http://docs.openstack.org/developer/oslo.i18n/usage.html .
"""
import oslo_i18n
DOMAIN = 'os_vif'
_translators = oslo_i18n.TranslatorFactory(domain=DOMAIN)
# The primary translation function using the well-known name "_"
_ = _translators.primary
# 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 translate(value, user_locale):
return oslo_i18n.translate(value, user_locale)
def get_available_languages():
return oslo_i18n.get_available_languages(DOMAIN)

View File

@ -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.
def register_all():
__import__('os_vif.objects.instance_info')
__import__('os_vif.objects.network')
__import__('os_vif.objects.subnet')
__import__('os_vif.objects.vif')

View File

@ -0,0 +1,36 @@
# 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 oslo_versionedobjects import base
from oslo_versionedobjects import fields
class InstanceInfo(base.VersionedObject):
"""Represents important information about a Nova instance."""
# Version 1.0: Initial version
VERSION = '1.0'
fields = {
# UUID of the instance
'uuid': fields.UUIDField(),
# The instance name, directly from the Nova instance field of the
# same name
'name': fields.StringField(),
# The project/tenant ID that owns the instance
'project_id': fields.StringField(),
}
@classmethod
def from_nova_instance(cls, instance):
return cls(uuid=instance.uuid,
name=instance.name,
project_id=instance.project_id)

45
os_vif/objects/network.py Normal file
View File

@ -0,0 +1,45 @@
# 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 oslo_versionedobjects import base
from oslo_versionedobjects import fields
class Network(base.VersionedObject):
"""Represents a network."""
# Version 1.0: Initial version
VERSION = '1.0'
fields = {
'id': fields.UUIDField(),
'bridge': fields.StringField(),
'label': fields.StringField(),
'subnets': fields.ObjectField('SubnetList', nullable=True),
'multi_host': fields.BooleanField(),
'should_provide_bridge': fields.BooleanField(),
'should_provide_vlan': fields.BooleanField(),
'bridge_interface': fields.StringField(nullable=True),
'vlan': fields.StringField(nullable=True),
}
obj_relationships = {
'subnets': [
('1.0', '1.0'),
],
}
def __init__(self, **kwargs):
kwargs.setdefault('subnets', [])
kwargs.setdefault('multi_host', False)
kwargs.setdefault('should_provide_bridge', False)
kwargs.setdefault('should_provide_vlan', False)
super(Network, self).__init__(**kwargs)

57
os_vif/objects/subnet.py Normal file
View File

@ -0,0 +1,57 @@
# 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 netaddr
from oslo_versionedobjects import base
from oslo_versionedobjects import fields
class Subnet(base.VersionedObject):
"""Represents a subnet."""
# Version 1.0: Initial version
VERSION = '1.0'
fields = {
'cidr': fields.StringField(nullable=True),
'dns': fields.ListOfStringsField(),
'gateway': fields.StringField(),
'ips': fields.ListOfStringsField(),
'routes': fields.ListOfStringsField(),
'version': fields.IntegerField(nullable=True),
}
def __init__(self, cidr=None, dns=None, gateway=None, ips=None,
routes=None, **kwargs):
dns = dns or set()
ips = ips or set()
routes = routes or set()
version = kwargs.pop('version', None)
if cidr and not version:
version = netaddr.IPNetwork(cidr).version
super(Subnet, self).__init__(cidr=cidr, dns=dns, gateway=gateway,
ips=ips, routes=routes, version=version)
def as_netaddr(self):
"""Convenience function to get cidr as a netaddr object."""
return netaddr.IPNetwork(self.cidr)
class SubnetList(base.ObjectListBase):
# Version 1.0: Initial version
VERSION = '1.0'
fields = {
'objects': fields.ListOfObjectsField('Subnet'),
}

147
os_vif/objects/vif.py Normal file
View File

@ -0,0 +1,147 @@
# 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 oslo_versionedobjects import base
from oslo_versionedobjects import fields
from os_vif import vnic_types
# Constants for dictionary keys in the 'vif_details' field in the VIF
# class
VIF_DETAILS_OVS_HYBRID_PLUG = 'ovs_hybrid_plug'
VIF_DETAILS_PHYSICAL_NETWORK = 'physical_network'
# The following two constants define the SR-IOV related fields in the
# 'vif_details'. 'profileid' should be used for VIF_TYPE_802_QBH,
# 'vlan' for VIF_TYPE_HW_VEB
VIF_DETAILS_PROFILEID = 'profileid'
VIF_DETAILS_VLAN = 'vlan'
# Constants for vhost-user related fields in 'vif_details'.
# vhost-user socket path
VIF_DETAILS_VHOSTUSER_SOCKET = 'vhostuser_socket'
# Specifies whether vhost-user socket should be plugged
# into ovs bridge. Valid values are True and False
VIF_DETAILS_VHOSTUSER_OVS_PLUG = 'vhostuser_ovs_plug'
# Constants for vhost-user related fields in 'vif_details'.
# Sets mode on vhost-user socket, valid values are 'client'
# and 'server'
VIF_DETAILS_VHOSTUSER_MODE = 'vhostuser_mode'
# Constant for max length of network interface names
# eg 'bridge' in the Network class or 'devname' in
# the VIF class
_NIC_NAME_LEN = 14
class VIF(base.VersionedObject):
"""Represents a virtual network interface."""
# Version 1.0: Initial version
VERSION = '1.0'
fields = {
'id': fields.UUIDField(),
'instance_info': fields.ObjectField('InstanceInfo'),
'ovs_interfaceid': fields.StringField(),
# MAC address
'address': fields.StringField(nullable=True),
'network': fields.ObjectField('Network', nullable=True),
# The name or alias of the plugin that should handle the VIF
'plugin': fields.StringField(),
'details': fields.DictOfStringsField(nullable=True),
'profile': fields.DictOfStringsField(nullable=True),
'devname': fields.StringField(nullable=True),
'vnic_type': fields.StringField(),
'active': fields.BooleanField(),
'preserve_on_delete': fields.BooleanField(),
}
def __init__(self, id=None, address=None, network=None, plugin=None,
details=None, devname=None, ovs_interfaceid=None,
qbh_params=None, qbg_params=None, active=False,
vnic_type=vnic_types.NORMAL, profile=None,
preserve_on_delete=False, instance_info=None):
details = details or {}
ovs_id = ovs_interfaceid or id
if not devname:
devname = ("nic" + id)[:_NIC_NAME_LEN]
super(VIF, self).__init__(id=id, address=address, network=network,
plugin=plugin, details=details,
devname=devname,
ovs_interfaceid=ovs_id,
qbg_params=qbg_params, qbh_params=qbh_params,
active=active, vnic_type=vnic_type,
profile=profile,
preserve_on_delete=preserve_on_delete,
instance_info=instance_info,
)
def devname_with_prefix(self, prefix):
"""Returns the device name for the VIF, with the a replaced prefix."""
return prefix + self.devname[3:]
# TODO(jaypipes): It's silly that there is a br_name and a (different)
# bridge_name attribute, but this comes from the original libvirt/vif.py.
# Clean this up and use better names for the attributes.
@property
def bridge_name(self):
return self.network.bridge
@property
def br_name(self):
return ("qbr" + self.id)[:_NIC_NAME_LEN]
@property
def veth_pair_names(self):
return (("qvb%s" % self.id)[:_NIC_NAME_LEN],
("qvo%s" % self.id)[:_NIC_NAME_LEN])
@property
def ovs_hybrid_plug(self):
return self.details.get(VIF_DETAILS_OVS_HYBRID_PLUG, False)
@property
def physical_network(self):
phy_network = self.network['meta'].get('physical_network')
if not phy_network:
phy_network = self.details.get(VIF_DETAILS_PHYSICAL_NETWORK)
return phy_network
@property
def profileid(self):
return self.details.get(VIF_DETAILS_PROFILEID)
@property
def vlan(self):
return self.details.get(VIF_DETAILS_VLAN)
@property
def vhostuser_mode(self):
return self.details.get(VIF_DETAILS_VHOSTUSER_MODE)
@property
def vhostuser_socket(self):
return self.details.get(VIF_DETAILS_VHOSTUSER_SOCKET)
@property
def vhostuser_ovs_plug(self):
return self.details.get(VIF_DETAILS_VHOSTUSER_OVS_PLUG)
@property
def fixed_ips(self):
return [fixed_ip for subnet in self.network['subnets']
for fixed_ip in subnet['ips']]
@property
def floating_ips(self):
return [floating_ip for fixed_ip in self.fixed_ips
for floating_ip in fixed_ip['floating_ips']]

86
os_vif/plugin.py Normal file
View File

@ -0,0 +1,86 @@
# 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 abc
import six
class PluginInfo(object):
"""
Class describing the plugin and the versions of VIF object it understands.
"""
def __init__(self, vif_types, vif_object_min_version,
vif_object_max_version):
"""
Constructs the PluginInfo object.
:param vif_types: set of strings identifying the VIF types that are
implemented by the plugin.
:param vif_object_min_version: String representing the earliest version
of the `os_vif.objects.VIF` object that the plugin
understands.
:param vif_object_max_version: String representing the latest version
of the `os_vif.objects.VIF` object that the plugin
understands.
"""
self.vif_types = vif_types
self.vif_object_min_version = vif_object_min_version
self.vif_object_max_version = vif_object_max_version
@six.add_metaclass(abc.ABCMeta)
class PluginBase(object):
"""Base class for all VIF plugins."""
def __init__(self, **config):
"""
Sets up the plugin using supplied kwargs representing configuration
options.
"""
self.config = config
@abs.abstractmethod
def describe(self):
"""
Return an object that describes the plugin's supported vif types and
the earliest/latest known VIF object versions.
:returns: A `os_vif.plugin.PluginInfo` instance
"""
raise NotImplementedError("describe")
@abc.abstractmethod
def plug(self, instance, vif):
"""
Given a model of a VIF, perform operations to plug the VIF properly.
:param instance: `nova.objects.Instance` object.
:param vif: `os_vif.objects.VIF` object.
:raises `processutils.ProcessExecutionError`. Plugins implementing
this method should let `processutils.ProcessExecutionError`
bubble up.
"""
raise NotImplementedError('plug')
@abc.abstractmethod
def unplug(self, vif):
"""
Given a model of a VIF, perform operations to unplug the VIF properly.
:param vif: `os_vif.objects.VIF` object.
:raises `processutils.ProcessExecutionError`. Plugins implementing
this method should let `processutils.ProcessExecutionError`
bubble up.
"""
raise NotImplementedError('unplug')

0
os_vif/tests/__init__.py Normal file
View File

24
os_vif/tests/base.py Normal file
View File

@ -0,0 +1,24 @@
# -*- coding: utf-8 -*-
# Copyright 2010-2011 OpenStack Foundation
# Copyright (c) 2013 Hewlett-Packard Development Company, L.P.
#
# 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 testtools
class TestCase(testtools.TestCase):
"""Test case base class for all unit tests."""
pass

View File

@ -0,0 +1,38 @@
# 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 six
from os_vif import exception
from os_vif.tests import base
"""Mostly inspired by os-brick's tests."""
class VIFExceptionTestCase(base.TestCase):
def test_default_error_msg(self):
class FakeVIFException(exception.ExceptionBase):
msg_fmt = "default message"
exc = FakeVIFException()
self.assertEqual(six.text_type(exc), 'default message')
def test_error_msg(self):
self.assertEqual(six.text_type(exception.ExceptionBase('test')),
'test')
def test_default_error_msg_with_kwargs(self):
class FakeVIFException(exception.ExceptionBase):
msg_fmt = "default message: %(foo)s"
exc = FakeVIFException(foo="bar")
self.assertEqual(six.text_type(exc), 'default message: bar')

View File

@ -0,0 +1,63 @@
# 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 mock
import os_vif
from os_vif import exception
from os_vif import objects
from os_vif.tests import base
class TestOSVIF(base.TestCase):
def setUp(self):
super(TestOSVIF, self).setUp()
os_vif._EXT_MANAGER = None
@mock.patch('stevedore.extension.ExtensionManager')
def test_initialize(self, mock_EM):
self.assertEqual(None, os_vif._EXT_MANAGER)
os_vif.initialize()
os_vif.initialize()
mock_EM.assert_called_once_with(
invoke_args={}, invoke_on_load=True, namespace='os_vif')
self.assertNotEqual(None, os_vif._EXT_MANAGER)
def test_plug_not_initialized(self):
self.assertRaises(
exception.LibraryNotInitialized,
os_vif.plug, None, None)
def test_unplug_not_initialized(self):
self.assertRaises(
exception.LibraryNotInitialized,
os_vif.plug, None, None)
def test_plug(self):
plugin = mock.MagicMock()
with mock.patch('stevedore.extension.ExtensionManager',
return_value={'foobar': plugin}):
os_vif.initialize()
instance = mock.MagicMock()
vif = objects.vif.VIF(id='uniq', plugin='foobar')
os_vif.plug(vif, instance)
plugin.plug.assert_called_once_with(vif, instance)
def test_unplug(self):
plugin = mock.MagicMock()
with mock.patch('stevedore.extension.ExtensionManager',
return_value={'foobar': plugin}):
os_vif.initialize()
vif = objects.vif.VIF(id='uniq', plugin='foobar')
os_vif.unplug(vif)
plugin.unplug.assert_called_once_with(vif)

17
os_vif/vnic_types.py Normal file
View File

@ -0,0 +1,17 @@
# 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.
# Define supported virtual NIC types. DIRECT and MACVTAP
# are used for SR-IOV ports
NORMAL = 'normal'
DIRECT = 'direct'
MACVTAP = 'macvtap'

15
requirements.txt Normal file
View File

@ -0,0 +1,15 @@
# 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.
pbr>=1.6
Babel>=1.3
netaddr>=0.7.12,!=0.7.16
oslo.concurrency>=2.3.0 # Apache-2.0
oslo.log>=1.14.0 # Apache-2.0
oslo.i18n>=1.5.0 # Apache-2.0
oslo.rootwrap>=2.0.0 # Apache-2.0
oslo.utils>=3.2.0 # Apache-2.0
oslo.versionedobjects>=0.13.0
six>=1.9.0
stevedore>=1.5.0 # Apache-2.0

55
setup.cfg Normal file
View File

@ -0,0 +1,55 @@
[metadata]
name = os_vif
summary = A library for plugging and unplugging virtual interfaces in OpenStack.
description-file = README.rst
author = OpenStack
author-email = openstack-dev@lists.openstack.org
home-page = http://www.openstack.org/
classifier =
Environment :: OpenStack
Intended Audience :: Information Technology
Intended Audience :: System Administrators
License :: OSI Approved :: Apache Software License
Operating System :: POSIX :: Linux
Programming Language :: Python
Programming Language :: Python :: 2
Programming Language :: Python :: 2.7
Programming Language :: Python :: 2.6
Programming Language :: Python :: 3
Programming Language :: Python :: 3.3
Programming Language :: Python :: 3.4
[global]
setup-hooks =
pbr.hooks.setup_hook
[files]
packages =
os_vif
[egg_info]
tag_build =
tag_date = 0
tag_svn_revision = 0
[build_sphinx]
source-dir = doc/source
build-dir = doc/build
all_files = 1
[upload_sphinx]
upload-dir = doc/build/html
[compile_catalog]
directory = os_vif/locale
domain = os_vif
[update_catalog]
domain = os_vif
output_dir = os_vif/locale
input_file = os_vif/locale/os-vif.pot
[extract_messages]
keywords = _ gettext ngettext l_ lazy_gettext
mapping_file = babel.cfg
output_file = os_vif/locale/os-vif.pot

43
setup.py Normal file
View File

@ -0,0 +1,43 @@
#!/usr/bin/env python
# Copyright (c) 2013 Hewlett-Packard Development Company, L.P.
#
# 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 FILE IS MANAGED BY THE GLOBAL REQUIREMENTS REPO - DO NOT EDIT
import setuptools
# In python < 2.7.4, a lazy loading of package `pbr` will break
# setuptools if some other modules registered functions in `atexit`.
# solution from: http://bugs.python.org/issue15881#msg170215
try:
import multiprocessing # noqa
except ImportError:
pass
setuptools.setup(
setup_requires=['pbr'],
entry_points={
'os_vif.plugin': [
'bridge = os_vif._plugins.linux_bridge:LinuxBridgePlugin',
'iovisor = os_vif._plugins.iovisor:IovisorPlugin',
'ivs = os_vif._plugins.ivs:IvsPlugin',
'ivs_hybrid = os_vif._plugins.ivs_hybrid:IvsHybridPlugin',
'ovs = os_vif._plugins.ovs:OvsPlugin',
'ovs_hybrid = os_vif._plugins.ovs_hybrid:OvsHybridPlugin',
'mlnx = os_vif._plugins.mellanox:MellanoxDirectPlugin',
'midonet = os_vif._plugins.midonet:MidonetPlugin',
'vhostuser = os_vif._plugins.vhostuser:VhostuserPlugin',
'vrouter = os_vif._plugins.vrouter:VrouterPlugin',
]},
pbr=True)

14
test-requirements.txt Normal file
View File

@ -0,0 +1,14 @@
# 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.
hacking>=0.10.2,<0.11
coverage>=3.6
discover
python-subunit>=0.0.18
sphinx>=1.1.2,!=1.2.0,!=1.3b1,<1.3
oslosphinx>=2.5.0,!=3.4.0 # Apache-2.0
oslotest>=1.10.0 # Apache-2.0
testrepository>=0.0.18
testscenarios>=0.4
testtools>=1.4.0

67
tox.ini Normal file
View File

@ -0,0 +1,67 @@
[tox]
minversion = 1.6
envlist = py27,py34,pep8
skipsdist = True
[testenv]
usedevelop = True
install_command = pip install -U {opts} {packages}
setenv =
VIRTUAL_ENV={envdir}
deps = -r{toxinidir}/requirements.txt
-r{toxinidir}/test-requirements.txt
commands = python setup.py testr --slowest --testr-args='{posargs}'
whitelist_externals = bash
[tox:jenkins]
downloadcache = ~/cache/pip
[testenv:pep8]
commands = flake8
[testenv:venv]
commands = {posargs}
[testenv:cover]
commands =
coverage erase
python setup.py testr --coverage --testr-args='--concurrency=1 {posargs}'
coverage combine
coverage html --include='os_vif/*' -d covhtml -i
[testenv:docs]
commands = python setup.py build_sphinx
[flake8]
# H803 skipped on purpose per list discussion.
# E123, E125 skipped as they are invalid PEP-8.
# Following checks are ignored on purpose.
#
# E251 unexpected spaces around keyword / parameter equals
# reason: no improvement in readability
#
# E265 block comment should start with '# '
# reason: no improvement in readability
#
# H402 one line docstring needs punctuation
# reason: removed in hacking (https://review.openstack.org/#/c/101497/)
#
# H803 git commit title should not end with period
# reason: removed in hacking (https://review.openstack.org/#/c/101498/)
#
# H904 wrap long lines in parentheses instead of a backslash
# reason: removed in hacking (https://review.openstack.org/#/c/101701/)
#
# H404 skipped on purpose per jay pipes discussion.
#
# Due to the upgrade to hacking 0.9.2 the following checking are
# ignored on purpose for the moment and should be re-enabled.
show-source = True
ignore = E123,E125,E251,E265,H302,H402,H405,H803,H904,H404
builtins = _
exclude=.venv,.git,.tox,dist,doc,*openstack/common*,*lib/python*,*egg,build
max-complexity=30
[hacking]
import_exceptions = os_vif.i18n