Implement OSC share access rules commands

In this patch we add openstack commands for:
share access create
share access delete
share access list
share access show
share access set
share access unset

These commands can be used to replace all 'manila access-...' commands.
'manila access-metadata' is replaced by:
'openstack share access set --property <key=value>' and
'openstack share access unset --property <key>'

Change-Id: Id2bd92bcb629905c7db12951d6e4ebe2d5b4d916
Partially-implements: bp openstack-client-support
This commit is contained in:
Maari Tamm
2020-01-16 17:06:06 +00:00
committed by Victoria Martinez de la Cruz
parent 134f07af6d
commit 9fc3723de8
5 changed files with 808 additions and 1 deletions

View File

@@ -33,3 +33,27 @@ def extract_key_value_options(pairs):
raise exceptions.CommandError(msg)
return result_dict
def format_properties(properties):
formatted_data = []
for item in properties:
formatted_data.append("%s : %s" % (item, properties[item]))
return "\n".join(formatted_data)
def extract_properties(properties):
result_dict = {}
for item in properties:
try:
(key, value) = item.split('=', 1)
if key in result_dict:
raise exceptions.CommandError(
"Argument '%s' is specified twice." % key)
else:
result_dict[key] = value
except ValueError:
raise exceptions.CommandError(
"Parsing error, expected format 'key=value' for " + item
)
return result_dict

View File

@@ -0,0 +1,383 @@
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import logging
from osc_lib.cli import parseractions
from osc_lib.command import command
from osc_lib import exceptions
from osc_lib import utils as oscutils
from manilaclient import api_versions
from manilaclient.common._i18n import _
from manilaclient.common.apiclient import utils as apiutils
from manilaclient.osc import utils
LOG = logging.getLogger(__name__)
ACCESS_RULE_ATTRIBUTES = [
'id',
'share_id',
'access_level',
'access_to',
'access_type',
'state',
'access_key',
'created_at',
'updated_at',
'properties'
]
class ShareAccessAllow(command.ShowOne):
"""Create a new share access rule."""
_description = _("Create new share access rule")
log = logging.getLogger(__name__ + ".CreateShareAccess")
def get_parser(self, prog_name):
parser = super(ShareAccessAllow, self).get_parser(prog_name)
parser.add_argument(
'share',
metavar="<share>",
help=_('Name or ID of the NAS share to modify.')
)
parser.add_argument(
'access_type',
metavar="<access_type>",
help=_('Access rule type (only "ip", "user" (user or group), '
'"cert" or "cephx" are supported).')
)
parser.add_argument(
'access_to',
metavar="<access_to>",
help=_('Value that defines access.')
)
# metadata --> properties in osc
parser.add_argument(
'--properties',
type=str,
nargs='*',
metavar='<key=value>',
help=_('Space separated list of key=value pairs of properties. '
'OPTIONAL: Default=None. '
'Available only for API microversion >= 2.45.'),
)
parser.add_argument(
'--access-level',
metavar="<access_level>",
type=str,
default=None,
choices=['rw', 'ro'],
help=_('Share access level ("rw" and "ro" access levels '
'are supported). Defaults to rw.')
)
return parser
def take_action(self, parsed_args):
share_client = self.app.client_manager.share
share = apiutils.find_resource(share_client.shares,
parsed_args.share)
properties = {}
if parsed_args.properties:
if share_client.api_version >= api_versions.APIVersion("2.45"):
properties = utils.extract_properties(parsed_args.properties)
else:
raise exceptions.CommandError(
"Adding properties to access rules is supported only "
"with API microversion 2.45 and beyond")
try:
share_access_rule = share.allow(
access_type=parsed_args.access_type,
access=parsed_args.access_to,
access_level=parsed_args.access_level,
metadata=properties
)
share_access_rule.update(
{
'properties': utils.format_properties(
share_access_rule.pop('metadata', {}))
}
)
return (ACCESS_RULE_ATTRIBUTES, oscutils.get_dict_properties(
share_access_rule,
ACCESS_RULE_ATTRIBUTES))
except Exception as e:
raise exceptions.CommandError(
"Failed to create access to share "
"'%s': %s" % (share, e))
class ShareAccessDeny(command.Command):
"""Delete a share access rule."""
_description = _("Delete a share access rule")
log = logging.getLogger(__name__ + ".DeleteShareAccess")
def get_parser(self, prog_name):
parser = super(ShareAccessDeny, self).get_parser(prog_name)
parser.add_argument(
'share',
metavar="<share>",
help=_('Name or ID of the NAS share to modify.')
)
parser.add_argument(
'id',
metavar="<id>",
help=_('ID of the access rule to be deleted.')
)
return parser
def take_action(self, parsed_args):
share_client = self.app.client_manager.share
share = apiutils.find_resource(share_client.shares,
parsed_args.share)
try:
share.deny(parsed_args.id)
except Exception as e:
raise exceptions.CommandError(
"Failed to delete share access rule for share "
"'%s': %s" % (share, e))
class ListShareAccess(command.Lister):
"""List share access rules."""
_description = _("List share access rule")
log = logging.getLogger(__name__ + ".ListShareAccess")
def get_parser(self, prog_name):
parser = super(ListShareAccess, self).get_parser(prog_name)
parser.add_argument(
'share',
metavar="<share>",
help=_('Name or ID of the share.')
)
parser.add_argument(
'--columns',
metavar="<columns>",
default=None,
help=_('Comma separated list of columns to be displayed. '
'Example --columns "access_type,access_to".')
)
# metadata --> properties in osc
parser.add_argument(
'--properties',
type=str,
nargs='*',
metavar='<key=value>',
default=None,
help=_('Filters results by properties (key=value). '
'OPTIONAL: Default=None. '
'Available only for API microversion >= 2.45'),
)
return parser
def take_action(self, parsed_args):
share_client = self.app.client_manager.share
share = apiutils.find_resource(share_client.shares,
parsed_args.share)
if share_client.api_version >= api_versions.APIVersion("2.45"):
search_opts = {}
if parsed_args.properties:
search_opts = {
'metadata': utils.extract_properties(
parsed_args.properties)
}
access_list = share_client.share_access_rules.access_list(
share,
search_opts)
elif parsed_args.properties:
raise exceptions.CommandError(
"Filtering access rules by properties is supported only "
"with API microversion 2.45 and beyond.")
else:
access_list = share.access_list()
list_of_keys = [
'id',
'access_type',
'access_to',
'access_level',
'state'
]
if share_client.api_version >= api_versions.APIVersion("2.21"):
list_of_keys.append('access_key')
if share_client.api_version >= api_versions.APIVersion("2.33"):
list_of_keys.append('created_at')
list_of_keys.append('updated_at')
if parsed_args.columns:
columns = parsed_args.columns.split(',')
for column in columns:
if column not in list_of_keys:
msg = ("No column named '%s'. Possible columns are: "
"'id', 'access_type', 'access_to', "
"'access_level', 'state', "
"'access_key'(API microversion 2.21 and beyond), "
"'created_at'(API microversion 2.33 and beyond), "
"'updated_at'(API microversion 2.33 and beyond)."
% column)
raise exceptions.CommandError(msg)
else:
columns = list_of_keys
values = (oscutils.get_item_properties(
a, columns) for a in access_list)
return (columns, values)
class ShowShareAccess(command.ShowOne):
"""Display a share access rule."""
_description = _(
"Display a share access rule. "
"Available for API microversion 2.45 and higher")
log = logging.getLogger(__name__ + ".ShowShareAccess")
def get_parser(self, prog_name):
parser = super(ShowShareAccess, self).get_parser(prog_name)
parser.add_argument(
'access_id',
metavar="<access_id>",
help=_('ID of the NAS share access rule.')
)
return parser
def take_action(self, parsed_args):
share_client = self.app.client_manager.share
if share_client.api_version >= api_versions.APIVersion("2.45"):
access_rule = share_client.share_access_rules.get(
parsed_args.access_id
)
access_rule._info.update(
{
'properties': utils.format_properties(
access_rule._info.pop('metadata', {}))
}
)
return (ACCESS_RULE_ATTRIBUTES, oscutils.get_dict_properties(
access_rule._info,
ACCESS_RULE_ATTRIBUTES))
else:
raise exceptions.CommandError(
"Displaying share access rule details is only available "
"with API microversion 2.45 and higher.")
class SetShareAccess(command.Command):
"""Set properties to share access rule."""
_description = _(
"Set properties to share access rule. "
"Available for API microversion 2.45 and higher")
log = logging.getLogger(__name__ + ".SetShareAccess")
def get_parser(self, prog_name):
parser = super(SetShareAccess, self).get_parser(prog_name)
parser.add_argument(
'access_id',
metavar="<access_id>",
help=_('ID of the NAS share access rule.')
)
# metadata --> properties in osc
parser.add_argument(
'--property',
metavar='<key=value>',
default={},
action=parseractions.KeyValueAction,
help=_('Set a property to this share access rule. '
'(Repeat option to set multiple properties) '
'Available only for API microversion >= 2.45.'),
)
return parser
def take_action(self, parsed_args):
share_client = self.app.client_manager.share
if share_client.api_version >= api_versions.APIVersion("2.45"):
access_rule = share_client.share_access_rules.get(
parsed_args.access_id
)
try:
share_client.share_access_rules.set_metadata(
access_rule,
parsed_args.property)
except Exception as e:
raise exceptions.CommandError(
"Failed to set properties to share access rule with ID "
"'%s': %s" % (access_rule.id, e))
else:
raise exceptions.CommandError(
"Setting properties to access rule is supported only "
"with API microversion 2.45 and higher")
class UnsetShareAccess(command.Command):
"""Unset properties of share access rule."""
_description = _(
"Unset properties of share access rule. "
"Available for API microversion 2.45 and higher")
log = logging.getLogger(__name__ + ".UnsetShareAccess")
def get_parser(self, prog_name):
parser = super(UnsetShareAccess, self).get_parser(prog_name)
parser.add_argument(
'access_id',
metavar="<access_id>",
help=_('ID of the NAS share access rule.')
)
# metadata --> properties in osc
parser.add_argument(
'--property',
metavar='<key>',
action='append',
help=_('Remove property from share access rule. '
'(Repeat option to remove multiple properties) '
'Available only for API microversion >= 2.45.'),
)
return parser
def take_action(self, parsed_args):
share_client = self.app.client_manager.share
if share_client.api_version >= api_versions.APIVersion("2.45"):
access_rule = share_client.share_access_rules.get(
parsed_args.access_id
)
if parsed_args.property:
try:
share_client.share_access_rules.unset_metadata(
access_rule,
parsed_args.property)
except Exception as e:
raise exceptions.CommandError(
"Failed to unset properties for share access rule "
"with ID '%s': %s" % (access_rule.id, e))
else:
raise exceptions.CommandError(
"Please specify '--property <key>' to unset a property. ")
else:
raise exceptions.CommandError(
"Option to unset properties of access rule is available only "
"for API microversion 2.45 and higher")

View File

@@ -12,6 +12,7 @@
#
import copy
import datetime
import mock
import random
import uuid
@@ -29,6 +30,7 @@ class FakeShareClient(object):
self.auth_token = kwargs['token']
self.management_url = kwargs['endpoint']
self.shares = mock.Mock()
self.share_access_rules = mock.Mock()
self.shares.resource_class = osc_fakes.FakeResource(None, {})
self.share_export_locations = mock.Mock()
self.share_export_locations.resource_class = (
@@ -66,7 +68,7 @@ class FakeShare(object):
"""Fake one or more shares."""
@staticmethod
def create_one_share(attrs=None):
def create_one_share(attrs=None, methods=None):
"""Create a fake share.
:param Dictionary attrs:
@@ -76,6 +78,7 @@ class FakeShare(object):
"""
attrs = attrs or {}
methods = methods or {}
# set default attributes.
share_info = {
@@ -113,6 +116,7 @@ class FakeShare(object):
share_info.update(attrs)
share = osc_fakes.FakeResource(info=copy.deepcopy(share_info),
methods=methods,
loaded=True)
return share
@@ -261,3 +265,36 @@ class FakeShareExportLocation(object):
share_export_location_info),
loaded=True)
return share_export_location
class FakeShareAccessRule(object):
"""Fake one or more share access rules"""
@staticmethod
def create_one_access_rule(attrs=None):
"""Create a fake share access rule
:param Dictionary attrs:
A dictionary with all attributes
:return:
A FakeResource object, with project_id, resource and so on
"""
share_access_rule = {
'id': 'access_rule-id-' + uuid.uuid4().hex,
'share_id': 'share-id-' + uuid.uuid4().hex,
'access_level': 'rw',
'access_to': 'demo',
'access_type': 'user',
'state': 'queued_to_apply',
'access_key': None,
'created_at': datetime.datetime.now().isoformat(),
'updated_at': None,
'properties': {}
}
share_access_rule.update(attrs)
share_access_rule = osc_fakes.FakeResource(info=copy.deepcopy(
share_access_rule),
loaded=True)
return share_access_rule

View File

@@ -0,0 +1,357 @@
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
#
from osc_lib import utils as oscutils
from manilaclient import api_versions
from manilaclient.osc.v2 import share_access_rules as osc_share_access_rules
from manilaclient.tests.unit.osc.v2 import fakes as manila_fakes
ACCESS_RULE_ATTRIBUTES = [
'id',
'share_id',
'access_level',
'access_to',
'access_type',
'state',
'access_key',
'created_at',
'updated_at',
'properties'
]
class TestShareAccess(manila_fakes.TestShare):
def setUp(self):
super(TestShareAccess, self).setUp()
self.shares_mock = self.app.client_manager.share.shares
self.app.client_manager.share.api_version = api_versions.APIVersion(
'2.51')
self.shares_mock.reset_mock()
self.access_rules_mock = (
self.app.client_manager.share.share_access_rules)
self.access_rules_mock.reset_mock()
class TestShareAccessCreate(TestShareAccess):
def setUp(self):
super(TestShareAccessCreate, self).setUp()
self.share = manila_fakes.FakeShare.create_one_share(
attrs={"is_public": False},
methods={'allow': None})
self.shares_mock.get.return_value = self.share
self.access_rule = (
manila_fakes.FakeShareAccessRule.create_one_access_rule(
attrs={"share_id": self.share.id}))
self.share.allow.return_value = self.access_rule._info
# Get the command object to test
self.cmd = osc_share_access_rules.ShareAccessAllow(self.app, None)
def test_share_access_create_user(self):
arglist = [
self.share.id,
'user',
'demo',
]
verifylist = [
("share", self.share.id),
("access_type", "user"),
("access_to", "demo"),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
columns, data = self.cmd.take_action(parsed_args)
self.shares_mock.get.assert_called_with(self.share.id)
self.share.allow.assert_called_with(
access_type="user",
access="demo",
access_level=None,
metadata={}
)
self.assertEqual(ACCESS_RULE_ATTRIBUTES, columns)
self.assertCountEqual(self.access_rule._info.values(), data)
def test_share_access_create_properties(self):
arglist = [
self.share.id,
'user',
'demo',
'--properties', 'key=value'
]
verifylist = [
("share", self.share.id),
("access_type", "user"),
("access_to", "demo"),
('properties', ['key=value'])
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
columns, data = self.cmd.take_action(parsed_args)
self.shares_mock.get.assert_called_with(self.share.id)
self.share.allow.assert_called_with(
access_type="user",
access="demo",
access_level=None,
metadata={'key': 'value'}
)
self.assertEqual(ACCESS_RULE_ATTRIBUTES, columns)
self.assertCountEqual(self.access_rule._info.values(), data)
def test_access_rule_create_access_level(self):
arglist = [
self.share.id,
'user',
'demo',
'--access-level', 'ro'
]
verifylist = [
("share", self.share.id),
("access_type", "user"),
("access_to", "demo"),
('access_level', 'ro')
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
columns, data = self.cmd.take_action(parsed_args)
self.shares_mock.get.assert_called_with(self.share.id)
self.share.allow.assert_called_with(
access_type="user",
access="demo",
access_level='ro',
metadata={}
)
self.assertEqual(ACCESS_RULE_ATTRIBUTES, columns)
self.assertCountEqual(self.access_rule._info.values(), data)
class TestShareAccessDelete(TestShareAccess):
def setUp(self):
super(TestShareAccessDelete, self).setUp()
self.share = manila_fakes.FakeShare.create_one_share(
methods={'deny': None})
self.shares_mock.get.return_value = self.share
self.access_rule = (
manila_fakes.FakeShareAccessRule.create_one_access_rule(
attrs={"share_id": self.share.id}))
# Get the command object to test
self.cmd = osc_share_access_rules.ShareAccessDeny(self.app, None)
def test_share_access_delete(self):
arglist = [
self.share.id,
self.access_rule.id
]
verifylist = [
("share", self.share.id),
("id", self.access_rule.id)
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
result = self.cmd.take_action(parsed_args)
self.shares_mock.get.assert_called_with(self.share.id)
self.share.deny.assert_called_with(self.access_rule.id)
self.assertIsNone(result)
class TestShareAccessList(TestShareAccess):
access_rules_columns = [
'id',
'access_type',
'access_to',
'access_level',
'state',
'access_key',
'created_at',
'updated_at'
]
def setUp(self):
super(TestShareAccessList, self).setUp()
self.share = manila_fakes.FakeShare.create_one_share()
self.access_rule_1 = (
manila_fakes.FakeShareAccessRule.create_one_access_rule(
attrs={"share_id": self.share.id}))
self.access_rule_2 = (
manila_fakes.FakeShareAccessRule.create_one_access_rule(
attrs={"share_id": self.share.id, "access_to": "admin"}))
self.access_rules = [self.access_rule_1, self.access_rule_2]
self.shares_mock.get.return_value = self.share
self.access_rules_mock.access_list.return_value = self.access_rules
self.values_list = (oscutils.get_dict_properties(
a._info, self.access_rules_columns) for a in self.access_rules)
# Get the command object to test
self.cmd = osc_share_access_rules.ListShareAccess(self.app, None)
def test_access_rules_list(self):
arglist = [
self.share.id
]
verifylist = [
("share", self.share.id)
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
columns, data = self.cmd.take_action(parsed_args)
self.shares_mock.get.assert_called_with(self.share.id)
self.access_rules_mock.access_list.assert_called_with(
self.share,
{})
self.assertEqual(self.access_rules_columns, columns)
self.assertEqual(tuple(self.values_list), tuple(data))
def test_access_rules_list_filter_properties(self):
arglist = [
self.share.id,
'--properties', 'key=value'
]
verifylist = [
("share", self.share.id),
('properties', ['key=value'])
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
columns, data = self.cmd.take_action(parsed_args)
self.shares_mock.get.assert_called_with(self.share.id)
self.access_rules_mock.access_list.assert_called_with(
self.share,
{'metadata': {'key': 'value'}})
self.assertEqual(self.access_rules_columns, columns)
self.assertEqual(tuple(self.values_list), tuple(data))
def test_access_rules_list_columns(self):
expected_columns = [
'id',
'access_to'
]
expected_data = (oscutils.get_dict_properties(
a._info, expected_columns) for a in self.access_rules)
arglist = [
self.share.id,
'--columns', 'id,access_to'
]
verifylist = [
("share", self.share.id),
('columns', 'id,access_to')
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
columns, data = self.cmd.take_action(parsed_args)
self.shares_mock.get.assert_called_with(self.share.id)
self.access_rules_mock.access_list.assert_called_with(
self.share,
{})
self.assertEqual(expected_columns, columns)
self.assertEqual(tuple(expected_data), tuple(data))
class TestShareAccessShow(TestShareAccess):
def setUp(self):
super(TestShareAccessShow, self).setUp()
self.share = manila_fakes.FakeShare.create_one_share()
self.access_rule = (
manila_fakes.FakeShareAccessRule.create_one_access_rule(
attrs={"share_id": self.share.id}))
self.access_rules_mock.get.return_value = self.access_rule
# Get the command object to test
self.cmd = osc_share_access_rules.ShowShareAccess(self.app, None)
def test_access_rule_show(self):
arglist = [
self.access_rule.id
]
verifylist = [
("access_id", self.access_rule.id)
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
columns, data = self.cmd.take_action(parsed_args)
self.access_rules_mock.get.assert_called_with(self.access_rule.id)
self.assertEqual(ACCESS_RULE_ATTRIBUTES, columns)
self.assertEqual(tuple(self.access_rule._info.values()), data)
class TestShareAccessSet(TestShareAccess):
def setUp(self):
super(TestShareAccessSet, self).setUp()
self.share = manila_fakes.FakeShare.create_one_share()
self.access_rule = (
manila_fakes.FakeShareAccessRule.create_one_access_rule(
attrs={"share_id": self.share.id}))
self.access_rules_mock.get.return_value = self.access_rule
# Get the command object to test
self.cmd = osc_share_access_rules.SetShareAccess(self.app, None)
def test_access_rule_set(self):
arglist = [
self.access_rule.id,
'--property', 'key1=value1'
]
verifylist = [
("access_id", self.access_rule.id),
('property', {'key1': 'value1'})
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
result = self.cmd.take_action(parsed_args)
self.access_rules_mock.set_metadata.assert_called_with(
self.access_rule,
{'key1': 'value1'})
self.assertIsNone(result)
class TestShareAccessUnset(TestShareAccess):
def setUp(self):
super(TestShareAccessUnset, self).setUp()
self.share = manila_fakes.FakeShare.create_one_share()
self.access_rule = (
manila_fakes.FakeShareAccessRule.create_one_access_rule(
attrs={"share_id": self.share.id}))
self.access_rules_mock.get.return_value = self.access_rule
# Get the command object to test
self.cmd = osc_share_access_rules.UnsetShareAccess(self.app, None)
def test_access_rule_unset(self):
arglist = [
self.access_rule.id,
'--property', 'key1'
]
verifylist = [
("access_id", self.access_rule.id),
('property', ['key1'])
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
result = self.cmd.take_action(parsed_args)
self.access_rules_mock.unset_metadata.assert_called_with(
self.access_rule,
['key1'])
self.assertIsNone(result)

View File

@@ -44,6 +44,12 @@ openstack.share.v2 =
share_show = manilaclient.osc.v2.share:ShowShare
share_set = manilaclient.osc.v2.share:SetShare
share_unset = manilaclient.osc.v2.share:UnsetShare
share_access_create = manilaclient.osc.v2.share_access_rules:ShareAccessAllow
share_access_delete = manilaclient.osc.v2.share_access_rules:ShareAccessDeny
share_access_list = manilaclient.osc.v2.share_access_rules:ListShareAccess
share_access_show = manilaclient.osc.v2.share_access_rules:ShowShareAccess
share_access_set = manilaclient.osc.v2.share_access_rules:SetShareAccess
share_access_unset = manilaclient.osc.v2.share_access_rules:UnsetShareAccess
[wheel]
universal = 1