Remove usage of six lib for third party/vendors drivers.

Python2 is no longer supported, so in this patch
set we remove the usage of the six (py2 and py3
compatibility library) in favor of py3 syntax.

Change-Id: I3ddfad568a1b578bee23a6d1a96de9551e336bb4
This commit is contained in:
haixin 2021-12-09 16:22:15 +08:00
parent 5b6197821b
commit a73b299374
72 changed files with 332 additions and 398 deletions

View File

@ -70,8 +70,6 @@ both should be in the same dir.
- python-zaqarclient - python-zaqarclient
- six
- System libs that install 'mount' and 'mount.nfs' apps. - System libs that install 'mount' and 'mount.nfs' apps.
3. Create file with following options: 3. Create file with following options:

View File

@ -25,7 +25,6 @@ import netaddr
from oslo_concurrency import processutils from oslo_concurrency import processutils
from oslo_config import cfg from oslo_config import cfg
from oslo_utils import timeutils from oslo_utils import timeutils
import six
opts = [ opts = [
cfg.IntOpt( cfg.IntOpt(
@ -52,8 +51,8 @@ CONF = cfg.CONF
def print_with_time(data): def print_with_time(data):
time = six.text_type(timeutils.utcnow()) time = str(timeutils.utcnow())
print(time + " " + six.text_type(data)) print(time + " " + str(data))
def print_pretty_dict(d): def print_pretty_dict(d):
@ -69,7 +68,7 @@ def pop_zaqar_messages(client, queues_names):
messages = [] messages = []
for queue_name in queues_names: for queue_name in queues_names:
queue = client.queue(queue_name) queue = client.queue(queue_name)
messages.extend([six.text_type(m.body) for m in queue.pop()]) messages.extend([str(m.body) for m in queue.pop()])
print_with_time( print_with_time(
"Received %(len)s message[s] from '%(q)s' " "Received %(len)s message[s] from '%(q)s' "
"queue using '%(u)s' user and '%(p)s' project." % { "queue using '%(u)s' user and '%(p)s' project." % {
@ -92,7 +91,7 @@ def signal_handler(signal, frame):
def parse_str_to_dict(string): def parse_str_to_dict(string):
if not isinstance(string, six.string_types): if not isinstance(string, str):
return string return string
result = eval(string) result = eval(string)
return result return result

View File

@ -13,15 +13,14 @@
# License for the specific language governing permissions and limitations # License for the specific language governing permissions and limitations
# under the License. # under the License.
from http import cookiejar as http_cookiejar
import pipes import pipes
from urllib import error as url_error
from urllib import request as url_request
from oslo_concurrency import processutils from oslo_concurrency import processutils
from oslo_log import log from oslo_log import log
from oslo_utils import excutils from oslo_utils import excutils
import six
from six.moves import http_cookiejar
from six.moves.urllib import error as url_error
from six.moves.urllib import request as url_request
from manila import exception from manila import exception
from manila.i18n import _ from manila.i18n import _
@ -84,7 +83,7 @@ class XMLAPIConnector(object):
if not self.debug: if not self.debug:
return return
headers = six.text_type(resp.headers).replace('\n', '\\n') headers = str(resp.headers).replace('\n', '\\n')
LOG.debug( LOG.debug(
'RESP: [%(code)s] %(resp_hdrs)s\n' 'RESP: [%(code)s] %(resp_hdrs)s\n'
@ -107,12 +106,12 @@ class XMLAPIConnector(object):
resp_body = resp.read() resp_body = resp.read()
self._http_log_resp(resp, resp_body) self._http_log_resp(resp, resp_body)
except url_error.HTTPError as http_err: except url_error.HTTPError as http_err:
if '403' == six.text_type(http_err.code): if '403' == str(http_err.code):
raise exception.NotAuthorized() raise exception.NotAuthorized()
else: else:
err = {'errorCode': -1, err = {'errorCode': -1,
'httpStatusCode': http_err.code, 'httpStatusCode': http_err.code,
'messages': six.text_type(http_err), 'messages': str(http_err),
'request': req_body} 'request': req_body}
msg = (_("The request is invalid. Reason: %(reason)s") % msg = (_("The request is invalid. Reason: %(reason)s") %
{'reason': err}) {'reason': err})

View File

@ -13,10 +13,10 @@
# License for the specific language governing permissions and limitations # License for the specific language governing permissions and limitations
# under the License. # under the License.
import io
import re import re
from lxml import etree from lxml import etree
import six
class XMLAPIParser(object): class XMLAPIParser(object):
@ -56,7 +56,7 @@ class XMLAPIParser(object):
events = ("start", "end") events = ("start", "end")
context = etree.iterparse(six.BytesIO(xml), context = etree.iterparse(io.BytesIO(xml),
events=events) events=events)
for action, elem in context: for action, elem in context:
self.tag = self._remove_ns(elem.tag) self.tag = self._remove_ns(elem.tag)

View File

@ -16,11 +16,8 @@
import abc import abc
import six
class StorageConnection(metaclass=abc.ABCMeta):
@six.add_metaclass(abc.ABCMeta)
class StorageConnection(object):
"""Subclasses should implement storage backend specific functionality.""" """Subclasses should implement storage backend specific functionality."""
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):

View File

@ -21,7 +21,6 @@ from oslo_config import cfg
from oslo_log import log from oslo_log import log
from oslo_utils import units from oslo_utils import units
from requests.exceptions import HTTPError from requests.exceptions import HTTPError
import six
from manila.common import constants as const from manila.common import constants as const
from manila import exception from manila import exception
@ -315,7 +314,7 @@ class IsilonStorageConnection(base.StorageConnection):
allowed_ips.remove(denied_ip) allowed_ips.remove(denied_ip)
data = {share_access_group: list(allowed_ips)} data = {share_access_group: list(allowed_ips)}
url = ('{0}/platform/1/protocols/nfs/exports/{1}' url = ('{0}/platform/1/protocols/nfs/exports/{1}'
.format(self._server_url, six.text_type(export_id))) .format(self._server_url, str(export_id)))
r = self._isilon_api.request('PUT', url, data=data) r = self._isilon_api.request('PUT', url, data=data)
r.raise_for_status() r.raise_for_status()
@ -371,7 +370,7 @@ class IsilonStorageConnection(base.StorageConnection):
int(emc_share_driver.configuration.safe_get("emc_nas_server_port")) int(emc_share_driver.configuration.safe_get("emc_nas_server_port"))
) )
self._server_url = ('https://' + self._server + ':' + self._server_url = ('https://' + self._server + ':' +
six.text_type(self._port)) str(self._port))
self._username = emc_share_driver.configuration.safe_get( self._username = emc_share_driver.configuration.safe_get(
"emc_nas_login") "emc_nas_login")
self._password = emc_share_driver.configuration.safe_get( self._password = emc_share_driver.configuration.safe_get(
@ -440,7 +439,7 @@ class IsilonStorageConnection(base.StorageConnection):
'read_only_clients': list(nfs_ro_ips) 'read_only_clients': list(nfs_ro_ips)
} }
url = ('{0}/platform/1/protocols/nfs/exports/{1}' url = ('{0}/platform/1/protocols/nfs/exports/{1}'
.format(self._server_url, six.text_type(export_id))) .format(self._server_url, str(export_id)))
r = self._isilon_api.request('PUT', url, data=data) r = self._isilon_api.request('PUT', url, data=data)
try: try:
r.raise_for_status() r.raise_for_status()

View File

@ -16,7 +16,6 @@
from enum import Enum from enum import Enum
from oslo_serialization import jsonutils from oslo_serialization import jsonutils
import requests import requests
import six
from manila import exception from manila import exception
from manila.i18n import _ from manila.i18n import _
@ -35,7 +34,7 @@ class IsilonApi(object):
headers = {"x-isi-ifs-target-type": "container"} headers = {"x-isi-ifs-target-type": "container"}
url = (self.host_url + "/namespace" + container_path + '?recursive=' url = (self.host_url + "/namespace" + container_path + '?recursive='
+ six.text_type(recursive)) + str(recursive))
r = self.request('PUT', url, r = self.request('PUT', url,
headers=headers) headers=headers)
return r.status_code == 200 return r.status_code == 200
@ -130,7 +129,7 @@ class IsilonApi(object):
response = self.request('GET', response = self.request('GET',
self.host_url + self.host_url +
'/platform/1/protocols/nfs/exports/' + '/platform/1/protocols/nfs/exports/' +
six.text_type(export_id)) str(export_id))
if response.status_code == 200: if response.status_code == 200:
return response.json()['exports'][0] return response.json()['exports'][0]
else: else:
@ -189,13 +188,13 @@ class IsilonApi(object):
r = self.request('DELETE', r = self.request('DELETE',
self.host_url + '/namespace' + fq_resource_path + self.host_url + '/namespace' + fq_resource_path +
'?recursive=' + six.text_type(recursive)) '?recursive=' + str(recursive))
r.raise_for_status() r.raise_for_status()
def delete_nfs_share(self, share_number): def delete_nfs_share(self, share_number):
response = self.session.delete( response = self.session.delete(
self.host_url + '/platform/1/protocols/nfs/exports' + '/' + self.host_url + '/platform/1/protocols/nfs/exports' + '/' +
six.text_type(share_number)) str(share_number))
return response.status_code == 204 return response.status_code == 204
def delete_smb_share(self, share_name): def delete_smb_share(self, share_name):

View File

@ -16,7 +16,6 @@
import copy import copy
import random import random
import six
from oslo_config import cfg from oslo_config import cfg
from oslo_log import log from oslo_log import log
@ -736,7 +735,7 @@ class PowerMaxStorageConnection(driver.StorageConnection):
} }
if ip_version == 6: if ip_version == 6:
interface['ip_version'] = ip_version interface['ip_version'] = ip_version
interface['net_mask'] = six.text_type( interface['net_mask'] = str(
utils.cidr_to_prefixlen( utils.cidr_to_prefixlen(
network_info['cidr'])) network_info['cidr']))
else: else:

View File

@ -20,7 +20,6 @@ from lxml import builder
from lxml import etree as ET from lxml import etree as ET
from oslo_concurrency import processutils from oslo_concurrency import processutils
from oslo_log import log from oslo_log import log
import six
from manila.common import constants as const from manila.common import constants as const
from manila import exception from manila import exception
@ -236,7 +235,7 @@ class FileSystem(StorageObject):
mover, mover,
self.elt_maker.StoragePool( self.elt_maker.StoragePool(
pool=pool_id, pool=pool_id,
size=six.text_type(size), size=str(size),
mayContainSlices='true' mayContainSlices='true'
), ),
name=name name=name
@ -360,7 +359,7 @@ class FileSystem(StorageObject):
self.elt_maker.ExtendFileSystem( self.elt_maker.ExtendFileSystem(
self.elt_maker.StoragePool( self.elt_maker.StoragePool(
pool=pool_id, pool=pool_id,
size=six.text_type(new_size - size) size=str(new_size - size)
), ),
fileSystem=enas_id, fileSystem=enas_id,
) )
@ -1036,7 +1035,7 @@ class Snapshot(StorageObject):
if ckpt_size: if ckpt_size:
elt_pool = self.elt_maker.StoragePool( elt_pool = self.elt_maker.StoragePool(
pool=pool_id, pool=pool_id,
size=six.text_type(ckpt_size) size=str(ckpt_size)
) )
else: else:
elt_pool = self.elt_maker.StoragePool(pool=pool_id) elt_pool = self.elt_maker.StoragePool(pool=pool_id)
@ -1161,11 +1160,11 @@ class MoverInterface(StorageObject):
mover_id = self._get_mover_id(mover_name, False) mover_id = self._get_mover_id(mover_name, False)
params = dict(device=device_name, params = dict(device=device_name,
ipAddress=six.text_type(ip_addr), ipAddress=str(ip_addr),
mover=mover_id, mover=mover_id,
name=name, name=name,
netMask=net_mask, netMask=net_mask,
vlanid=six.text_type(vlan_id)) vlanid=str(vlan_id))
if interface.get('ip_version') == 6: if interface.get('ip_version') == 6:
params['ipVersion'] = 'IPv6' params['ipVersion'] = 'IPv6'
@ -1197,7 +1196,7 @@ class MoverInterface(StorageObject):
# vlan id, PowerMax will leave an interface with vlan id 0 in the # vlan id, PowerMax will leave an interface with vlan id 0 in the
# backend. So we should explicitly remove the interface. # backend. So we should explicitly remove the interface.
try: try:
self.delete(six.text_type(ip_addr), mover_name) self.delete(str(ip_addr), mover_name)
except exception.EMCPowerMaxXMLAPIError: except exception.EMCPowerMaxXMLAPIError:
pass pass
message = (_("Invalid vlan id %s. Other interfaces on this " message = (_("Invalid vlan id %s. Other interfaces on this "
@ -1235,7 +1234,7 @@ class MoverInterface(StorageObject):
request = self._build_task_package( request = self._build_task_package(
self.elt_maker.DeleteMoverInterface( self.elt_maker.DeleteMoverInterface(
ipAddress=six.text_type(ip_addr), ipAddress=str(ip_addr),
mover=mover_id mover=mover_id
) )
) )

View File

@ -12,7 +12,6 @@
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations # License for the specific language governing permissions and limitations
# under the License. # under the License.
import six
from oslo_log import log from oslo_log import log
from oslo_utils import excutils from oslo_utils import excutils
@ -206,7 +205,7 @@ class UnityClient(object):
'exists.', {'snap': name, 'fs': filesystem.name}) 'exists.', {'snap': name, 'fs': filesystem.name})
def create_snap_of_snap(self, src_snap, dst_snap_name): def create_snap_of_snap(self, src_snap, dst_snap_name):
if isinstance(src_snap, six.string_types): if isinstance(src_snap, str):
snap = self.get_snapshot(name=src_snap) snap = self.get_snapshot(name=src_snap)
else: else:
snap = src_snap snap = src_snap

View File

@ -16,7 +16,6 @@
import copy import copy
import random import random
import six
from oslo_config import cfg from oslo_config import cfg
from oslo_log import log from oslo_log import log
@ -725,7 +724,7 @@ class VNXStorageConnection(driver.StorageConnection):
if ip_version == 6: if ip_version == 6:
interface['ip_version'] = ip_version interface['ip_version'] = ip_version
interface['net_mask'] = six.text_type( interface['net_mask'] = str(
utils.cidr_to_prefixlen(network_info['cidr'])) utils.cidr_to_prefixlen(network_info['cidr']))
else: else:
interface['net_mask'] = utils.cidr_to_netmask( interface['net_mask'] = utils.cidr_to_netmask(

View File

@ -20,7 +20,6 @@ from lxml import builder
from lxml import etree as ET from lxml import etree as ET
from oslo_concurrency import processutils from oslo_concurrency import processutils
from oslo_log import log from oslo_log import log
import six
from manila.common import constants as const from manila.common import constants as const
from manila import exception from manila import exception
@ -236,7 +235,7 @@ class FileSystem(StorageObject):
mover, mover,
self.elt_maker.StoragePool( self.elt_maker.StoragePool(
pool=pool_id, pool=pool_id,
size=six.text_type(size), size=str(size),
mayContainSlices='true' mayContainSlices='true'
), ),
name=name name=name
@ -360,7 +359,7 @@ class FileSystem(StorageObject):
self.elt_maker.ExtendFileSystem( self.elt_maker.ExtendFileSystem(
self.elt_maker.StoragePool( self.elt_maker.StoragePool(
pool=pool_id, pool=pool_id,
size=six.text_type(new_size - size) size=str(new_size - size)
), ),
fileSystem=id, fileSystem=id,
) )
@ -1035,7 +1034,7 @@ class Snapshot(StorageObject):
if ckpt_size: if ckpt_size:
elt_pool = self.elt_maker.StoragePool( elt_pool = self.elt_maker.StoragePool(
pool=pool_id, pool=pool_id,
size=six.text_type(ckpt_size) size=str(ckpt_size)
) )
else: else:
elt_pool = self.elt_maker.StoragePool(pool=pool_id) elt_pool = self.elt_maker.StoragePool(pool=pool_id)
@ -1160,11 +1159,11 @@ class MoverInterface(StorageObject):
mover_id = self._get_mover_id(mover_name, False) mover_id = self._get_mover_id(mover_name, False)
params = dict(device=device_name, params = dict(device=device_name,
ipAddress=six.text_type(ip_addr), ipAddress=str(ip_addr),
mover=mover_id, mover=mover_id,
name=name, name=name,
netMask=net_mask, netMask=net_mask,
vlanid=six.text_type(vlan_id)) vlanid=str(vlan_id))
if interface.get('ip_version') == 6: if interface.get('ip_version') == 6:
params['ipVersion'] = 'IPv6' params['ipVersion'] = 'IPv6'
@ -1199,7 +1198,7 @@ class MoverInterface(StorageObject):
# vlan id, VNX will leave an interface with vlan id 0 in the # vlan id, VNX will leave an interface with vlan id 0 in the
# backend. So we should explicitly remove the interface. # backend. So we should explicitly remove the interface.
try: try:
self.delete(six.text_type(ip_addr), mover_name) self.delete(str(ip_addr), mover_name)
except exception.EMCVnxXMLAPIError: except exception.EMCVnxXMLAPIError:
pass pass
message = (_("Invalid vlan id %s. Other interfaces on this " message = (_("Invalid vlan id %s. Other interfaces on this "
@ -1237,7 +1236,7 @@ class MoverInterface(StorageObject):
request = self._build_task_package( request = self._build_task_package(
self.elt_maker.DeleteMoverInterface( self.elt_maker.DeleteMoverInterface(
ipAddress=six.text_type(ip_addr), ipAddress=str(ip_addr),
mover=mover_id mover=mover_id
) )
) )

View File

@ -31,7 +31,7 @@ CONF = cfg.CONF
LOG = log.getLogger(__name__) LOG = log.getLogger(__name__)
class NASHelperBase(object, metaclass=abc.ABCMeta): class NASHelperBase(metaclass=abc.ABCMeta):
"""Interface to work with share.""" """Interface to work with share."""
# drivers that use a helper derived from this class # drivers that use a helper derived from this class

View File

@ -21,7 +21,6 @@ import xml.etree.cElementTree as etree
from oslo_config import cfg from oslo_config import cfg
from oslo_log import log from oslo_log import log
import six
from manila import exception from manila import exception
from manila.i18n import _ from manila.i18n import _
@ -361,7 +360,7 @@ class GlusterManager(object):
"%(server)s, minimum requirement: %(minvers)s") % { "%(server)s, minimum requirement: %(minvers)s") % {
'server': self.host, 'server': self.host,
'version': '.'.join(vers), 'version': '.'.join(vers),
'minvers': '.'.join(six.text_type(c) for c in minvers)}) 'minvers': '.'.join(str(c) for c in minvers)})
def numreduct(vers): def numreduct(vers):

View File

@ -24,7 +24,6 @@ import errno
from oslo_config import cfg from oslo_config import cfg
from oslo_utils import importutils from oslo_utils import importutils
import six
from manila import exception from manila import exception
from manila.i18n import _ from manila.i18n import _
@ -202,8 +201,7 @@ class GlusterfsShareDriverBase(driver.ShareDriver):
super(GlusterfsShareDriverBase, self)._update_share_stats(data) super(GlusterfsShareDriverBase, self)._update_share_stats(data)
@six.add_metaclass(abc.ABCMeta) class GlusterfsShareLayoutBase(metaclass=abc.ABCMeta):
class GlusterfsShareLayoutBase(object):
"""Base class for share layouts.""" """Base class for share layouts."""
def __init__(self, driver, *args, **kwargs): def __init__(self, driver, *args, **kwargs):

View File

@ -20,7 +20,6 @@ import os
from oslo_config import cfg from oslo_config import cfg
from oslo_log import log from oslo_log import log
import six
import xml.etree.cElementTree as etree import xml.etree.cElementTree as etree
from manila import exception from manila import exception
@ -218,7 +217,7 @@ class GlusterfsDirectoryMappedLayout(layout.GlusterfsShareLayoutBase):
self._set_directory_quota(share, new_size) self._set_directory_quota(share, new_size)
def _set_directory_quota(self, share, new_size): def _set_directory_quota(self, share, new_size):
sizestr = six.text_type(new_size) + 'GB' sizestr = str(new_size) + 'GB'
share_dir = '/' + share['name'] share_dir = '/' + share['name']
args = ('volume', 'quota', self.gluster_manager.volume, args = ('volume', 'quota', self.gluster_manager.volume,

View File

@ -25,7 +25,6 @@ import xml.etree.cElementTree as etree
from oslo_config import cfg from oslo_config import cfg
from oslo_log import log from oslo_log import log
import six
from manila import exception from manila import exception
from manila.i18n import _ from manila.i18n import _
@ -125,7 +124,7 @@ class GlusterfsVolumeMappedLayout(layout.GlusterfsShareLayoutBase):
glusterfs_versions[srvaddr] = self._glustermanager( glusterfs_versions[srvaddr] = self._glustermanager(
srvaddr, False).get_gluster_version() srvaddr, False).get_gluster_version()
except exception.GlusterfsException as exc: except exception.GlusterfsException as exc:
exceptions[srvaddr] = six.text_type(exc) exceptions[srvaddr] = str(exc)
if exceptions: if exceptions:
for srvaddr, excmsg in exceptions.items(): for srvaddr, excmsg in exceptions.items():
LOG.error("'gluster version' failed on server " LOG.error("'gluster version' failed on server "
@ -140,7 +139,7 @@ class GlusterfsVolumeMappedLayout(layout.GlusterfsShareLayoutBase):
notsupp_servers.append(srvaddr) notsupp_servers.append(srvaddr)
if notsupp_servers: if notsupp_servers:
gluster_version_min_str = '.'.join( gluster_version_min_str = '.'.join(
six.text_type(c) for c in self.driver.GLUSTERFS_VERSION_MIN) str(c) for c in self.driver.GLUSTERFS_VERSION_MIN)
for srvaddr in notsupp_servers: for srvaddr in notsupp_servers:
LOG.error("GlusterFS version %(version)s on server " LOG.error("GlusterFS version %(version)s on server "
"%(server)s is not supported, " "%(server)s is not supported, "
@ -475,7 +474,7 @@ class GlusterfsVolumeMappedLayout(layout.GlusterfsShareLayoutBase):
vers = self.glusterfs_versions[old_gmgr.host_access] vers = self.glusterfs_versions[old_gmgr.host_access]
minvers = (3, 7) minvers = (3, 7)
if common.numreduct(vers) < minvers: if common.numreduct(vers) < minvers:
minvers_str = '.'.join(six.text_type(c) for c in minvers) minvers_str = '.'.join(str(c) for c in minvers)
vers_str = '.'.join(vers) vers_str = '.'.join(vers)
msg = (_("GlusterFS version %(version)s on server %(server)s does " msg = (_("GlusterFS version %(version)s on server %(server)s does "
"not support creation of shares from snapshot. " "not support creation of shares from snapshot. "

View File

@ -34,7 +34,6 @@ from oslo_concurrency import processutils
from oslo_config import cfg from oslo_config import cfg
from oslo_log import log from oslo_log import log
from oslo_utils import units from oslo_utils import units
import six
from manila import exception from manila import exception
from manila.i18n import _ from manila.i18n import _
@ -99,7 +98,7 @@ class HDFSNativeShareDriver(driver.ExecuteMixin, driver.ShareDriver):
self._hdfs_bin = 'hdfs' self._hdfs_bin = 'hdfs'
self._hdfs_base_path = ( self._hdfs_base_path = (
'hdfs://' + self.configuration.hdfs_namenode_ip + ':' 'hdfs://' + self.configuration.hdfs_namenode_ip + ':'
+ six.text_type(self.configuration.hdfs_namenode_port)) + str(self.configuration.hdfs_namenode_port))
def _hdfs_local_execute(self, *cmd, **kwargs): def _hdfs_local_execute(self, *cmd, **kwargs):
if 'run_as_root' not in kwargs: if 'run_as_root' not in kwargs:
@ -151,7 +150,7 @@ class HDFSNativeShareDriver(driver.ExecuteMixin, driver.ShareDriver):
except Exception as e: except Exception as e:
msg = (_('Error running SSH command: %(cmd)s. ' msg = (_('Error running SSH command: %(cmd)s. '
'Error: %(excmsg)s.') % 'Error: %(excmsg)s.') %
{'cmd': command, 'excmsg': six.text_type(e)}) {'cmd': command, 'excmsg': str(e)})
LOG.error(msg) LOG.error(msg)
raise exception.HDFSException(msg) raise exception.HDFSException(msg)
@ -159,9 +158,9 @@ class HDFSNativeShareDriver(driver.ExecuteMixin, driver.ShareDriver):
share_dir = '/' + share['name'] share_dir = '/' + share['name']
if not size: if not size:
sizestr = six.text_type(share['size']) + 'g' sizestr = str(share['size']) + 'g'
else: else:
sizestr = six.text_type(size) + 'g' sizestr = str(size) + 'g'
try: try:
self._hdfs_execute(self._hdfs_bin, 'dfsadmin', self._hdfs_execute(self._hdfs_bin, 'dfsadmin',
@ -170,7 +169,7 @@ class HDFSNativeShareDriver(driver.ExecuteMixin, driver.ShareDriver):
msg = (_('Failed to set space quota for the ' msg = (_('Failed to set space quota for the '
'share %(sharename)s. Error: %(excmsg)s.') % 'share %(sharename)s. Error: %(excmsg)s.') %
{'sharename': share['name'], {'sharename': share['name'],
'excmsg': six.text_type(e)}) 'excmsg': str(e)})
LOG.error(msg) LOG.error(msg)
raise exception.HDFSException(msg) raise exception.HDFSException(msg)
@ -190,7 +189,7 @@ class HDFSNativeShareDriver(driver.ExecuteMixin, driver.ShareDriver):
msg = (_('Failed to create directory in hdfs for the ' msg = (_('Failed to create directory in hdfs for the '
'share %(sharename)s. Error: %(excmsg)s.') % 'share %(sharename)s. Error: %(excmsg)s.') %
{'sharename': share['name'], {'sharename': share['name'],
'excmsg': six.text_type(e)}) 'excmsg': str(e)})
LOG.error(msg) LOG.error(msg)
raise exception.HDFSException(msg) raise exception.HDFSException(msg)
@ -204,7 +203,7 @@ class HDFSNativeShareDriver(driver.ExecuteMixin, driver.ShareDriver):
msg = (_('Failed to allow snapshot for the ' msg = (_('Failed to allow snapshot for the '
'share %(sharename)s. Error: %(excmsg)s.') % 'share %(sharename)s. Error: %(excmsg)s.') %
{'sharename': share['name'], {'sharename': share['name'],
'excmsg': six.text_type(e)}) 'excmsg': str(e)})
LOG.error(msg) LOG.error(msg)
raise exception.HDFSException(msg) raise exception.HDFSException(msg)
@ -251,7 +250,7 @@ class HDFSNativeShareDriver(driver.ExecuteMixin, driver.ShareDriver):
'snapshot %(snapshotname)s. Error: %(excmsg)s.') % 'snapshot %(snapshotname)s. Error: %(excmsg)s.') %
{'sharename': share['name'], {'sharename': share['name'],
'snapshotname': snapshot['name'], 'snapshotname': snapshot['name'],
'excmsg': six.text_type(e)}) 'excmsg': str(e)})
LOG.error(msg) LOG.error(msg)
raise exception.HDFSException(msg) raise exception.HDFSException(msg)
@ -271,7 +270,7 @@ class HDFSNativeShareDriver(driver.ExecuteMixin, driver.ShareDriver):
'the share %(sharename)s. Error: %(excmsg)s.') % 'the share %(sharename)s. Error: %(excmsg)s.') %
{'snapshotname': snapshot_name, {'snapshotname': snapshot_name,
'sharename': snapshot['share_name'], 'sharename': snapshot['share_name'],
'excmsg': six.text_type(e)}) 'excmsg': str(e)})
LOG.error(msg) LOG.error(msg)
raise exception.HDFSException(msg) raise exception.HDFSException(msg)
@ -286,7 +285,7 @@ class HDFSNativeShareDriver(driver.ExecuteMixin, driver.ShareDriver):
msg = (_('Failed to delete share %(sharename)s. ' msg = (_('Failed to delete share %(sharename)s. '
'Error: %(excmsg)s.') % 'Error: %(excmsg)s.') %
{'sharename': share['name'], {'sharename': share['name'],
'excmsg': six.text_type(e)}) 'excmsg': str(e)})
LOG.error(msg) LOG.error(msg)
raise exception.HDFSException(msg) raise exception.HDFSException(msg)
@ -302,7 +301,7 @@ class HDFSNativeShareDriver(driver.ExecuteMixin, driver.ShareDriver):
msg = (_('Failed to delete snapshot %(snapshotname)s. ' msg = (_('Failed to delete snapshot %(snapshotname)s. '
'Error: %(excmsg)s.') % 'Error: %(excmsg)s.') %
{'snapshotname': snapshot['name'], {'snapshotname': snapshot['name'],
'excmsg': six.text_type(e)}) 'excmsg': str(e)})
LOG.error(msg) LOG.error(msg)
raise exception.HDFSException(msg) raise exception.HDFSException(msg)
@ -343,7 +342,7 @@ class HDFSNativeShareDriver(driver.ExecuteMixin, driver.ShareDriver):
'Error: %(excmsg)s.') % 'Error: %(excmsg)s.') %
{'sharename': share['name'], {'sharename': share['name'],
'username': access['access_to'], 'username': access['access_to'],
'excmsg': six.text_type(e)}) 'excmsg': str(e)})
LOG.error(msg) LOG.error(msg)
raise exception.HDFSException(msg) raise exception.HDFSException(msg)
@ -362,7 +361,7 @@ class HDFSNativeShareDriver(driver.ExecuteMixin, driver.ShareDriver):
'Error: %(excmsg)s.') % 'Error: %(excmsg)s.') %
{'sharename': share['name'], {'sharename': share['name'],
'username': access['access_to'], 'username': access['access_to'],
'excmsg': six.text_type(e)}) 'excmsg': str(e)})
LOG.error(msg) LOG.error(msg)
raise exception.HDFSException(msg) raise exception.HDFSException(msg)
@ -375,7 +374,7 @@ class HDFSNativeShareDriver(driver.ExecuteMixin, driver.ShareDriver):
(out, __) = self._hdfs_execute(self._hdfs_bin, 'fsck', '/') (out, __) = self._hdfs_execute(self._hdfs_bin, 'fsck', '/')
except exception.ProcessExecutionError as e: except exception.ProcessExecutionError as e:
msg = (_('Failed to check hdfs state. Error: %(excmsg)s.') % msg = (_('Failed to check hdfs state. Error: %(excmsg)s.') %
{'excmsg': six.text_type(e)}) {'excmsg': str(e)})
LOG.error(msg) LOG.error(msg)
raise exception.HDFSException(msg) raise exception.HDFSException(msg)
if 'HEALTHY' in out: if 'HEALTHY' in out:
@ -405,7 +404,7 @@ class HDFSNativeShareDriver(driver.ExecuteMixin, driver.ShareDriver):
except exception.ProcessExecutionError as e: except exception.ProcessExecutionError as e:
msg = (_('Failed to check available capacity for hdfs.' msg = (_('Failed to check available capacity for hdfs.'
'Error: %(excmsg)s.') % 'Error: %(excmsg)s.') %
{'excmsg': six.text_type(e)}) {'excmsg': str(e)})
LOG.error(msg) LOG.error(msg)
raise exception.HDFSException(msg) raise exception.HDFSException(msg)
@ -416,7 +415,7 @@ class HDFSNativeShareDriver(driver.ExecuteMixin, driver.ShareDriver):
except (IndexError, ValueError) as e: except (IndexError, ValueError) as e:
msg = (_('Failed to get hdfs capacity info. ' msg = (_('Failed to get hdfs capacity info. '
'Error: %(excmsg)s.') % 'Error: %(excmsg)s.') %
{'excmsg': six.text_type(e)}) {'excmsg': str(e)})
LOG.error(msg) LOG.error(msg)
raise exception.HDFSException(msg) raise exception.HDFSException(msg)
return total, free return total, free

View File

@ -19,7 +19,6 @@ from oslo_config import cfg
from oslo_log import log from oslo_log import log
from oslo_utils import excutils from oslo_utils import excutils
from oslo_utils import importutils from oslo_utils import importutils
import six
from manila.common import constants from manila.common import constants
from manila import exception from manila import exception
@ -591,7 +590,7 @@ class HitachiHNASDriver(driver.ShareDriver):
LOG.info("Share %(shr_id)s successfully extended to " LOG.info("Share %(shr_id)s successfully extended to "
"%(shr_size)s.", "%(shr_size)s.",
{'shr_id': share['id'], {'shr_id': share['id'],
'shr_size': six.text_type(new_size)}) 'shr_size': str(new_size)})
# TODO(alyson): Implement in DHSS = true mode # TODO(alyson): Implement in DHSS = true mode
def get_network_allocations_number(self): def get_network_allocations_number(self):
@ -633,7 +632,7 @@ class HitachiHNASDriver(driver.ShareDriver):
} }
LOG.info("HNAS Capabilities: %(data)s.", LOG.info("HNAS Capabilities: %(data)s.",
{'data': six.text_type(data)}) {'data': str(data)})
super(HitachiHNASDriver, self)._update_share_stats(data) super(HitachiHNASDriver, self)._update_share_stats(data)
@ -797,7 +796,7 @@ class HitachiHNASDriver(driver.ShareDriver):
LOG.info("Share %(shr_id)s successfully shrunk to " LOG.info("Share %(shr_id)s successfully shrunk to "
"%(shr_size)sG.", "%(shr_size)sG.",
{'shr_id': share['id'], {'shr_id': share['id'],
'shr_size': six.text_type(new_size)}) 'shr_size': str(new_size)})
def revert_to_snapshot(self, context, snapshot, share_access_rules, def revert_to_snapshot(self, context, snapshot, share_access_rules,
snapshot_access_rules, share_server=None): snapshot_access_rules, share_server=None):

View File

@ -18,7 +18,6 @@ from oslo_log import log
from oslo_utils import strutils from oslo_utils import strutils
from oslo_utils import units from oslo_utils import units
import paramiko import paramiko
import six
import os import os
import time import time
@ -39,7 +38,7 @@ class HNASSSHBackend(object):
self.password = hnas_password self.password = hnas_password
self.priv_key = ssh_private_key self.priv_key = ssh_private_key
self.admin_ip0 = cluster_admin_ip0 self.admin_ip0 = cluster_admin_ip0
self.evs_id = six.text_type(evs_id) self.evs_id = str(evs_id)
self.fs_name = fs_name self.fs_name = fs_name
self.evs_ip = evs_ip self.evs_ip = evs_ip
self.sshpool = None self.sshpool = None
@ -154,10 +153,10 @@ class HNASSSHBackend(object):
if len(host_list) == 0: if len(host_list) == 0:
command.append('127.0.0.1') command.append('127.0.0.1')
else: else:
string_command = '"' + six.text_type(host_list[0]) string_command = '"' + str(host_list[0])
for i in range(1, len(host_list)): for i in range(1, len(host_list)):
string_command += ',' + (six.text_type(host_list[i])) string_command += ',' + (str(host_list[i]))
string_command += '"' string_command += '"'
command.append(string_command) command.append(string_command)
@ -456,7 +455,7 @@ class HNASSSHBackend(object):
raise exception.HNASBackendException(msg=msg) raise exception.HNASBackendException(msg=msg)
def quota_add(self, vvol_name, vvol_quota): def quota_add(self, vvol_name, vvol_quota):
str_quota = six.text_type(vvol_quota) + 'G' str_quota = str(vvol_quota) + 'G'
command = ['quota', 'add', '--usage-limit', command = ['quota', 'add', '--usage-limit',
str_quota, '--usage-hard-limit', str_quota, '--usage-hard-limit',
'yes', self.fs_name, vvol_name] 'yes', self.fs_name, vvol_name]
@ -469,7 +468,7 @@ class HNASSSHBackend(object):
raise exception.HNASBackendException(msg=msg) raise exception.HNASBackendException(msg=msg)
def modify_quota(self, vvol_name, new_size): def modify_quota(self, vvol_name, new_size):
str_quota = six.text_type(new_size) + 'G' str_quota = str(new_size) + 'G'
command = ['quota', 'mod', '--usage-limit', str_quota, command = ['quota', 'mod', '--usage-limit', str_quota,
self.fs_name, vvol_name] self.fs_name, vvol_name]
try: try:
@ -585,7 +584,7 @@ class HNASSSHBackend(object):
LOG.error(msg) LOG.error(msg)
raise exception.HNASItemNotFoundException(msg=msg) raise exception.HNASItemNotFoundException(msg=msg)
else: else:
bytes_usage = strutils.string_to_bytes(six.text_type(quota.usage) + bytes_usage = strutils.string_to_bytes(str(quota.usage) +
quota.usage_unit) quota.usage_unit)
return bytes_usage / units.Gi return bytes_usage / units.Gi

View File

@ -23,7 +23,6 @@ import re
from oslo_config import cfg from oslo_config import cfg
from oslo_config import types from oslo_config import types
from oslo_log import log from oslo_log import log
import six
from manila.common import config from manila.common import config
from manila import exception from manila import exception
@ -115,7 +114,7 @@ class FPG(types.String, types.IPAddress):
return 'FPG' return 'FPG'
def _formatter(self, value): def _formatter(self, value):
return six.text_type(value) return str(value)
HPE3PAR_OPTS = [ HPE3PAR_OPTS = [
@ -176,7 +175,7 @@ CONF.register_opts(HPE3PAR_OPTS)
def to_list(var): def to_list(var):
"""Convert var to list type if not""" """Convert var to list type if not"""
if isinstance(var, six.string_types): if isinstance(var, str):
return [var] return [var]
else: else:
return var return var
@ -350,7 +349,7 @@ class HPE3ParShareDriver(driver.ShareDriver):
# with startup. This is just debug info to identify the source # with startup. This is just debug info to identify the source
# code. If it doesn't work, just log a debug message. # code. If it doesn't work, just log a debug message.
LOG.debug('Source code SHA1 not logged due to: %s', LOG.debug('Source code SHA1 not logged due to: %s',
six.text_type(e)) str(e))
@staticmethod @staticmethod
def sha1_hash(clazz): def sha1_hash(clazz):

View File

@ -21,7 +21,6 @@ driver.
from oslo_log import log from oslo_log import log
from oslo_utils import importutils from oslo_utils import importutils
from oslo_utils import units from oslo_utils import units
import six
from manila.data import utils as data_utils from manila.data import utils as data_utils
from manila import exception from manila import exception
@ -130,8 +129,8 @@ class HPE3ParMediator(object):
'Version %(minimum)s or greater required. Run "pip' 'Version %(minimum)s or greater required. Run "pip'
' install --upgrade python-3parclient" to upgrade' ' install --upgrade python-3parclient" to upgrade'
' the hpe3parclient.') % ' the hpe3parclient.') %
{'found': '.'.join(map(six.text_type, self.client_version)), {'found': '.'.join(map(str, self.client_version)),
'minimum': '.'.join(map(six.text_type, 'minimum': '.'.join(map(str,
MIN_CLIENT_VERSION))}) MIN_CLIENT_VERSION))})
LOG.error(msg) LOG.error(msg)
raise exception.HPE3ParInvalidClient(message=msg) raise exception.HPE3ParInvalidClient(message=msg)
@ -141,7 +140,7 @@ class HPE3ParMediator(object):
self.hpe3par_api_url) self.hpe3par_api_url)
except Exception as e: except Exception as e:
msg = (_('Failed to connect to HPE 3PAR File Persona Client: %s') % msg = (_('Failed to connect to HPE 3PAR File Persona Client: %s') %
six.text_type(e)) str(e))
LOG.exception(msg) LOG.exception(msg)
raise exception.ShareBackendException(message=msg) raise exception.ShareBackendException(message=msg)
@ -163,7 +162,7 @@ class HPE3ParMediator(object):
except Exception as e: except Exception as e:
msg = (_('Failed to set SSH options for HPE 3PAR File Persona ' msg = (_('Failed to set SSH options for HPE 3PAR File Persona '
'Client: %s') % six.text_type(e)) 'Client: %s') % str(e))
LOG.exception(msg) LOG.exception(msg)
raise exception.ShareBackendException(message=msg) raise exception.ShareBackendException(message=msg)
@ -177,7 +176,7 @@ class HPE3ParMediator(object):
LOG.info("3PAR WSAPI %s", wsapi_version) LOG.info("3PAR WSAPI %s", wsapi_version)
except Exception as e: except Exception as e:
msg = (_('Failed to get 3PAR WSAPI version: %s') % msg = (_('Failed to get 3PAR WSAPI version: %s') %
six.text_type(e)) str(e))
LOG.exception(msg) LOG.exception(msg)
raise exception.ShareBackendException(message=msg) raise exception.ShareBackendException(message=msg)
@ -192,7 +191,7 @@ class HPE3ParMediator(object):
"because: %(err)s") % "because: %(err)s") %
{'url': self.hpe3par_api_url, {'url': self.hpe3par_api_url,
'user': self.hpe3par_username, 'user': self.hpe3par_username,
'err': six.text_type(e)}) 'err': str(e)})
LOG.error(msg) LOG.error(msg)
raise exception.ShareBackendException(msg=msg) raise exception.ShareBackendException(msg=msg)
@ -202,7 +201,7 @@ class HPE3ParMediator(object):
except Exception as e: except Exception as e:
msg = ("Failed to Logout from 3PAR (%(url)s) because %(err)s") msg = ("Failed to Logout from 3PAR (%(url)s) because %(err)s")
LOG.warning(msg, {'url': self.hpe3par_api_url, LOG.warning(msg, {'url': self.hpe3par_api_url,
'err': six.text_type(e)}) 'err': str(e)})
# don't raise exception on logout() # don't raise exception on logout()
@staticmethod @staticmethod
@ -227,7 +226,7 @@ class HPE3ParMediator(object):
try: try:
result = self._client.getfsquota(fpg=fpg) result = self._client.getfsquota(fpg=fpg)
except Exception as e: except Exception as e:
result = {'message': six.text_type(e)} result = {'message': str(e)}
error_msg = result.get('message') error_msg = result.get('message')
if error_msg: if error_msg:
@ -248,7 +247,7 @@ class HPE3ParMediator(object):
result = self._client.getfpg(fpg) result = self._client.getfpg(fpg)
except Exception as e: except Exception as e:
msg = (_('Failed to get capacity for fpg %(fpg)s: %(e)s') % msg = (_('Failed to get capacity for fpg %(fpg)s: %(e)s') %
{'fpg': fpg, 'e': six.text_type(e)}) {'fpg': fpg, 'e': str(e)})
LOG.error(msg) LOG.error(msg)
raise exception.ShareBackendException(msg=msg) raise exception.ShareBackendException(msg=msg)
@ -441,7 +440,7 @@ class HPE3ParMediator(object):
"""Update 3PAR quotas and return setfsquota output.""" """Update 3PAR quotas and return setfsquota output."""
if self.hpe3par_fstore_per_share: if self.hpe3par_fstore_per_share:
hcapacity = six.text_type(new_size * units.Ki) hcapacity = str(new_size * units.Ki)
scapacity = hcapacity scapacity = hcapacity
else: else:
hard_size_mb = (new_size - old_size) * units.Ki hard_size_mb = (new_size - old_size) * units.Ki
@ -453,8 +452,8 @@ class HPE3ParMediator(object):
if len(quotas) == 1: if len(quotas) == 1:
hard_size_mb += int(quotas[0].get('hardBlock', '0')) hard_size_mb += int(quotas[0].get('hardBlock', '0'))
soft_size_mb += int(quotas[0].get('softBlock', '0')) soft_size_mb += int(quotas[0].get('softBlock', '0'))
hcapacity = six.text_type(hard_size_mb) hcapacity = str(hard_size_mb)
scapacity = six.text_type(soft_size_mb) scapacity = str(soft_size_mb)
return self._client.setfsquota(vfs, return self._client.setfsquota(vfs,
fpg=fpg, fpg=fpg,
@ -471,7 +470,7 @@ class HPE3ParMediator(object):
'%(size)s on %(fstore)s with exception: %(e)s') % '%(size)s on %(fstore)s with exception: %(e)s') %
{'size': new_size - old_size, {'size': new_size - old_size,
'fstore': fstore, 'fstore': fstore,
'e': six.text_type(e)}) 'e': str(e)})
LOG.error(msg) LOG.error(msg)
raise exception.ShareBackendException(msg=msg) raise exception.ShareBackendException(msg=msg)
@ -522,7 +521,7 @@ class HPE3ParMediator(object):
LOG.debug("createfstore result=%s", result) LOG.debug("createfstore result=%s", result)
except Exception as e: except Exception as e:
msg = (_('Failed to create fstore %(fstore)s: %(e)s') % msg = (_('Failed to create fstore %(fstore)s: %(e)s') %
{'fstore': fstore, 'e': six.text_type(e)}) {'fstore': fstore, 'e': str(e)})
LOG.exception(msg) LOG.exception(msg)
raise exception.ShareBackendException(msg=msg) raise exception.ShareBackendException(msg=msg)
@ -544,7 +543,7 @@ class HPE3ParMediator(object):
except Exception as e: except Exception as e:
msg = (_('Failed to create share %(share_name)s: %(e)s') % msg = (_('Failed to create share %(share_name)s: %(e)s') %
{'share_name': share_name, 'e': six.text_type(e)}) {'share_name': share_name, 'e': str(e)})
LOG.exception(msg) LOG.exception(msg)
raise exception.ShareBackendException(msg=msg) raise exception.ShareBackendException(msg=msg)
@ -557,7 +556,7 @@ class HPE3ParMediator(object):
except Exception as e: except Exception as e:
msg = (_('Failed to get fshare %(share_name)s after creating it: ' msg = (_('Failed to get fshare %(share_name)s after creating it: '
'%(e)s') % {'share_name': share_name, '%(e)s') % {'share_name': share_name,
'e': six.text_type(e)}) 'e': str(e)})
LOG.exception(msg) LOG.exception(msg)
raise exception.ShareBackendException(msg=msg) raise exception.ShareBackendException(msg=msg)
@ -790,7 +789,7 @@ class HPE3ParMediator(object):
err_data = progress err_data = progress
except Exception as err: except Exception as err:
err_msg = _("Failed to copy data, reason: %s.") err_msg = _("Failed to copy data, reason: %s.")
err_data = six.text_type(err) err_data = str(err)
if err_msg: if err_msg:
raise exception.ShareBackendException(msg=err_msg % err_data) raise exception.ShareBackendException(msg=err_msg % err_data)
@ -802,7 +801,7 @@ class HPE3ParMediator(object):
except Exception as e: except Exception as e:
msg = (_('Failed to remove share %(share_name)s: %(e)s') % msg = (_('Failed to remove share %(share_name)s: %(e)s') %
{'share_name': share_name, 'e': six.text_type(e)}) {'share_name': share_name, 'e': str(e)})
LOG.exception(msg) LOG.exception(msg)
raise exception.ShareBackendException(msg=msg) raise exception.ShareBackendException(msg=msg)
@ -846,7 +845,7 @@ class HPE3ParMediator(object):
self._client.removefstore(vfs, fstore, fpg=fpg) self._client.removefstore(vfs, fstore, fpg=fpg)
except Exception as e: except Exception as e:
msg = (_('Failed to remove fstore %(fstore)s: %(e)s') % msg = (_('Failed to remove fstore %(fstore)s: %(e)s') %
{'fstore': fstore, 'e': six.text_type(e)}) {'fstore': fstore, 'e': str(e)})
LOG.exception(msg) LOG.exception(msg)
raise exception.ShareBackendException(msg=msg) raise exception.ShareBackendException(msg=msg)
@ -867,7 +866,7 @@ class HPE3ParMediator(object):
data = { data = {
'fstore': fstore, 'fstore': fstore,
'share': share_name, 'share': share_name,
'e': six.text_type(e), 'e': str(e),
} }
LOG.warning(msg, data) LOG.warning(msg, data)
@ -966,7 +965,7 @@ class HPE3ParMediator(object):
{'name': SUPER_SHARE, 'result': result}) {'name': SUPER_SHARE, 'result': result})
except Exception as e: except Exception as e:
msg = (_('Failed to create share %(share_name)s: %(e)s'), msg = (_('Failed to create share %(share_name)s: %(e)s'),
{'share_name': SUPER_SHARE, 'e': six.text_type(e)}) {'share_name': SUPER_SHARE, 'e': str(e)})
LOG.exception(msg) LOG.exception(msg)
raise exception.ShareBackendException(msg=msg) raise exception.ShareBackendException(msg=msg)
@ -980,7 +979,7 @@ class HPE3ParMediator(object):
except Exception as err: except Exception as err:
message = ("There was an error creating mount directory: " message = ("There was an error creating mount directory: "
"%s. The nested file tree will not be deleted.", "%s. The nested file tree will not be deleted.",
six.text_type(err)) str(err))
LOG.warning(message) LOG.warning(message)
def _mount_share(self, protocol, export_location, mount_dir): def _mount_share(self, protocol, export_location, mount_dir):
@ -1006,7 +1005,7 @@ class HPE3ParMediator(object):
except Exception as err: except Exception as err:
message = ("There was an error mounting the super share: " message = ("There was an error mounting the super share: "
"%s. The nested file tree will not be deleted.", "%s. The nested file tree will not be deleted.",
six.text_type(err)) str(err))
LOG.warning(message) LOG.warning(message)
def _unmount_share(self, mount_location): def _unmount_share(self, mount_location):
@ -1017,7 +1016,7 @@ class HPE3ParMediator(object):
"%(mount_location)s: %(error)s") "%(mount_location)s: %(error)s")
msg_data = { msg_data = {
'mount_location': mount_location, 'mount_location': mount_location,
'error': six.text_type(err), 'error': str(err),
} }
LOG.warning(message, msg_data) LOG.warning(message, msg_data)
@ -1027,7 +1026,7 @@ class HPE3ParMediator(object):
except Exception as err: except Exception as err:
message = ("There was an error removing the share: " message = ("There was an error removing the share: "
"%s. The nested file tree will not be deleted.", "%s. The nested file tree will not be deleted.",
six.text_type(err)) str(err))
LOG.warning(message) LOG.warning(message)
def _generate_mount_path(self, protocol, fpg, vfs, fstore, share_ip): def _generate_mount_path(self, protocol, fpg, vfs, fstore, share_ip):
@ -1051,7 +1050,7 @@ class HPE3ParMediator(object):
result = self._client.getvfs(fpg=fpg, vfs=vfs) result = self._client.getvfs(fpg=fpg, vfs=vfs)
except Exception as e: except Exception as e:
msg = (_('Exception during getvfs %(vfs)s: %(e)s') % msg = (_('Exception during getvfs %(vfs)s: %(e)s') %
{'vfs': vfs, 'e': six.text_type(e)}) {'vfs': vfs, 'e': str(e)})
LOG.exception(msg) LOG.exception(msg)
raise exception.ShareBackendException(msg=msg) raise exception.ShareBackendException(msg=msg)
@ -1138,7 +1137,7 @@ class HPE3ParMediator(object):
msg = (_('Failed to create snapshot for FPG/VFS/fstore ' msg = (_('Failed to create snapshot for FPG/VFS/fstore '
'%(fpg)s/%(vfs)s/%(fstore)s: %(e)s') % '%(fpg)s/%(vfs)s/%(fstore)s: %(e)s') %
{'fpg': fpg, 'vfs': vfs, 'fstore': fstore, {'fpg': fpg, 'vfs': vfs, 'fstore': fstore,
'e': six.text_type(e)}) 'e': str(e)})
LOG.exception(msg) LOG.exception(msg)
raise exception.ShareBackendException(msg=msg) raise exception.ShareBackendException(msg=msg)
@ -1165,7 +1164,7 @@ class HPE3ParMediator(object):
except Exception as e: except Exception as e:
msg = (_('Unexpected exception while getting share list. ' msg = (_('Unexpected exception while getting share list. '
'Cannot delete snapshot without checking for ' 'Cannot delete snapshot without checking for '
'dependent shares first: %s') % six.text_type(e)) 'dependent shares first: %s') % str(e))
LOG.exception(msg) LOG.exception(msg)
raise exception.ShareBackendException(msg=msg) raise exception.ShareBackendException(msg=msg)
@ -1203,7 +1202,7 @@ class HPE3ParMediator(object):
'vfs': vfs, 'vfs': vfs,
'fstore': fstore, 'fstore': fstore,
'snapname': snapname, 'snapname': snapname,
'e': six.text_type(e)}) 'e': str(e)})
LOG.exception(msg) LOG.exception(msg)
raise exception.ShareBackendException(msg=msg) raise exception.ShareBackendException(msg=msg)
@ -1377,7 +1376,7 @@ class HPE3ParMediator(object):
'type': access_type, 'type': access_type,
'to': access_to, 'to': access_to,
'level': access_level, 'level': access_level,
'e': six.text_type(e), 'e': str(e),
} }
LOG.info(msg, msg_data) LOG.info(msg, msg_data)
return return
@ -1414,7 +1413,7 @@ class HPE3ParMediator(object):
plus_or_minus, access_type, access_to, result) plus_or_minus, access_type, access_to, result)
except Exception as e: except Exception as e:
result = six.text_type(e) result = str(e)
LOG.debug("setfshare result=%s", result) LOG.debug("setfshare result=%s", result)
if result: if result:
@ -1485,7 +1484,7 @@ class HPE3ParMediator(object):
return shares[0] return shares[0]
except Exception as e: except Exception as e:
msg = (_('Unexpected exception while getting share list: %s') % msg = (_('Unexpected exception while getting share list: %s') %
six.text_type(e)) str(e))
raise exception.ShareBackendException(msg=msg) raise exception.ShareBackendException(msg=msg)
def _find_fsnap(self, project_id, share_id, orig_proto, snapshot_tag, def _find_fsnap(self, project_id, share_id, orig_proto, snapshot_tag,
@ -1510,7 +1509,7 @@ class HPE3ParMediator(object):
return snapshots[0] return snapshots[0]
except Exception as e: except Exception as e:
msg = (_('Unexpected exception while getting snapshots: %s') % msg = (_('Unexpected exception while getting snapshots: %s') %
six.text_type(e)) str(e))
raise exception.ShareBackendException(msg=msg) raise exception.ShareBackendException(msg=msg)
def update_access(self, project_id, share_id, share_proto, extra_specs, def update_access(self, project_id, share_id, share_proto, extra_specs,
@ -1668,7 +1667,7 @@ class HPE3ParMediator(object):
def create_fsip(self, ip, subnet, vlantag, fpg, vfs): def create_fsip(self, ip, subnet, vlantag, fpg, vfs):
vlantag_str = six.text_type(vlantag) if vlantag else '0' vlantag_str = str(vlantag) if vlantag else '0'
# Try to create it. It's OK if it already exists. # Try to create it. It's OK if it already exists.
try: try:

View File

@ -16,11 +16,8 @@
"""Abstract base class to work with share.""" """Abstract base class to work with share."""
import abc import abc
import six
class HuaweiBase(metaclass=abc.ABCMeta):
@six.add_metaclass(abc.ABCMeta)
class HuaweiBase(object):
"""Interface to work with share.""" """Interface to work with share."""
def __init__(self, configuration): def __init__(self, configuration):

View File

@ -26,7 +26,6 @@ from oslo_serialization import jsonutils
from oslo_utils import excutils from oslo_utils import excutils
from oslo_utils import strutils from oslo_utils import strutils
from oslo_utils import units from oslo_utils import units
import six
from manila.common import constants as common_constants from manila.common import constants as common_constants
from manila.data import utils as data_utils from manila.data import utils as data_utils
@ -586,7 +585,7 @@ class V3StorageConnection(driver.HuaweiBase):
message = (_("Failed to unmount share %(share)s. " message = (_("Failed to unmount share %(share)s. "
"Reason: %(reason)s.") "Reason: %(reason)s.")
% {'share': share['name'], % {'share': share['name'],
'reason': six.text_type(err)}) 'reason': str(err)})
raise exception.ShareUmountException(reason=message) raise exception.ShareUmountException(reason=message)
def mount_share_to_host(self, share, access): def mount_share_to_host(self, share, access):
@ -611,7 +610,7 @@ class V3StorageConnection(driver.HuaweiBase):
message = (_('Bad response from mount share: %(share)s. ' message = (_('Bad response from mount share: %(share)s. '
'Reason: %(reason)s.') 'Reason: %(reason)s.')
% {'share': share['name'], % {'share': share['name'],
'reason': six.text_type(err)}) 'reason': str(err)})
raise exception.ShareMountException(reason=message) raise exception.ShareMountException(reason=message)
def get_network_allocations_number(self): def get_network_allocations_number(self):

View File

@ -21,7 +21,6 @@ from xml.etree import ElementTree as ET
from oslo_log import log from oslo_log import log
from oslo_serialization import jsonutils from oslo_serialization import jsonutils
import six
from manila import exception from manila import exception
from manila.i18n import _ from manila.i18n import _
@ -93,7 +92,7 @@ class RestHelper(object):
res.raise_for_status() res.raise_for_status()
except requests.HTTPError as exc: except requests.HTTPError as exc:
return {"error": {"code": exc.response.status_code, return {"error": {"code": exc.response.status_code,
"description": six.text_type(exc)}} "description": str(exc)}}
result = res.json() result = res.json()
LOG.debug('Response Data: %s', result) LOG.debug('Response Data: %s', result)
@ -198,11 +197,11 @@ class RestHelper(object):
node = root.find('Storage/%s' % key) node = root.find('Storage/%s' % key)
if node.text.startswith(prefix_name): if node.text.startswith(prefix_name):
logininfo[key] = base64.b64decode( logininfo[key] = base64.b64decode(
six.b(node.text[4:])).decode() (node.text[4:]).encode("latin-1")).decode()
else: else:
logininfo[key] = node.text logininfo[key] = node.text
node.text = prefix_name + base64.b64encode( node.text = prefix_name + base64.b64encode(
six.b(node.text)).decode() node.text.encode("latin-1")).decode()
need_encode = True need_encode = True
if need_encode: if need_encode:
self._change_file_mode(filename) self._change_file_mode(filename)
@ -445,8 +444,8 @@ class RestHelper(object):
share_client_type): share_client_type):
range_end = range_begin + 100 range_end = range_begin + 100
url = ("/" + share_client_type + "?filter=PARENTID::" url = ("/" + share_client_type + "?filter=PARENTID::"
+ share_id + "&range=[" + six.text_type(range_begin) + share_id + "&range=[" + str(range_begin)
+ "-" + six.text_type(range_end) + "]") + "-" + str(range_end) + "]")
result = self.call(url, None, "GET") result = self.call(url, None, "GET")
self._assert_rest_result(result, 'Get access id by share error!') self._assert_rest_result(result, 'Get access id by share error!')
return result.get('data', []) return result.get('data', [])
@ -674,8 +673,8 @@ class RestHelper(object):
"""Get share by share name.""" """Get share by share name."""
range_end = range_begin + 100 range_end = range_begin + 100
url = ("/" + share_url_type + "?range=[" url = ("/" + share_url_type + "?range=["
+ six.text_type(range_begin) + "-" + str(range_begin) + "-"
+ six.text_type(range_end) + "]") + str(range_end) + "]")
result = self.call(url, None, "GET") result = self.call(url, None, "GET")
self._assert_rest_result(result, 'Get share by name error!') self._assert_rest_result(result, 'Get share by name error!')
@ -1130,7 +1129,7 @@ class RestHelper(object):
result = self.call(url, None, 'GET') result = self.call(url, None, 'GET')
self._assert_rest_result(result, _('Get vlan error.')) self._assert_rest_result(result, _('Get vlan error.'))
vlan_tag = six.text_type(vlan_tag) vlan_tag = str(vlan_tag)
if "data" in result: if "data" in result:
for item in result['data']: for item in result['data']:
if port_id == item['PORTID'] and vlan_tag == item['TAG']: if port_id == item['PORTID'] and vlan_tag == item['TAG']:
@ -1142,7 +1141,7 @@ class RestHelper(object):
url = "/vlan" url = "/vlan"
data = jsonutils.dumps({"PORTID": port_id, data = jsonutils.dumps({"PORTID": port_id,
"PORTTYPE": port_type, "PORTTYPE": port_type,
"TAG": six.text_type(vlan_tag), "TAG": str(vlan_tag),
"TYPE": "280"}) "TYPE": "280"})
result = self.call(url, data, "POST") result = self.call(url, data, "POST")
self._assert_rest_result(result, _('Create vlan error.')) self._assert_rest_result(result, _('Create vlan error.'))

View File

@ -32,6 +32,7 @@ import abc
import math import math
import os import os
import re import re
import shlex
import socket import socket
from oslo_config import cfg from oslo_config import cfg
@ -40,7 +41,6 @@ from oslo_utils import excutils
from oslo_utils import importutils from oslo_utils import importutils
from oslo_utils import strutils from oslo_utils import strutils
from oslo_utils import units from oslo_utils import units
import six
from manila.common import constants from manila.common import constants
from manila import exception from manila import exception
@ -161,7 +161,7 @@ class GPFSShareDriver(driver.ExecuteMixin, driver.GaneshaMixin,
def _sanitize_command(self, cmd_list): def _sanitize_command(self, cmd_list):
# pylint: disable=too-many-function-args # pylint: disable=too-many-function-args
return ' '.join(six.moves.shlex_quote(cmd_arg) for cmd_arg in cmd_list) return ' '.join(shlex.quote(cmd_arg) for cmd_arg in cmd_list)
def _run_ssh(self, host, cmd_list, ignore_exit_code=None, def _run_ssh(self, host, cmd_list, ignore_exit_code=None,
check_exit_code=True): check_exit_code=True):
@ -782,8 +782,7 @@ class GPFSShareDriver(driver.ExecuteMixin, driver.GaneshaMixin,
snapshot["name"]) snapshot["name"])
@six.add_metaclass(abc.ABCMeta) class NASHelperBase(metaclass=abc.ABCMeta):
class NASHelperBase(object):
"""Interface to work with share.""" """Interface to work with share."""
def __init__(self, execute, config_object): def __init__(self, execute, config_object):

View File

@ -22,7 +22,6 @@ import ipaddress
from oslo_config import cfg from oslo_config import cfg
from oslo_log import log as logging from oslo_log import log as logging
from oslo_utils import units from oslo_utils import units
import six
from manila.common import constants from manila.common import constants
from manila import exception from manila import exception
@ -328,7 +327,7 @@ class InfiniboxShareDriver(driver.ShareDriver):
address, returns only that IP address. address, returns only that IP address.
""" """
ip_address = six.text_type(ip_address) ip_address = str(ip_address)
# try treating the ip_address parameter as a range of IP addresses: # try treating the ip_address parameter as a range of IP addresses:
ip_network = ipaddress.ip_network(ip_address, strict=False) ip_network = ipaddress.ip_network(ip_address, strict=False)

View File

@ -22,7 +22,6 @@ import functools
import json import json
import re import re
import requests import requests
import six
import time import time
from oslo_config import cfg from oslo_config import cfg
@ -142,13 +141,13 @@ class RestAPIExecutor(object):
try: try:
return self.send_api(method, params, request_type) return self.send_api(method, params, request_type)
except exception.NetworkException as e: except exception.NetworkException as e:
msge = six.text_type(e) msge = str(e)
LOG.error(msge) LOG.error(msge)
self.refresh_token(force=True) self.refresh_token(force=True)
eventlet.sleep(1) eventlet.sleep(1)
except exception.ShareBackendException as e: except exception.ShareBackendException as e:
msge = six.text_type(e) msge = str(e)
break break
msg = (_('Access RestAPI /rest/%(method)s by %(type)s failed,' msg = (_('Access RestAPI /rest/%(method)s by %(type)s failed,'

View File

@ -19,7 +19,6 @@ CLI helpers for Inspur InStorage
import paramiko import paramiko
import re import re
import six
from eventlet import greenthread from eventlet import greenthread
@ -150,7 +149,7 @@ class CLIParser(object):
else: else:
yield [] yield []
if isinstance(self.raw, six.string_types): if isinstance(self.raw, str):
stdout, stderr = self.raw, '' stdout, stderr = self.raw, ''
else: else:
stdout, stderr = self.raw stdout, stderr = self.raw

View File

@ -18,7 +18,6 @@ Driver for Inspur InStorage
import ipaddress import ipaddress
import itertools import itertools
import six
from oslo_config import cfg from oslo_config import cfg
from oslo_log import log from oslo_log import log
@ -496,14 +495,14 @@ class InStorageAssistant(object):
msg = _('only ip access type is supported when using NFS protocol') msg = _('only ip access type is supported when using NFS protocol')
raise exception.ShareBackendException(msg=msg) raise exception.ShareBackendException(msg=msg)
network = ipaddress.ip_network(six.text_type(access_rule['access_to'])) network = ipaddress.ip_network(str(access_rule['access_to']))
if network.version != 4: if network.version != 4:
msg = _('only IPV4 is accepted when using NFS protocol') msg = _('only IPV4 is accepted when using NFS protocol')
raise exception.ShareBackendException(msg=msg) raise exception.ShareBackendException(msg=msg)
client_spec = self.NFS_CLIENT_SPEC_PATTERN % { client_spec = self.NFS_CLIENT_SPEC_PATTERN % {
'ip': six.text_type(network.network_address), 'ip': str(network.network_address),
'mask': six.text_type(network.netmask), 'mask': str(network.netmask),
'rights': access_rule['access_level'], 'rights': access_rule['access_level'],
'all_squash': 'all_squash', 'all_squash': 'all_squash',
'root_squash': 'root_squash' 'root_squash': 'root_squash'

View File

@ -22,7 +22,6 @@ import socket
from oslo_concurrency import processutils from oslo_concurrency import processutils
from oslo_log import log from oslo_log import log
import six
from manila.common import constants from manila.common import constants
from manila import exception from manila import exception
@ -79,7 +78,7 @@ class BaseDriverUtil(object):
msg = ('Error running SSH command. Trying another host') msg = ('Error running SSH command. Trying another host')
LOG.error(msg) LOG.error(msg)
else: else:
raise exception.ProcessExecutionError(six.text_type(e)) raise exception.ProcessExecutionError(str(e))
def _run_ssh(self, host, cmd_list, check_exit_code=False): def _run_ssh(self, host, cmd_list, check_exit_code=False):
command = ' '.join(pipes.quote(cmd_arg) for cmd_arg in cmd_list) command = ' '.join(pipes.quote(cmd_arg) for cmd_arg in cmd_list)
@ -137,7 +136,7 @@ class BaseDriverUtil(object):
# delete size param as it is set separately # delete size param as it is set separately
if kwargs.get('quota'): if kwargs.get('quota'):
del kwargs['quota'] del kwargs['quota']
sizestr = six.text_type(size) + 'G' sizestr = str(size) + 'G'
cmd = [self.maprcli_bin, 'volume', 'create', '-name', cmd = [self.maprcli_bin, 'volume', 'create', '-name',
name, '-path', path, '-quota', name, '-path', path, '-quota',
sizestr, '-readAce', '', '-writeAce', ''] sizestr, '-readAce', '', '-writeAce', '']
@ -158,7 +157,7 @@ class BaseDriverUtil(object):
raise exception.ProcessExecutionError(out) raise exception.ProcessExecutionError(out)
def set_volume_size(self, name, size): def set_volume_size(self, name, size):
sizestr = six.text_type(size) + 'G' sizestr = str(size) + 'G'
cmd = [self.maprcli_bin, 'volume', 'modify', '-name', name, '-quota', cmd = [self.maprcli_bin, 'volume', 'modify', '-name', name, '-quota',
sizestr] sizestr]
self._execute(*cmd) self._execute(*cmd)

View File

@ -26,7 +26,6 @@ from oslo_log import log
from oslo_serialization import jsonutils from oslo_serialization import jsonutils
import requests import requests
from requests import auth from requests import auth
import six
from manila import exception from manila import exception
from manila.i18n import _ from manila.i18n import _
@ -142,8 +141,8 @@ class BaseClient(object):
try: try:
self._api_major_version = int(major) self._api_major_version = int(major)
self._api_minor_version = int(minor) self._api_minor_version = int(minor)
self._api_version = (six.text_type(major) + "." + self._api_version = (str(major) + "." +
six.text_type(minor)) str(minor))
except ValueError: except ValueError:
raise ValueError('Major and minor versions must be integers') raise ValueError('Major and minor versions must be integers')
self._refresh_conn = True self._refresh_conn = True
@ -171,7 +170,7 @@ class BaseClient(object):
int(port) int(port)
except ValueError: except ValueError:
raise ValueError('Port must be integer') raise ValueError('Port must be integer')
self._port = six.text_type(port) self._port = str(port)
self._refresh_conn = True self._refresh_conn = True
def get_port(self): def get_port(self):
@ -338,7 +337,7 @@ class ZapiClient(BaseClient):
except requests.HTTPError as e: except requests.HTTPError as e:
raise NaApiError(e.errno, e.strerror) raise NaApiError(e.errno, e.strerror)
except requests.URLRequired as e: except requests.URLRequired as e:
raise exception.StorageCommunicationException(six.text_type(e)) raise exception.StorageCommunicationException(str(e))
except Exception as e: except Exception as e:
raise NaApiError(message=e) raise NaApiError(message=e)
@ -523,7 +522,7 @@ class RestClient(BaseClient):
except requests.HTTPError as e: except requests.HTTPError as e:
raise NaApiError(e.errno, e.strerror) raise NaApiError(e.errno, e.strerror)
except requests.URLRequired as e: except requests.URLRequired as e:
raise exception.StorageCommunicationException(six.text_type(e)) raise exception.StorageCommunicationException(str(e))
except Exception as e: except Exception as e:
raise NaApiError(message=e) raise NaApiError(message=e)
@ -851,8 +850,8 @@ class NaElement(object):
self.add_child_elem(child) self.add_child_elem(child)
elif isinstance( elif isinstance(
value, value,
six.string_types + six.integer_types + (float, )): (str, ) + (int, ) + (float, )):
self.add_new_child(key, six.text_type(value)) self.add_new_child(key, str(value))
elif isinstance(value, (list, tuple, dict)): elif isinstance(value, (list, tuple, dict)):
child = NaElement(key) child = NaElement(key)
child.translate_struct(value) child.translate_struct(value)
@ -902,7 +901,7 @@ class NaElement(object):
child.translate_struct(data_struct[k]) child.translate_struct(data_struct[k])
else: else:
if data_struct[k]: if data_struct[k]:
child.set_content(six.text_type(data_struct[k])) child.set_content(str(data_struct[k]))
self.add_child_elem(child) self.add_child_elem(child)
else: else:
raise ValueError(_('Type cannot be converted into NaElement.')) raise ValueError(_('Type cannot be converted into NaElement.'))
@ -993,7 +992,7 @@ def create_api_request(api_name, query=None, des_result=None,
if additional_elems: if additional_elems:
api_el.translate_struct(additional_elems) api_el.translate_struct(additional_elems)
if is_iter: if is_iter:
api_el.add_new_child('max-records', six.text_type(record_step)) api_el.add_new_child('max-records', str(record_step))
if tag: if tag:
api_el.add_new_child('tag', tag, True) api_el.add_new_child('tag', tag, True)
return api_el return api_el

View File

@ -24,7 +24,6 @@ import time
from oslo_log import log from oslo_log import log
from oslo_utils import strutils from oslo_utils import strutils
from oslo_utils import units from oslo_utils import units
import six
from manila import exception from manila import exception
from manila.i18n import _ from manila.i18n import _
@ -169,7 +168,7 @@ class NetAppCmodeClient(client_base.NetAppBaseClient):
next_tag = next_result.get_child_content('next-tag') next_tag = next_result.get_child_content('next-tag')
result.get_child_by_name('num-records').set_content( result.get_child_by_name('num-records').set_content(
six.text_type(num_records)) str(num_records))
result.get_child_by_name('next-tag').set_content('') result.get_child_by_name('next-tag').set_content('')
return result return result
@ -590,7 +589,7 @@ class NetAppCmodeClient(client_base.NetAppBaseClient):
def sort_key(port): def sort_key(port):
value = port.get('speed') value = port.get('speed')
if not (value and isinstance(value, six.string_types)): if not (value and isinstance(value, str)):
return 0 return 0
elif value.isdigit(): elif value.isdigit():
return int(value) return int(value)
@ -1561,7 +1560,8 @@ class NetAppCmodeClient(client_base.NetAppBaseClient):
if security_service.get('dns_ip'): if security_service.get('dns_ip'):
self.configure_dns(security_service) self.configure_dns(security_service)
config_name = hashlib.md5(six.b(security_service['id'])).hexdigest() config_name = hashlib.md5(
security_service['id'].encode("latin-1")).hexdigest()
api_args = { api_args = {
'ldap-client-config': config_name, 'ldap-client-config': config_name,
'tcp-port': '389', 'tcp-port': '389',
@ -1621,14 +1621,15 @@ class NetAppCmodeClient(client_base.NetAppBaseClient):
@na_utils.trace @na_utils.trace
def _delete_ldap_client(self, security_service): def _delete_ldap_client(self, security_service):
config_name = ( config_name = (
hashlib.md5(six.b(security_service['id'])).hexdigest()) hashlib.md5(security_service['id'].encode("latin-1")).hexdigest())
api_args = {'ldap-client-config': config_name} api_args = {'ldap-client-config': config_name}
self.send_request('ldap-client-delete', api_args) self.send_request('ldap-client-delete', api_args)
@na_utils.trace @na_utils.trace
def configure_ldap(self, security_service, timeout=30): def configure_ldap(self, security_service, timeout=30):
"""Configures LDAP on Vserver.""" """Configures LDAP on Vserver."""
config_name = hashlib.md5(six.b(security_service['id'])).hexdigest() config_name = hashlib.md5(
security_service['id'].encode("latin-1")).hexdigest()
self._create_ldap_client(security_service) self._create_ldap_client(security_service)
self._enable_ldap_client(config_name, timeout=timeout) self._enable_ldap_client(config_name, timeout=timeout)
@ -1655,7 +1656,8 @@ class NetAppCmodeClient(client_base.NetAppBaseClient):
LOG.debug(msg) LOG.debug(msg)
new_config_name = ( new_config_name = (
hashlib.md5(six.b(new_security_service['id'])).hexdigest()) hashlib.md5(
new_security_service['id'].encode("latin-1")).hexdigest())
# Create ldap config with the new client # Create ldap config with the new client
api_args = {'client-config': new_config_name, 'client-enabled': 'true'} api_args = {'client-config': new_config_name, 'client-enabled': 'true'}
self.send_request('ldap-config-create', api_args) self.send_request('ldap-config-create', api_args)
@ -1666,8 +1668,9 @@ class NetAppCmodeClient(client_base.NetAppBaseClient):
except netapp_api.NaApiError as e: except netapp_api.NaApiError as e:
if e.code != netapp_api.EOBJECTNOTFOUND: if e.code != netapp_api.EOBJECTNOTFOUND:
current_config_name = ( current_config_name = (
hashlib.md5(six.b( hashlib.md5(
current_security_service['id'])).hexdigest()) current_security_service['id'].encode(
"latin-1")).hexdigest())
msg = _("An error occurred while deleting original LDAP " msg = _("An error occurred while deleting original LDAP "
"client configuration %(current_config)s. " "client configuration %(current_config)s. "
"Error details: %(e_msg)s") "Error details: %(e_msg)s")
@ -2049,7 +2052,7 @@ class NetAppCmodeClient(client_base.NetAppBaseClient):
api_args = { api_args = {
'containing-aggr-name': aggregate_name, 'containing-aggr-name': aggregate_name,
'size': six.text_type(size_gb) + 'g', 'size': str(size_gb) + 'g',
'volume': volume_name, 'volume': volume_name,
} }
api_args.update(self._get_create_volume_api_args( api_args.update(self._get_create_volume_api_args(
@ -2293,7 +2296,7 @@ class NetAppCmodeClient(client_base.NetAppBaseClient):
'attributes': { 'attributes': {
'volume-attributes': { 'volume-attributes': {
'volume-snapshot-attributes': { 'volume-snapshot-attributes': {
'snapdir-access-enabled': six.text_type( 'snapdir-access-enabled': str(
not hide_snapdir).lower(), not hide_snapdir).lower(),
}, },
}, },
@ -2325,7 +2328,7 @@ class NetAppCmodeClient(client_base.NetAppBaseClient):
'attributes': { 'attributes': {
'volume-attributes': { 'volume-attributes': {
'volume-space-attributes': { 'volume-space-attributes': {
'is-filesys-size-fixed': six.text_type( 'is-filesys-size-fixed': str(
filesys_size_fixed).lower(), filesys_size_fixed).lower(),
}, },
}, },
@ -2477,7 +2480,7 @@ class NetAppCmodeClient(client_base.NetAppBaseClient):
# Value of hide_snapdir needs to be inverted for ZAPI parameter # Value of hide_snapdir needs to be inverted for ZAPI parameter
api_args['attributes']['volume-attributes'][ api_args['attributes']['volume-attributes'][
'volume-snapshot-attributes'][ 'volume-snapshot-attributes'][
'snapdir-access-enabled'] = six.text_type( 'snapdir-access-enabled'] = str(
not hide_snapdir).lower() not hide_snapdir).lower()
self.send_request('volume-modify-iter', api_args) self.send_request('volume-modify-iter', api_args)
@ -3040,7 +3043,7 @@ class NetAppCmodeClient(client_base.NetAppBaseClient):
"""Gets a volume junction path.""" """Gets a volume junction path."""
api_args = { api_args = {
'volume': volume_name, 'volume': volume_name,
'is-style-cifs': six.text_type(is_style_cifs).lower(), 'is-style-cifs': str(is_style_cifs).lower(),
} }
result = self.send_request('volume-get-volume-path', api_args) result = self.send_request('volume-get-volume-path', api_args)
return result.get_child_content('junction') return result.get_child_content('junction')
@ -3070,7 +3073,7 @@ class NetAppCmodeClient(client_base.NetAppBaseClient):
"""Unmounts a volume.""" """Unmounts a volume."""
api_args = { api_args = {
'volume-name': volume_name, 'volume-name': volume_name,
'force': six.text_type(force).lower(), 'force': str(force).lower(),
} }
try: try:
self.send_request('volume-unmount', api_args) self.send_request('volume-unmount', api_args)
@ -3553,7 +3556,7 @@ class NetAppCmodeClient(client_base.NetAppBaseClient):
rule_indices = [int(export_rule_info.get_child_content('rule-index')) rule_indices = [int(export_rule_info.get_child_content('rule-index'))
for export_rule_info in export_rule_info_list] for export_rule_info in export_rule_info_list]
rule_indices.sort() rule_indices.sort()
return [six.text_type(rule_index) for rule_index in rule_indices] return [str(rule_index) for rule_index in rule_indices]
@na_utils.trace @na_utils.trace
def remove_nfs_export_rule(self, policy_name, client_match): def remove_nfs_export_rule(self, policy_name, client_match):
@ -4072,7 +4075,7 @@ class NetAppCmodeClient(client_base.NetAppBaseClient):
'true' if strutils.bool_from_string( 'true' if strutils.bool_from_string(
is_unauthenticated_access_permitted) else 'false') is_unauthenticated_access_permitted) else 'false')
if passphrase_minimum_length is not None: if passphrase_minimum_length is not None:
api_args['passphrase-minlength'] = six.text_type( api_args['passphrase-minlength'] = str(
passphrase_minimum_length) passphrase_minimum_length)
self.send_request('cluster-peer-policy-modify', api_args) self.send_request('cluster-peer-policy-modify', api_args)

View File

@ -32,7 +32,6 @@ from oslo_utils import excutils
from oslo_utils import timeutils from oslo_utils import timeutils
from oslo_utils import units from oslo_utils import units
from oslo_utils import uuidutils from oslo_utils import uuidutils
import six
from manila.common import constants from manila.common import constants
from manila import coordination from manila import coordination
@ -1393,12 +1392,12 @@ class NetAppCmodeFileStorageLibrary(object):
if 'maxiops' in qos_specs: if 'maxiops' in qos_specs:
return '%siops' % qos_specs['maxiops'] return '%siops' % qos_specs['maxiops']
elif 'maxiopspergib' in qos_specs: elif 'maxiopspergib' in qos_specs:
return '%siops' % six.text_type( return '%siops' % str(
int(qos_specs['maxiopspergib']) * int(share_size)) int(qos_specs['maxiopspergib']) * int(share_size))
elif 'maxbps' in qos_specs: elif 'maxbps' in qos_specs:
return '%sB/s' % qos_specs['maxbps'] return '%sB/s' % qos_specs['maxbps']
elif 'maxbpspergib' in qos_specs: elif 'maxbpspergib' in qos_specs:
return '%sB/s' % six.text_type( return '%sB/s' % str(
int(qos_specs['maxbpspergib']) * int(share_size)) int(qos_specs['maxbpspergib']) * int(share_size))
@na_utils.trace @na_utils.trace
@ -1926,7 +1925,7 @@ class NetAppCmodeFileStorageLibrary(object):
self._check_aggregate_extra_specs_validity(pool_name, extra_specs) self._check_aggregate_extra_specs_validity(pool_name, extra_specs)
except exception.ManilaException as ex: except exception.ManilaException as ex:
raise exception.ManageExistingShareTypeMismatch( raise exception.ManageExistingShareTypeMismatch(
reason=six.text_type(ex)) reason=str(ex))
# Ensure volume is manageable. # Ensure volume is manageable.
self._validate_volume_for_manage(volume, vserver_client) self._validate_volume_for_manage(volume, vserver_client)
@ -2428,7 +2427,7 @@ class NetAppCmodeFileStorageLibrary(object):
for aggregate_name in aggregate_names: for aggregate_name in aggregate_names:
aggregate = self._client.get_aggregate(aggregate_name) aggregate = self._client.get_aggregate(aggregate_name)
hybrid = (six.text_type(aggregate.get('is-hybrid')).lower() hybrid = (str(aggregate.get('is-hybrid')).lower()
if 'is-hybrid' in aggregate else None) if 'is-hybrid' in aggregate else None)
disk_types = self._client.get_aggregate_disk_types(aggregate_name) disk_types = self._client.get_aggregate_disk_types(aggregate_name)

View File

@ -15,8 +15,6 @@ Abstract base class for NetApp NAS protocol helper classes.
import abc import abc
import six
from manila.common import constants from manila.common import constants
from manila import utils from manila import utils
@ -38,8 +36,7 @@ def access_rules_synchronized(f):
return wrapped_func return wrapped_func
@six.add_metaclass(abc.ABCMeta) class NetAppBaseHelper(metaclass=abc.ABCMeta):
class NetAppBaseHelper(object):
"""Interface for protocol-specific NAS drivers.""" """Interface for protocol-specific NAS drivers."""
def __init__(self): def __init__(self):

View File

@ -18,7 +18,6 @@ NetApp cDOT NFS protocol helper class.
import uuid import uuid
from oslo_log import log from oslo_log import log
import six
from manila.common import constants from manila.common import constants
from manila import exception from manila import exception
@ -180,7 +179,7 @@ class NetAppCmodeNFSHelper(base.NetAppBaseHelper):
@staticmethod @staticmethod
def _get_temp_export_policy_name(): def _get_temp_export_policy_name():
"""Builds export policy name for an NFS share.""" """Builds export policy name for an NFS share."""
return 'temp_' + six.text_type(uuid.uuid1()).replace('-', '_') return 'temp_' + str(uuid.uuid1()).replace('-', '_')
@staticmethod @staticmethod
def _get_export_policy_name(share): def _get_export_policy_name(share):

View File

@ -23,7 +23,6 @@ import re
from oslo_concurrency import processutils as putils from oslo_concurrency import processutils as putils
from oslo_log import log from oslo_log import log
from oslo_utils import timeutils from oslo_utils import timeutils
import six
from manila import exception from manila import exception
from manila.i18n import _ from manila.i18n import _
@ -79,7 +78,7 @@ def round_down(value, precision='0.00'):
Example: round_down(float(total_space_in_bytes) / units.Gi, '0.01') Example: round_down(float(total_space_in_bytes) / units.Gi, '0.01')
""" """
return float(decimal.Decimal(six.text_type(value)).quantize( return float(decimal.Decimal(str(value)).quantize(
decimal.Decimal(precision), rounding=decimal.ROUND_DOWN)) decimal.Decimal(precision), rounding=decimal.ROUND_DOWN))
@ -120,7 +119,7 @@ def convert_to_list(value):
if value is None: if value is None:
return [] return []
elif isinstance(value, six.string_types): elif isinstance(value, str):
return [value] return [value]
elif isinstance(value, abc.Iterable): elif isinstance(value, abc.Iterable):
return list(value) return list(value)

View File

@ -16,11 +16,11 @@
import hashlib import hashlib
import json import json
import posixpath import posixpath
from urllib import parse as urlparse
from eventlet import greenthread from eventlet import greenthread
from oslo_log import log as logging from oslo_log import log as logging
import requests import requests
import six
from manila import exception from manila import exception
from manila.i18n import _ from manila.i18n import _
@ -44,7 +44,7 @@ class NefException(exception.ManilaException):
kwargs[key] = data[key] kwargs[key] = data[key]
else: else:
kwargs[key] = defaults[key] kwargs[key] = defaults[key]
elif isinstance(data, six.string_types): elif isinstance(data, str):
if 'message' not in kwargs: if 'message' not in kwargs:
kwargs['message'] = data kwargs['message'] = data
for key in defaults: for key in defaults:
@ -329,7 +329,7 @@ class NefCollections(object):
self.proxy = proxy self.proxy = proxy
def path(self, name): def path(self, name):
quoted_name = six.moves.urllib.parse.quote_plus(name) quoted_name = urlparse.quote_plus(name)
return posixpath.join(self.root, quoted_name) return posixpath.join(self.root, quoted_name)
def get(self, name, payload=None): def get(self, name, payload=None):
@ -549,14 +549,14 @@ class NefProxy(object):
prop = self.settings.get('system.guid') prop = self.settings.get('system.guid')
guid = prop.get('value') guid = prop.get('value')
path = '%s:%s' % (guid, self.path) path = '%s:%s' % (guid, self.path)
if isinstance(path, six.text_type): if isinstance(path, str):
path = path.encode('utf-8') path = path.encode('utf-8')
self.lock = hashlib.md5(path).hexdigest() self.lock = hashlib.md5(path).hexdigest()
def url(self, path): def url(self, path):
netloc = '%s:%d' % (self.host, int(self.port)) netloc = '%s:%d' % (self.host, int(self.port))
components = (self.scheme, netloc, str(path), None, None) components = (self.scheme, netloc, str(path), None, None)
url = six.moves.urllib.parse.urlunsplit(components) url = urlparse.urlunsplit(components)
return url return url
def delay(self, attempt): def delay(self, attempt):

View File

@ -14,7 +14,6 @@
# under the License. # under the License.
import re import re
import six
from oslo_utils import units from oslo_utils import units
@ -29,7 +28,7 @@ def str2size(s, scale=1024):
""" """
if not s: if not s:
return 0 return 0
if isinstance(s, six.integer_types): if isinstance(s, int):
return s return s
match = re.match(r'^([\.\d]+)\s*([BbKkMmGgTtPpEeZzYy]?)', s) match = re.match(r'^([\.\d]+)\s*([BbKkMmGgTtPpEeZzYy]?)', s)

View File

@ -17,8 +17,10 @@ API for QNAP Storage.
""" """
import base64 import base64
import functools import functools
from http import client as http_client
import re import re
import ssl import ssl
from urllib import parse as urlparse
try: try:
import xml.etree.cElementTree as ET import xml.etree.cElementTree as ET
@ -26,9 +28,6 @@ except ImportError:
import xml.etree.ElementTree as ET import xml.etree.ElementTree as ET
from oslo_log import log as logging from oslo_log import log as logging
import six
from six.moves import http_client
from six.moves import urllib
from manila import exception from manila import exception
from manila.i18n import _ from manila.i18n import _
@ -50,7 +49,7 @@ def _connection_checker(func):
try: try:
return func(self, *args, **kwargs) return func(self, *args, **kwargs)
except exception.ShareBackendException as e: except exception.ShareBackendException as e:
matches = pattern.match(six.text_type(e)) matches = pattern.match(str(e))
if matches: if matches:
LOG.debug('Session might have expired.' LOG.debug('Session might have expired.'
' Trying to relogin') ' Trying to relogin')
@ -155,7 +154,7 @@ class QnapAPIExecutor(object):
} }
sanitized_params = self._sanitize_params(params) sanitized_params = self._sanitize_params(params)
sanitized_params = urllib.parse.urlencode(sanitized_params) sanitized_params = urlparse.urlencode(sanitized_params)
url = ('/cgi-bin/authLogin.cgi?%s' % sanitized_params) url = ('/cgi-bin/authLogin.cgi?%s' % sanitized_params)
res_details = self._execute_and_get_response_details(self.ip, url) res_details = self._execute_and_get_response_details(self.ip, url)
@ -178,9 +177,9 @@ class QnapAPIExecutor(object):
value = params[key] value = params[key]
if value is not None: if value is not None:
if isinstance(value, list): if isinstance(value, list):
sanitized_params[key] = [six.text_type(v) for v in value] sanitized_params[key] = [str(v) for v in value]
else: else:
sanitized_params[key] = six.text_type(value) sanitized_params[key] = str(value)
return sanitized_params return sanitized_params
@_connection_checker @_connection_checker
@ -193,7 +192,7 @@ class QnapAPIExecutor(object):
'wiz_func': 'share_create', 'wiz_func': 'share_create',
'action': 'add_share', 'action': 'add_share',
'vol_name': create_share_name, 'vol_name': create_share_name,
'vol_size': six.text_type(share['size']) + 'GB', 'vol_size': str(share['size']) + 'GB',
'threshold': '80', 'threshold': '80',
'dedup': ('sha512' 'dedup': ('sha512'
if kwargs['qnap_deduplication'] is True if kwargs['qnap_deduplication'] is True
@ -222,7 +221,7 @@ class QnapAPIExecutor(object):
} }
sanitized_params = self._sanitize_params(params) sanitized_params = self._sanitize_params(params)
sanitized_params = urllib.parse.urlencode(sanitized_params) sanitized_params = urlparse.urlencode(sanitized_params)
url = ('/cgi-bin/wizReq.cgi?%s' % sanitized_params) url = ('/cgi-bin/wizReq.cgi?%s' % sanitized_params)
res_details = self._execute_and_get_response_details(self.ip, url) res_details = self._execute_and_get_response_details(self.ip, url)
@ -259,7 +258,7 @@ class QnapAPIExecutor(object):
} }
sanitized_params = self._sanitize_params(params) sanitized_params = self._sanitize_params(params)
sanitized_params = urllib.parse.urlencode(sanitized_params) sanitized_params = urlparse.urlencode(sanitized_params)
url = ('/cgi-bin/disk/disk_manage.cgi?%s' % sanitized_params) url = ('/cgi-bin/disk/disk_manage.cgi?%s' % sanitized_params)
res_details = self._execute_and_get_response_details(self.ip, url) res_details = self._execute_and_get_response_details(self.ip, url)
@ -283,7 +282,7 @@ class QnapAPIExecutor(object):
} }
sanitized_params = self._sanitize_params(params) sanitized_params = self._sanitize_params(params)
sanitized_params = urllib.parse.urlencode(sanitized_params) sanitized_params = urlparse.urlencode(sanitized_params)
url = ('/cgi-bin/disk/disk_manage.cgi?%s' % sanitized_params) url = ('/cgi-bin/disk/disk_manage.cgi?%s' % sanitized_params)
res_details = self._execute_and_get_response_details(self.ip, url) res_details = self._execute_and_get_response_details(self.ip, url)
@ -318,7 +317,7 @@ class QnapAPIExecutor(object):
} }
sanitized_params = self._sanitize_params(params) sanitized_params = self._sanitize_params(params)
sanitized_params = urllib.parse.urlencode(sanitized_params) sanitized_params = urlparse.urlencode(sanitized_params)
url = ('/cgi-bin/disk/disk_manage.cgi?%s' % sanitized_params) url = ('/cgi-bin/disk/disk_manage.cgi?%s' % sanitized_params)
res_details = self._execute_and_get_response_details(self.ip, url) res_details = self._execute_and_get_response_details(self.ip, url)
@ -355,7 +354,7 @@ class QnapAPIExecutor(object):
} }
sanitized_params = self._sanitize_params(params) sanitized_params = self._sanitize_params(params)
sanitized_params = urllib.parse.urlencode(sanitized_params) sanitized_params = urlparse.urlencode(sanitized_params)
url = ('/cgi-bin/disk/disk_manage.cgi?%s' % sanitized_params) url = ('/cgi-bin/disk/disk_manage.cgi?%s' % sanitized_params)
res_details = self._execute_and_get_response_details(self.ip, url) res_details = self._execute_and_get_response_details(self.ip, url)
@ -383,7 +382,7 @@ class QnapAPIExecutor(object):
} }
sanitized_params = self._sanitize_params(params) sanitized_params = self._sanitize_params(params)
sanitized_params = urllib.parse.urlencode(sanitized_params) sanitized_params = urlparse.urlencode(sanitized_params)
url = ('/cgi-bin/disk/snapshot.cgi?%s' % sanitized_params) url = ('/cgi-bin/disk/snapshot.cgi?%s' % sanitized_params)
res_details = self._execute_and_get_response_details(self.ip, url) res_details = self._execute_and_get_response_details(self.ip, url)
@ -425,7 +424,7 @@ class QnapAPIExecutor(object):
} }
sanitized_params = self._sanitize_params(params) sanitized_params = self._sanitize_params(params)
sanitized_params = urllib.parse.urlencode(sanitized_params) sanitized_params = urlparse.urlencode(sanitized_params)
url = ('/cgi-bin/disk/snapshot.cgi?%s' % sanitized_params) url = ('/cgi-bin/disk/snapshot.cgi?%s' % sanitized_params)
res_details = self._execute_and_get_response_details(self.ip, url) res_details = self._execute_and_get_response_details(self.ip, url)
@ -447,7 +446,7 @@ class QnapAPIExecutor(object):
} }
sanitized_params = self._sanitize_params(params) sanitized_params = self._sanitize_params(params)
sanitized_params = urllib.parse.urlencode(sanitized_params) sanitized_params = urlparse.urlencode(sanitized_params)
url = ('/cgi-bin/disk/snapshot.cgi?%s' % sanitized_params) url = ('/cgi-bin/disk/snapshot.cgi?%s' % sanitized_params)
res_details = self._execute_and_get_response_details(self.ip, url) res_details = self._execute_and_get_response_details(self.ip, url)
@ -479,7 +478,7 @@ class QnapAPIExecutor(object):
} }
sanitized_params = self._sanitize_params(params) sanitized_params = self._sanitize_params(params)
sanitized_params = urllib.parse.urlencode(sanitized_params) sanitized_params = urlparse.urlencode(sanitized_params)
url = ('/cgi-bin/disk/snapshot.cgi?%s' % sanitized_params) url = ('/cgi-bin/disk/snapshot.cgi?%s' % sanitized_params)
res_details = self._execute_and_get_response_details(self.ip, url) res_details = self._execute_and_get_response_details(self.ip, url)
@ -516,10 +515,10 @@ class QnapAPIExecutor(object):
'sid': self.sid, 'sid': self.sid,
} }
if share_dict.get('new_size'): if share_dict.get('new_size'):
params['vol_size'] = six.text_type(share_dict['new_size']) + 'GB' params['vol_size'] = str(share_dict['new_size']) + 'GB'
sanitized_params = self._sanitize_params(params) sanitized_params = self._sanitize_params(params)
sanitized_params = urllib.parse.urlencode(sanitized_params) sanitized_params = urlparse.urlencode(sanitized_params)
url = ('/cgi-bin/priv/privWizard.cgi?%s' % sanitized_params) url = ('/cgi-bin/priv/privWizard.cgi?%s' % sanitized_params)
res_details = self._execute_and_get_response_details(self.ip, url) res_details = self._execute_and_get_response_details(self.ip, url)
@ -541,7 +540,7 @@ class QnapAPIExecutor(object):
} }
sanitized_params = self._sanitize_params(params) sanitized_params = self._sanitize_params(params)
sanitized_params = urllib.parse.urlencode(sanitized_params) sanitized_params = urlparse.urlencode(sanitized_params)
url = ('/cgi-bin/accessrights/accessrightsRequest.cgi?%s' % url = ('/cgi-bin/accessrights/accessrightsRequest.cgi?%s' %
sanitized_params) sanitized_params)
@ -577,7 +576,7 @@ class QnapAPIExecutor(object):
} }
sanitized_params = self._sanitize_params(params) sanitized_params = self._sanitize_params(params)
sanitized_params = urllib.parse.urlencode(sanitized_params) sanitized_params = urlparse.urlencode(sanitized_params)
url = ('/cgi-bin/accessrights/accessrightsRequest.cgi?%s' % url = ('/cgi-bin/accessrights/accessrightsRequest.cgi?%s' %
sanitized_params) sanitized_params)
@ -601,7 +600,7 @@ class QnapAPIExecutor(object):
sanitized_params = self._sanitize_params(params) sanitized_params = self._sanitize_params(params)
# urlencode with True parameter to parse ipv4_list # urlencode with True parameter to parse ipv4_list
sanitized_params = urllib.parse.urlencode(sanitized_params, True) sanitized_params = urlparse.urlencode(sanitized_params, True)
url = ('/cgi-bin/accessrights/accessrightsRequest.cgi?%s' % url = ('/cgi-bin/accessrights/accessrightsRequest.cgi?%s' %
sanitized_params) sanitized_params)
@ -623,7 +622,7 @@ class QnapAPIExecutor(object):
} }
sanitized_params = self._sanitize_params(params) sanitized_params = self._sanitize_params(params)
sanitized_params = urllib.parse.urlencode(sanitized_params) sanitized_params = urlparse.urlencode(sanitized_params)
url = ('/cgi-bin/accessrights/accessrightsRequest.cgi?%s' % url = ('/cgi-bin/accessrights/accessrightsRequest.cgi?%s' %
sanitized_params) sanitized_params)
@ -647,7 +646,7 @@ class QnapAPIExecutor(object):
} }
sanitized_params = self._sanitize_params(params) sanitized_params = self._sanitize_params(params)
sanitized_params = urllib.parse.urlencode(sanitized_params) sanitized_params = urlparse.urlencode(sanitized_params)
url = ('/cgi-bin/priv/privWizard.cgi?%s' % sanitized_params) url = ('/cgi-bin/priv/privWizard.cgi?%s' % sanitized_params)
res_details = self._execute_and_get_response_details(self.ip, url) res_details = self._execute_and_get_response_details(self.ip, url)
@ -678,7 +677,7 @@ class QnapAPIExecutorTS(QnapAPIExecutor):
} }
sanitized_params = self._sanitize_params(params) sanitized_params = self._sanitize_params(params)
sanitized_params = urllib.parse.urlencode(sanitized_params) sanitized_params = urlparse.urlencode(sanitized_params)
url = ('/cgi-bin/disk/snapshot.cgi?%s' % sanitized_params) url = ('/cgi-bin/disk/snapshot.cgi?%s' % sanitized_params)
res_details = self._execute_and_get_response_details(self.ip, url) res_details = self._execute_and_get_response_details(self.ip, url)

View File

@ -21,11 +21,10 @@ Control Quobyte over its JSON RPC API.
import requests import requests
from requests import auth from requests import auth
from requests import codes from requests import codes
from urllib import parse as urlparse
from oslo_log import log from oslo_log import log
from oslo_serialization import jsonutils from oslo_serialization import jsonutils
import six
import six.moves.urllib.parse as urlparse
from manila import exception from manila import exception
from manila import utils from manila import utils
@ -71,7 +70,7 @@ class JsonRpc(object):
'jsonrpc': '2.0', 'jsonrpc': '2.0',
'method': method_name, 'method': method_name,
'params': parameters, 'params': parameters,
'id': six.text_type(self._id), 'id': str(self._id),
} }
LOG.debug("Request payload to be send is: %s", LOG.debug("Request payload to be send is: %s",
jsonutils.dumps(post_data)) jsonutils.dumps(post_data))
@ -118,5 +117,5 @@ class JsonRpc(object):
result=result["error"]["message"], result=result["error"]["message"],
qbcode=result["error"]["code"]) qbcode=result["error"]["code"])
else: else:
raise exception.QBException(six.text_type(result["error"])) raise exception.QBException(str(result["error"]))
return result["result"] return result["result"]

View File

@ -25,7 +25,6 @@ import math
from oslo_config import cfg from oslo_config import cfg
from oslo_log import log from oslo_log import log
from oslo_utils import units from oslo_utils import units
import six
from manila.common import constants from manila.common import constants
from manila import exception from manila import exception
@ -404,12 +403,12 @@ class QuobyteShareDriver(driver.ExecuteMixin, driver.ShareDriver,):
existing_rules) existing_rules)
for a_rule in missing_rules: for a_rule in missing_rules:
LOG.debug("Adding rule %s in recovery.", LOG.debug("Adding rule %s in recovery.",
six.text_type(a_rule)) str(a_rule))
self._allow_access(context, share, a_rule) self._allow_access(context, share, a_rule)
superfluous_rules = self._subtract_access_lists(existing_rules, superfluous_rules = self._subtract_access_lists(existing_rules,
access_rules) access_rules)
for d_rule in superfluous_rules: for d_rule in superfluous_rules:
LOG.debug("Removing rule %s in recovery.", LOG.debug("Removing rule %s in recovery.",
six.text_type(d_rule)) str(d_rule))
self._deny_access(context, share, d_rule) self._deny_access(context, share, d_rule)

View File

@ -18,7 +18,6 @@ Share driver for Tegile storage.
import json import json
import requests import requests
import six
from oslo_config import cfg from oslo_config import cfg
from oslo_log import log from oslo_log import log
@ -232,7 +231,7 @@ class TegileShareDriver(driver.ShareDriver):
TEGILE_LOCAL_CONTAINER_NAME, TEGILE_LOCAL_CONTAINER_NAME,
project, project,
share_name), share_name),
six.text_type(new_size), str(new_size),
'GB') 'GB')
self._api('resizeShare', params) self._api('resizeShare', params)

View File

@ -20,6 +20,7 @@ Limitation:
""" """
import hashlib import hashlib
from http import client as http_client
import json import json
from oslo_config import cfg from oslo_config import cfg
@ -28,8 +29,6 @@ from oslo_utils import units
from random import shuffle from random import shuffle
import requests import requests
import requests.auth import requests.auth
import six
from six.moves import http_client
from manila.common import constants as const from manila.common import constants as const
from manila import exception from manila import exception
@ -257,7 +256,7 @@ class ACCESSShareDriver(driver.ExecuteMixin, driver.ShareDriver):
if ips['type'] == 'Virtual' and ips['status'] == 'ONLINE': if ips['type'] == 'Virtual' and ips['status'] == 'ONLINE':
vip.append(ips['ip']) vip.append(ips['ip'])
shuffle(vip) shuffle(vip)
return six.text_type(vip[0]) return str(vip[0])
def delete_share(self, context, share, share_server=None): def delete_share(self, context, share, share_server=None):
"""Delete a share from ACCESS.""" """Delete a share from ACCESS."""
@ -297,7 +296,7 @@ class ACCESSShareDriver(driver.ExecuteMixin, driver.ShareDriver):
def extend_share(self, share, new_size, share_server=None): def extend_share(self, share, new_size, share_server=None):
"""Extend existing share to new size.""" """Extend existing share to new size."""
sharename = share['name'] sharename = share['name']
size = '%s%s' % (six.text_type(new_size), 'g') size = '%s%s' % (str(new_size), 'g')
va_sharename = self._get_va_share_name(sharename) va_sharename = self._get_va_share_name(sharename)
path = self._fs_extend_str path = self._fs_extend_str
provider = '%s:%s' % (self.host, self._port) provider = '%s:%s' % (self.host, self._port)
@ -318,7 +317,7 @@ class ACCESSShareDriver(driver.ExecuteMixin, driver.ShareDriver):
"""Shrink existing share to new size.""" """Shrink existing share to new size."""
sharename = share['name'] sharename = share['name']
va_sharename = self._get_va_share_name(sharename) va_sharename = self._get_va_share_name(sharename)
size = '%s%s' % (six.text_type(new_size), 'g') size = '%s%s' % (str(new_size), 'g')
path = self._fs_extend_str path = self._fs_extend_str
provider = '%s:%s' % (self.host, self._port) provider = '%s:%s' % (self.host, self._port)
data1 = {"operationOption": "shrinkto", "tier": "primary"} data1 = {"operationOption": "shrinkto", "tier": "primary"}
@ -346,8 +345,8 @@ class ACCESSShareDriver(driver.ExecuteMixin, driver.ShareDriver):
if access_level not in (const.ACCESS_LEVEL_RW, const.ACCESS_LEVEL_RO): if access_level not in (const.ACCESS_LEVEL_RW, const.ACCESS_LEVEL_RO):
raise exception.InvalidShareAccessLevel(level=access_level) raise exception.InvalidShareAccessLevel(level=access_level)
export_path = share['export_locations'][0]['path'].split(':', 1) export_path = share['export_locations'][0]['path'].split(':', 1)
va_sharepath = six.text_type(export_path[1]) va_sharepath = str(export_path[1])
access_level = '%s,%s' % (six.text_type(access_level), access_level = '%s,%s' % (str(access_level),
'sync,no_root_squash') 'sync,no_root_squash')
path = self._nfs_add_str path = self._nfs_add_str
@ -390,7 +389,7 @@ class ACCESSShareDriver(driver.ExecuteMixin, driver.ShareDriver):
if access_type != 'ip': if access_type != 'ip':
return return
export_path = share['export_locations'][0]['path'].split(':', 1) export_path = share['export_locations'][0]['path'].split(':', 1)
va_sharepath = six.text_type(export_path[1]) va_sharepath = str(export_path[1])
LOG.debug("ACCESSShareDriver deny_access sharepath %s server %s", LOG.debug("ACCESSShareDriver deny_access sharepath %s server %s",
va_sharepath, server) va_sharepath, server)
@ -444,14 +443,14 @@ class ACCESSShareDriver(driver.ExecuteMixin, driver.ShareDriver):
access_rules) access_rules)
for rule in d_rule: for rule in d_rule:
LOG.debug("Removing rule %s in recovery.", LOG.debug("Removing rule %s in recovery.",
six.text_type(rule)) str(rule))
self._deny_access(context, share, rule, share_server) self._deny_access(context, share, rule, share_server)
a_rule = self._return_access_lists_difference(access_rules, a_rule = self._return_access_lists_difference(access_rules,
existing_a_rules) existing_a_rules)
for rule in a_rule: for rule in a_rule:
LOG.debug("Adding rule %s in recovery.", LOG.debug("Adding rule %s in recovery.",
six.text_type(rule)) str(rule))
self._allow_access(context, share, rule, share_server) self._allow_access(context, share, rule, share_server)
def create_snapshot(self, context, snapshot, share_server=None): def create_snapshot(self, context, snapshot, share_server=None):
@ -597,7 +596,7 @@ class ACCESSShareDriver(driver.ExecuteMixin, driver.ShareDriver):
json.dumps(data), 'GET') json.dumps(data), 'GET')
for pool in pool_details: for pool in pool_details:
if pool['device_group_name'] == six.text_type(self._pool): if pool['device_group_name'] == str(self._pool):
total_capacity = (int(pool['capacity']) / units.Gi) total_capacity = (int(pool['capacity']) / units.Gi)
used_size = (int(pool['used_size']) / units.Gi) used_size = (int(pool['used_size']) / units.Gi)
return (total_capacity, (total_capacity - used_size)) return (total_capacity, (total_capacity - used_size))
@ -610,7 +609,7 @@ class ACCESSShareDriver(driver.ExecuteMixin, driver.ShareDriver):
"""Retrieve status info from share volume group.""" """Retrieve status info from share volume group."""
LOG.debug("VRTSISA Updating share status.") LOG.debug("VRTSISA Updating share status.")
self.host = six.text_type(self._va_ip) self.host = str(self._va_ip)
self.session = self._authenticate_access(self._va_ip, self.session = self._authenticate_access(self._va_ip,
self._user, self._pwd) self._user, self._pwd)
total_capacity, free_capacity = self._get_access_pool_details() total_capacity, free_capacity = self._get_access_pool_details()

View File

@ -20,7 +20,6 @@ from oslo_config import cfg
from oslo_log import log from oslo_log import log
from oslo_utils import importutils from oslo_utils import importutils
from oslo_utils import strutils from oslo_utils import strutils
import six
from manila import exception from manila import exception
from manila.i18n import _ from manila.i18n import _
@ -120,7 +119,7 @@ class WinRMHelper(object):
def _parse_command(self, command): def _parse_command(self, command):
if isinstance(command, list) or isinstance(command, tuple): if isinstance(command, list) or isinstance(command, tuple):
command = " ".join([six.text_type(c) for c in command]) command = " ".join([str(c) for c in command])
sanitized_cmd = strutils.mask_password(command) sanitized_cmd = strutils.mask_password(command)

View File

@ -24,7 +24,6 @@ Module for storing ZFSonLinux driver utility stuff such as:
import abc import abc
from oslo_log import log from oslo_log import log
import six
from manila.common import constants from manila.common import constants
from manila import exception from manila import exception
@ -151,8 +150,7 @@ class ExecuteMixin(driver.ExecuteMixin):
return self.execute_with_retry('sudo', 'zfs', *cmd, **kwargs) return self.execute_with_retry('sudo', 'zfs', *cmd, **kwargs)
@six.add_metaclass(abc.ABCMeta) class NASHelperBase(metaclass=abc.ABCMeta):
class NASHelperBase(object):
"""Base class for share helpers of 'ZFS on Linux' driver.""" """Base class for share helpers of 'ZFS on Linux' driver."""
def __init__(self, configuration): def __init__(self, configuration):

View File

@ -18,13 +18,13 @@ TODO(diemtran): this module needs to be placed in a library common to OpenStack
base and imported from the relevant library. base and imported from the relevant library.
""" """
from http import client as http_client
import io
import time import time
from urllib import error as urlerror
from urllib import request as urlrequest
from oslo_serialization import jsonutils from oslo_serialization import jsonutils
import six
from six.moves import http_client
from six.moves.urllib import error as urlerror
from six.moves.urllib import request as urlrequest
def log_debug_msg(obj, message): def log_debug_msg(obj, message):
@ -232,7 +232,7 @@ class RestClientURL(object): # pylint: disable=R0902
:cmd_params args: The path part. :cmd_params args: The path part.
:cmd_params kwargs: The query part. :cmd_params kwargs: The query part.
""" """
buf = six.StringIO() buf = io.StringIO()
query = "?" query = "?"
for arg in args: for arg in args:
buf.write("/") buf.write("/")
@ -263,7 +263,7 @@ class RestClientURL(object): # pylint: disable=R0902
if body: if body:
if isinstance(body, dict): if isinstance(body, dict):
body = six.text_type(jsonutils.dumps(body)) body = str(jsonutils.dumps(body))
if body and len(body): if body and len(body):
out_hdrs['content-length'] = len(body) out_hdrs['content-length'] = len(body)

View File

@ -20,7 +20,6 @@ import math
from oslo_config import cfg from oslo_config import cfg
from oslo_log import log from oslo_log import log
from oslo_utils import units from oslo_utils import units
import six
from manila import exception from manila import exception
from manila.i18n import _ from manila.i18n import _
@ -138,7 +137,7 @@ class ZFSSAShareDriver(driver.ShareDriver):
self.zfssa = factory_zfssa() self.zfssa = factory_zfssa()
self.zfssa.set_host(lcfg.zfssa_host, timeout=lcfg.zfssa_rest_timeout) self.zfssa.set_host(lcfg.zfssa_host, timeout=lcfg.zfssa_rest_timeout)
creds = '%s:%s' % (lcfg.zfssa_auth_user, lcfg.zfssa_auth_password) creds = '%s:%s' % (lcfg.zfssa_auth_user, lcfg.zfssa_auth_password)
auth_str = base64.encodebytes(six.b(creds))[:-1] auth_str = base64.encodebytes(creds.encode("latin-1"))[:-1]
self.zfssa.login(auth_str) self.zfssa.login(auth_str)
if lcfg.zfssa_nas_mountpoint == '': if lcfg.zfssa_nas_mountpoint == '':
self.mountpoint += lcfg.zfssa_project self.mountpoint += lcfg.zfssa_project

View File

@ -14,11 +14,11 @@
# under the License. # under the License.
from unittest import mock from unittest import mock
from urllib import error as url_error
from urllib import request as url_request
from eventlet import greenthread from eventlet import greenthread
from oslo_concurrency import processutils from oslo_concurrency import processutils
from six.moves.urllib import error as url_error
from six.moves.urllib import request as url_request
from manila import exception from manila import exception
from manila.share import configuration as conf from manila.share import configuration as conf

View File

@ -17,7 +17,6 @@ import doctest
from unittest import mock from unittest import mock
from lxml import doctestcompare from lxml import doctestcompare
import six
CHECKER = doctestcompare.LXMLOutputChecker() CHECKER = doctestcompare.LXMLOutputChecker()
@ -92,10 +91,10 @@ class EMCMock(mock.Mock):
except StopIteration: except StopIteration:
return True return True
if not isinstance(expect, six.binary_type): if not isinstance(expect, bytes):
expect = six.b(expect) expect = expect.encode("latin-1")
if not isinstance(actual, six.binary_type): if not isinstance(actual, bytes):
actual = six.b(actual) actual = actual.encode("latin-1")
if not CHECKER.check_output(expect, actual, PARSE_XML): if not CHECKER.check_output(expect, actual, PARSE_XML):
raise AssertionError( raise AssertionError(
'Mismatch error.\nExpected: %r\n' 'Mismatch error.\nExpected: %r\n'

View File

@ -19,7 +19,6 @@ import ddt
from oslo_log import log from oslo_log import log
from oslo_utils import units from oslo_utils import units
from requests.exceptions import HTTPError from requests.exceptions import HTTPError
import six
from manila.common import constants as const from manila.common import constants as const
from manila import exception from manila import exception
@ -117,7 +116,7 @@ class IsilonTest(test.TestCase):
# verify expected REST API call is executed # verify expected REST API call is executed
expected_url = (self.API_URL + '/platform/1/protocols/nfs/exports/' + expected_url = (self.API_URL + '/platform/1/protocols/nfs/exports/' +
six.text_type(fake_export_id)) str(fake_export_id))
expected_data = {'read_only_clients': ['10.1.1.10']} expected_data = {'read_only_clients': ['10.1.1.10']}
self._mock_isilon_api.request.assert_called_once_with( self._mock_isilon_api.request.assert_called_once_with(
'PUT', expected_url, data=expected_data) 'PUT', expected_url, data=expected_data)
@ -138,7 +137,7 @@ class IsilonTest(test.TestCase):
# verify expected REST API call is executed # verify expected REST API call is executed
expected_url = (self.API_URL + '/platform/1/protocols/nfs/exports/' + expected_url = (self.API_URL + '/platform/1/protocols/nfs/exports/' +
six.text_type(fake_export_id)) str(fake_export_id))
expected_data = {'clients': ['10.1.1.10']} expected_data = {'clients': ['10.1.1.10']}
self._mock_isilon_api.request.assert_called_once_with( self._mock_isilon_api.request.assert_called_once_with(
'PUT', expected_url, data=expected_data) 'PUT', expected_url, data=expected_data)
@ -200,7 +199,7 @@ class IsilonTest(test.TestCase):
# verify that a call is made to remove an existing IP from the list # verify that a call is made to remove an existing IP from the list
expected_url = (self.API_URL + '/platform/1/protocols/nfs/exports/' + expected_url = (self.API_URL + '/platform/1/protocols/nfs/exports/' +
six.text_type(fake_export_id)) str(fake_export_id))
expected_data = {'read_only_clients': []} expected_data = {'read_only_clients': []}
self._mock_isilon_api.request.assert_called_once_with( self._mock_isilon_api.request.assert_called_once_with(
'PUT', expected_url, data=expected_data 'PUT', expected_url, data=expected_data
@ -860,7 +859,7 @@ class IsilonTest(test.TestCase):
self.mock_context, share, access_rules, [], delete_rules) self.mock_context, share, access_rules, [], delete_rules)
expected_url = (self.API_URL + '/platform/1/protocols/nfs/exports/' + expected_url = (self.API_URL + '/platform/1/protocols/nfs/exports/' +
six.text_type(fake_export_id)) str(fake_export_id))
expected_data = {'clients': [], 'read_only_clients': []} expected_data = {'clients': [], 'read_only_clients': []}
self._mock_isilon_api.request.assert_called_once_with( self._mock_isilon_api.request.assert_called_once_with(
'PUT', expected_url, data=expected_data) 'PUT', expected_url, data=expected_data)
@ -1061,7 +1060,7 @@ class IsilonTest(test.TestCase):
self.mock_context, share, access_rules, [], []) self.mock_context, share, access_rules, [], [])
expected_url = (self.API_URL + '/platform/1/protocols/nfs/exports/' + expected_url = (self.API_URL + '/platform/1/protocols/nfs/exports/' +
six.text_type(fake_export_id)) str(fake_export_id))
expected_data = { expected_data = {
'clients': ['10.1.1.10'], 'clients': ['10.1.1.10'],
'read_only_clients': ['10.1.1.2'] 'read_only_clients': ['10.1.1.2']

View File

@ -17,7 +17,6 @@ import ddt
from oslo_serialization import jsonutils as json from oslo_serialization import jsonutils as json
import requests import requests
import requests_mock import requests_mock
import six
from manila import exception from manila import exception
from manila.share.drivers.dell_emc.plugins.isilon import isilon_api from manila.share.drivers.dell_emc.plugins.isilon import isilon_api
@ -407,7 +406,7 @@ class IsilonApiTest(test.TestCase):
self.assertEqual(0, len(m.request_history)) self.assertEqual(0, len(m.request_history))
fq_path = '/ifs/home/admin/test' fq_path = '/ifs/home/admin/test'
m.delete(self._mock_url + '/namespace' + fq_path + '?recursive=' m.delete(self._mock_url + '/namespace' + fq_path + '?recursive='
+ six.text_type(is_recursive_delete), status_code=204) + str(is_recursive_delete), status_code=204)
self.isilon_api.delete(fq_path, recursive=is_recursive_delete) self.isilon_api.delete(fq_path, recursive=is_recursive_delete)
@ -593,12 +592,12 @@ class IsilonApiTest(test.TestCase):
# verify a call is made to create a quota # verify a call is made to create a quota
expected_create_json = { expected_create_json = {
six.text_type('path'): quota_path, str('path'): quota_path,
six.text_type('type'): 'directory', str('type'): 'directory',
six.text_type('include_snapshots'): False, str('include_snapshots'): False,
six.text_type('thresholds_include_overhead'): False, str('thresholds_include_overhead'): False,
six.text_type('enforced'): True, str('enforced'): True,
six.text_type('thresholds'): {six.text_type('hard'): quota_size}, str('thresholds'): {str('hard'): quota_size},
} }
create_request_json = json.loads(m.request_history[1].body) create_request_json = json.loads(m.request_history[1].body)
self.assertEqual(expected_create_json, create_request_json) self.assertEqual(expected_create_json, create_request_json)
@ -827,7 +826,7 @@ class IsilonApiTest(test.TestCase):
def _add_create_directory_response(self, m, path, is_recursive): def _add_create_directory_response(self, m, path, is_recursive):
url = '{0}/namespace{1}?recursive={2}'.format( url = '{0}/namespace{1}?recursive={2}'.format(
self._mock_url, path, six.text_type(is_recursive)) self._mock_url, path, str(is_recursive))
m.put(url, status_code=200) m.put(url, status_code=200)
def _add_file_clone_response(self, m, fq_dest_path, snapshot_name): def _add_file_clone_response(self, m, fq_dest_path, snapshot_name):
@ -850,7 +849,7 @@ class IsilonApiTest(test.TestCase):
def _verify_dir_creation_request(self, request, path, is_recursive): def _verify_dir_creation_request(self, request, path, is_recursive):
self.assertEqual('PUT', request.method) self.assertEqual('PUT', request.method)
expected_url = '{0}/namespace{1}?recursive={2}'.format( expected_url = '{0}/namespace{1}?recursive={2}'.format(
self._mock_url, path, six.text_type(is_recursive)) self._mock_url, path, str(is_recursive))
self.assertEqual(expected_url, request.url) self.assertEqual(expected_url, request.url)
self.assertIn("x-isi-ifs-target-type", request.headers) self.assertIn("x-isi-ifs-target-type", request.headers)
self.assertEqual("container", self.assertEqual("container",

View File

@ -15,7 +15,6 @@
import copy import copy
import ddt import ddt
import six
from manila import exception from manila import exception
from manila.share.drivers.dell_emc.common.enas import utils as enas_utils from manila.share.drivers.dell_emc.common.enas import utils as enas_utils
@ -643,9 +642,9 @@ class TestConnection(test.TestCase):
@res_mock.patch_connection @res_mock.patch_connection
def test_get_proto_enum(self, connection): def test_get_proto_enum(self, connection):
self.assertIn('FSSupportedProtocolEnum.CIFS', self.assertIn('FSSupportedProtocolEnum.CIFS',
six.text_type(connection._get_proto_enum('CIFS'))) str(connection._get_proto_enum('CIFS')))
self.assertIn('FSSupportedProtocolEnum.NFS', self.assertIn('FSSupportedProtocolEnum.NFS',
six.text_type(connection._get_proto_enum('nfs'))) str(connection._get_proto_enum('nfs')))
@res_mock.mock_manila_input @res_mock.mock_manila_input
@res_mock.patch_connection @res_mock.patch_connection

View File

@ -19,7 +19,6 @@ from unittest import mock
from oslo_concurrency import processutils from oslo_concurrency import processutils
from oslo_config import cfg from oslo_config import cfg
import six
from manila import context from manila import context
from manila import exception from manila import exception
@ -92,7 +91,7 @@ class HDFSNativeShareDriverTestCase(test.TestCase):
def test__set_share_size(self): def test__set_share_size(self):
share_dir = '/' + self.share['name'] share_dir = '/' + self.share['name']
sizestr = six.text_type(self.share['size']) + 'g' sizestr = str(self.share['size']) + 'g'
self._driver._hdfs_execute = mock.Mock(return_value=True) self._driver._hdfs_execute = mock.Mock(return_value=True)
self._driver._set_share_size(self.share) self._driver._set_share_size(self.share)
self._driver._hdfs_execute.assert_called_once_with( self._driver._hdfs_execute.assert_called_once_with(
@ -100,7 +99,7 @@ class HDFSNativeShareDriverTestCase(test.TestCase):
def test__set_share_size_exception(self): def test__set_share_size_exception(self):
share_dir = '/' + self.share['name'] share_dir = '/' + self.share['name']
sizestr = six.text_type(self.share['size']) + 'g' sizestr = str(self.share['size']) + 'g'
self._driver._hdfs_execute = mock.Mock( self._driver._hdfs_execute = mock.Mock(
side_effect=exception.ProcessExecutionError) side_effect=exception.ProcessExecutionError)
self.assertRaises(exception.HDFSException, self.assertRaises(exception.HDFSException,

View File

@ -20,7 +20,6 @@ import ddt
from oslo_concurrency import processutils as putils from oslo_concurrency import processutils as putils
from oslo_config import cfg from oslo_config import cfg
import paramiko import paramiko
import six
from manila import exception from manila import exception
from manila.share.drivers.hitachi.hnas import ssh from manila.share.drivers.hitachi.hnas import ssh
@ -1521,7 +1520,7 @@ class HNASSSHTestCase(test.TestCase):
def test__locked_selectfs_create_operation(self): def test__locked_selectfs_create_operation(self):
exec_command = ['selectfs', self.fs_name, '\n', 'ssc', '127.0.0.1', exec_command = ['selectfs', self.fs_name, '\n', 'ssc', '127.0.0.1',
'console-context', '--evs', six.text_type(self.evs_id), 'console-context', '--evs', str(self.evs_id),
'mkdir', '-p', '/path'] 'mkdir', '-p', '/path']
self.mock_object(ssh.HNASSSHBackend, '_execute') self.mock_object(ssh.HNASSSHBackend, '_execute')
@ -1531,7 +1530,7 @@ class HNASSSHTestCase(test.TestCase):
def test__locked_selectfs_create_operation_error(self): def test__locked_selectfs_create_operation_error(self):
exec_command = ['selectfs', self.fs_name, '\n', 'ssc', '127.0.0.1', exec_command = ['selectfs', self.fs_name, '\n', 'ssc', '127.0.0.1',
'console-context', '--evs', six.text_type(self.evs_id), 'console-context', '--evs', str(self.evs_id),
'mkdir', '-p', '/path'] 'mkdir', '-p', '/path']
self.mock_object( self.mock_object(
ssh.HNASSSHBackend, '_execute', ssh.HNASSSHBackend, '_execute',
@ -1545,7 +1544,7 @@ class HNASSSHTestCase(test.TestCase):
def test__locked_selectfs_create_operation_context_change(self): def test__locked_selectfs_create_operation_context_change(self):
exec_command = ['selectfs', self.fs_name, '\n', 'ssc', '127.0.0.1', exec_command = ['selectfs', self.fs_name, '\n', 'ssc', '127.0.0.1',
'console-context', '--evs', six.text_type(self.evs_id), 'console-context', '--evs', str(self.evs_id),
'mkdir', '-p', '/path'] 'mkdir', '-p', '/path']
self.mock_object( self.mock_object(
ssh.HNASSSHBackend, '_execute', ssh.HNASSSHBackend, '_execute',
@ -1560,7 +1559,7 @@ class HNASSSHTestCase(test.TestCase):
def test__locked_selectfs_delete_operation_successful(self): def test__locked_selectfs_delete_operation_successful(self):
exec_command = ['selectfs', self.fs_name, '\n', 'ssc', '127.0.0.1', exec_command = ['selectfs', self.fs_name, '\n', 'ssc', '127.0.0.1',
'console-context', '--evs', six.text_type(self.evs_id), 'console-context', '--evs', str(self.evs_id),
'rmdir', '/path'] 'rmdir', '/path']
self.mock_object(ssh.HNASSSHBackend, '_execute') self.mock_object(ssh.HNASSSHBackend, '_execute')

View File

@ -19,7 +19,6 @@ import ddt
if 'hpe3parclient' not in sys.modules: if 'hpe3parclient' not in sys.modules:
sys.modules['hpe3parclient'] = mock.Mock() sys.modules['hpe3parclient'] = mock.Mock()
from oslo_utils import units from oslo_utils import units
import six
from manila.data import utils as data_utils from manila.data import utils as data_utils
from manila import exception from manila import exception
@ -1176,8 +1175,8 @@ class HPE3ParMediatorTestCase(test.TestCase):
mock.call.setfsquota(constants.EXPECTED_VFS, mock.call.setfsquota(constants.EXPECTED_VFS,
fpg=constants.EXPECTED_FPG, fpg=constants.EXPECTED_FPG,
fstore=constants.EXPECTED_FSTORE, fstore=constants.EXPECTED_FSTORE,
scapacity=six.text_type(expected_capacity), scapacity=str(expected_capacity),
hcapacity=six.text_type(expected_capacity))] hcapacity=str(expected_capacity))]
self.mock_client.assert_has_calls(expected_calls) self.mock_client.assert_has_calls(expected_calls)
expected_mount_path = constants.EXPECTED_MOUNT_PATH + ( expected_mount_path = constants.EXPECTED_MOUNT_PATH + (
@ -1509,7 +1508,7 @@ class HPE3ParMediatorTestCase(test.TestCase):
self.assertTrue(mock_log.debug.called) self.assertTrue(mock_log.debug.called)
self.assertTrue(mock_log.exception.called) self.assertTrue(mock_log.exception.called)
@ddt.data(six.text_type('volname.1'), ['volname.2', 'volname.3']) @ddt.data('volname.1', ['volname.2', 'volname.3'])
def test_mediator_get_fpg_status(self, volume_name_or_list): def test_mediator_get_fpg_status(self, volume_name_or_list):
"""Mediator converts client stats to capacity result.""" """Mediator converts client stats to capacity result."""
expected_capacity = constants.EXPECTED_SIZE_2 expected_capacity = constants.EXPECTED_SIZE_2
@ -2310,8 +2309,8 @@ class HPE3ParMediatorTestCase(test.TestCase):
constants.EXPECTED_VFS, constants.EXPECTED_VFS,
fpg=constants.EXPECTED_FPG, fpg=constants.EXPECTED_FPG,
fstore=fstore, fstore=fstore,
scapacity=six.text_type(expected_capacity), scapacity=str(expected_capacity),
hcapacity=six.text_type(expected_capacity)) hcapacity=str(expected_capacity))
@ddt.data(['This is a fake setfsquota returned error'], Exception('boom')) @ddt.data(['This is a fake setfsquota returned error'], Exception('boom'))
def test_mediator_resize_share_setfsquota_side_effects(self, side_effect): def test_mediator_resize_share_setfsquota_side_effects(self, side_effect):
@ -2347,8 +2346,8 @@ class HPE3ParMediatorTestCase(test.TestCase):
constants.EXPECTED_VFS, constants.EXPECTED_VFS,
fpg=constants.EXPECTED_FPG, fpg=constants.EXPECTED_FPG,
fstore=fstore, fstore=fstore,
scapacity=six.text_type(expected_capacity), scapacity=str(expected_capacity),
hcapacity=six.text_type(expected_capacity)) hcapacity=str(expected_capacity))
def test_mediator_resize_share_not_found(self): def test_mediator_resize_share_not_found(self):
self.init_mediator() self.init_mediator()

View File

@ -19,7 +19,6 @@
import os import os
import requests import requests
import shutil import shutil
import six
import tempfile import tempfile
import time import time
from unittest import mock from unittest import mock
@ -342,7 +341,7 @@ class FakeHuaweiNasHelper(helper.RestHelper):
if self.custom_results and self.custom_results.get(url): if self.custom_results and self.custom_results.get(url):
result = self.custom_results[url] result = self.custom_results[url]
if isinstance(result, six.string_types): if isinstance(result, str):
return jsonutils.loads(result) return jsonutils.loads(result)
if isinstance(result, dict) and result.get(method): if isinstance(result, dict) and result.get(method):

View File

@ -18,7 +18,6 @@ from unittest import mock
from oslo_concurrency import processutils from oslo_concurrency import processutils
from oslo_config import cfg from oslo_config import cfg
import six
from manila import context from manila import context
from manila import exception from manila import exception
@ -248,7 +247,7 @@ class MapRFSNativeShareDriverTestCase(test.TestCase):
def test__set_volume_size(self): def test__set_volume_size(self):
volume = self._driver._volume_name(self.share['name']) volume = self._driver._volume_name(self.share['name'])
sizestr = six.text_type(self.share['size']) + 'G' sizestr = str(self.share['size']) + 'G'
self._driver._maprfs_util._execute = mock.Mock(return_value=('', 0)) self._driver._maprfs_util._execute = mock.Mock(return_value=('', 0))
self._driver._maprfs_util.set_volume_size(volume, self._driver._maprfs_util.set_volume_size(volume,
@ -420,7 +419,7 @@ class MapRFSNativeShareDriverTestCase(test.TestCase):
self.assertEqual(self.export_path, result[0]['path']) self.assertEqual(self.export_path, result[0]['path'])
def test_create_share(self): def test_create_share(self):
size_str = six.text_type(self.share['size']) + 'G' size_str = str(self.share['size']) + 'G'
path = self._driver._share_dir(self.share['name']) path = self._driver._share_dir(self.share['name'])
self._driver.api.get_share_metadata = mock.Mock( self._driver.api.get_share_metadata = mock.Mock(
return_value={'_fake': 'fake'}) return_value={'_fake': 'fake'})
@ -440,7 +439,7 @@ class MapRFSNativeShareDriverTestCase(test.TestCase):
'777') '777')
def test_create_share_with_custom_name(self): def test_create_share_with_custom_name(self):
size_str = six.text_type(self.share['size']) + 'G' size_str = str(self.share['size']) + 'G'
self._driver.api.get_share_metadata = mock.Mock( self._driver.api.get_share_metadata = mock.Mock(
return_value={'_name': 'fake', '_path': 'fake'}) return_value={'_name': 'fake', '_path': 'fake'})
self._driver._maprfs_util._execute = mock.Mock(return_value=('', 0)) self._driver._maprfs_util._execute = mock.Mock(return_value=('', 0))
@ -473,7 +472,7 @@ class MapRFSNativeShareDriverTestCase(test.TestCase):
def test_create_share_from_snapshot(self): def test_create_share_from_snapshot(self):
fake_snapshot = dict(self.snapshot) fake_snapshot = dict(self.snapshot)
fake_snapshot.update(share_instance={'share_id': 1}) fake_snapshot.update(share_instance={'share_id': 1})
size_str = six.text_type(self.share['size']) + 'G' size_str = str(self.share['size']) + 'G'
path = self._driver._share_dir(self.share['name']) path = self._driver._share_dir(self.share['name'])
snapthot_path = self._driver._get_snapshot_path(self.snapshot) + '/*' snapthot_path = self._driver._get_snapshot_path(self.snapshot) + '/*'
self._driver._maprfs_util._execute = mock.Mock( self._driver._maprfs_util._execute = mock.Mock(

View File

@ -21,7 +21,6 @@ from unittest import mock
import ddt import ddt
from oslo_log import log from oslo_log import log
import six
from manila import exception from manila import exception
from manila.share.drivers.netapp.dataontap.client import api as netapp_api from manila.share.drivers.netapp.dataontap.client import api as netapp_api
@ -2553,7 +2552,8 @@ class NetAppClientCmodeTestCase(test.TestCase):
self.client.configure_ldap(sec_service) self.client.configure_ldap(sec_service)
config_name = hashlib.md5(six.b(sec_service['id'])).hexdigest() config_name = hashlib.md5(
sec_service['id'].encode("latin-1")).hexdigest()
ldap_client_create_args = { ldap_client_create_args = {
'ldap-client-config': config_name, 'ldap-client-config': config_name,
@ -3807,7 +3807,7 @@ class NetAppClientCmodeTestCase(test.TestCase):
'attributes': { 'attributes': {
'volume-attributes': { 'volume-attributes': {
'volume-snapshot-attributes': { 'volume-snapshot-attributes': {
'snapdir-access-enabled': six.text_type( 'snapdir-access-enabled': str(
not hide_snapdir).lower(), not hide_snapdir).lower(),
}, },
}, },
@ -3851,7 +3851,7 @@ class NetAppClientCmodeTestCase(test.TestCase):
'attributes': { 'attributes': {
'volume-attributes': { 'volume-attributes': {
'volume-space-attributes': { 'volume-space-attributes': {
'is-filesys-size-fixed': six.text_type( 'is-filesys-size-fixed': str(
filesys_size_fixed).lower(), filesys_size_fixed).lower(),
}, },
}, },
@ -8063,7 +8063,8 @@ class NetAppClientCmodeTestCase(test.TestCase):
def test_modify_ldap(self, api_not_found): def test_modify_ldap(self, api_not_found):
current_ldap_service = fake.LDAP_AD_SECURITY_SERVICE current_ldap_service = fake.LDAP_AD_SECURITY_SERVICE
new_ldap_service = fake.LDAP_LINUX_SECURITY_SERVICE new_ldap_service = fake.LDAP_LINUX_SECURITY_SERVICE
config_name = hashlib.md5(six.b(new_ldap_service['id'])).hexdigest() config_name = hashlib.md5(
new_ldap_service['id'].encode("latin-1")).hexdigest()
api_result = (self._mock_api_error(code=netapp_api.EOBJECTNOTFOUND) api_result = (self._mock_api_error(code=netapp_api.EOBJECTNOTFOUND)
if api_not_found else mock.Mock()) if api_not_found else mock.Mock())
mock_create_client = self.mock_object( mock_create_client = self.mock_object(
@ -8107,7 +8108,8 @@ class NetAppClientCmodeTestCase(test.TestCase):
def test_modify_ldap_current_config_delete_error(self): def test_modify_ldap_current_config_delete_error(self):
current_ldap_service = fake.LDAP_AD_SECURITY_SERVICE current_ldap_service = fake.LDAP_AD_SECURITY_SERVICE
new_ldap_service = fake.LDAP_LINUX_SECURITY_SERVICE new_ldap_service = fake.LDAP_LINUX_SECURITY_SERVICE
config_name = hashlib.md5(six.b(new_ldap_service['id'])).hexdigest() config_name = hashlib.md5(
new_ldap_service['id'].encode("latin-1")).hexdigest()
mock_create_client = self.mock_object( mock_create_client = self.mock_object(
self.client, '_create_ldap_client') self.client, '_create_ldap_client')
mock_send_request = self.mock_object( mock_send_request = self.mock_object(

View File

@ -14,8 +14,6 @@
from unittest import mock from unittest import mock
import six
from manila import exception from manila import exception
from manila.share.drivers.netapp import common as na_common from manila.share.drivers.netapp import common as na_common
from manila.share.drivers.netapp.dataontap.cluster_mode import drv_multi_svm from manila.share.drivers.netapp.dataontap.cluster_mode import drv_multi_svm
@ -113,7 +111,7 @@ class NetAppDriverFactoryTestCase(test.TestCase):
registry = na_common.NETAPP_UNIFIED_DRIVER_REGISTRY registry = na_common.NETAPP_UNIFIED_DRIVER_REGISTRY
for family in six.iterkeys(registry): for family in iter(registry.keys()):
for mode, full_class_name in registry[family].items(): for mode, full_class_name in registry[family].items():
config = na_fakes.create_configuration() config = na_fakes.create_configuration()

View File

@ -21,10 +21,10 @@ import hashlib
import json import json
import posixpath import posixpath
from unittest import mock from unittest import mock
from urllib import parse as urlparse
import uuid import uuid
import requests import requests
import six
from manila.share import configuration as conf from manila.share import configuration as conf
from manila.share.drivers.nexenta.ns5 import jsonrpc from manila.share.drivers.nexenta.ns5 import jsonrpc
@ -803,7 +803,7 @@ class TestNefCollections(test.TestCase):
def test_path(self): def test_path(self):
path = 'path/to/item name + - & # $ = 0' path = 'path/to/item name + - & # $ = 0'
result = self.instance.path(path) result = self.instance.path(path)
quoted_path = six.moves.urllib.parse.quote_plus(path) quoted_path = urlparse.quote_plus(path)
expected = posixpath.join(self.instance.root, quoted_path) expected = posixpath.join(self.instance.root, quoted_path)
self.assertEqual(expected, result) self.assertEqual(expected, result)
@ -1155,7 +1155,7 @@ class TestNefProxy(test.TestCase):
get_settings.return_value = settings get_settings.return_value = settings
self.assertIsNone(self.proxy.update_lock()) self.assertIsNone(self.proxy.update_lock())
path = '%s:%s' % (guid, self.proxy.path) path = '%s:%s' % (guid, self.proxy.path)
if isinstance(path, six.text_type): if isinstance(path, str):
path = path.encode('utf-8') path = path.encode('utf-8')
expected = hashlib.md5(path).hexdigest() expected = hashlib.md5(path).hexdigest()
self.assertEqual(expected, self.proxy.lock) self.assertEqual(expected, self.proxy.lock)

View File

@ -14,12 +14,11 @@
# under the License. # under the License.
import base64 import base64
import ddt
from http import client as http_client
import time import time
from unittest import mock from unittest import mock
from urllib import parse as urlparse
import ddt
import six
from six.moves import urllib
from manila import exception from manila import exception
from manila.share.drivers.qnap import qnap from manila.share.drivers.qnap import qnap
@ -82,7 +81,7 @@ class QnapAPITestCase(QnapShareDriverBaseTestCase):
fake_parms['serviceKey'] = 1 fake_parms['serviceKey'] = 1
sanitized_params = self._sanitize_params(fake_parms) sanitized_params = self._sanitize_params(fake_parms)
self.login_url = ('/cgi-bin/authLogin.cgi?%s' % sanitized_params) self.login_url = ('/cgi-bin/authLogin.cgi?%s' % sanitized_params)
self.mock_object(six.moves.http_client, 'HTTPConnection') self.mock_object(http_client, 'HTTPConnection')
self.share = fake_share.fake_share( self.share = fake_share.fake_share(
share_proto='NFS', share_proto='NFS',
id='shareId', id='shareId',
@ -97,17 +96,17 @@ class QnapAPITestCase(QnapShareDriverBaseTestCase):
value = params[key] value = params[key]
if value is not None: if value is not None:
if isinstance(value, list): if isinstance(value, list):
sanitized_params[key] = [six.text_type(v) for v in value] sanitized_params[key] = [str(v) for v in value]
else: else:
sanitized_params[key] = six.text_type(value) sanitized_params[key] = str(value)
sanitized_params = urllib.parse.urlencode(sanitized_params, doseq) sanitized_params = urlparse.urlencode(sanitized_params, doseq)
return sanitized_params return sanitized_params
@ddt.data('fake_share_name', 'fakeLabel') @ddt.data('fake_share_name', 'fakeLabel')
def test_create_share_api(self, fake_name): def test_create_share_api(self, fake_name):
"""Test create share api.""" """Test create share api."""
mock_http_connection = six.moves.http_client.HTTPConnection mock_http_connection = http_client.HTTPConnection
mock_http_connection.return_value.getresponse.side_effect = [ mock_http_connection.return_value.getresponse.side_effect = [
fakes.FakeLoginResponse(), fakes.FakeLoginResponse(),
fakes.FakeGetBasicInfoResponseEs_1_1_3(), fakes.FakeGetBasicInfoResponseEs_1_1_3(),
@ -169,7 +168,7 @@ class QnapAPITestCase(QnapShareDriverBaseTestCase):
def test_api_delete_share(self): def test_api_delete_share(self):
"""Test delete share api.""" """Test delete share api."""
mock_http_connection = six.moves.http_client.HTTPConnection mock_http_connection = http_client.HTTPConnection
mock_http_connection.return_value.getresponse.side_effect = [ mock_http_connection.return_value.getresponse.side_effect = [
fakes.FakeLoginResponse(), fakes.FakeLoginResponse(),
fakes.FakeGetBasicInfoResponseEs_1_1_3(), fakes.FakeGetBasicInfoResponseEs_1_1_3(),
@ -203,7 +202,7 @@ class QnapAPITestCase(QnapShareDriverBaseTestCase):
def test_get_specific_poolinfo(self): def test_get_specific_poolinfo(self):
"""Test get specific poolinfo api.""" """Test get specific poolinfo api."""
mock_http_connection = six.moves.http_client.HTTPConnection mock_http_connection = http_client.HTTPConnection
mock_http_connection.return_value.getresponse.side_effect = [ mock_http_connection.return_value.getresponse.side_effect = [
fakes.FakeLoginResponse(), fakes.FakeLoginResponse(),
fakes.FakeGetBasicInfoResponseEs_1_1_3(), fakes.FakeGetBasicInfoResponseEs_1_1_3(),
@ -240,7 +239,7 @@ class QnapAPITestCase(QnapShareDriverBaseTestCase):
{'pool_id': "Storage Pool 1", 'vol_label': 'fakeShareName'}) {'pool_id': "Storage Pool 1", 'vol_label': 'fakeShareName'})
def test_get_share_info(self, dict_parm): def test_get_share_info(self, dict_parm):
"""Test get share info api.""" """Test get share info api."""
mock_http_connection = six.moves.http_client.HTTPConnection mock_http_connection = http_client.HTTPConnection
mock_http_connection.return_value.getresponse.side_effect = [ mock_http_connection.return_value.getresponse.side_effect = [
fakes.FakeLoginResponse(), fakes.FakeLoginResponse(),
fakes.FakeGetBasicInfoResponseEs_1_1_3(), fakes.FakeGetBasicInfoResponseEs_1_1_3(),
@ -273,7 +272,7 @@ class QnapAPITestCase(QnapShareDriverBaseTestCase):
def test_get_specific_volinfo(self): def test_get_specific_volinfo(self):
"""Test get specific volume info api.""" """Test get specific volume info api."""
mock_http_connection = six.moves.http_client.HTTPConnection mock_http_connection = http_client.HTTPConnection
mock_http_connection.return_value.getresponse.side_effect = [ mock_http_connection.return_value.getresponse.side_effect = [
fakes.FakeLoginResponse(), fakes.FakeLoginResponse(),
fakes.FakeGetBasicInfoResponseEs_1_1_3(), fakes.FakeGetBasicInfoResponseEs_1_1_3(),
@ -307,7 +306,7 @@ class QnapAPITestCase(QnapShareDriverBaseTestCase):
def test_get_snapshot_info_es(self): def test_get_snapshot_info_es(self):
"""Test get snapsho info api.""" """Test get snapsho info api."""
mock_http_connection = six.moves.http_client.HTTPConnection mock_http_connection = http_client.HTTPConnection
mock_http_connection.return_value.getresponse.side_effect = [ mock_http_connection.return_value.getresponse.side_effect = [
fakes.FakeLoginResponse(), fakes.FakeLoginResponse(),
fakes.FakeGetBasicInfoResponseEs_1_1_3(), fakes.FakeGetBasicInfoResponseEs_1_1_3(),
@ -342,7 +341,7 @@ class QnapAPITestCase(QnapShareDriverBaseTestCase):
def test_create_snapshot_api(self): def test_create_snapshot_api(self):
"""Test create snapshot api.""" """Test create snapshot api."""
mock_http_connection = six.moves.http_client.HTTPConnection mock_http_connection = http_client.HTTPConnection
mock_http_connection.return_value.getresponse.side_effect = [ mock_http_connection.return_value.getresponse.side_effect = [
fakes.FakeLoginResponse(), fakes.FakeLoginResponse(),
fakes.FakeGetBasicInfoResponseEs_1_1_3(), fakes.FakeGetBasicInfoResponseEs_1_1_3(),
@ -381,7 +380,7 @@ class QnapAPITestCase(QnapShareDriverBaseTestCase):
fakes.FakeDeleteSnapshotResponseShareNotExist()) fakes.FakeDeleteSnapshotResponseShareNotExist())
def test_delete_snapshot_api(self, fakeDeleteSnapshotResponse): def test_delete_snapshot_api(self, fakeDeleteSnapshotResponse):
"""Test delete snapshot api.""" """Test delete snapshot api."""
mock_http_connection = six.moves.http_client.HTTPConnection mock_http_connection = http_client.HTTPConnection
mock_http_connection.return_value.getresponse.side_effect = [ mock_http_connection.return_value.getresponse.side_effect = [
fakes.FakeLoginResponse(), fakes.FakeLoginResponse(),
fakes.FakeGetBasicInfoResponseEs_1_1_3(), fakes.FakeGetBasicInfoResponseEs_1_1_3(),
@ -413,7 +412,7 @@ class QnapAPITestCase(QnapShareDriverBaseTestCase):
def test_clone_snapshot_api(self): def test_clone_snapshot_api(self):
"""Test clone snapshot api.""" """Test clone snapshot api."""
mock_http_connection = six.moves.http_client.HTTPConnection mock_http_connection = http_client.HTTPConnection
mock_http_connection.return_value.getresponse.side_effect = [ mock_http_connection.return_value.getresponse.side_effect = [
fakes.FakeLoginResponse(), fakes.FakeLoginResponse(),
fakes.FakeGetBasicInfoResponseEs_1_1_3(), fakes.FakeGetBasicInfoResponseEs_1_1_3(),
@ -450,7 +449,7 @@ class QnapAPITestCase(QnapShareDriverBaseTestCase):
def test_edit_share_api(self): def test_edit_share_api(self):
"""Test edit share api.""" """Test edit share api."""
mock_http_connection = six.moves.http_client.HTTPConnection mock_http_connection = http_client.HTTPConnection
mock_http_connection.return_value.getresponse.side_effect = [ mock_http_connection.return_value.getresponse.side_effect = [
fakes.FakeLoginResponse(), fakes.FakeLoginResponse(),
fakes.FakeGetBasicInfoResponseTs_4_3_0(), fakes.FakeGetBasicInfoResponseTs_4_3_0(),
@ -511,7 +510,7 @@ class QnapAPITestCase(QnapShareDriverBaseTestCase):
fakes.FakeGetNoHostListResponse()) fakes.FakeGetNoHostListResponse())
def test_get_host_list(self, fakeGetHostListResponse): def test_get_host_list(self, fakeGetHostListResponse):
"""Test get host list api.""" """Test get host list api."""
mock_http_connection = six.moves.http_client.HTTPConnection mock_http_connection = http_client.HTTPConnection
mock_http_connection.return_value.getresponse.side_effect = [ mock_http_connection.return_value.getresponse.side_effect = [
fakes.FakeLoginResponse(), fakes.FakeLoginResponse(),
fakes.FakeGetBasicInfoResponseEs_1_1_3(), fakes.FakeGetBasicInfoResponseEs_1_1_3(),
@ -543,7 +542,7 @@ class QnapAPITestCase(QnapShareDriverBaseTestCase):
def test_add_host(self): def test_add_host(self):
"""Test add host api.""" """Test add host api."""
mock_http_connection = six.moves.http_client.HTTPConnection mock_http_connection = http_client.HTTPConnection
mock_http_connection.return_value.getresponse.side_effect = [ mock_http_connection.return_value.getresponse.side_effect = [
fakes.FakeLoginResponse(), fakes.FakeLoginResponse(),
fakes.FakeGetBasicInfoResponseEs_1_1_3(), fakes.FakeGetBasicInfoResponseEs_1_1_3(),
@ -578,7 +577,7 @@ class QnapAPITestCase(QnapShareDriverBaseTestCase):
def test_edit_host(self): def test_edit_host(self):
"""Test edit host api.""" """Test edit host api."""
mock_http_connection = six.moves.http_client.HTTPConnection mock_http_connection = http_client.HTTPConnection
mock_http_connection.return_value.getresponse.side_effect = [ mock_http_connection.return_value.getresponse.side_effect = [
fakes.FakeLoginResponse(), fakes.FakeLoginResponse(),
fakes.FakeGetBasicInfoResponseEs_1_1_3(), fakes.FakeGetBasicInfoResponseEs_1_1_3(),
@ -613,7 +612,7 @@ class QnapAPITestCase(QnapShareDriverBaseTestCase):
def test_delete_host(self): def test_delete_host(self):
"""Test delete host api.""" """Test delete host api."""
mock_http_connection = six.moves.http_client.HTTPConnection mock_http_connection = http_client.HTTPConnection
mock_http_connection.return_value.getresponse.side_effect = [ mock_http_connection.return_value.getresponse.side_effect = [
fakes.FakeLoginResponse(), fakes.FakeLoginResponse(),
fakes.FakeGetBasicInfoResponseEs_1_1_3(), fakes.FakeGetBasicInfoResponseEs_1_1_3(),
@ -647,7 +646,7 @@ class QnapAPITestCase(QnapShareDriverBaseTestCase):
@ddt.data(fakes.FakeGetHostListResponse()) @ddt.data(fakes.FakeGetHostListResponse())
def test_set_nfs_access(self, fakeGetHostListResponse): def test_set_nfs_access(self, fakeGetHostListResponse):
"""Test get host list api.""" """Test get host list api."""
mock_http_connection = six.moves.http_client.HTTPConnection mock_http_connection = http_client.HTTPConnection
mock_http_connection.return_value.getresponse.side_effect = [ mock_http_connection.return_value.getresponse.side_effect = [
fakes.FakeLoginResponse(), fakes.FakeLoginResponse(),
fakes.FakeGetBasicInfoResponseEs_1_1_3(), fakes.FakeGetBasicInfoResponseEs_1_1_3(),
@ -683,7 +682,7 @@ class QnapAPITestCase(QnapShareDriverBaseTestCase):
def test_get_snapshot_info_ts_api(self): def test_get_snapshot_info_ts_api(self):
"""Test get snapshot info api.""" """Test get snapshot info api."""
mock_http_connection = six.moves.http_client.HTTPConnection mock_http_connection = http_client.HTTPConnection
mock_http_connection.return_value.getresponse.side_effect = [ mock_http_connection.return_value.getresponse.side_effect = [
fakes.FakeLoginResponse(), fakes.FakeLoginResponse(),
fakes.FakeGetBasicInfoResponseTs_4_3_0(), fakes.FakeGetBasicInfoResponseTs_4_3_0(),
@ -722,7 +721,7 @@ class QnapAPITestCase(QnapShareDriverBaseTestCase):
fakes.FakeEsResCodeNegativeResponse()) fakes.FakeEsResCodeNegativeResponse())
def test_api_create_share_with_fail_response(self, fake_fail_response): def test_api_create_share_with_fail_response(self, fake_fail_response):
"""Test create share api with fail response.""" """Test create share api with fail response."""
mock_http_connection = six.moves.http_client.HTTPConnection mock_http_connection = http_client.HTTPConnection
mock_http_connection.return_value.getresponse.side_effect = [ mock_http_connection.return_value.getresponse.side_effect = [
fakes.FakeLoginResponse(), fakes.FakeLoginResponse(),
fakes.FakeGetBasicInfoResponseEs_1_1_3(), fakes.FakeGetBasicInfoResponseEs_1_1_3(),
@ -900,7 +899,7 @@ class QnapAPITestCase(QnapShareDriverBaseTestCase):
self, api, dict_parm, self, api, dict_parm,
fake_fail_response, fake_basic_info): fake_fail_response, fake_basic_info):
"""Test get snapshot info api with fail response.""" """Test get snapshot info api with fail response."""
mock_http_connection = six.moves.http_client.HTTPConnection mock_http_connection = http_client.HTTPConnection
mock_http_connection.return_value.getresponse.side_effect = [ mock_http_connection.return_value.getresponse.side_effect = [
fakes.FakeLoginResponse(), fakes.FakeLoginResponse(),
fake_basic_info, fake_basic_info,

View File

@ -13,6 +13,7 @@
# License for the specific language governing permissions and limitations # License for the specific language governing permissions and limitations
# under the License. # under the License.
from http import client as http_client
import time import time
from unittest import mock from unittest import mock
@ -24,7 +25,6 @@ except ImportError:
import ddt import ddt
from eventlet import greenthread from eventlet import greenthread
from oslo_config import cfg from oslo_config import cfg
import six
from manila import exception from manila import exception
from manila.share.drivers.qnap import api from manila.share.drivers.qnap import api
@ -81,8 +81,8 @@ class QnapShareDriverLoginTestCase(QnapShareDriverBaseTestCase):
def setUp(self): def setUp(self):
"""Setup the Qnap Share Driver login TestCase.""" """Setup the Qnap Share Driver login TestCase."""
super(QnapShareDriverLoginTestCase, self).setUp() super(QnapShareDriverLoginTestCase, self).setUp()
self.mock_object(six.moves.http_client, 'HTTPConnection') self.mock_object(http_client, 'HTTPConnection')
self.mock_object(six.moves.http_client, 'HTTPSConnection') self.mock_object(http_client, 'HTTPSConnection')
@ddt.unpack @ddt.unpack
@ddt.data({'mng_url': 'http://1.2.3.4:8080', 'port': '8080', 'ssl': False}, @ddt.data({'mng_url': 'http://1.2.3.4:8080', 'port': '8080', 'ssl': False},
@ -93,9 +93,9 @@ class QnapShareDriverLoginTestCase(QnapShareDriverBaseTestCase):
fake_get_basic_info_response_es = ( fake_get_basic_info_response_es = (
fakes.FakeGetBasicInfoResponseEs_1_1_3()) fakes.FakeGetBasicInfoResponseEs_1_1_3())
if ssl: if ssl:
mock_connection = six.moves.http_client.HTTPSConnection mock_connection = http_client.HTTPSConnection
else: else:
mock_connection = six.moves.http_client.HTTPConnection mock_connection = http_client.HTTPConnection
mock_connection.return_value.getresponse.side_effect = [ mock_connection.return_value.getresponse.side_effect = [
fake_login_response, fake_login_response,
fake_get_basic_info_response_es, fake_get_basic_info_response_es,
@ -128,7 +128,7 @@ class QnapShareDriverLoginTestCase(QnapShareDriverBaseTestCase):
def test_do_setup_positive_with_diff_nas(self, fake_basic_info): def test_do_setup_positive_with_diff_nas(self, fake_basic_info):
"""Test do_setup with different NAS model.""" """Test do_setup with different NAS model."""
fake_login_response = fakes.FakeLoginResponse() fake_login_response = fakes.FakeLoginResponse()
mock_connection = six.moves.http_client.HTTPSConnection mock_connection = http_client.HTTPSConnection
mock_connection.return_value.getresponse.side_effect = [ mock_connection.return_value.getresponse.side_effect = [
fake_login_response, fake_login_response,
fake_basic_info, fake_basic_info,
@ -173,7 +173,7 @@ class QnapShareDriverLoginTestCase(QnapShareDriverBaseTestCase):
def test_create_api_executor(self, fake_basic_info, expect_result): def test_create_api_executor(self, fake_basic_info, expect_result):
"""Test do_setup with different NAS model.""" """Test do_setup with different NAS model."""
fake_login_response = fakes.FakeLoginResponse() fake_login_response = fakes.FakeLoginResponse()
mock_connection = six.moves.http_client.HTTPSConnection mock_connection = http_client.HTTPSConnection
mock_connection.return_value.getresponse.side_effect = [ mock_connection.return_value.getresponse.side_effect = [
fake_login_response, fake_login_response,
fake_basic_info, fake_basic_info,
@ -206,7 +206,7 @@ class QnapShareDriverLoginTestCase(QnapShareDriverBaseTestCase):
fake_basic_info, expect_result): fake_basic_info, expect_result):
"""Test do_setup with different NAS model.""" """Test do_setup with different NAS model."""
fake_login_response = fakes.FakeLoginResponse() fake_login_response = fakes.FakeLoginResponse()
mock_connection = six.moves.http_client.HTTPSConnection mock_connection = http_client.HTTPSConnection
mock_connection.return_value.getresponse.side_effect = [ mock_connection.return_value.getresponse.side_effect = [
fake_login_response, fake_login_response,
fake_basic_info, fake_basic_info,
@ -225,7 +225,7 @@ class QnapShareDriverLoginTestCase(QnapShareDriverBaseTestCase):
fake_login_response = fakes.FakeLoginResponse() fake_login_response = fakes.FakeLoginResponse()
fake_get_basic_info_response_error = ( fake_get_basic_info_response_error = (
fakes.FakeGetBasicInfoResponseError()) fakes.FakeGetBasicInfoResponseError())
mock_connection = six.moves.http_client.HTTPSConnection mock_connection = http_client.HTTPSConnection
mock_connection.return_value.getresponse.side_effect = [ mock_connection.return_value.getresponse.side_effect = [
fake_login_response, fake_login_response,
fake_get_basic_info_response_error, fake_get_basic_info_response_error,

View File

@ -20,7 +20,6 @@ from unittest import mock
import requests import requests
from requests import auth from requests import auth
from requests import exceptions from requests import exceptions
import six
from manila import exception from manila import exception
from manila.share.drivers.quobyte import jsonrpc from manila.share.drivers.quobyte import jsonrpc
@ -32,7 +31,7 @@ class FakeResponse(object):
self.status_code = status self.status_code = status
self.reason = "HTTP reason" self.reason = "HTTP reason"
self.body = body self.body = body
self.text = six.text_type(body) self.text = str(body)
def json(self): def json(self):
return self.body return self.body

View File

@ -17,7 +17,6 @@ from unittest import mock
from oslo_config import cfg from oslo_config import cfg
from oslo_utils import units from oslo_utils import units
import six
from manila import context from manila import context
from manila import exception from manila import exception
@ -353,8 +352,8 @@ class QuobyteShareDriverTestCase(test.TestCase):
self._driver._get_qb_replication_factor = mock.Mock( self._driver._get_qb_replication_factor = mock.Mock(
return_value=replfact) return_value=replfact)
self._driver.rpc.call = mock.Mock( self._driver.rpc.call = mock.Mock(
return_value={'total_physical_capacity': six.text_type(capval), return_value={'total_physical_capacity': str(capval),
'total_physical_usage': six.text_type(useval)}) 'total_physical_usage': str(useval)})
self.assertEqual((39.223160718, 6.960214182), self.assertEqual((39.223160718, 6.960214182),
self._driver._get_capacities()) self._driver._get_capacities())
@ -366,8 +365,8 @@ class QuobyteShareDriverTestCase(test.TestCase):
self._driver._get_qb_replication_factor = mock.Mock( self._driver._get_qb_replication_factor = mock.Mock(
return_value=replfact) return_value=replfact)
self._driver.rpc.call = mock.Mock( self._driver.rpc.call = mock.Mock(
return_value={'total_physical_capacity': six.text_type(capval), return_value={'total_physical_capacity': str(capval),
'total_physical_usage': six.text_type(useval)}) 'total_physical_usage': str(useval)})
self.assertEqual((3.0, 0), self._driver._get_capacities()) self.assertEqual((3.0, 0), self._driver._get_capacities())
@ -378,7 +377,7 @@ class QuobyteShareDriverTestCase(test.TestCase):
return_value={'configuration': return_value={'configuration':
{'volume_metadata_configuration': {'volume_metadata_configuration':
{'replication_factor': {'replication_factor':
six.text_type(fakerepl)}}}) str(fakerepl)}}})
self.assertEqual(fakerepl, self._driver._get_qb_replication_factor()) self.assertEqual(fakerepl, self._driver._get_qb_replication_factor())

View File

@ -21,7 +21,6 @@ from unittest import mock
import ddt import ddt
from oslo_config import cfg from oslo_config import cfg
import requests import requests
import six
from manila.common import constants as const from manila.common import constants as const
from manila import context from manila import context
@ -528,7 +527,7 @@ class TegileShareDriverTestCase(test.TestCase):
extend_path = '%s/%s/%s/%s' % ( extend_path = '%s/%s/%s/%s' % (
'fake_pool', 'Local', 'fake_project', test_share['name']) 'fake_pool', 'Local', 'fake_project', test_share['name'])
extend_params = (extend_path, six.text_type(12), 'GB') extend_params = (extend_path, str(12), 'GB')
mock_api.assert_called_once_with('resizeShare', extend_params) mock_api.assert_called_once_with('resizeShare', extend_params)
mock_params.assert_called_once_with(test_share) mock_params.assert_called_once_with(test_share)
@ -545,7 +544,7 @@ class TegileShareDriverTestCase(test.TestCase):
extend_path = '%s/%s/%s/%s' % ( extend_path = '%s/%s/%s/%s' % (
'fake_pool', 'Local', 'fake_project', test_share['name']) 'fake_pool', 'Local', 'fake_project', test_share['name'])
extend_params = (extend_path, six.text_type(30), 'GB') extend_params = (extend_path, str(30), 'GB')
mock_api.assert_called_once_with('resizeShare', extend_params) mock_api.assert_called_once_with('resizeShare', extend_params)
def test_shrink_share(self): def test_shrink_share(self):
@ -559,7 +558,7 @@ class TegileShareDriverTestCase(test.TestCase):
shrink_path = '%s/%s/%s/%s' % ( shrink_path = '%s/%s/%s/%s' % (
'fake_pool', 'Local', 'fake_project', test_share['name']) 'fake_pool', 'Local', 'fake_project', test_share['name'])
shrink_params = (shrink_path, six.text_type(15), 'GB') shrink_params = (shrink_path, str(15), 'GB')
mock_api.assert_called_once_with('resizeShare', shrink_params) mock_api.assert_called_once_with('resizeShare', shrink_params)
mock_params.assert_called_once_with(test_share) mock_params.assert_called_once_with(test_share)
@ -576,7 +575,7 @@ class TegileShareDriverTestCase(test.TestCase):
shrink_path = '%s/%s/%s/%s' % ( shrink_path = '%s/%s/%s/%s' % (
'fake_pool', 'Local', 'fake_project', test_share['name']) 'fake_pool', 'Local', 'fake_project', test_share['name'])
shrink_params = (shrink_path, six.text_type(30), 'GB') shrink_params = (shrink_path, str(30), 'GB')
mock_api.assert_called_once_with('resizeShare', shrink_params) mock_api.assert_called_once_with('resizeShare', shrink_params)
@ddt.data('ip', 'user') @ddt.data('ip', 'user')

View File

@ -92,7 +92,7 @@ class GaneshaNASHelperTestCase(test.TestCase):
fake_template2])) fake_template2]))
self.mock_object(ganesha.ganesha_utils, 'patch', self.mock_object(ganesha.ganesha_utils, 'patch',
mock.Mock(side_effect=fake_patch_run)) mock.Mock(side_effect=fake_patch_run))
with mock.patch('six.moves.builtins.open', with mock.patch('builtins.open',
mock.mock_open()) as mockopen: mock.mock_open()) as mockopen:
mockopen().read.side_effect = ['fakeconf0', 'fakeconf1'] mockopen().read.side_effect = ['fakeconf0', 'fakeconf1']
ret = self._helper._load_conf_dir(self.fake_conf_dir_path) ret = self._helper._load_conf_dir(self.fake_conf_dir_path)
@ -119,7 +119,7 @@ class GaneshaNASHelperTestCase(test.TestCase):
self.mock_object(ganesha.LOG, 'info') self.mock_object(ganesha.LOG, 'info')
self.mock_object(ganesha.ganesha_manager, 'parseconf') self.mock_object(ganesha.ganesha_manager, 'parseconf')
self.mock_object(ganesha.ganesha_utils, 'patch') self.mock_object(ganesha.ganesha_utils, 'patch')
with mock.patch('six.moves.builtins.open', with mock.patch('builtins.open',
mock.mock_open(read_data='fakeconf')) as mockopen: mock.mock_open(read_data='fakeconf')) as mockopen:
ret = self._helper._load_conf_dir(self.fake_conf_dir_path, ret = self._helper._load_conf_dir(self.fake_conf_dir_path,
must_exist=False) must_exist=False)

View File

@ -23,7 +23,6 @@ from unittest import mock
import ddt import ddt
from oslo_concurrency import processutils from oslo_concurrency import processutils
from oslo_config import cfg from oslo_config import cfg
from six import moves
from manila.common import constants as const from manila.common import constants as const
from manila import compute from manila import compute
@ -404,17 +403,17 @@ class GenericShareDriverTestCase(test.TestCase):
self._driver._unmount_device(self.share, self.server) self._driver._unmount_device(self.share, self.server)
self.assertEqual(1, time.sleep.call_count) self.assertEqual(1, time.sleep.call_count)
self.assertEqual([mock.call(self.share) for i in moves.range(2)], self.assertEqual([mock.call(self.share) for i in range(2)],
self._driver._get_mount_path.mock_calls) self._driver._get_mount_path.mock_calls)
self.assertEqual([mock.call(mount_path, self.assertEqual([mock.call(mount_path,
self.server) for i in moves.range(2)], self.server) for i in range(2)],
self._driver._is_device_mounted.mock_calls) self._driver._is_device_mounted.mock_calls)
self._driver._remove_mount_permanently.assert_called_once_with( self._driver._remove_mount_permanently.assert_called_once_with(
self.share.id, self.server) self.share.id, self.server)
self.assertEqual( self.assertEqual(
[mock.call(self.server, ['sudo', 'umount', mount_path, [mock.call(self.server, ['sudo', 'umount', mount_path,
'&&', 'sudo', 'rmdir', mount_path]) '&&', 'sudo', 'rmdir', mount_path])
for i in moves.range(2)], for i in range(2)],
self._driver._ssh_exec.mock_calls, self._driver._ssh_exec.mock_calls,
) )

View File

@ -24,7 +24,6 @@ import ddt
import netaddr import netaddr
from oslo_config import cfg from oslo_config import cfg
from oslo_utils import importutils from oslo_utils import importutils
import six
from manila import exception from manila import exception
from manila.share import configuration from manila.share import configuration
@ -2065,7 +2064,7 @@ class NeutronNetworkHelperTestCase(test.TestCase):
def test__get_cidr_for_subnet_success(self): def test__get_cidr_for_subnet_success(self):
expected = ( expected = (
fake_get_config_option('service_network_cidr').split('/')[0] + fake_get_config_option('service_network_cidr').split('/')[0] +
'/' + six.text_type( '/' + str(
fake_get_config_option('service_network_division_mask'))) fake_get_config_option('service_network_division_mask')))
instance = self._init_neutron_network_plugin() instance = self._init_neutron_network_plugin()
self.mock_object( self.mock_object(
@ -2082,7 +2081,7 @@ class NeutronNetworkHelperTestCase(test.TestCase):
fake_get_config_option('service_network_cidr')) fake_get_config_option('service_network_cidr'))
division_mask = fake_get_config_option('service_network_division_mask') division_mask = fake_get_config_option('service_network_division_mask')
for subnet in serv_cidr.subnet(division_mask): for subnet in serv_cidr.subnet(division_mask):
subnets.append(dict(cidr=six.text_type(subnet.cidr))) subnets.append(dict(cidr=str(subnet.cidr)))
instance = self._init_neutron_network_plugin() instance = self._init_neutron_network_plugin()
self.mock_object( self.mock_object(
instance, '_get_all_service_subnets', instance, '_get_all_service_subnets',

View File

@ -20,7 +20,6 @@ from unittest import mock
from oslo_config import cfg from oslo_config import cfg
import requests import requests
import six
from manila import context from manila import context
from manila import exception from manila import exception
@ -189,8 +188,8 @@ class ACCESSShareDriverTestCase(test.TestCase):
sharepath = self._driver._get_va_share_path(sharename) sharepath = self._driver._get_va_share_path(sharename)
self._driver._get_vip.return_value = '1.1.1.1' self._driver._get_vip.return_value = '1.1.1.1'
vip = self._driver._get_vip() vip = self._driver._get_vip()
location = (six.text_type(vip) + ':' + location = (str(vip) + ':' +
six.text_type(sharepath) + ':' + six.text_type(snapname)) str(sharepath) + ':' + str(snapname))
ret = self._driver.create_share_from_snapshot(self._context, ret = self._driver.create_share_from_snapshot(self._context,
self.share, self.share,

View File

@ -19,7 +19,6 @@ from unittest import mock
import ddt import ddt
from oslo_concurrency import processutils from oslo_concurrency import processutils
from oslo_config import cfg from oslo_config import cfg
import six
from manila import exception from manila import exception
from manila.share import configuration from manila.share import configuration
@ -83,7 +82,7 @@ class WindowsServiceInstanceManagerTestCase(test.TestCase):
if not use_cert_auth: if not use_cert_auth:
mock_check_complexity.assert_called_once_with( mock_check_complexity.assert_called_once_with(
six.text_type(mock.sentinel.password)) str(mock.sentinel.password))
@ddt.data(False, True) @ddt.data(False, True)
def test_get_auth_info(self, use_cert_auth): def test_get_auth_info(self, use_cert_auth):
@ -166,7 +165,7 @@ class WindowsServiceInstanceManagerTestCase(test.TestCase):
expected_kwargs = dict(user_data=mock_cert_data) expected_kwargs = dict(user_data=mock_cert_data)
else: else:
expected_kwargs = dict( expected_kwargs = dict(
meta=dict(admin_pass=six.text_type(mock.sentinel.admin_pass))) meta=dict(admin_pass=str(mock.sentinel.admin_pass)))
create_kwargs = self._mgr._get_service_instance_create_kwargs() create_kwargs = self._mgr._get_service_instance_create_kwargs()

View File

@ -2337,7 +2337,7 @@ class ZFSonLinuxShareDriverTestCase(test.TestCase):
'dataset_name': src_dataset_name, 'dataset_name': src_dataset_name,
} }
) )
with mock.patch("six.moves.builtins.open", with mock.patch("builtins.open",
mock.mock_open(read_data="data")) as mock_file: mock.mock_open(read_data="data")) as mock_file:
self.driver.migration_start( self.driver.migration_start(
self._context, src_share, dst_share, None, None) self._context, src_share, dst_share, None, None)