Skip to content
183 changes: 158 additions & 25 deletions qa/tasks/cephfs/test_nfs.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import json
import time
import logging
from io import BytesIO
from io import BytesIO, StringIO

from tasks.mgr.mgr_test_case import MgrTestCase
from teuthology import contextutil
Expand All @@ -21,6 +21,12 @@ def _cmd(self, *args):
def _nfs_cmd(self, *args):
return self._cmd("nfs", *args)

def _nfs_complete_cmd(self, cmd):
return self.mgr_cluster.mon_manager.run_cluster_cmd(args=f"nfs {cmd}",
stdout=StringIO(),
stderr=StringIO(),
check_status=False)

def _orch_cmd(self, *args):
return self._cmd("orch", *args)

Expand Down Expand Up @@ -106,13 +112,12 @@ def _check_nfs_cluster_status(self, expected_status, fail_msg):
:param expected_status: Status to be verified
:param fail_msg: Message to be printed if test failed
'''
# Wait for two minutes as ganesha daemon takes some time to be deleted/created
wait_time = 10
while wait_time <= 120:
time.sleep(wait_time)
if expected_status in self._fetch_nfs_daemons_details():
return
wait_time += 10
# Wait for a minute as ganesha daemon takes some time to be
# deleted/created
with contextutil.safe_while(sleep=6, tries=10, _raise=False) as proceed:
while proceed():
if expected_status in self._fetch_nfs_daemons_details():
return
self.fail(fail_msg)

def _check_auth_ls(self, export_id=1, check_in=False):
Expand Down Expand Up @@ -145,11 +150,24 @@ def _test_create_cluster(self):
'''
Test single nfs cluster deployment.
'''
# Disable any running nfs ganesha daemon
self._check_nfs_server_status()
self._nfs_cmd('cluster', 'create', self.cluster_id)
# Check for expected status and daemon name (nfs.<cluster_id>)
self._check_nfs_cluster_status('running', 'NFS Ganesha cluster deployment failed')
with contextutil.safe_while(sleep=4, tries=10) as proceed:
while proceed():
try:
# Disable any running nfs ganesha daemon
self._check_nfs_server_status()
cluster_create = self._nfs_complete_cmd(
f'cluster create {self.cluster_id}')
if cluster_create.stderr and 'cluster already exists' \
in cluster_create.stderr.getvalue():
self._test_delete_cluster()
continue
# Check for expected status and daemon name
# (nfs.<cluster_id>)
self._check_nfs_cluster_status(
'running', 'NFS Ganesha cluster deployment failed')
break
except (AssertionError, CommandFailedError) as e:
log.warning(f'{e}, retrying')

def _test_delete_cluster(self):
'''
Expand Down Expand Up @@ -282,9 +300,20 @@ def _get_port_ip_info(self):
'''
Return port and ip for a cluster
'''
#{'test': {'backend': [{'hostname': 'smithi068', 'ip': '172.21.15.68', 'port': 2049}]}}
info_output = json.loads(self._nfs_cmd('cluster', 'info', self.cluster_id))['test']['backend'][0]
return info_output["port"], info_output["ip"]
#{'test': {'backend': [{'hostname': 'smithi068', 'ip': '172.21.15.68',
#'port': 2049}]}}
with contextutil.safe_while(sleep=5, tries=6) as proceed:
while proceed():
try:
info_output = json.loads(
self._nfs_cmd('cluster', 'info',
self.cluster_id))['test']['backend'][0]
return info_output["port"], info_output["ip"]
except (IndexError, CommandFailedError) as e:
if 'list index out of range' in str(e):
log.warning('no port and/or ip found, retrying')
else:
log.warning(f'{e}, retrying')

def _test_mnt(self, pseudo_path, port, ip, check=True):
'''
Expand Down Expand Up @@ -334,6 +363,49 @@ def _write_to_read_only_export(self, pseudo_path, port, ip):
else:
self.fail('expected write to a read-only export to fail')

def _create_cluster_with_fs(self, fs_name, mnt_pt=None):
"""
create a cluster along with fs and mount it to the path supplied
:param fs_name: name of CephFS volume to be created
:param mnt_pt: mount fs to the path
"""
self._test_create_cluster()
self._cmd('fs', 'volume', 'create', fs_name)
with contextutil.safe_while(sleep=5, tries=30) as proceed:
while proceed():
output = self._cmd(
'orch', 'ls', '-f', 'json',
'--service-name', f'mds.{fs_name}'
)
j = json.loads(output)
if j[0]['status']['running']:
break
if mnt_pt:
with contextutil.safe_while(sleep=3, tries=3) as proceed:
while proceed():
try:
self.ctx.cluster.run(args=['sudo', 'ceph-fuse', mnt_pt])
break
except CommandFailedError as e:
log.warning(f'{e}, retrying')
self.ctx.cluster.run(args=['sudo', 'chmod', '1777', mnt_pt])

def _delete_cluster_with_fs(self, fs_name, mnt_pt=None, mode=None):
"""
delete cluster along with fs and unmount it from the path supplied
:param fs_name: name of CephFS volume to be deleted
:param mnt_pt: unmount fs from the path
:param mode: revert to this mode
"""
if mnt_pt:
self.ctx.cluster.run(args=['sudo', 'umount', mnt_pt])
if mode:
if isinstance(mode, bytes):
mode = mode.decode().strip()
self.ctx.cluster.run(args=['sudo', 'chmod', mode, mnt_pt])
self._cmd('fs', 'volume', 'rm', fs_name, '--yes-i-really-mean-it')
self._test_delete_cluster()

def test_create_and_delete_cluster(self):
'''
Test successful creation and deletion of the nfs cluster.
Expand Down Expand Up @@ -584,15 +656,20 @@ def test_cluster_set_user_config_with_non_existing_clusterid(self):
'''
Test setting user config for non-existing nfs cluster.
'''
try:
cluster_id = 'invalidtest'
self.ctx.cluster.run(args=['ceph', 'nfs', 'cluster',
'config', 'set', self.cluster_id, '-i', '-'], stdin='testing')
self.fail(f"User config set for non-existing cluster {cluster_id}")
except CommandFailedError as e:
# Command should fail for test to pass
if e.exitstatus != errno.ENOENT:
raise
cluster_id = 'invalidtest'
with contextutil.safe_while(sleep=3, tries=3) as proceed:
while proceed():
try:
self.ctx.cluster.run(args=['ceph', 'nfs', 'cluster',
'config', 'set', cluster_id,
'-i', '-'], stdin='testing')
self.fail(f"User config set for non-existing cluster"
f"{cluster_id}")
except CommandFailedError as e:
# Command should fail for test to pass
if e.exitstatus == errno.ENOENT:
break
log.warning('exitstatus != ENOENT, retrying')

def test_cluster_reset_user_config_with_non_existing_clusterid(self):
'''
Expand Down Expand Up @@ -744,3 +821,59 @@ def test_non_existent_cluster(self):
except CommandFailedError as e:
if e.exitstatus != errno.ENOENT:
raise

def test_nfs_export_with_invalid_path(self):
"""
Test that nfs exports can't be created with invalid path
"""
self._test_create_cluster()
try:
self._create_export(export_id='123',
extra_cmd=['--pseudo-path', self.pseudo_path,
'--path', '/non_existent_dir'])
except CommandFailedError as e:
if e.exitstatus != errno.ENOENT:
raise
self._test_delete_cluster()

def test_nfs_export_creation_at_filepath(self):
"""
Test that nfs exports can't be created at a filepath
"""
mnt_pt = '/mnt'
preserve_mode = self._sys_cmd(['stat', '-c', '%a', mnt_pt])
self._create_cluster_with_fs(self.fs_name, mnt_pt)
self.ctx.cluster.run(args=['touch', f'{mnt_pt}/testfile'])
try:
self._create_export(export_id='123', extra_cmd=['--pseudo-path',
self.pseudo_path,
'--path',
'/testfile'])
except CommandFailedError as e:
# NotADirectoryError is raised as EINVAL
if e.exitstatus != errno.EINVAL:
raise
self.ctx.cluster.run(args=['rm', '-rf', '/mnt/testfile'])
self._delete_cluster_with_fs(self.fs_name, mnt_pt, preserve_mode)

def test_nfs_export_creation_at_symlink(self):
"""
Test that nfs exports can't be created at a symlink path
"""
mnt_pt = '/mnt'
preserve_mode = self._sys_cmd(['stat', '-c', '%a', mnt_pt])
self._create_cluster_with_fs(self.fs_name, mnt_pt)
self.ctx.cluster.run(args=['mkdir', f'{mnt_pt}/testdir'])
self.ctx.cluster.run(args=['ln', '-s', 'testdir', 'testdir_symlink'],
cwd=f'{mnt_pt}')
try:
self._create_export(export_id='123',
extra_cmd=['--pseudo-path',
self.pseudo_path,
'--path',
f'{mnt_pt}/testdir_symlink'])
except CommandFailedError as e:
if e.exitstatus != errno.ENOENT:
raise
self.ctx.cluster.run(args=['rm', '-rf', f'{mnt_pt}/*'])
self._delete_cluster_with_fs(self.fs_name, mnt_pt, preserve_mode)
5 changes: 4 additions & 1 deletion src/pybind/mgr/nfs/export.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@
conf_obj_name,
available_clusters,
check_fs,
restart_nfs_service)
restart_nfs_service, check_cephfs_path)

if TYPE_CHECKING:
from nfs.module import Module
Expand Down Expand Up @@ -658,6 +658,9 @@ def create_cephfs_export(self,
access_type: str,
clients: list = [],
sectype: Optional[List[str]] = None) -> Dict[str, Any]:

check_cephfs_path(self.mgr, fs_name, path)

pseudo_path = normalize_path(pseudo_path)

if not self._fetch_export(cluster_id, pseudo_path):
Expand Down
3 changes: 2 additions & 1 deletion src/pybind/mgr/nfs/tests/test_nfs.py
Original file line number Diff line number Diff line change
Expand Up @@ -251,7 +251,8 @@ def mock_list_daemons(cls, *args, **kwargs):
mock.patch('nfs.export.check_fs', return_value=True), \
mock.patch('nfs.ganesha_conf.check_fs', return_value=True), \
mock.patch('nfs.export.ExportMgr._create_user_key',
return_value='thekeyforclientabc'):
return_value='thekeyforclientabc'), \
mock.patch('nfs.export.check_cephfs_path'):

rados.open_ioctx.return_value.__enter__.return_value = self.io_mock
rados.open_ioctx.return_value.__exit__ = mock.Mock(return_value=None)
Expand Down
30 changes: 30 additions & 0 deletions src/pybind/mgr/nfs/utils.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,13 @@
import errno
import functools
import logging
import stat
from typing import List, Tuple, TYPE_CHECKING

from object_format import ErrorResponseBase
import orchestrator
import cephfs
from mgr_util import CephfsClient, open_filesystem

if TYPE_CHECKING:
from nfs.module import Module
Expand All @@ -10,6 +16,8 @@
CONF_PREFIX: str = "conf-nfs."
USER_CONF_PREFIX: str = "userconf-nfs."

log = logging.getLogger(__name__)


class NonFatalError(ErrorResponseBase):
"""Raise this exception when you want to interrupt the flow of a function
Expand Down Expand Up @@ -82,3 +90,25 @@ def check_fs(mgr: 'Module', fs_name: str) -> bool:
'''
fs_map = mgr.get('fs_map')
return fs_name in [fs['mdsmap']['fs_name'] for fs in fs_map['filesystems']]


def check_cephfs_path(mgr: 'Module', fs: str, path: str) -> None:
@functools.lru_cache(maxsize=1)
Comment thread
vshankar marked this conversation as resolved.
Resolved
def _get_cephfs_client() -> CephfsClient:
return CephfsClient(mgr)
try:
cephfs_client = _get_cephfs_client()
with open_filesystem(cephfs_client, fs) as fs_handle:
stx = fs_handle.statx(path.encode('utf-8'),
cephfs.CEPH_STATX_MODE, 0)
if not stat.S_ISDIR(stx.get('mode')):
raise NotADirectoryError(f"{path} is not a dir")
except cephfs.ObjectNotFound as e:
log.exception(f"{-errno.ENOENT}: {e.args[1]}")
raise e
except cephfs.Error as e:
log.exception(f"{e.args[0]}: {e.args[1]}")
raise e
except Exception as e:
log.exception(f"unknown exception occurred: {e}")
raise e