Init os-acc

1.Imply os-acc to attach or detach accelerator.
2.This implementation couples with libvirt, we must improve
  it later.
3.Here is a patch of nova. I hope it can help to review this
  commit.
  https://github.com/wangzh1993/openstack_patch/tree/master/cyborg-os_acc-nova-patch/nova
4.Add UT
5.Remove unnecessary file.
6.Remove unused config in tox.

Change-Id: I140cb63549dbe2f70ac84122c569564193001e18
This commit is contained in:
wangzh21 2018-07-17 11:35:40 +08:00
parent 1145487d0a
commit eec685efae
36 changed files with 1291 additions and 0 deletions

4
.coveragerc Normal file
View File

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

58
.gitignore vendored Normal file
View File

@ -0,0 +1,58 @@
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
.stestr
# Translations
*.mo
# Mr Developer
.mr.developer.cfg
.project
.pydevproject
# Complexity
output/*.html
output/*/index.html
# Sphinx
doc/build
# Release notes
releasenotes/build/
# pbr generates these
AUTHORS
ChangeLog
# Editors
*~
.*.swp
.*sw?

3
.stestr.conf Normal file
View File

@ -0,0 +1,3 @@
[DEFAULT]
test_path=${OS_TEST_PATH:-.}
top_dir=./

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-acc

4
HACKING.rst Normal file
View File

@ -0,0 +1,4 @@
os_acc Style Commandments
=========================
Read the OpenStack Style Commandments https://docs.openstack.org/hacking/latest/

175
LICENSE Normal file
View File

@ -0,0 +1,175 @@
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.

15
README.rst Normal file
View File

@ -0,0 +1,15 @@
========================
Team and repository tags
========================
======
os-acc
======
A library for attaching and detaching accelerators in OpenStack.
* License: Apache License, Version 2.0
* Documentation:
* Source:
* Bugs:
* Release Notes:

2
babel.cfg Normal file
View File

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

54
doc/source/conf.py Normal file
View File

@ -0,0 +1,54 @@
# 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.
# -- 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',
'openstackdocstheme',
'reno.sphinxext',
]
# openstackdocstheme options
repository_name = 'openstack/os-acc'
bug_project = 'os-acc'
bug_tag = ''
html_last_updated_fmt = '%Y-%m-%d %H:%M'
# The suffix of source filenames.
source_suffix = '.rst'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'os-acc'
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. See the documentation for
# a list of builtin themes.
html_theme = 'openstackdocs'

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

@ -0,0 +1,13 @@
======
os-acc
======
`os-acc` is a library for attaching and detaching accelerators in OpenStack.
Installation Guide
------------------
.. toctree::
:maxdepth: 2
install/index

View File

@ -0,0 +1,24 @@
============
Installation
============
At the command line:
.. code-block:: shell
$ pip install os-acc
Or, if you have virtualenvwrapper installed:
.. code-block:: shell
$ mkvirtualenv os-acc
$ pip install os-acc
Or, from source:
.. code-block:: shell
$ git clone https://github.com/openstack/os-acc
$ cd os-acc
$ python setup.py install

102
os_acc/__init__.py Normal file
View File

@ -0,0 +1,102 @@
# Copyright 2018 Beijing Lenovo Software Ltd.
#
# 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_log import log as logging
from stevedore import extension
import os_acc.exception
from os_acc.i18n import _
_EXT_MANAGER = None
LOG = logging.getLogger(__name__)
def initialize(reset=False):
global _EXT_MANAGER
if reset or (_EXT_MANAGER is None):
_EXT_MANAGER = extension.ExtensionManager(namespace='os_acc',
invoke_on_load=False)
loaded_plugins = []
for plugin_name in _EXT_MANAGER.names():
cls = _EXT_MANAGER[plugin_name].plugin
obj = cls.load(plugin_name)
LOG.debug(("Loaded ACC plugin class '%(cls)s' "
"with name '%(plugin_name)s'"),
{'cls': cls, 'plugin_name': plugin_name})
loaded_plugins.append(plugin_name)
_EXT_MANAGER[plugin_name].obj = obj
LOG.info("Loaded ACC plugins: %s", ", ".join(loaded_plugins))
def get_config(acc, instance=None, inst_type=None):
if _EXT_MANAGER is None:
raise os_acc.exception.LibraryNotInitialized()
acc_type = acc['type']
if acc_type is None:
raise os_acc.exception.InternalError(
_("acc_type parameter must be present "
"for this acc_type implementation"))
try:
plugin = _EXT_MANAGER[acc_type].obj
except KeyError:
raise os_acc.exception.NoMatchingPlugin(plugin_name=acc_type)
conf = plugin.get_config(acc, instance, inst_type)
return conf
def attach(acc, guest=None, host=None, instance=None, inst_type=None):
if _EXT_MANAGER is None:
raise os_acc.exception.LibraryNotInitialized()
acc_type = acc['type']
if acc_type is None:
raise os_acc.exception.InternalError(
_("acc_type parameter must be present "
"for this acc_type implementation"))
try:
plugin = _EXT_MANAGER[acc_type].obj
except KeyError:
raise os_acc.exception.NoMatchingPlugin(plugin_name=acc_type)
try:
LOG.debug("Attach acc %s", acc)
plugin.attach(acc, guest, host, instance, inst_type)
LOG.info("Successfully Attached acc %s", acc)
except Exception as err:
LOG.error("Failed to attach acc %(acc)s",
{"acc": acc}, exc_info=True)
raise os_acc.exception.AttachException(acc=acc, err=err)
def detach(acc, guest=None, host=None, instance=None, inst_type=None):
if _EXT_MANAGER is None:
raise os_acc.exception.LibraryNotInitialized()
acc_type = acc['type']
if acc_type is None:
raise os_acc.exception.InternalError(
_("acc_type parameter must be present "
"for this acc_type implementation"))
try:
plugin = _EXT_MANAGER[acc_type].obj
except KeyError:
raise os_acc.exception.NoMatchingPlugin(plugin_name=acc_type)
try:
LOG.debug("Detaching acc %s", acc)
plugin.detach(acc, guest, host, instance, inst_type)
LOG.info("Successfully detached acc %s", acc)
except Exception as err:
LOG.error("Failed to unplug acc %(acc)s",
{"acc": acc}, exc_info=True)
raise os_acc.exception.DetachException(acc=acc, err=err)

99
os_acc/base.py Normal file
View File

@ -0,0 +1,99 @@
# Copyright 2018 Beijing Lenovo Software Ltd.
#
# 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
from oslo_config import cfg
import six
CONF = cfg.CONF
@six.add_metaclass(abc.ABCMeta)
class PluginBase(object):
"""Base class for all ACC plugins."""
# Override to provide a tuple of oslo_config.Opt instances for
# the plugin config parameters
CONFIG_OPTS = ()
def __init__(self, config):
"""
Initialize the plugin object with the provided config
:param config: `oslo_config.ConfigOpts.GroupAttr` instance:
"""
self.config = config
@abc.abstractmethod
def get_config(self, acc, instance=None, inst_type=None):
"""
Generate config of specified accelerator.
:param instance: Instance information dict.
:param inst_type: Flavor information dict.
:param acc: Accelerator information
:return: Different LibvirtConfig. For example,
`nova.virt.libvirt.config.LibvirtConfigGuestHostdevPCI` object.
"""
@abc.abstractmethod
def attach(self, acc, guest=None, host=None, instance=None,
inst_type=None):
"""
Given required parameters, perform operations to attach the ACC
properly.
:param acc: Accelerator information
:param guest: `nova.virt.libvirt.guest.Guest` object.
:param host: `nova.virt.libvirt.guest.Host` object.
:param instance: Instance information dict.
:param inst_type: Flavor information dict.
:return:
"""
@abc.abstractmethod
def detach(self, acc, guest=None, host=None, instance=None,
inst_type=None):
"""
Given required parameters, perform operations to detach the ACC
properly.
:param acc: Accelerator information
:param guest: `nova.virt.libvirt.guest.Guest` object.
:param host: `nova.virt.libvirt.guest.Host` object.
:param instance: Instance information dict.
:param inst_type: Flavor information dict.
:return:
"""
@classmethod
def load(cls, plugin_name):
"""
Load a plugin, registering its configuration options
:param plugin_name: the name of the plugin extension
:returns: an initialized instance of the class
"""
cfg_group_name = "os_acc_" + plugin_name
cfg_opts = getattr(cls, "CONFIG_OPTS")
cfg_vals = None
if cfg_opts and len(cfg_opts) > 0:
cfg_group = cfg.OptGroup(
cfg_group_name,
"os-acc plugin %s options" % plugin_name)
CONF.register_opts(cfg_opts, group=cfg_group)
cfg_vals = getattr(CONF, cfg_group_name)
return cls(cfg_vals)

63
os_acc/exception.py Normal file
View File

@ -0,0 +1,63 @@
# Copyright 2018 Beijing Lenovo Software Ltd.
#
# 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_acc.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):
return self.args[0]
class LibraryNotInitialized(ExceptionBase):
msg_fmt = _("Before using the os_acc library, you need to call "
"os_acc.initialize()")
class AttachException(ExceptionBase):
msg_fmt = _("Failed to attach ACC %(acc)s. Got error: %(err)s")
class DetachException(ExceptionBase):
msg_fmt = _("Failed to detach ACC %(acc)s. Got error: %(err)s")
class InternalError(ExceptionBase):
msg_fmt = _("%(err)s")
class NoMatchingPlugin(ExceptionBase):
msg_fmt = _("No ACC plugin was found with the name %(plugin_name)s")

21
os_acc/i18n.py Normal file
View File

@ -0,0 +1,21 @@
# Copyright 2018 Beijing Lenovo Software Ltd.
#
# 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 oslo_i18n as i18n
_translators = i18n.TranslatorFactory(domain='os-acc')
# The primary translation function using the well-known name "_"
_ = _translators.primary

57
os_acc/pci.py Normal file
View File

@ -0,0 +1,57 @@
# Copyright 2018 Beijing Lenovo Software Ltd.
#
# 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_acc import base
class PciAccelerator(base.PluginBase):
def get_config(self, acc, instance=None, inst_type=None):
pcie_addr = acc["pcie_address"]
domain, bus, slot, func = self._get_pci_address_fields(pcie_addr)
from nova.virt.libvirt.config import LibvirtConfigGuestHostdevPCI
conf = LibvirtConfigGuestHostdevPCI()
conf.domain = domain
conf.bus = bus
conf.slot = slot
conf.function = func
return conf
def attach(self, acc, guest=None, host=None, instance=None,
inst_type=None):
conf = self.get_config(instance, inst_type, acc)
state = guest.get_power_state(host)
from nova.compute import power_state
live = state in (power_state.RUNNING, power_state.PAUSED)
guest.attach_device(conf, persistent=True, live=live)
def detach(self, acc, guest=None, host=None, instance=None,
inst_type=None):
conf = self.get_config(instance, inst_type, acc)
state = guest.get_power_state(host)
from nova.compute import power_state
live = state in (power_state.RUNNING, power_state.PAUSED)
guest.detach_device(conf, persistent=True, live=live)
def _get_pci_address_fields(self, pci_addr):
"""Parse a fully-specified PCI device address.
:param pci_addr: A string of the form
"<domain>:<bus>:<slot>.<function>".
:return: A 4-tuple of strings
("<domain>", "<bus>", "<slot>", "<function>")
"""
dbs, sep, func = pci_addr.partition('.')
domain, bus, slot = dbs.split(':')
return domain, bus, slot, func

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

View File

View File

21
os_acc/tests/unit/base.py Normal file
View File

@ -0,0 +1,21 @@
# Copyright 2018 Beijing Lenovo Software Ltd.
#
# 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 @@
# Copyright 2018 Beijing Lenovo Software Ltd.
#
# 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_acc import exception
from os_acc.tests.unit import base
class ACCExceptionTestCase(base.TestCase):
def test_default_error_msg(self):
class FakeACCException(exception.ExceptionBase):
msg_fmt = "default message"
exc = FakeACCException()
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 FakeACCException(exception.ExceptionBase):
msg_fmt = "default message: %(foo)s"
exc = FakeACCException(foo="bar")
self.assertEqual(six.text_type(exc), 'default message: bar')

View File

@ -0,0 +1,171 @@
# Copyright 2018 Beijing Lenovo Software Ltd.
#
# 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
from oslo_config import cfg
from stevedore import extension
import os_acc
from os_acc import base as plugin_base
from os_acc import exception
from os_acc.tests.unit import base
class DemoPlugin(plugin_base.PluginBase):
CONFIG_OPTS = (
cfg.BoolOpt("make_it_work",
default=False,
help="Make everything work correctly by setting this"),
cfg.IntOpt("sleep_time",
default=0,
help="How long to artifically sleep")
)
def get_config(self, acc, instance=None, inst_type=None):
pass
def attach(self, acc, guest=None, host=None, instance=None,
inst_type=None):
pass
def detach(self, acc, guest=None, host=None, instance=None,
inst_type=None):
pass
class DemoPluginNoConfig(plugin_base.PluginBase):
def get_config(self, acc, instance=None, inst_type=None):
pass
def attach(self, acc, guest=None, host=None, instance=None,
inst_type=None):
pass
def detach(self, acc, guest=None, host=None, instance=None,
inst_type=None):
pass
class TestOSACC(base.TestCase):
def setUp(self):
super(TestOSACC, self).setUp()
os_acc._EXT_MANAGER = None
@mock.patch('stevedore.extension.ExtensionManager')
def test_initialize(self, mock_EM):
self.assertIsNone(os_acc._EXT_MANAGER)
# Note: the duplicate call for initialize is to validate
# that the extension manager is only initialized once
os_acc.initialize()
os_acc.initialize()
mock_EM.assert_called_once_with(
invoke_on_load=False, namespace='os_acc')
self.assertIsNotNone(os_acc._EXT_MANAGER)
def test_load_plugin(self):
obj = DemoPlugin.load("demo")
self.assertTrue(hasattr(cfg.CONF, "os_acc_demo"))
self.assertTrue(hasattr(cfg.CONF.os_acc_demo, "make_it_work"))
self.assertTrue(hasattr(cfg.CONF.os_acc_demo, "sleep_time"))
self.assertEqual(cfg.CONF.os_acc_demo.make_it_work, False)
self.assertEqual(cfg.CONF.os_acc_demo.sleep_time, 0)
self.assertEqual(obj.config, cfg.CONF.os_acc_demo)
def test_load_plugin_no_config(self):
obj = DemoPluginNoConfig.load("demonocfg")
self.assertFalse(hasattr(cfg.CONF, "os_acc_demonocfg"))
self.assertIsNone(obj.config)
def test_attach_not_initialized(self):
self.assertRaises(
exception.LibraryNotInitialized,
os_acc.attach, None, None, None, None, None)
def test_detach_not_initialized(self):
self.assertRaises(
exception.LibraryNotInitialized,
os_acc.detach, None, None, None, None, None)
@mock.patch.object(DemoPlugin, "attach")
def test_attach(self, mock_attach):
plg = extension.Extension(name="demo",
entry_point="os-acc",
plugin=DemoPlugin,
obj=None)
with mock.patch('stevedore.extension.ExtensionManager.names',
return_value=['foobar']),\
mock.patch('stevedore.extension.ExtensionManager.__getitem__',
return_value=plg):
os_acc.initialize()
fake_acc = {"instance_uuid": "", "type": "demo",
"name": "NVIDIA Corporation GP100GL",
"pcie_address": "0000:81:00.0"}
fake_instance = {}
fake_inst_type = {}
fake_guest = ""
fake_host = ""
os_acc.attach(fake_acc, fake_guest, fake_host, fake_instance,
fake_inst_type)
mock_attach.assert_called_once_with(fake_acc, fake_guest,
fake_host, fake_instance,
fake_inst_type)
@mock.patch.object(DemoPlugin, "get_config")
def test_get_config(self, mock_get_config):
plg = extension.Extension(name="demo",
entry_point="os-acc",
plugin=DemoPlugin,
obj=None)
with mock.patch('stevedore.extension.ExtensionManager.names',
return_value=['foobar']),\
mock.patch('stevedore.extension.ExtensionManager.__getitem__',
return_value=plg):
os_acc.initialize()
fake_acc = {"instance_uuid": "", "type": "demo",
"name": "NVIDIA Corporation GP100GL",
"pcie_address": "0000:81:00.0"}
fake_instance = {}
fake_inst_type = {}
os_acc.get_config(fake_acc, fake_instance, fake_inst_type)
mock_get_config.assert_called_once_with(fake_acc, fake_instance,
fake_inst_type)
@mock.patch.object(DemoPlugin, "detach")
def test_detach(self, mock_detach):
plg = extension.Extension(name="demo",
entry_point="os-acc",
plugin=DemoPlugin,
obj=None)
with mock.patch('stevedore.extension.ExtensionManager.names',
return_value=['foobar']),\
mock.patch('stevedore.extension.ExtensionManager.__getitem__',
return_value=plg):
os_acc.initialize()
fake_acc = {"instance_uuid": "", "type": "demo",
"name": "NVIDIA Corporation GP100GL",
"pcie_address": "0000:81:00.0"}
fake_instance = {}
fake_inst_type = {}
fake_guest = ""
fake_host = ""
os_acc.detach(fake_acc, fake_guest, fake_host, fake_instance,
fake_inst_type)
mock_detach.assert_called_once_with(fake_acc, fake_guest,
fake_host, fake_instance,
fake_inst_type)

View File

@ -0,0 +1,79 @@
# Copyright 2018 Beijing Lenovo Software Ltd.
#
# 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_acc
from os_acc import pci
from os_acc.tests.unit import base
class TestPCI(base.TestCase):
def setUp(self):
super(TestPCI, self).setUp()
@mock.patch.object(pci.PciAccelerator, 'attach')
def attach_pci_device(self, mock_attach):
os_acc.initialize(reset=True)
fake_acc = {"instance_uuid": "", "type": "pci",
"name": "NVIDIA Corporation GP100GL",
"pcie_address": "0000:81:00.0"}
class FakeGuest(object):
def attach_device(self, conf, persistent, live):
pass
def detach_device(self, conf, persistent, live):
pass
def get_power_state(self, host):
pass
fake_instance = {}
fake_inst_type = {}
fake_guest = FakeGuest()
fake_host = ""
os_acc.attach(fake_acc, fake_guest, fake_host, fake_instance,
fake_inst_type)
mock_attach.assert_called_once_with(fake_acc, fake_guest,
fake_host, fake_instance,
fake_inst_type)
@mock.patch.object(pci.PciAccelerator, 'detach')
def detach_pci_device(self, mock_detach):
os_acc.initialize(reset=True)
fake_acc = {"instance_uuid": "", "type": "pci",
"name": "NVIDIA Corporation GP100GL",
"pcie_address": "0000:81:00.0"}
class FakeGuest(object):
def attach_device(self, conf, persistent, live):
pass
def detach_device(self, conf, persistent, live):
pass
def get_power_state(self, host):
pass
fake_instance = {}
fake_inst_type = {}
fake_guest = FakeGuest()
fake_host = ""
os_acc.detach(fake_acc, fake_guest, fake_host, fake_instance,
fake_inst_type)
mock_detach.assert_called_once_with(fake_acc, fake_guest,
fake_host, fake_instance,
fake_inst_type)

19
os_acc/version.py Normal file
View File

@ -0,0 +1,19 @@
# Copyright 2018 Beijing Lenovo Software Ltd.
#
# 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 pbr.version
version_info = pbr.version.VersionInfo('os-acc')
__version__ = version_info.version_string()

View File

View File

View File

@ -0,0 +1,56 @@
# 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.
#
# os-acc Release Notes documentation build configuration file
# -- 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 = [
'openstackdocstheme',
'reno.sphinxext',
]
# The suffix of source filenames.
source_suffix = '.rst'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'os-acc release Notes'
copyright = u'2018, OpenStack Foundation'
# Release notes do not need a version in the title, they span
# multiple versions.
# The full version, including alpha/beta/rc tags.
release = ''
# The short X.Y version.
version = ''
# 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. See the documentation for
# a list of builtin themes.
html_theme = 'openstackdocs'
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']

View File

@ -0,0 +1,9 @@
=============
Release Notes
=============
.. toctree::
:maxdepth: 1
unreleased

View File

@ -0,0 +1,5 @@
==============================
Current Series Release Notes
==============================
.. release-notes::

10
requirements.txt Normal file
View File

@ -0,0 +1,10 @@
# 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!=2.1.0,>=2.0.0 # Apache-2.0
oslo.config>=5.1.0 # Apache-2.0
oslo.log>=3.30.0 # Apache-2.0
oslo.i18n>=3.15.3 # Apache-2.0
six>=1.10.0 # MIT
stevedore>=1.20.0 # Apache-2.0

59
setup.cfg Normal file
View File

@ -0,0 +1,59 @@
[metadata]
name = os_acc
summary = A library for attaching and detaching accelerators in OpenStack.
description-file = README.rst
author = OpenStack
author-email = openstack-dev@lists.openstack.org
home-page = https://docs.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 :: 3
Programming Language :: Python :: 3.5
[global]
setup-hooks =
pbr.hooks.setup_hook
[files]
packages =
os_acc
[egg_info]
tag_build =
tag_date = 0
tag_svn_revision = 0
[build_sphinx]
builders = html
all-files = 1
warning-is-error = 1
source-dir = doc/source
build-dir = doc/build
[upload_sphinx]
upload-dir = doc/build/html
[compile_catalog]
directory = os_acc/locale
domain = os_acc
[update_catalog]
domain = os_acc
output_dir = os_acc/locale
input_file = os_acc/locale/os-acc.pot
[extract_messages]
keywords = _ gettext ngettext l_ lazy_gettext
mapping_file = babel.cfg
output_file = os_acc/locale/os-acc.pot
[entry_points]
os_acc =
pci = os_acc.pci:PciAccelerator

26
setup.py Normal file
View File

@ -0,0 +1,26 @@
# 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>=2.0.0'],
pbr=True)

15
test-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.
hacking<0.11,>=0.10.2
coverage!=4.4,>=4.0 # Apache-2.0
python-subunit>=1.0.0 # Apache-2.0/BSD
reno>=2.5.0 # Apache-2.0
sphinx>=1.6.2 # BSD
openstackdocstheme>=1.17.0 # Apache-2.0
oslotest>=1.10.0 # Apache-2.0
stestr>=1.0.0 # Apache-2.0
testrepository>=0.0.18 # Apache-2.0/BSD
testscenarios>=0.4 # Apache-2.0/BSD
testtools>=2.2.0 # MIT

66
tox.ini Normal file
View File

@ -0,0 +1,66 @@
[tox]
minversion = 2.0
envlist = py35,py27,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
whitelist_externals = bash
commands = stestr run --black-regex ".tests.functional" {posargs}
[testenv:pep8]
basepython = python3
commands = flake8
[testenv:venv]
basepython = python3
commands = {posargs}
[testenv:functional]
basepython = python2.7
setenv =
{[testenv]setenv}
commands =
stestr run --black-regex ".tests.unit" '{posargs}'
[testenv:docs]
basepython = python3
commands = python setup.py build_sphinx
[testenv:releasenotes]
basepython = python3
commands = sphinx-build -a -E -W -d releasenotes/build/doctrees -b html releasenotes/source releasenotes/build/html
[flake8]
# 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
#
# 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.
# H106: Dont put vim configuration in source files
# H203: Use assertIs(Not)None to check for None
show-source = True
ignore = E123,E125,E126,E127,E128,E251,E265,H302,H405,H904,H404
builtins = _
exclude=.venv,.git,.tox,dist,*lib/python*,*egg,build
max-complexity=30
[hacking]
import_exceptions = os_acc.i18n