Initial Load of Cinder FusionCompute Project

Change-Id: I4c54edd5560060fcfda445895921e97764c92224
This commit is contained in:
DongZhi 2016-11-08 20:34:18 +08:00 committed by Dong Zhi
parent 9bc6dbb48e
commit 09bf790158
57 changed files with 7392 additions and 0 deletions

6
.coveragerc Normal file
View File

@ -0,0 +1,6 @@
[run]
branch = True
source = cinder-fusioncompute
[report]
ignore_errors = True

58
.gitignore vendored Normal file
View File

@ -0,0 +1,58 @@
*.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
cover/
.coverage*
!.coveragerc
.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?
# Files created by releasenotes build
releasenotes/build

View File

@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
<component name="TemplatesService">
<option name="TEMPLATE_FOLDERS">
<list>
<option value="$MODULE_DIR$/releasenotes/source/_templates" />
</list>
</option>
</component>
</module>

14
.idea/misc.xml Normal file
View File

@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectLevelVcsManager" settingsEditedManually="false">
<OptionsSetting value="true" id="Add" />
<OptionsSetting value="true" id="Remove" />
<OptionsSetting value="true" id="Checkout" />
<OptionsSetting value="true" id="Update" />
<OptionsSetting value="true" id="Status" />
<OptionsSetting value="true" id="Edit" />
<ConfirmationsSetting value="0" id="Add" />
<ConfirmationsSetting value="0" id="Remove" />
</component>
<component name="ProjectRootManager" version="2" project-jdk-name="Python 2.7.12 (C:\Python27\python.exe)" project-jdk-type="Python SDK" />
</project>

8
.idea/modules.xml Normal file
View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/cinder-fusioncompute.iml" filepath="$PROJECT_DIR$/.idea/cinder-fusioncompute.iml" />
</modules>
</component>
</project>

42
.idea/workspace.xml Normal file
View File

@ -0,0 +1,42 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ChangeListManager">
<option name="TRACKING_ENABLED" value="true" />
<option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" />
<option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
<option name="LAST_RESOLUTION" value="IGNORE" />
</component>
<component name="CreatePatchCommitExecutor">
<option name="PATCH_PATH" value="" />
</component>
<component name="ProjectLevelVcsManager" settingsEditedManually="false">
<OptionsSetting value="true" id="Add" />
<OptionsSetting value="true" id="Remove" />
<OptionsSetting value="true" id="Checkout" />
<OptionsSetting value="true" id="Update" />
<OptionsSetting value="true" id="Status" />
<OptionsSetting value="true" id="Edit" />
<ConfirmationsSetting value="0" id="Add" />
<ConfirmationsSetting value="0" id="Remove" />
</component>
<component name="ShelveChangesManager" show_recycled="false">
<option name="remove_strategy" value="false" />
</component>
<component name="TaskManager">
<task active="true" id="Default" summary="Default task">
<created>1478503875341</created>
<option name="number" value="Default" />
<option name="presentableId" value="Default" />
<updated>1478503875341</updated>
</task>
<servers />
</component>
<component name="VcsContentAnnotationSettings">
<option name="myLimit" value="2678400000" />
</component>
<component name="XDebuggerManager">
<breakpoint-manager />
<watches-manager />
</component>
</project>

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

17
CONTRIBUTING.rst Normal file
View File

@ -0,0 +1,17 @@
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
If you already have a good understanding of how the system works and your
OpenStack accounts are set up, you can skip to the development workflow
section of this documentation to learn how changes to OpenStack should be
submitted for review via the Gerrit tool:
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/cinder-fusioncompute

4
HACKING.rst Normal file
View File

@ -0,0 +1,4 @@
cinder-fusioncompute 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

19
README.rst Normal file
View File

@ -0,0 +1,19 @@
===============================
cinder-fusioncompute
===============================
Implementation of Cinder driver for Huawei Fusioncompute.
Please fill here a long description which must be at least 3 lines wrapped on
80 cols, so that distribution package maintainers can use it in their packages.
Note that this is a hard requirement.
* Free software: Apache license
* Documentation: http://docs.openstack.org/developer/cinder-fusioncompute
* Source: http://git.openstack.org/cgit/openstack/cinder-fusioncompute
* Bugs: http://bugs.launchpad.net/cinder-fusioncompute
Features
--------
* TODO

2
babel.cfg Normal file
View File

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

20
cinder/__init__.py Normal file
View File

@ -0,0 +1,20 @@
# Copyright 2016 Huawei Technologies Co.,LTD.
# 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 pbr.version
__version__ = pbr.version.VersionInfo(
'cinder-fusioncompute').version_string()

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

View File

View File

View File

@ -0,0 +1,23 @@
# -*- 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.
from oslotest import base
class TestCase(base.BaseTestCase):
"""Test case base class for all unit tests."""

View File

@ -0,0 +1,28 @@
# -*- 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.
"""
test_cinder-fusioncompute
----------------------------------
Tests for `cinder-fusioncompute` module.
"""
from cinder.tests.units.volume.drivers.huawei.fusioncompute import base
class TestCinder(base.TestCase):
def test_something(self):
pass

View File

View File

@ -0,0 +1,18 @@
# Copyright 2016 Huawei Technologies Co.,LTD.
# 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.
'''
init
'''

View File

@ -0,0 +1,92 @@
# Copyright 2016 Huawei Technologies Co.,LTD.
# 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.
"""
[VRM DRIVER] VRM CLIENT.
"""
import urlparse
from oslo_config import cfg
from oslo_log import log as logging
from cinder.volume.drivers.huawei.vrm.conf import FC_DRIVER_CONF
from cinder.volume.drivers.huawei.vrm.http_client import VRMHTTPClient
TASK_WAITING = 'waiting'
TASK_RUNNING = 'running'
TASK_SUCCESS = 'success'
TASK_FAILED = 'failed'
TASK_CANCELLING = 'cancelling'
TASK_UNKNOWN = 'unknown'
CONF = cfg.CONF
LOG = logging.getLogger(__name__)
class BaseProxy(object):
'''BaseProxy
BaseProxy
'''
def __init__(self):
self.vrmhttpclient = VRMHTTPClient()
self.site_uri = self.vrmhttpclient.get_siteuri()
self.site_urn = self.vrmhttpclient.get_siteurn()
self.limit = 100
self.BASIC_URI = '/service'
def _joined_params(self, params):
'''_joined_params
:param params:
:return:
'''
param_str = []
for k, v in params.items():
if (k is None) or (v is None) or len(k) == 0:
continue
if k == 'scope' and v == self.site_urn:
continue
param_str.append("%s=%s" % (k, str(v)))
return '&'.join(param_str)
def _generate_url(self, path, query=None, frag=None):
'''_generate_url
:param path:
:param query:
:param frag:
:return:url
'''
if CONF.vrm_ssl:
scheme = 'https'
else:
scheme = 'http'
fc_ip = FC_DRIVER_CONF.fc_ip
netloc = str(fc_ip) + ':' + str(CONF.vrm_port)
if path.startswith(self.BASIC_URI):
url = urlparse.urlunsplit((scheme, netloc, path, query, frag))
else:
url = urlparse.urlunsplit(
(scheme, netloc, self.BASIC_URI + str(path), query, frag))
return url

View File

@ -0,0 +1,88 @@
# Copyright 2016 Huawei Technologies Co.,LTD.
# 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.
"""
[VRM DRIVER] VRM CLIENT.
"""
from oslo_log import log as logging
from cinder.i18n import _
from cinder.volume.drivers.huawei.vrm.base_proxy import BaseProxy
TASK_WAITING = 'waiting'
TASK_RUNNING = 'running'
TASK_SUCCESS = 'success'
TASK_FAILED = 'failed'
TASK_CANCELLING = 'cancelling'
TASK_UNKNOWN = 'unknown'
LOG = logging.getLogger(__name__)
class ClusterProxy(BaseProxy):
'''ClusterProxy
'''
def __init__(self):
super(ClusterProxy, self).__init__()
def list_cluster(self):
'''list_cluster
Get <cluster_uri>?tag=xxx&clusterUrns=urn1&clusterUrns=urn2 HTTP/1.1
Host: https://<ip>:<port>
Accept: application/json;version=<version>; charset=UTF-8
X-Auth-Token: <Authen_TOKEN>
:param:
:return:
'''
LOG.info(_("[VRM-CINDER] start list_cluster()"))
uri = '/clusters'
method = 'GET'
path = self.site_uri + uri
new_url = self._generate_url(path)
resp, body = self.vrmhttpclient.request(new_url, method)
clusters = body.get('clusters')
return clusters
def list_hosts(self, **kwargs):
'''list_hosts
Get <host_uri>?limit=20&offset=0&scope=xxx HTTP/1.1
Host: https://<ip>:<port>
Accept: application/json;version=<version>; charset=UTF-8
X-Auth-Token: <Authen_TOKEN>
:param kwargs:
:return:
'''
LOG.info(_("[VRM-CINDER] start list_host()"))
uri = '/hosts'
method = 'GET'
path = self.site_uri + uri
params = {
'scope': kwargs.get('clusterUrn'),
}
appendix = self._joined_params(params)
new_url = self._generate_url(path, appendix)
resp, body = self.vrmhttpclient.request(new_url, method)
hosts = body.get('hosts')
return hosts

View File

@ -0,0 +1,110 @@
# Copyright 2016 Huawei Technologies Co.,LTD.
# 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.
"""
[VRM DRIVER] CONFIG
"""
from oslo_config import cfg
vrm_http_opts = [
cfg.StrOpt('vrm_version',
default='v6.0',
help='Management version of VRM'),
cfg.BoolOpt('vrm_ssl',
default=True,
help='Use SSL connection'),
cfg.StrOpt('vrm_port',
default=7443,
help='Management port of VRM'),
cfg.StrOpt('vrm_user',
default='gesysman',
help='User name for the VRM'),
cfg.StrOpt('vrm_password',
default='',
help='Password for the VRM'),
cfg.StrOpt('vrm_authtype',
default='0',
help='User name for the VRM'),
cfg.StrOpt('vrm_usertype',
default='2',
help='User type for the VRM'),
cfg.IntOpt('vrm_retries',
default=3,
help='retry times for http request'),
cfg.IntOpt('vrm_snapshot_sleeptime',
default=300,
help='sleep times for retry request'),
cfg.IntOpt('vrm_vol_snapshot_retries',
default=3,
help='retry times for http request'),
cfg.IntOpt('vrm_timeout',
default=30000,
help='timeout(s) for task result'),
cfg.IntOpt('vrm_limit',
default=100,
help='limit per step for retrive mass reources result set'),
cfg.IntOpt('vrm_sm_periodrate',
default=1,
help='timeout(s) for task result'),
]
VRM_group = cfg.OptGroup(name='VRM', title='VRM config')
VRM_opts = [
cfg.StrOpt('fc_user',
help='FusionCompute user name'),
cfg.StrOpt('fc_pwd_for_cinder', secret=True,
help='FusionCompute user password'),
cfg.StrOpt('fc_ip',
help='Management IP of FusionCompute'),
cfg.StrOpt('fc_image_path',
help='NFS Image server path'),
cfg.StrOpt('glance_server_ip',
help='FusionSphere glance server ip'),
cfg.StrOpt('s3_store_access_key_for_cinder', secret=True,
help='FusionCompute uds image access key'),
cfg.StrOpt('s3_store_secret_key_for_cinder', secret=True,
help='FusionCompute uds image secret key'),
cfg.StrOpt('export_image_type',
help='FusionCompute export image type : nfs, glance, uds'),
cfg.StrOpt('uds_ip',
help='FusionSphere uds server ip'),
cfg.StrOpt('uds_port',
help='FusionSphere uds server port'),
cfg.StrOpt('uds_bucket_name',
help='FusionSphere uds server bucket name'),
cfg.StrOpt('uds_bucket_type',
help='FusionSphere uds server bucket type fixed or wildcard'),
cfg.ListOpt('vrm_ds_types',
default=['advanceSan', 'DSWARE', 'san', 'NAS', 'LUNPOME',
'LOCAL', 'LOCALPOME'],
help='Management port of VRM'),
cfg.StrOpt('vrm_ds_hosts_share',
default='false',
help='FusionSphere support all host model'),
cfg.StrOpt('vrm_is_thin',
default='true',
help='FusionSphere create volume default type'),
cfg.StrOpt('export_version',
default='v6.0',
help='export version of VHD'),
]
CONF = cfg.CONF
CONF.register_group(VRM_group)
CONF.register_opts(VRM_opts, VRM_group)
CONF.register_opts(vrm_http_opts)
FC_DRIVER_CONF = CONF.VRM

View File

@ -0,0 +1,114 @@
# Copyright 2016 Huawei Technologies Co.,LTD.
# 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.
"""
[VRM DRIVER] VRM CLIENT.
"""
import json
from oslo_log import log as logging
from cinder.i18n import _
from cinder.volume.drivers.huawei.vrm.base_proxy import BaseProxy
from cinder.volume.drivers.huawei.vrm import exception as driver_exception
TASK_WAITING = 'waiting'
TASK_RUNNING = 'running'
TASK_SUCCESS = 'success'
TASK_FAILED = 'failed'
TASK_CANCELLING = 'cancelling'
TASK_UNKNOWN = 'unknown'
LOG = logging.getLogger(__name__)
class DatastoreProxy(BaseProxy):
'''DatastoreProxy
DatastoreProxy
'''
def __init__(self):
super(DatastoreProxy, self).__init__()
def list_datastore(self, **kwargs):
'''list_datastore
:param kwargs:
:return:
'''
# LOG.info(_("[VRM-CINDER] start list_datastore()"))
uri = '/datastores'
method = 'GET'
path = self.site_uri + uri
offset = 0
datastores = []
while True:
parames = {'limit': self.limit,
'offset': offset,
'scope': kwargs.get('scope')}
appendix = self._joined_params(parames)
new_url = self._generate_url(path, appendix)
resp, body = self.vrmhttpclient.request(new_url, method)
total = int(body.get('total') or 0)
if total > 0:
res = body.get('datastores')
datastores += res
offset += len(res)
if offset >= total or len(datastores) >= total or len(
res) < self.limit:
break
else:
break
return datastores
def query_datastore(self, **kwargs):
'''Query DataStore
:param kwargs:
:return:
'''
# LOG.info(_("[VRM-CINDER] start list_datastore()"))
uri = '/datastores' + '/' + kwargs.get('id')
method = 'GET'
path = self.site_uri + uri
new_url = self._generate_url(path)
resp, body = self.vrmhttpclient.request(new_url, method)
return body
def check_ds_connect_cluster(self, **kwargs):
'''Check cluster connected to the datastore
:param kwargs:
:return:
'''
LOG.info(_("[VRM-CINDER] start _check_ds_connect_cluster()"))
uri = '/datastores'
method = 'POST'
body = {'clusterUrn': kwargs.get('cluster_urn')}
path = self.site_uri + uri + '/' + kwargs.get(
'datastore_id') + '/action/ifconcluster'
new_url = self._generate_url(path)
resp, body = self.vrmhttpclient.request(new_url, method,
body=json.dumps(body))
if_connect_flag = body.get('ifConnectFlag')
if if_connect_flag and if_connect_flag is True:
return
else:
raise driver_exception.NoNeededData()

View File

@ -0,0 +1,184 @@
# Copyright 2016 Huawei Technologies Co.,LTD.
# 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.
"""
[VRM DRIVER] EXCEPTION
"""
from cinder import exception
"""
Exception definitions.
"""
class UnsupportedFeature(exception.CinderException):
'''UnsupportedFeature
UnsupportedFeature
'''
pass
class UnsupportedVersion(UnsupportedFeature):
'''UnsupportedVersion
UnsupportedVersion
'''
pass
class UnsupportedCommand(UnsupportedFeature):
'''UnsupportedCommand
UnsupportedCommand
'''
pass
class AuthorizationFailure(exception.CinderException):
'''AuthorizationFailure
AuthorizationFailure
'''
pass
class NoNeededData(exception.CinderException):
'''NoNeededData
NoNeededData
'''
pass
class ClientException(exception.CinderException):
'''ClientException
ClientException
'''
def __init__(self, code=None, message=None, error_code=None,
error_des=None):
self.code = code
self.errorCode = error_code
self.errorDes = error_des
if message:
self.message = message
else:
self.message = "client exception."
super(ClientException, self).__init__(self.message)
def __str__(self):
formatted_string = "%s (HTTP %s)" % (self.message, self.code)
if self.errorCode:
formatted_string += " (errorCode: %s)" % self.errorCode
if self.errorDes:
formatted_string += " (errorDes: %s)" % self.errorDes
return formatted_string
class BadRequest(ClientException):
"""BadRequest
HTTP 400 - Bad request: you sent some malformed data.
"""
http_status = 400
message = "Bad request"
class Unauthorized(ClientException):
"""Unauthorized
HTTP 401 - Unauthorized: bad credentials.
"""
http_status = 401
message = "Unauthorized"
class Forbidden(ClientException):
"""Forbidden
HTTP 403 - Forbidden: your credentials don't give you access to this
resource.
"""
http_status = 403
message = "Forbidden"
class NotFound(ClientException):
"""NotFound
HTTP 404 - Not found
"""
http_status = 404
message = "Not found"
class OverLimit(ClientException):
"""OverLimit
HTTP 413 - Over limit: you're over the API limits for this time period.
"""
http_status = 413
message = "Over limit"
class HTTPNotImplemented(ClientException):
"""HTTPNotImplemented
HTTP 501 - Not Implemented: the server does not support this operation.
"""
http_status = 501
message = "Not Implemented"
class FusionComputeDriverException(ClientException):
'''FusionComputeDriverException
FusionComputeDriverException
'''
http_status = 500
message = "FusionCompute driver exception occurred."
_code_map = dict((c.http_status, c) for c in [BadRequest, Unauthorized,
Forbidden, NotFound,
OverLimit, HTTPNotImplemented])
def exception_from_response(response, body):
"""exception_from_response
Return an instance of an ClientException or subclass
based on an requests response.
Usage::
resp, body = requests.request(...)
if resp.status_code != 200:
raise exception_from_response(resp, rest.text)
"""
cls = _code_map.get(response.status_code, ClientException)
if body:
error_code = body.get('errorCode', None)
error_des = body.get('errorDes', None)
return cls(code=response.status_code, errorCode=error_code,
errorDes=error_des)
else:
return cls(code=response.status_code)

View File

@ -0,0 +1,77 @@
# Copyright 2016 Huawei Technologies Co.,LTD.
# 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.
"""
[VRM DRIVER] VRM CLIENT.
"""
from oslo_log import log as logging
from cinder.volume.drivers.huawei.vrm.base_proxy import BaseProxy
TASK_WAITING = 'waiting'
TASK_RUNNING = 'running'
TASK_SUCCESS = 'success'
TASK_FAILED = 'failed'
TASK_CANCELLING = 'cancelling'
TASK_UNKNOWN = 'unknown'
LOG = logging.getLogger(__name__)
class HostProxy(BaseProxy):
'''HostProxy
'''
def __init__(self):
super(HostProxy, self).__init__()
def list_host(self, **kwargs):
'''list_host
:param kwargs:
:return:
'''
# LOG.info(_("[VRM-CINDER] start list_host()"))
uri = '/hosts'
method = 'GET'
path = self.site_uri + uri
offset = 0
hosts = []
while True:
parameters = {'limit': self.limit,
'offset': offset,
'scope': kwargs.get('scope')}
appendix = self._joined_params(parameters)
new_url = self._generate_url(path, appendix)
resp, body = self.vrmhttpclient.request(new_url, method)
total = int(body.get('total') or 0)
if total > 0:
res = body.get('hosts')
hosts += res
offset += len(res)
if offset >= total or len(hosts) >= total or len(
res) < self.limit:
break
else:
break
return hosts

View File

@ -0,0 +1,399 @@
# Copyright 2016 Huawei Technologies Co.,LTD.
# 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.
"""
[VRM DRIVER] VRM CLIENT.
"""
import json
import requests
import urlparse
from oslo_config import cfg
from oslo_log import log as logging
from cinder.i18n import _
from cinder.volume.drivers.huawei.vrm.conf import FC_DRIVER_CONF
from cinder.volume.drivers.huawei.vrm import exception as driver_exception
from cinder.volume.drivers.huawei.vrm import utils as apiutils
try:
from eventlet import sleep
except ImportError:
from time import sleep
TASK_WAITING = 'waiting'
TASK_RUNNING = 'running'
TASK_SUCCESS = 'success'
TASK_FAILED = 'failed'
TASK_CANCELLING = 'cancelling'
TASK_UNKNOWN = 'unknown'
CONF = cfg.CONF
LOG = logging.getLogger(__name__)
class VRMHTTPClient(object):
"""Executes volume driver commands on VRM."""
USER_AGENT = 'VRM-HTTP-Client for OpenStack'
RESOURCE_URI = 'uri'
TASK_URI = 'taskUri'
BASIC_URI = '/service'
vrm_commands = None
def __init__(self):
'''VRMHTTPClient init
__init__
:return:
'''
fc_ip = FC_DRIVER_CONF.fc_ip
fc_image_path = FC_DRIVER_CONF.fc_image_path
fc_user = FC_DRIVER_CONF.fc_user
fc_pwd = FC_DRIVER_CONF.fc_pwd_for_cinder
self.ssl = CONF.vrm_ssl
self.host = fc_ip
self.port = CONF.vrm_port
self.user = fc_user
self.userType = CONF.vrm_usertype
self.password = apiutils.sha256_based_key(fc_pwd)
self.retries = CONF.vrm_retries
self.timeout = CONF.vrm_timeout
self.limit = CONF.vrm_limit
self.image_url = fc_image_path
self.image_type = '.xml'
self.versions = None
self.version = None
self.auth_uri = None
self.auth_url = None
self.auth_token = None
self.sites = None
self.site_uri = None
self.site_urn = None
self.site_url = None
self.shared_hosts = None
self.shared_datastores = None
self.shared_volumes = None
def _generate_url(self, path, query=None, frag=None):
'''_generate_url
_generate_url
:param path:
:param query:
:param frag:
:return:
'''
if CONF.vrm_ssl:
scheme = 'https'
else:
scheme = 'http'
fc_ip = FC_DRIVER_CONF.fc_ip
netloc = str(fc_ip) + ':' + str(CONF.vrm_port)
if path.startswith(self.BASIC_URI):
url = urlparse.urlunsplit((scheme, netloc, path, query, frag))
else:
url = urlparse.urlunsplit(
(scheme, netloc, self.BASIC_URI + str(path), query, frag))
return url
def _http_log_req(self, args, kwargs):
'''_http_log_req
_http_log_req
:param args:
:param kwargs:
:return:
'''
string_parts = ['\n curl -i']
for element in args:
if element in ('GET', 'POST', 'DELETE', 'PUT'):
string_parts.append(' -X %s' % element)
else:
string_parts.append(' %s' % element)
for element in kwargs['headers']:
header = ' -H "%s: %s"' % (element, kwargs['headers'][element])
string_parts.append(header)
if 'body' in kwargs:
string_parts.append(" -d '%s'" % (kwargs['body']))
def _http_log_resp(self, resp):
'''_http_log_resp
_http_log_resp
:param resp:
:return:
'''
try:
if resp.status_code:
if int(resp.status_code) != 200:
LOG.info(_("RESP status_code: [%s]"), resp.status_code)
except Exception:
LOG.info(_("[VRM-CINDER] _http_log_resp exception"))
def request(self, url, method, **kwargs):
'''request
request
:param url:
:param method:
:param kwargs:
:return:
'''
auth_attempts = 0
attempts = 0
step = 1
while True:
step *= 2
attempts += 1
if not self.auth_url or not self.auth_token or not self.site_uri:
LOG.info(_("[VRM-CINDER] auth_url is none. "))
kwargs.setdefault('headers', {})['X-Auth-Token'] = self.auth_token
try:
resp, body = self.try_request(url, method, **kwargs)
return resp, body
except driver_exception.Unauthorized as e:
LOG.error('[VRM-CINDER] error message is :%s' % e)
if e.errorCode == '10000040':
if auth_attempts > 2:
LOG.error("license error.")
raise driver_exception.ClientException(101)
if auth_attempts > 10:
raise driver_exception.ClientException(101)
LOG.info("Unauthorized, reauthenticating.")
attempts -= 1
auth_attempts += 1
sleep(step)
self.authenticate()
continue
except driver_exception.ClientException as ex:
if attempts > self.retries:
LOG.info(_("[VRM-CINDER] ClientException "))
raise ex
if 500 <= ex.code <= 599:
LOG.info(_("[VRM-CINDER] ClientException "))
else:
LOG.info(_("[VRM-CINDER] ClientException "))
raise ex
except requests.exceptions.ConnectionError as ex:
LOG.error("Connection Error: %s" % ex)
LOG.error("Connection Error: %s" % ex.message)
raise ex
LOG.info(
"Failed attempt(%s of %s), retrying in %s seconds" %
(attempts, self.retries, step))
sleep(step)
def try_request(self, url, method, **kwargs):
'''try_request
request
:param url:
:param method:
:param kwargs:
:return:
'''
no_version = False
if not self.version:
no_version = True
if url.endswith('session'):
no_version = True
kwargs.setdefault('headers', kwargs.get('headers', {}))
kwargs['headers']['User-Agent'] = self.USER_AGENT
if no_version:
kwargs['headers']['Accept'] = 'application/json;charset=UTF-8'
else:
version = self.version.lstrip(' v')
if url.endswith('/action/export'):
export_version = FC_DRIVER_CONF.export_version
version = '1.2' if export_version == 'v1.2' else \
self.version.lstrip(' v')
kwargs['headers']['Accept'] = 'application/json;version=' + \
version + ';charset=UTF-8'
kwargs['headers']['X-Auth-Token'] = self.auth_token
kwargs['headers']['Accept-Language'] = 'en_US'
if 'body' in kwargs:
if kwargs['body'] and len(kwargs['body']) > 0:
kwargs['headers'][
'Content-Type'] = 'application/json;charset=UTF-8'
kwargs['data'] = kwargs['body']
body = apiutils.str_drop_password_key(kwargs['body'])
# LOG.info(_("[VRM-CINDER] request body [%s]"), body)
del kwargs['body']
self._http_log_req((url, method,), kwargs)
resp = requests.request(
method,
url,
verify=False,
**kwargs)
self._http_log_resp(resp)
if resp.content:
try:
body = json.loads(resp.content)
except ValueError:
body = None
else:
body = None
# LOG.info(_("[VRM-CINDER] request status_code [%d]"), resp.status_code)
if resp.status_code >= 400:
LOG.error(_("error response, error is %s"), body)
raise driver_exception.exception_from_response(resp, body)
return resp, body
def _prepare_version_and_auth_url(self):
'''_prepare_version_and_auth_url
_prepare_version_and_auth_url
:return:
'''
self.version = CONF.vrm_version
self.auth_uri = '/service/session'
self.auth_url = self._generate_url(self.auth_uri)
def _prepare_auth_token(self):
'''_prepare_auth_token
_prepare_auth_token
:return:
'''
uri = '/service/session'
new_url = self._generate_url(uri)
# self.auth_token = None
headers = {'X-Auth-User': self.user,
'X-Auth-Key': self.password,
'X-Auth-UserType': self.userType, }
resp, body = self.try_request(new_url, 'POST', headers=headers)
if resp.status_code in (200, 204):
self.auth_token = resp.headers['x-auth-token']
def _prepare_site_uri(self):
'''_prepare_site_uri
_prepare_site_uri
:return:
'''
self.site_uri = self.site_urn = self.site_url = None
url = self._generate_url('/sites')
headers = {'X-Auth-Token': self.auth_token}
resp, body = self.try_request(url, 'GET', headers=headers)
if resp.status_code in (200, 204):
self.sites = body['sites']
if len(self.sites) == 1:
self.site_uri = self.sites[0]['uri']
self.site_urn = self.sites[0]['urn']
self.site_url = self._generate_url(self.site_uri)
return
else:
for si in self.sites:
if si['urn'] == FC_DRIVER_CONF.vrm_siteurn:
self.site_uri = si['uri']
self.site_urn = si['urn']
self.site_url = self._generate_url(self.site_uri)
return
raise driver_exception.NotFound()
def authenticate(self):
'''authenticate
authenticate
:return:
'''
self._prepare_version_and_auth_url()
self._prepare_auth_token()
self._prepare_site_uri()
if not self.version:
LOG.info(_("[VRM-CINDER] (%s)"), 'AuthorizationFailure')
raise driver_exception.AuthorizationFailure
if not self.auth_url:
LOG.info(_("[VRM-CINDER] (%s)"), 'AuthorizationFailure')
raise driver_exception.AuthorizationFailure
if not self.site_uri:
LOG.info(_("[VRM-CINDER] (%s)"), 'AuthorizationFailure')
raise driver_exception.AuthorizationFailure
def get_version(self):
'''get_version
get_version
:return:
'''
return self.version
def get_siteurn(self):
'''get_siteurn
get_siteurn
:return:
'''
if self.site_uri is None:
self.init()
return self.site_urn
def get_siteuri(self):
'''get_siteuri
get_siteurn
:return:
'''
if self.site_uri is None:
self.init()
return self.site_uri
def init(self):
'''init
init
:return:
'''
LOG.info(_("[VRM-CINDER] start init()"))
self.authenticate()

View File

@ -0,0 +1,130 @@
# Copyright 2016 Huawei Technologies Co.,LTD.
# 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.
"""
[VRM DRIVER] VRM CLIENT.
"""
from oslo_config import cfg
from oslo_log import log as logging
from cinder.i18n import _
from cinder.volume.drivers.huawei.vrm.base_proxy import BaseProxy
from cinder.volume.drivers.huawei.vrm import exception as driver_exception
from cinder.volume.drivers.huawei.vrm.utils import Delete_Snapshot_Code
try:
from eventlet import sleep
except ImportError:
from time import sleep
TASK_WAITING = 'waiting'
TASK_RUNNING = 'running'
TASK_SUCCESS = 'success'
TASK_FAILED = 'failed'
TASK_CANCELLING = 'cancelling'
TASK_UNKNOWN = 'unknown'
CONF = cfg.CONF
LOG = logging.getLogger(__name__)
class TaskProxy(BaseProxy):
'''TaskProxy
TaskProxy
'''
def __init__(self):
super(TaskProxy, self).__init__()
def wait_task(self, isShortQuery=0, **kwargs):
'''wait_task
:param kwargs:
:return:
'''
LOG.info(_("[VRM-CINDER] start wait_task()"))
task_uri = kwargs.get('task_uri')
method = 'GET'
if task_uri is None:
LOG.info(_("[VRM-CINDER] task_uri is none."))
raise driver_exception.ClientException(101)
else:
new_url = self._generate_url(task_uri)
retry = 0
error_num = 0
while retry < int(CONF.vrm_timeout):
if isShortQuery == 0:
if retry > 10:
retry += 10
sleep(10)
else:
retry += 3
sleep(3)
else:
if retry > 10:
retry += 10
sleep(10)
else:
retry += 1
sleep(1)
try:
resp, body = self.vrmhttpclient.request(new_url, method)
except Exception as ex:
LOG.info(_("[VRM-CINDER] querytask request exception."))
error_num += 1
if 30 < error_num:
LOG.info(
_("[VRM-CINDER] querytask request exception."))
raise ex
else:
continue
if body:
status = body.get('status')
if status in [TASK_WAITING, TASK_RUNNING]:
continue
elif status in [TASK_SUCCESS]:
LOG.info(
_("[VRM-CINDER] return TASK_SUCCESS wait_task()"))
return status
elif status in [TASK_FAILED, TASK_CANCELLING]:
LOG.info(
_("[VRM-CINDER] return TASK_FAILED wait_task()"))
if body.get('reason') in Delete_Snapshot_Code:
raise driver_exception.ClientException(
code=101,
message=body.get('reasonDes'),
errorCode=body.get('reason'))
raise driver_exception.ClientException(101)
else:
LOG.info(_("[VRM-CINDER] pass wait_task()"))
error_num += 1
if 30 < error_num:
raise driver_exception.ClientException(101)
else:
continue
else:
LOG.info(_("[VRM-CINDER] body is none."))
error_num += 1
if 30 < error_num:
raise driver_exception.ClientException(101)
else:
continue

View File

@ -0,0 +1,92 @@
# Copyright 2016 Huawei Technologies Co.,LTD.
# 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.
"""
FC Driver utils function
"""
import hashlib
import sys
import traceback
from cinder.i18n import _
from oslo_log import log as logging
LOG = logging.getLogger(__name__)
def log_exception(exception=None):
"""log_exception
:param exception:
:return:
"""
if exception:
pass
etype, value, track_tb = sys.exc_info()
error_list = traceback.format_exception(etype, value, track_tb)
for error_info in error_list:
LOG.error(error_info)
def str_drop_password_key(str_data):
"""str_drop_password_key
remove json password key item
:param data:
:return:
"""
dict_data = eval(str_data)
if isinstance(dict_data, dict):
drop_password_key(dict_data)
return str(dict_data)
else:
LOG.info(
_("[BRM-DRIVER] str_data can't change to dict, str_data:(%s) "),
str_data)
return
def drop_password_key(data):
"""remove json password key item
:param data:
:return:
"""
encrypt_list = ['password', 'vncpassword', 'oldpassword',
'domainpassword', 'vncoldpassword', 'vncnewpassword',
'auth_token', 'token', 'fc_pwd', 'accessKey',
'secretKey']
for key in data.keys():
if key in encrypt_list:
del data[key]
elif data[key] and isinstance(data[key], dict):
drop_password_key(data[key])
def sha256_based_key(key):
"""sha256_based_key
generate sha256 based key
:param key:
:return:
"""
hash_ = hashlib.sha256()
hash_.update(key)
return hash_.hexdigest()
Delete_Snapshot_Code = ['10400004']

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,601 @@
# Copyright 2016 Huawei Technologies Co.,LTD.
# 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.
"""
[VRM DRIVER] VRM CLIENT.
"""
import json
from cinder import exception as cinder_exception
from cinder.i18n import _
from cinder.volume.drivers.huawei.vrm.base_proxy import BaseProxy
from cinder.volume.drivers.huawei.vrm import exception as driver_exception
from cinder.volume.drivers.huawei.vrm.task_proxy import TaskProxy
from oslo_log import log as logging
TASK_WAITING = 'waiting'
TASK_RUNNING = 'running'
TASK_SUCCESS = 'success'
TASK_FAILED = 'failed'
TASK_CANCELLING = 'cancelling'
TASK_UNKNOWN = 'unknown'
LOG = logging.getLogger(__name__)
class VolumeProxy(BaseProxy):
def __init__(self):
super(VolumeProxy, self).__init__()
self.task_proxy = TaskProxy()
def filter_not_none_dict(self, src_dic):
obj_dic = {}
for index_dic in src_dic:
if src_dic.get(index_dic) is not None:
obj_dic.update({index_dic: src_dic.get(index_dic)})
return obj_dic
def query_volume(self, **kwargs):
'''query_volume
'query_volume': ('GET',
('/volumes', kwargs.get(self.RESOURCE_URI),
None,
kwargs.get('id')),
{'limit': kwargs.get('limit'),
'offset': kwargs.get('offset'),
'scope': kwargs.get('scope')
},
{},
False),
'''
LOG.info(_("[VRM-CINDER] start query_volume()"))
uri = '/volumes'
method = 'GET'
path = self.site_uri + uri + '/' + kwargs.get('id')
new_url = self._generate_url(path)
resp, body = self.vrmhttpclient.request(new_url, method)
return body
def query_volume_replications(self, **kwargs):
'''query_volume_replications
'query_volume_replications': ('GET',
('/volumes/{volume_id}/action/replications',
kwargs.get(self.RESOURCE_URI), None,
kwargs.get('volume_id')),
False),
'''
LOG.info(_("[VRM-CINDER] start query_volume_replications()"))
uri = '/volumes'
method = 'GET'
path = self.site_uri + uri + '/' + kwargs.get(
'volume_id') + '/action/replications'
new_url = self._generate_url(path)
resp, body = self.vrmhttpclient.request(new_url, method)
return body
def list_volumes(self, **kwargs):
'''list_volumes
'list_volumes': ('GET',
('/volumes', kwargs.get(self.RESOURCE_URI),
None,
kwargs.get('id')),
{'limit': kwargs.get('limit'),
'offset': kwargs.get('offset'),
'scope': kwargs.get('scope')
},
{},
False),
'''
LOG.info(_("[VRM-CINDER] start query_volumesnapshot()"))
uri = '/volumes/compatibility/discovery '
method = 'GET'
path = self.site_uri + uri
offset = 0
volumes = []
volumes_map = {} # use map to clean repeat
while True:
parames = {
'limit': self.limit,
'offset': offset,
'scope': kwargs.get('scope'),
'uuid': kwargs.get('uuid')
}
appendix = self._joined_params(parames)
new_url = self._generate_url(path, appendix)
resp, body = self.vrmhttpclient.request(new_url, method)
total = int(body.get('total') or 0)
if total > 0:
res = body.get('volumes')
for volume in res:
volumes_map[volume.get('uuid')] = volume
volumes = volumes_map.values()
volumes += res
offset += len(res)
if offset >= total or len(volumes) >= total or len(
res) < self.limit:
break
if offset > 5:
offset -= 5
else:
break
for index_volume in volumes:
if index_volume.get(
'customProperties') is not None and index_volume.get(
'customProperties').get('external_uuid') is not None:
index_volume["uuid"] = index_volume["customProperties"][
"external_uuid"]
return volumes
def list_volumes_extend(self, **kwargs):
'''list_volumes_extend
'list_volumes_extend': ('GET',
('/volumes', kwargs.get(self.RESOURCE_URI),
None,
kwargs.get('id')),
{'limit': kwargs.get('limit'),
'offset': kwargs.get('offset'),
'scope': kwargs.get('scope')
},
{},
False),
'''
LOG.info(_("[VRM-CINDER] start query_volumesnapshot()"))
uri = '/volumes/extend'
method = 'GET'
path = self.site_uri + uri
offset = 0
volumes = []
volumes_map = {} # use map to clean repeat
while True:
parames = {
'limit': self.limit,
'offset': offset,
'scope': kwargs.get('scope'),
'uuid': kwargs.get('uuid')
}
appendix = self._joined_params(parames)
new_url = self._generate_url(path, appendix)
resp, body = self.vrmhttpclient.request(new_url, method)
total = int(body.get('total') or 0)
if total > 0:
res = body.get('volumes')
for volume in res:
volumes_map[volume.get('uuid')] = volume
volumes = volumes_map.values()
volumes += res
offset += len(res)
if offset >= total or len(volumes) >= total or len(
res) < self.limit:
break
if offset > 5:
offset -= 5
else:
break
for index_volume in volumes:
if index_volume.get(
'customProperties') is not None and index_volume.get(
'customProperties').get('external_uuid') is not None:
index_volume["uuid"] = index_volume["customProperties"][
"external_uuid"]
return volumes
def create_volume(self, **kwargs):
'''create_volume
'create_volume': ('POST',
('/volumes', None, None, None),
{},
{'name': kwargs.get('name'),
'quantityGB': kwargs.get('quantityGB'),
'datastoreUrn': kwargs.get('datastoreUrn'),
'uuid': kwargs.get('uuid'),
'isThin': kwargs.get('isThin'),
'type': kwargs.get('type'),
'indepDisk': kwargs.get('indepDisk'),
'persistentDisk':
kwargs.get('persistentDisk'),
'volumeId': kwargs.get('volumeId'),
'snapshotUuid': kwargs.get('snapshotUuid'),
'imageUrl': kwargs.get('imageUrl'),
},
True),
'''
LOG.info(_("[VRM-CINDER] start create_volume()"))
uri = '/volumes'
method = 'POST'
path = self.site_uri + uri
new_url = self._generate_url(path)
body = {
'name': kwargs.get('name'),
'quantityGB': kwargs.get('size'),
'datastoreUrn': kwargs.get('ds_urn'),
'uuid': kwargs.get('uuid'),
'isThin': kwargs.get('is_thin'),
'type': kwargs.get('type'),
'indepDisk': kwargs.get('independent'),
'customProperties': {"external_uuid": kwargs.get('uuid')}
}
support_pvscsi = kwargs.get('support_pvscsi', None)
if support_pvscsi is not None:
body.update({'pvscsiSupport': support_pvscsi})
resp, body = self.vrmhttpclient.request(new_url, method,
body=json.dumps(body))
return body
def delete_volume(self, **kwargs):
'''delete_volume
'delete_volume': ('DELETE',
('/volumes', kwargs.get(self.RESOURCE_URI),
None,
None),
{},
{},
True),
'''
LOG.info(_("[VRM-CINDER] start delete_volume()"))
method = 'DELETE'
path = kwargs.get('volume_uri')
new_url = self._generate_url(path)
error_busy = ['10300057', '10420005', '10420009', '10410154',
'10420137', '10420138', '10430058']
try:
resp, body = self.vrmhttpclient.request(new_url, method)
task_uri = body.get('taskUri')
self.task_proxy.wait_task(task_uri=task_uri)
except driver_exception.ClientException as ex:
LOG.info(_("[VRM-CINDER] delete volume (%s)"), ex.errorCode)
if ex.errorCode == "10420004":
return
elif ex.errorCode in error_busy:
LOG.info(_(
"[VRM-CINDER] volume status conflicts, try delete later."))
raise cinder_exception.VolumeIsBusy(message=ex.errorCode)
else:
raise ex
def clone_volume(self, **kwargs):
'''clone_volume
'clone_volume': ('POST',
('/volumes', None, kwargs.get('src_name'),'action/copyVol'),
{},
{'destinationVolumeID':
kwargs.get('dest_name')
},
True),
'''
LOG.info(_("[VRM-CINDER] start clone_volume()"))
uri = '/volumes'
method = 'POST'
path = self.site_uri + uri + '/' + kwargs.get(
'src_volume_id') + '/action/copyVol'
body = {'dstVolUrn': kwargs.get('dest_volume_urn')}
new_url = self._generate_url(path)
resp, body = self.vrmhttpclient.request(new_url, method,
body=json.dumps(body))
task_uri = body.get('taskUri')
self.task_proxy.wait_task(task_uri=task_uri)
def _copy_nfs_image_to_volume(self, **kwargs):
'''_copy_nfs_image_to_volume
'copy_image_to_volume': ('POST',
('/volumes/imagetovolume', None, None, None),
{},
{
'volumePara': {
'quantityGB':
kwargs.get('volume_size'),
'urn': kwargs.get('volume_urn')
},
'imagePara': {
'id': kwargs.get('image_id'),
'url': kwargs.get('image_location')
},
'location': kwargs.get('cluster_urn'),
'needCreateVolume': False
},
True),
'''
LOG.info(_("[VRM-CINDER] start copy_image_to_volume()"))
uri = '/volumes/imagetovolume'
method = 'POST'
path = self.site_uri + uri
new_url = self._generate_url(path)
body = {
'volumePara': {
'quantityGB': kwargs.get('volume_size'),
'urn': kwargs.get('volume_urn')
},
'imagePara': {
'id': kwargs.get('image_id'),
'url': kwargs.get('image_location')
},
'location': kwargs.get('cluster_urn'),
'needCreateVolume': False
}
resp, body = self.vrmhttpclient.request(new_url, method,
body=json.dumps(body))
task_uri = body.get('taskUri')
self.task_proxy.wait_task(task_uri=task_uri)
def _copy_volume_to_image(self, **kwargs):
'''_copy_volume_to_image
'copy_volume_to_image': ('POST',
('/volumes/volumetoimage', None, None, None),
{},
{
'volumePara': {'urn':
kwargs.get('volume_urn'),
'quantityGB':
kwargs.get('volume_size')},
'imagePara': {
'id': kwargs.get(
'image_id'),
'url': kwargs.get(
'image_url')}
},
True),
'''
LOG.info(_("[VRM-CINDER] start stop_vm()"))
uri = '/volumes/volumetoimage'
method = 'POST'
path = self.site_uri + uri
new_url = self._generate_url(path)
body = {
'volumePara': {
'urn': kwargs.get('volume_urn'),
'quantityGB': kwargs.get('volume_size')},
'imagePara': {
'id': kwargs.get('image_id'),
'url': kwargs.get('image_url')}
}
resp, body = self.vrmhttpclient.request(new_url, method,
body=json.dumps(body))
task_uri = body.get('taskUri')
self.task_proxy.wait_task(task_uri=task_uri)
def manage_existing(self, **kwargs):
'''manage_existing
'manage_existing': ('POST',
('/volumes', None, None, None),
{},
{'name': kwargs.get('name'),
'quantityGB': kwargs.get('quantityGB'),
'datastoreUrn': kwargs.get('datastoreUrn'),
'uuid': kwargs.get('uuid'),
'type': kwargs.get('type'),
'indepDisk': kwargs.get('indepDisk'),
'persistentDisk':
kwargs.get('persistentDisk'),
'volumeId': kwargs.get('volumeId'),
'snapshotUuid': kwargs.get('snapshotUuid'),
'imageUrl': kwargs.get('imageUrl'),
},
True),
'''
LOG.info(_("[VRM-CINDER] start create_volume()"))
uri = '/volumes/registevol'
method = 'POST'
path = self.site_uri + uri
new_url = self._generate_url(path)
body = {
'name': kwargs.get('name'),
'quantityGB': kwargs.get('quantityGB'),
'volInfoUrl': kwargs.get('volInfoUrl'),
'uuid': kwargs.get('uuid'),
'customProperties': {"external_uuid": kwargs.get('uuid')},
'type': kwargs.get('type'),
'maxReadBytes': kwargs.get('maxReadBytes'),
'maxWriteBytes': kwargs.get('maxWriteBytes'),
'maxReadRequest': kwargs.get('maxReadRequest'),
'maxWriteRequest': kwargs.get('maxWriteRequest')}
resp, body = self.vrmhttpclient.request(new_url, method,
body=json.dumps(body))
return body
def unmanage(self, **kwargs):
'''unmanage
'unmanage': ('DELETE',
('/volumes?isOnlyDelDB=1',
kwargs.get(self.RESOURCE_URI), None, None),
{},
{},
True),
'''
LOG.info(_("[VRM-CINDER] start unmanage()"))
method = 'DELETE'
path = kwargs.get('volume_uri') + '?isOnlyDelDB=1'
new_url = self._generate_url(path)
try:
resp, body = self.vrmhttpclient.request(new_url, method)
task_uri = body.get('taskUri')
self.task_proxy.wait_task(task_uri=task_uri)
except driver_exception.ClientException as ex:
LOG.info(_("[VRM-CINDER] unmanage volume (%s)"), ex.errorCode)
if ex.errorCode == "10420004":
return
else:
raise ex
def migrate_volume(self, **kwargs):
'''migrate_volume
Post <vol_uri>/<volid>/action/migratevol HTTP/1.1
Host https://<ip>:<port>
Accept application/json;version=<version>; charset=UTF-8
X-Auth-Token: <Authen_TOKEN>
{
'datastoreUrn':string,
'speed': integer
}
'''
LOG.info(_("[VRM-CINDER] start migrate_volume()"))
uri = '/volumes'
method = 'POST'
path = self.site_uri + uri + '/' + kwargs.get(
'volume_id') + '/action/migratevol'
body = {'datastoreUrn': kwargs.get('dest_ds_urn'),
'speed': kwargs.get('speed'),
'migrateType': kwargs.get('migrate_type')}
new_url = self._generate_url(path)
resp, body = self.vrmhttpclient.request(new_url, method,
body=json.dumps(body))
task_uri = body.get('taskUri')
self.task_proxy.wait_task(task_uri=task_uri)
def modify_volume(self, **kwargs):
LOG.info(_("[VRM-CINDER] start modify_volume()"))
uri = '/volumes'
method = 'PUT'
path = self.site_uri + uri + '/' + kwargs.get('volume_id')
body = {}
if kwargs.get('type') is not None:
body.update({'type': kwargs.get('type')})
if kwargs.get('name') is not None:
body.update({'name': kwargs.get('name')})
new_url = self._generate_url(path)
resp, body = self.vrmhttpclient.request(new_url, method,
body=json.dumps(body))
if resp.status_code not in (200, 204):
raise driver_exception.ClientException(101)
def extend_volume(self, **kwargs):
'''extend_volume
'extend_volume': ('POST',
(kwargs.get('volume_uri'),'/action/expandVol',
None, None),
{},
{},
True),
'''
LOG.info(_("[VRM-CINDER] start extend_volume()"))
method = 'POST'
body = {'size': kwargs.get('size')}
volume_uri = kwargs.get('volume_uri')
path = volume_uri + '/action/expandVol'
new_url = self._generate_url(path)
try:
resp, body = self.vrmhttpclient.request(new_url, method,
body=json.dumps(body))
task_uri = body.get('taskUri')
self.task_proxy.wait_task(task_uri=task_uri)
except driver_exception.ClientException as ex:
LOG.info(_("[VRM-CINDER] extend volume (%s)"), ex.errorCode)
raise ex
except Exception as ex:
LOG.info(_("[VRM-CINDER] extend volume (%s)"), ex)
raise ex
def wait_task(self, **kwargs):
task_uri = kwargs.get('taskUri')
self.task_proxy.wait_task(task_uri=task_uri)
def query_volume_by_custom_properties(self, **kwargs):
'''query_volume_by_custom_properties
'query_volume_by_custom_properties': ('POST',
('/volumes/queryby/custom-properties', None, None,
None),
{},
{"condition": {"name": "external_uuid",
"value": "93DF26A9-2D3B-43A6-A7D8-CF5E9D0DC17C"
},
"offset": 0,
limit": 10
},
True),
'''
LOG.info(_("[VRM-CINDER] start query_volume_by_custom_properties()"))
uri = '/volumes/queryby/custom-properties'
method = 'POST'
path = self.site_uri + uri
new_url = self._generate_url(path)
body = {
'condition': {
'name': 'external_uuid',
'value': kwargs.get('external_uuid')
}
}
resp, body = self.vrmhttpclient.request(new_url, method,
body=json.dumps(body))
volumes = []
total = int(body.get('total') or 0)
if total > 0:
res = body.get('volumes')
volumes += res
return volumes[0]
return None
def update_custom_properties(self, **kwargs):
'''update_custom_properties
'update_by_custom_properties': ('POST',
('/volumes/properties/custom', None, None, None),
{},
{"volumes": [
'volumeUrn': kwargs.get('volumeUrn'),
'customProperties': {
'external_uuid': kwargs.get('external_uuid')
}]
},
True),
'''
LOG.info(_("[VRM-CINDER] start modify_custom_properties()"))
uri = '/volumes/properties/custom'
method = 'POST'
path = self.site_uri + uri
new_url = self._generate_url(path)
body = {
'volumes': [
{
'volumeUrn': kwargs.get('volume_urn'),
'customProperties': {
'external_uuid': kwargs.get('external_uuid')
}
}
]
}
resp, body = self.vrmhttpclient.request(new_url, method,
body=json.dumps(body))
return body

View File

@ -0,0 +1,308 @@
# Copyright 2016 Huawei Technologies Co.,LTD.
# 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.
"""
[VRM DRIVER] VRM CLIENT.
"""
import json
from oslo_config import cfg
from oslo_log import log as logging
from cinder import exception as cinder_exception
from cinder.i18n import _
from cinder.volume.drivers.huawei.vrm.base_proxy import BaseProxy
from cinder.volume.drivers.huawei.vrm import exception as driver_exception
from cinder.volume.drivers.huawei.vrm.task_proxy import TaskProxy
from cinder.volume.drivers.huawei.vrm.utils import Delete_Snapshot_Code
CONF = cfg.CONF
try:
from eventlet import sleep
except ImportError:
from time import sleep
TASK_WAITING = 'waiting'
TASK_RUNNING = 'running'
TASK_SUCCESS = 'success'
TASK_FAILED = 'failed'
TASK_CANCELLING = 'cancelling'
TASK_UNKNOWN = 'unknown'
LOG = logging.getLogger(__name__)
class VolumeSnapshotProxy(BaseProxy):
def __init__(self, *args, **kwargs):
super(VolumeSnapshotProxy, self).__init__()
LOG.info(_("[VRM-CINDER] start __init__()"))
self.task_proxy = TaskProxy()
self.create_retry = ['10000009', '10430056', '10430050', '10300421',
'10430057', '10300318', '10300162', '10300026']
self.delete_retry = Delete_Snapshot_Code
self.number = CONF.vrm_vol_snapshot_retries
self.sleep_time = CONF.vrm_snapshot_sleeptime
if not self.number:
LOG.error('conf number is None, use 3')
self.number = 3
if not self.sleep_time:
LOG.error('conf sleeptime is None, use 300')
self.sleep_time = 300
def query_volumesnapshot(self, **kwargs):
'''query_volumesnapshot
'list_volumesnapshot': ('GET',
('/volumesnapshots', None, kwargs.get('uuid'),
None),
{'limit': kwargs.get('limit'),
'offset': kwargs.get('offset'),
'scope': kwargs.get('scope')
},
{},
False),
'''
LOG.info(_("[VRM-CINDER] start query_volumesnapshot()"))
uri = '/volumesnapshots'
method = 'GET'
path = self.site_uri + uri + '/' + kwargs.get('uuid')
new_url = self._generate_url(path)
try:
resp, body = self.vrmhttpclient.request(new_url, method)
except driver_exception.ClientException as ex:
LOG.info(_("[VRM-CINDER] query snapshot (%s)"), ex.errorCode)
if ex.errorCode == "10430051":
return None
else:
raise ex
'''
error_code = body.get('errorCode')
if error_code != None:
if '10430010' == error_code:
LOG.info(_("[VRM-CINDER] snapshot not exist"))
return None
'''
return body
def list_snapshot(self, **kwargs):
'''list_snapshot
'list_volumesnapshot': ('GET',
('/volumesnapshots', None, kwargs.get('uuid'),
None),
{'limit': kwargs.get('limit'),
'offset': kwargs.get('offset'),
'scope': kwargs.get('scope')
},
{},
False),
'''
LOG.info(_("[VRM-CINDER] start list_snapshot()"))
uri = '/volumesnapshots/queryVolumeSnapshots'
method = 'GET'
path = self.site_uri + uri
body = None
offset = 0
snapshots = []
while True:
parames = {
'limit': self.limit,
'offset': offset}
appendix = self._joined_params(parames)
new_url = self._generate_url(path, appendix)
resp, body = self.vrmhttpclient.request(new_url, method)
total = int(body.get('total') or 0)
if total > 0:
res = body.get('snapshots')
snapshots += res
offset += len(res)
if offset >= total or len(snapshots) >= total or len(
res) < self.limit:
break
else:
break
return snapshots
def create_volumesnapshot(self, **kwargs):
'''create_volumesnapshot
'create_volumesnapshot': ('POST',
('/volumesnapshots', None, None, None),
{},
{'volumeUrn': kwargs.get('vol_urn'),
'snapshotUuid': kwargs.get('uuid'),
},
False),
'''
LOG.info(_("[VRM-CINDER] start create_volumesnapshot()"))
uri = '/volumesnapshots'
method = 'POST'
path = self.site_uri + uri
body = {
'volumeUrn': kwargs.get('vol_urn'),
'snapshotUuid': kwargs.get('snapshot_uuid')
}
enable_active = kwargs.get('enable_active', None)
if enable_active is not None:
body.update({'enableActive': enable_active})
new_url = self._generate_url(path)
number = self.number
sleep_time = self.sleep_time
while(number >= 0):
try:
resp, body = self.vrmhttpclient.request(new_url, method,
body=json.dumps(body))
task_uri = body.get('taskUri')
if task_uri is not None:
self.task_proxy.wait_task(task_uri=task_uri)
return body
except driver_exception.ClientException as ex:
LOG.info(_("[VRM-CINDER] create volumesnapshot (%s)"),
ex.errorCode)
if ex.errorCode not in self.create_retry:
raise ex
LOG.debug(
'[VRM-CINDER] The errorcode is in retry list:%d' % number)
number -= 1
if number < 0:
raise ex
sleep(sleep_time)
def active_snapshots(self, **kwargs):
'''active_snapshots
'active_snapshots': ('POST',
('/volumesnapshots/enableSnapshots',
None, None, None),
{},
{'snapshotList': kwargs.get('snapshot_urns')},
False),
'''
LOG.info(_("[VRM-CINDER] start active_snapshots()"))
uri = '/volumesnapshots/enableSnapshots'
method = 'POST'
path = self.site_uri + uri
body = {
'snapshotUuidList': kwargs.get('snapshot_uuids')
}
new_url = self._generate_url(path)
resp, body = self.vrmhttpclient.request(new_url, method,
body=json.dumps(body))
task_uri = body.get('taskUri')
if task_uri is not None:
self.task_proxy.wait_task(task_uri=task_uri)
return body
def delete_volumesnapshot(self, **kwargs):
'''delete_volumesnapshot
'delete_volumesnapshot': ('DELETE',
('/volumesnapshots', None, None,
kwargs.get('id')),
{},
{
'snapshotUuid': kwargs.get('snapshotUuid'),
},
True),
'''
LOG.info(_("[VRM-CINDER] start delete_volumesnapshot()"))
uri = '/volumesnapshots'
method = 'DELETE'
path = self.site_uri + uri + '/' + kwargs.get('id')
body = {
'volumeUrn': kwargs.get('vol_urn'),
'snapshotUuid': kwargs.get('snapshot_uuid')}
new_url = self._generate_url(path)
number = self.number
sleep_time = self.sleep_time
while(number >= 0):
try:
resp, body = self.vrmhttpclient.request(new_url, method)
task_uri = body.get('taskUri')
self.task_proxy.wait_task(task_uri=task_uri)
break
except driver_exception.ClientException as ex:
LOG.info(_("[VRM-CINDER] delete volumesnapshot (%s)"),
ex.errorCode)
normal_errorcode = ['10300026', '10300057', '10430052',
'10430054', '10430056', '10300421',
'10300318', '10300162', '10300153',
'10300170', '10000009', '10300421',
'10420138']
if ex.errorCode in normal_errorcode:
LOG.error(_(
"[VRM-CINDER] snapshot status conflicts, "
"try delete later."))
raise cinder_exception.SnapshotIsBusy(
snapshot_name=kwargs.get('snapshot_uuid'))
if ex.errorCode not in self.delete_retry:
raise ex
LOG.info(
'[VRM-CINDER] The errorcode is in retry list, number:%d' %
number)
number -= 1
if number < 0:
raise ex
sleep(sleep_time)
def create_volume_from_snapshot(self, **kwargs):
'''create_volume_from_snapshot
'createvolumefromsnapshot': ('POST',
('/volumesnapshots', None, "createvol",
None),
{},
{'snapshotUuid': kwargs.get('uuid'),
'volumeName': kwargs.get('name'),
'volumeType': normal/share
'volumeUuid': uuid
'snapshotVolumeType': 0/1
},
True),
'''
LOG.info(_("[VRM-CINDER] start createvolumefromsnapshot()"))
uri = '/volumesnapshots/createvol'
method = 'POST'
path = self.site_uri + uri
snapshotVolumeType = 0
if str(kwargs.get('full_clone')) == '0':
snapshotVolumeType = 1
body = {
'snapshotUuid': kwargs.get('snapshot_uuid'),
'volumeName': kwargs.get('volume_name'),
'volumeType': kwargs.get('type'),
'volumeUuid': kwargs.get('volume_uuid'),
'snapshotVolumeType': snapshotVolumeType,
}
if kwargs.get('volume_size') is not None:
body.update({'volumeSize': kwargs.get('volume_size')})
new_url = self._generate_url(path)
resp, body = self.vrmhttpclient.request(new_url, method,
body=json.dumps(body))
task_uri = body.get('taskUri')
self.task_proxy.wait_task(task_uri=task_uri)
return body

View File

@ -0,0 +1,441 @@
# Copyright 2016 Huawei Technologies Co.,LTD.
# 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 json
import urlparse
from oslo_config import cfg
from oslo_log import log as logging
from cinder import exception as cinder_exception
from cinder.i18n import _
from cinder.volume.drivers.huawei.vrm.conf import FC_DRIVER_CONF
from cinder.volume.drivers.huawei.vrm import exception as driver_exception
TASK_WAITING = 'waiting'
TASK_RUNNING = 'running'
TASK_SUCCESS = 'success'
TASK_FAILED = 'failed'
TASK_CANCELLING = 'cancelling'
TASK_UNKNOWN = 'unknown'
CONF = cfg.CONF
LOG = logging.getLogger(__name__)
class VRM_COMMANDS(object):
USER_AGENT = 'VRM-HTTP-Client for OpenStack'
RESOURCE_URI = 'uri'
TASK_URI = 'taskUri'
BASIC_URI = '/service'
glanceServer_host = ''
glanceServer_port = ''
version = CONF.vrm_version
site_uri = ''
def __init__(self):
self.site_urn = None
self.site_uri = None
glanceServer_Info = str(CONF.glance_api_servers).split(':')
LOG.info("glance_api_servers is [%s]", CONF.glance_api_servers)
LOG.info("sxmatch glanceServer_Info is %s", glanceServer_Info)
self.glanceServer_host =\
glanceServer_Info[0] + ":" + glanceServer_Info[1]
self.glanceServer_host = self.glanceServer_host.replace("['", '')
LOG.info("sxmatch glanceServer_host is %s", self.glanceServer_host)
self.glanceServer_port = glanceServer_Info[1].replace("']", '')
LOG.info("sxmatch glanceServer_port is %s", self.glanceServer_port)
"""Generate command to be sent to VRM."""
def _joined_params(self, params):
param_str = []
for k, v in params.items():
if (k is None) or (v is None) or len(k) == 0:
continue
if k == 'scope' and v == self.site_urn:
continue
param_str.append("%s=%s" % (k, str(v)))
return '&'.join(param_str)
def _joined_body(self, params):
param_str = []
for k, v in params.items():
if k is None or v is None or \
len(k) == 0:
continue
if type(v) in [int]:
param_str.append('"%s":%s' % (k, str(v)))
elif type(v) in [str, unicode]:
param_str.append('"%s":"%s"' % (k, str(v)))
elif type(v) in [bool]:
param_str.append('"%s":%s' % (k, str(v).lower()))
elif type(v) in [dict]:
param_str1 = json.dumps(v)
param_str.append('"%s":%s' % (k, param_str1))
else:
pass
if len(param_str) > 0:
return '{' + ','.join(param_str) + '}'
else:
return None
def _combine_vmConfig(self, **kwargs):
cpu_quantity = 1
mem_quantityMB = 1024
datastoreUrn = CONF.vrm_sm_datastoreurn
disk_quantityGB = 10
image_size = 10
if image_size > disk_quantityGB:
LOG.error(_("image is larger than sys-vol."))
raise cinder_exception.ImageTooLarge
cpu = {'quantity': cpu_quantity}
memory = {'quantityMB': mem_quantityMB}
disks = [
{
'datastoreUrn': datastoreUrn,
'quantityGB': disk_quantityGB,
'volType': 0,
'sequenceNum': 1,
}
]
properties = {
'isEnableHa': True,
'reoverByHost': False,
'isEnableFt': False
}
vmConfigBody = {
'cpu': cpu,
'memory': memory,
'disks': disks,
'properties': properties,
}
return vmConfigBody
def _combine_os_options(self, **kwargs):
osOptions = {
'osType': 'Windows',
'osVersion': 26
}
return osOptions
def init_site(self, uri, urn):
self.site_uri = uri
self.site_urn = urn
return
def _generate_url(self, path, query=None, frag=None):
LOG.info(_("[BRM-DRIVER] call _generate_url() "))
if CONF.vrm_ssl:
scheme = 'https'
else:
scheme = 'http'
fc_ip = FC_DRIVER_CONF.fc_ip
netloc = str(fc_ip) + ':' + str(CONF.vrm_port)
if path.startswith(self.BASIC_URI):
url = urlparse.urlunsplit((scheme, netloc, path, query, frag))
else:
url = urlparse.urlunsplit(
(scheme, netloc, self.BASIC_URI + str(path), query, frag))
return url
def generate_vrm_cmd(self, cmd, **kwargs):
COMMANDS = {
'v5.1': {
'list_tasks': ('GET',
('/tasks', kwargs.get(self.RESOURCE_URI), None,
None),
{},
{},
False),
'list_hosts': ('GET',
('/hosts', kwargs.get(self.RESOURCE_URI), None,
None),
{'limit': kwargs.get('limit'),
'offset': kwargs.get('offset'),
'scope': kwargs.get('scope')},
{},
False),
'list_datastores': ('GET',
('/datastores',
kwargs.get(self.RESOURCE_URI), None,
None),
{'limit': kwargs.get('limit'),
'offset': kwargs.get('offset'),
'scope': kwargs.get('scope')},
{},
False),
'list_volumes': ('GET',
('/volumes', kwargs.get(self.RESOURCE_URI),
None, kwargs.get('id')),
{'limit': kwargs.get('limit'),
'offset': kwargs.get('offset'),
'scope': kwargs.get('scope')},
{},
False),
'create_volume': ('POST',
('/volumes', None, None, None),
{},
{'name': kwargs.get('name'),
'quantityGB': kwargs.get('quantityGB'),
'datastoreUrn': kwargs.get('datastoreUrn'),
'uuid': kwargs.get('uuid'),
'isThin': kwargs.get('isThin'),
'type': kwargs.get('type'),
'indepDisk': kwargs.get('indepDisk'),
'persistentDisk': kwargs.get(
'persistentDisk'),
'volumeId': kwargs.get('volumeId')},
True),
'delete_volume': ('DELETE',
('/volumes', kwargs.get(self.RESOURCE_URI),
None, None),
{},
{},
True),
'list_volumesnapshot': ('GET',
('/volumesnapshots', None,
kwargs.get('uuid'), None),
{'limit': kwargs.get('limit'),
'offset': kwargs.get('offset'),
'scope': kwargs.get('scope')},
{},
False),
'create_volumesnapshot': ('POST',
('/volumesnapshots', None, None,
None),
{},
{'volumeUrn': kwargs.get('vol_urn'),
'snapshotUuid': kwargs.get('uuid')},
False),
'delete_volumesnapshot': ('DELETE',
('/volumesnapshots', None, None,
kwargs.get('id')),
{},
{
'snapshotUuid': kwargs.get(
'snapshotUuid')
},
True),
'createvolumefromsnapshot': ('POST',
('/volumesnapshots', None,
"createvol", None),
{},
{'snapshotUuid': kwargs.get(
'uuid'),
'volumeName':
kwargs.get('name')},
True),
'clone_volume': ('POST',
('/volumes', None, kwargs.get('src_name'),
'action/copyVol'),
{},
{'destinationVolumeID': kwargs.get(
'dest_name')},
True),
'copy_image_to_volume': ('POST',
('/volumes/imagetovolume', None, None,
None),
{},
{
'volumePara': {
'quantityGB': kwargs.get(
'volume_size'),
'urn': kwargs.get(
'volume_urn')
},
'imagePara': {
'id': kwargs.get('image_id'),
'url': kwargs.get(
'image_location')
},
'location': kwargs.get(
'host_urn'),
'needCreateVolume': False
},
True),
'copy_volume_to_image': ('POST',
('/volumes/volumetoimage', None, None,
None),
{},
{
'volumePara': {'urn': kwargs.get(
'volume_urn'),
'quantityGB': kwargs.get(
'volume_size')},
'imagePara': {
'id': kwargs.get('image_id'),
'url': kwargs.get(
'image_url')}
},
True),
'import_vm_from_image': ('POST',
('/vms/action/import', None, None,
None),
{},
dict({
'name': 'name',
'location': kwargs.get(
'host_urn'),
'autoBoot': 'false',
'url': kwargs.get('url'),
'protocol': 'nfs',
'vmConfig': {
'cpu': {
'quantity': 1
},
'memory': {
'quantityMB': 1024
},
'disks': [
{
'pciType': 'IDE',
'datastoreUrn':
kwargs.get(
'ds_urn'),
'quantityGB':
kwargs.get(
'vol_size'),
'volType': 0,
'sequenceNum': 1},
]
},
'osOptions': {
'osType': 'Windows',
'osVersion': 32
}
}),
True),
'detach_vol_from_vm': ('POST',
('/vms', None, kwargs.get('vm_id'),
'action/detachvol'),
{},
{'volUrn': kwargs.get('volUrn')},
True),
'stop_vm': ('POST',
('/vms', None, kwargs.get('vm_id'), 'action/stop'),
{},
{'mode': kwargs.get('mode')},
True),
'delete_vm': ('DELETE',
('/vms', None, kwargs.get('vm_id'), None),
{},
{},
True),
'query_vm': ('GET',
('/vms', None, kwargs.get('vm_id'), None),
{},
{},
False),
'list_templates': ('GET',
('/vms', None, None, None),
{'limit': kwargs.get('limit'),
'offset': kwargs.get('offset'),
'scope': kwargs.get('scope'),
'isTemplate': 'true'},
{},
False),
'clone_vm': ('POST',
('/vms', None, kwargs.get('template_id'),
'action/clone'),
{},
dict({
"name": "cinder-plugin-temp-vm",
"description": "cinder-plugin-temp-vm",
"isLinkClone": kwargs.get('linked_clone'),
'location': kwargs.get('host_urn'),
'autoBoot': 'false',
'vmConfig':
{
'cpu': {
'quantity': 2
},
'memory':
{
'quantityMB': 1024
},
'disks':
[{
'pciType': 'IDE',
'datastoreUrn': kwargs.get('ds_urn'),
'quantityGB': kwargs.get(
'volume_size'),
'volType': 0,
'sequenceNum': 1,
'isThin': kwargs.get('is_thin')
}]
},
}),
True),
},
'v2.0': {}
}
path = query = body = None
LOG.info("[BRM-DRIVER] version is [%s]", self.version)
if self.version not in COMMANDS.keys():
raise driver_exception.UnsupportedVersion()
else:
commands = COMMANDS[self.version]
if cmd not in commands.keys():
raise driver_exception.UnsupportedCommand()
else:
(method, pathparams, queryparams, bodyparams, hastask) = commands[
cmd]
resource, resource_uri, tag1, tag2 = pathparams
if resource_uri:
path = resource_uri
LOG.info(_("[VRM-CINDER] [%s]"), path)
else:
path = self.site_uri + resource
LOG.info(_("[VRM-CINDER] [%s]"), path)
if tag1:
path += ('/' + str(tag1))
LOG.info(_("[VRM-CINDER] [%s]"), path)
if tag2:
path += ('/' + str(tag2))
LOG.info(_("[VRM-CINDER] [%s]"), path)
if method == 'GET':
query = self._joined_params(queryparams)
elif method == 'DELETE':
query = self._joined_params(queryparams)
elif method == 'POST':
query = self._joined_params(queryparams)
LOG.info("[BRM-DRIVER] _generate_vrm_cmd bodyparams is [%s]",
bodyparams)
body = json.dumps(bodyparams)
LOG.info("[BRM-DRIVER] _generate_vrm_cmd body is [%s]", body)
else:
raise cinder_exception.UnknownCmd(cmd=method)
url = self._generate_url(path, query)
LOG.info("[BRM-DRIVER] _generate_vrm_cmd url is [%s]", url)
return (method, url, body, hastask)

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,200 @@
# Copyright 2016 Huawei Technologies Co.,LTD.
# 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 oslo_config import cfg
from oslo_log import log as logging
from cinder import context as cinder_context
from cinder.i18n import _
from cinder.volume.drivers.huawei.vrm.vrm_driver import VRMDriver
def metadata_to_dict(metadata):
result = {}
for item in metadata:
if not item.get('deleted'):
result[item['key']] = item['value']
return result
LOG = logging.getLogger(__name__)
CONF = cfg.CONF
class VRMDriverHuawei(VRMDriver):
VENDOR = 'Huawei'
BACKEND = 'VRM'
VERSION = 'v1.1'
def __init__(self, *args, **kwargs):
'''__init__
:param args:
:param kwargs:
:return:
'''
super(VRMDriverHuawei, self).__init__(*args, **kwargs)
def create_volume(self, volume):
'''create_volume
create_volume
{
"name":string,
quantityGB:integer,
datastoreUrn:string,
"isThin":boolean,
"type":string,
indepDisk:boolean,
persistentDisk:boolean
}
:param volume:
:return:
'''
LOG.info(_("[CINDER-VRM] start create_volume() "))
vol_meta = volume.get('volume_metadata')
vol_meta_dict = metadata_to_dict(vol_meta)
context = cinder_context.get_admin_context()
temp_str = vol_meta_dict.get('urn')
fc_vol_id = temp_str[temp_str.rfind(':') + 1:]
name = volume.get('name')
model_update, metadata = self._vrm_get_volume_meta(id=fc_vol_id)
self.db.volume_metadata_update(context, volume['id'], metadata, False)
try:
self.volume_proxy.update_custom_properties(volume_urn=temp_str,
external_uuid=volume[
'id'])
# modify volume name
self.volume_proxy.modify_volume(volume_id=fc_vol_id, name=name)
except Exception as ex:
LOG.error(
_("[CINDER-VRM] modify volume information failed after create "
"volume.volume id is [%s] ") % fc_vol_id)
LOG.exception(ex)
return model_update
def delete_volume(self, volume):
'''delete_volume
:param volume:
:return:
'''
LOG.info(_("[CINDER-VRM] start delete_volume() "))
vol_meta = volume.get('volume_metadata')
vol_meta_dict = metadata_to_dict(vol_meta)
fc_volume_name = vol_meta_dict.get('fc_volume_name')
temp_str = vol_meta_dict.get('urn')
fc_vol_id = temp_str[temp_str.rfind(':') + 1:]
try:
self.volume_proxy.update_custom_properties(volume_urn=temp_str,
external_uuid="")
# modify volume name
self.volume_proxy.modify_volume(volume_id=fc_vol_id,
name=fc_volume_name)
except Exception as ex:
LOG.error(
_("[CINDER-VRM] modify volume information failed after create"
" volume.volume id is [%s] ") % fc_vol_id)
LOG.exception(ex)
return
def _try_get_volume_stats(self, refresh=False):
'''_try_get_volume_stats
:param refresh:If 'refresh' is True, run the update first.
:return:Return the current state of the volume service.
'''
# LOG.info(_("[BRM-DRIVER] start _try_get_volume_stats() "))
if refresh:
self.left_periodrate -= 1
if self.left_periodrate <= 0:
self._refresh_storage_info(refresh)
stats = self._build_volume_stats()
ds_meta = {}
ds_names = [ds['name'] for ds in self.SHARED_DATASTORES]
for pool in self.pool_list:
if pool not in ds_names:
continue
new_pool = {}
ds_meta['ds_name'] = pool
datastore = self._choose_datastore(ds_meta)
if datastore.get('storageType') == 'advanceSan' and datastore.get(
'version') is not None:
new_pool.update(dict(consistencygroup_support=True))
if 'NORMAL' != datastore['status']:
new_pool.update(dict(
pool_name=pool,
free_capacity_gb=0,
reserved_percentage=self.reserved_percentage,
total_capacity_gb=0,
provisioned_capacity_gb=0,
max_over_subscription_ratio=self.over_ratio,
affine_rate=1
))
stats["pools"].append(new_pool)
continue
if self.current_list is not None and pool in self.current_list:
new_pool.update(dict(
pool_name=pool,
free_capacity_gb="infinite",
reserved_percentage=self.reserved_percentage,
total_capacity_gb="infinite",
provisioned_capacity_gb=datastore['usedSizeGB'],
max_over_subscription_ratio=self.over_ratio,
affine_rate=self.affine_rate
))
else:
new_pool.update(dict(
pool_name=pool,
free_capacity_gb="infinite",
reserved_percentage=self.reserved_percentage,
total_capacity_gb="infinite",
provisioned_capacity_gb=datastore['usedSizeGB'],
max_over_subscription_ratio=self.over_ratio,
affine_rate=1
))
if self.thin_provision is True:
new_pool.update(dict(
thin_provisioning_support=True,
thick_provisioning_support=False
))
else:
new_pool.update(dict(
thin_provisioning_support=False,
thick_provisioning_support=True
))
tier_size = datastore.get('tierSize', None)
type_v3 = []
if tier_size and len(tier_size) >= 3:
if tier_size[0] > 0:
type_v3.append('ssd')
if tier_size[1] > 0:
type_v3.append('sas')
if tier_size[2] > 0:
type_v3.append('nl_sas')
if len(type_v3) > 0:
type_v3_str = ';'.join(type_v3)
LOG.info(_("[CINDER-BRM] type of v3 is %s"), type_v3_str)
new_pool.update(dict(type=type_v3_str))
stats["pools"].append(new_pool)
# LOG.info(_("[CINDER-BRM] (%d)--%s"), self.left_periodrate, stats)
return stats

75
doc/source/conf.py Normal 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'cinder-fusioncompute'
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}

View File

@ -0,0 +1,4 @@
============
Contributing
============
.. include:: ../../CONTRIBUTING.rst

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

@ -0,0 +1,25 @@
.. cinder-fusioncompute documentation master file, created by
sphinx-quickstart on Tue Jul 9 22:26:36 2013.
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.
Welcome to cinder-fusioncompute's documentation!
========================================================
Contents:
.. toctree::
:maxdepth: 2
readme
installation
usage
contributing
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`

View File

@ -0,0 +1,12 @@
============
Installation
============
At the command line::
$ pip install cinder-fusioncompute
Or, if you have virtualenvwrapper installed::
$ mkvirtualenv cinder-fusioncompute
$ pip install cinder-fusioncompute

1
doc/source/readme.rst Normal file
View File

@ -0,0 +1 @@
.. include:: ../../README.rst

7
doc/source/usage.rst Normal file
View File

@ -0,0 +1,7 @@
========
Usage
========
To use cinder-fusioncompute in a project::
import cinder-fusioncompute

View File

View File

275
releasenotes/source/conf.py Normal file
View File

@ -0,0 +1,275 @@
# -*- 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.
# Glance Release Notes documentation build configuration file, created by
# sphinx-quickstart on Tue Nov 3 17:40:50 2015.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
# sys.path.insert(0, os.path.abspath('.'))
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
# needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'oslosphinx',
'reno.sphinxext',
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
# source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'cinder-fusioncompute Release Notes'
copyright = u'2016, OpenStack Foundation'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
# The full version, including alpha/beta/rc tags.
release = ''
# The short X.Y version.
version = ''
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
# language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
# today = ''
# Else, today_fmt is used as the format for a strftime call.
# today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = []
# The reST default role (used for this markup: `text`) to use for all
# documents.
# default_role = None
# 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
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
# show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
# modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
# keep_warnings = False
# -- 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 = 'default'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
# html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
# html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
# html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
# html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
# html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
# html_favicon = None
# 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']
# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
# html_extra_path = []
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
# html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
# html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
# html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
# html_additional_pages = {}
# If false, no module index is generated.
# html_domain_indices = True
# If false, no index is generated.
# html_use_index = True
# If true, the index is split into individual pages for each letter.
# html_split_index = False
# If true, links to the reST sources are added to the pages.
# html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
# html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
# html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
# html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
# html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'GlanceReleaseNotesdoc'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
# 'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
('index', 'GlanceReleaseNotes.tex', u'Glance Release Notes Documentation',
u'Glance Developers', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
# latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
# latex_use_parts = False
# If true, show page references after internal links.
# latex_show_pagerefs = False
# If true, show URL addresses after external links.
# latex_show_urls = False
# Documents to append as an appendix to all manuals.
# latex_appendices = []
# If false, no module index is generated.
# latex_domain_indices = True
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'glancereleasenotes', u'Glance Release Notes Documentation',
[u'Glance Developers'], 1)
]
# If true, show URL addresses after external links.
# man_show_urls = False
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'GlanceReleaseNotes', u'Glance Release Notes Documentation',
u'Glance Developers', 'GlanceReleaseNotes',
'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
# texinfo_appendices = []
# If false, no module index is generated.
# texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
# texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
# texinfo_no_detailmenu = False
# -- Options for Internationalization output ------------------------------
locale_dirs = ['locale/']

View File

@ -0,0 +1,8 @@
============================================
cinder-fusioncompute Release Notes
============================================
.. toctree::
:maxdepth: 1
unreleased

View File

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

18
requirements.txt Normal file
View File

@ -0,0 +1,18 @@
# 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.8 # Apache-2.0
oslo.config!=3.18.0,>=3.14.0 # Apache-2.0
oslo.cache>=1.5.0 # Apache-2.0
oslo.concurrency>=3.8.0 # Apache-2.0
oslo.context>=2.9.0 # Apache-2.0
oslo.log>=3.11.0 # Apache-2.0
oslo.reports>=0.6.0 # Apache-2.0
oslo.serialization>=1.10.0 # Apache-2.0
oslo.db!=4.13.1,!=4.13.2,>=4.11.0 # Apache-2.0
oslo.rootwrap>=5.0.0 # Apache-2.0
oslo.messaging>=5.2.0 # Apache-2.0
oslo.privsep>=1.9.0 # Apache-2.0
oslo.i18n>=2.1.0 # Apache-2.0
oslo.service>=1.10.0 # Apache-2.0

51
setup.cfg Normal file
View File

@ -0,0 +1,51 @@
[metadata]
name = cinder-fusioncompute
summary = Implementation of Cinder driver for Huawei Fusioncompute.
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 :: 3
Programming Language :: Python :: 3.3
Programming Language :: Python :: 3.4
[files]
packages =
cinder-fusioncompute
[build_sphinx]
source-dir = doc/source
build-dir = doc/build
all_files = 1
[upload_sphinx]
upload-dir = doc/build/html
[compile_catalog]
directory = cinder-fusioncompute/locale
domain = cinder-fusioncompute
[update_catalog]
domain = cinder-fusioncompute
output_dir = cinder-fusioncompute/locale
input_file = cinder-fusioncompute/locale/cinder-fusioncompute.pot
[extract_messages]
keywords = _ gettext ngettext l_ lazy_gettext
mapping_file = babel.cfg
output_file = cinder-fusioncompute/locale/cinder-fusioncompute.pot
[build_releasenotes]
all_files = 1
build-dir = releasenotes/build
source-dir = releasenotes/source

29
setup.py Normal file
View File

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

17
test-requirements.txt Normal file
View File

@ -0,0 +1,17 @@
# 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.13,>=0.12.0 # Apache-2.0
coverage>=4.0 # Apache-2.0
python-subunit>=0.0.18 # Apache-2.0/BSD
sphinx>=1.2.1,!=1.3b1,<1.4 # BSD
oslosphinx>=4.7.0 # Apache-2.0
oslotest>=1.10.0 # Apache-2.0
testrepository>=0.0.18 # Apache-2.0/BSD
testscenarios>=0.4 # Apache-2.0/BSD
testtools>=1.4.0 # MIT
# releasenotes
reno>=1.8.0 # Apache-2.0

40
tox.ini Normal file
View File

@ -0,0 +1,40 @@
[tox]
minversion = 2.0
envlist = py34,py27,pypy,pep8
skipsdist = True
[testenv]
usedevelop = True
install_command = pip install -c{env:UPPER_CONSTRAINTS_FILE:https://git.openstack.org/cgit/openstack/requirements/plain/upper-constraints.txt} {opts} {packages}
setenv =
VIRTUAL_ENV={envdir}
PYTHONWARNINGS=default::DeprecationWarning
deps = -r{toxinidir}/test-requirements.txt
commands = python setup.py test --slowest --testr-args='{posargs}'
[testenv:pep8]
commands = flake8 {posargs}
[testenv:venv]
commands = {posargs}
[testenv:cover]
commands = python setup.py test --coverage --testr-args='{posargs}'
[testenv:docs]
commands = python setup.py build_sphinx
[testenv:releasenotes]
commands =
sphinx-build -a -E -W -d releasenotes/build/doctrees -b html releasenotes/source releasenotes/build/html
[testenv:debug]
commands = oslo_debug_helper {posargs}
[flake8]
# E123, E125 skipped as they are invalid PEP-8.
show-source = True
ignore = E123,E125,N342,H104,W391
builtins = _
exclude=.venv,.git,.tox,dist,doc,*lib/python*,*egg,build