]> git.proxmox.com Git - ceph.git/blame - ceph/qa/tasks/cephfs/cephfs_test_case.py
import new upstream nautilus stable release 14.2.8
[ceph.git] / ceph / qa / tasks / cephfs / cephfs_test_case.py
CommitLineData
81eedcae 1import time
7c673cae
FG
2import json
3import logging
4from unittest import case
5from tasks.ceph_test_case import CephTestCase
6import os
7import re
8from StringIO import StringIO
9
10from tasks.cephfs.fuse_mount import FuseMount
11
12from teuthology.orchestra import run
13from teuthology.orchestra.run import CommandFailedError
14
15
16log = logging.getLogger(__name__)
17
18
19def for_teuthology(f):
20 """
21 Decorator that adds an "is_for_teuthology" attribute to the wrapped function
22 """
23 f.is_for_teuthology = True
24 return f
25
26
27def needs_trimming(f):
28 """
29 Mark fn as requiring a client capable of trimming its cache (i.e. for ceph-fuse
30 this means it needs to be able to run as root, currently)
31 """
32 f.needs_trimming = True
33 return f
34
35
36class CephFSTestCase(CephTestCase):
37 """
38 Test case for Ceph FS, requires caller to populate Filesystem and Mounts,
39 into the fs, mount_a, mount_b class attributes (setting mount_b is optional)
40
41 Handles resetting the cluster under test between tests.
42 """
43
44 # FIXME weird explicit naming
45 mount_a = None
46 mount_b = None
181888fb 47 recovery_mount = None
7c673cae
FG
48
49 # Declarative test requirements: subclasses should override these to indicate
50 # their special needs. If not met, tests will be skipped.
51 CLIENTS_REQUIRED = 1
52 MDSS_REQUIRED = 1
53 REQUIRE_KCLIENT_REMOTE = False
54 REQUIRE_ONE_CLIENT_REMOTE = False
7c673cae
FG
55
56 # Whether to create the default filesystem during setUp
57 REQUIRE_FILESYSTEM = True
58
181888fb
FG
59 # requires REQUIRE_FILESYSTEM = True
60 REQUIRE_RECOVERY_FILESYSTEM = False
61
7c673cae
FG
62 LOAD_SETTINGS = []
63
64 def setUp(self):
65 super(CephFSTestCase, self).setUp()
66
67 if len(self.mds_cluster.mds_ids) < self.MDSS_REQUIRED:
68 raise case.SkipTest("Only have {0} MDSs, require {1}".format(
69 len(self.mds_cluster.mds_ids), self.MDSS_REQUIRED
70 ))
71
72 if len(self.mounts) < self.CLIENTS_REQUIRED:
73 raise case.SkipTest("Only have {0} clients, require {1}".format(
74 len(self.mounts), self.CLIENTS_REQUIRED
75 ))
76
77 if self.REQUIRE_KCLIENT_REMOTE:
78 if not isinstance(self.mounts[0], FuseMount) or not isinstance(self.mounts[1], FuseMount):
79 # kclient kill() power cycles nodes, so requires clients to each be on
80 # their own node
81 if self.mounts[0].client_remote.hostname == self.mounts[1].client_remote.hostname:
82 raise case.SkipTest("kclient clients must be on separate nodes")
83
84 if self.REQUIRE_ONE_CLIENT_REMOTE:
85 if self.mounts[0].client_remote.hostname in self.mds_cluster.get_mds_hostnames():
86 raise case.SkipTest("Require first client to be on separate server from MDSs")
87
7c673cae
FG
88 # Create friendly mount_a, mount_b attrs
89 for i in range(0, self.CLIENTS_REQUIRED):
90 setattr(self, "mount_{0}".format(chr(ord('a') + i)), self.mounts[i])
91
92 self.mds_cluster.clear_firewall()
93
94 # Unmount all clients, we are about to blow away the filesystem
95 for mount in self.mounts:
96 if mount.is_mounted():
97 mount.umount_wait(force=True)
98
99 # To avoid any issues with e.g. unlink bugs, we destroy and recreate
100 # the filesystem rather than just doing a rm -rf of files
7c673cae 101 self.mds_cluster.delete_all_filesystems()
92f5a8d4 102 self.mds_cluster.mds_restart() # to reset any run-time configs, etc.
7c673cae 103 self.fs = None # is now invalid!
181888fb 104 self.recovery_fs = None
7c673cae 105
7c673cae
FG
106 # In case anything is in the OSD blacklist list, clear it out. This is to avoid
107 # the OSD map changing in the background (due to blacklist expiry) while tests run.
108 try:
109 self.mds_cluster.mon_manager.raw_cluster_cmd("osd", "blacklist", "clear")
110 except CommandFailedError:
111 # Fallback for older Ceph cluster
112 blacklist = json.loads(self.mds_cluster.mon_manager.raw_cluster_cmd("osd",
113 "dump", "--format=json-pretty"))['blacklist']
114 log.info("Removing {0} blacklist entries".format(len(blacklist)))
115 for addr, blacklisted_at in blacklist.items():
116 self.mds_cluster.mon_manager.raw_cluster_cmd("osd", "blacklist", "rm", addr)
117
118 client_mount_ids = [m.client_id for m in self.mounts]
119 # In case the test changes the IDs of clients, stash them so that we can
120 # reset in tearDown
121 self._original_client_ids = client_mount_ids
122 log.info(client_mount_ids)
123
124 # In case there were any extra auth identities around from a previous
125 # test, delete them
126 for entry in self.auth_list():
127 ent_type, ent_id = entry['entity'].split(".")
128 if ent_type == "client" and ent_id not in client_mount_ids and ent_id != "admin":
129 self.mds_cluster.mon_manager.raw_cluster_cmd("auth", "del", entry['entity'])
130
131 if self.REQUIRE_FILESYSTEM:
181888fb 132 self.fs = self.mds_cluster.newfs(create=True)
7c673cae
FG
133
134 # In case some test messed with auth caps, reset them
135 for client_id in client_mount_ids:
136 self.mds_cluster.mon_manager.raw_cluster_cmd_result(
137 'auth', 'caps', "client.{0}".format(client_id),
138 'mds', 'allow',
139 'mon', 'allow r',
140 'osd', 'allow rw pool={0}'.format(self.fs.get_data_pool_name()))
141
92f5a8d4 142 # wait for ranks to become active
7c673cae
FG
143 self.fs.wait_for_daemons()
144
145 # Mount the requested number of clients
146 for i in range(0, self.CLIENTS_REQUIRED):
147 self.mounts[i].mount()
148 self.mounts[i].wait_until_mounted()
149
181888fb
FG
150 if self.REQUIRE_RECOVERY_FILESYSTEM:
151 if not self.REQUIRE_FILESYSTEM:
152 raise case.SkipTest("Recovery filesystem requires a primary filesystem as well")
153 self.fs.mon_manager.raw_cluster_cmd('fs', 'flag', 'set',
154 'enable_multiple', 'true',
155 '--yes-i-really-mean-it')
156 self.recovery_fs = self.mds_cluster.newfs(name="recovery_fs", create=False)
157 self.recovery_fs.set_metadata_overlay(True)
158 self.recovery_fs.set_data_pool_name(self.fs.get_data_pool_name())
159 self.recovery_fs.create()
160 self.recovery_fs.getinfo(refresh=True)
161 self.recovery_fs.mds_restart()
162 self.recovery_fs.wait_for_daemons()
163
7c673cae
FG
164 # Load an config settings of interest
165 for setting in self.LOAD_SETTINGS:
c07f9fc5 166 setattr(self, setting, float(self.fs.mds_asok(
7c673cae
FG
167 ['config', 'get', setting], self.mds_cluster.mds_ids[0]
168 )[setting]))
169
170 self.configs_set = set()
171
172 def tearDown(self):
173 super(CephFSTestCase, self).tearDown()
174
175 self.mds_cluster.clear_firewall()
176 for m in self.mounts:
177 m.teardown()
178
179 for i, m in enumerate(self.mounts):
180 m.client_id = self._original_client_ids[i]
181
182 for subsys, key in self.configs_set:
183 self.mds_cluster.clear_ceph_conf(subsys, key)
184
185 def set_conf(self, subsys, key, value):
186 self.configs_set.add((subsys, key))
187 self.mds_cluster.set_ceph_conf(subsys, key, value)
188
189 def auth_list(self):
190 """
c07f9fc5 191 Convenience wrapper on "ceph auth ls"
7c673cae
FG
192 """
193 return json.loads(self.mds_cluster.mon_manager.raw_cluster_cmd(
c07f9fc5 194 "auth", "ls", "--format=json-pretty"
7c673cae
FG
195 ))['auth_dump']
196
197 def assert_session_count(self, expected, ls_data=None, mds_id=None):
198 if ls_data is None:
199 ls_data = self.fs.mds_asok(['session', 'ls'], mds_id=mds_id)
200
31f18b77
FG
201 alive_count = len([s for s in ls_data if s['state'] != 'killing'])
202
203 self.assertEqual(expected, alive_count, "Expected {0} sessions, found {1}".format(
204 expected, alive_count
7c673cae
FG
205 ))
206
207 def assert_session_state(self, client_id, expected_state):
208 self.assertEqual(
209 self._session_by_id(
210 self.fs.mds_asok(['session', 'ls'])).get(client_id, {'state': None})['state'],
211 expected_state)
212
213 def get_session_data(self, client_id):
214 return self._session_by_id(client_id)
215
216 def _session_list(self):
217 ls_data = self.fs.mds_asok(['session', 'ls'])
218 ls_data = [s for s in ls_data if s['state'] not in ['stale', 'closed']]
219 return ls_data
220
221 def get_session(self, client_id, session_ls=None):
222 if session_ls is None:
223 session_ls = self.fs.mds_asok(['session', 'ls'])
224
225 return self._session_by_id(session_ls)[client_id]
226
227 def _session_by_id(self, session_ls):
228 return dict([(s['id'], s) for s in session_ls])
229
92f5a8d4
TL
230 def wait_until_evicted(self, client_id, timeout=30):
231 def is_client_evicted():
232 ls = self._session_list()
233 for s in ls:
234 if s['id'] == client_id:
235 return False
236 return True
237 self.wait_until_true(is_client_evicted, timeout)
238
7c673cae
FG
239 def wait_for_daemon_start(self, daemon_ids=None):
240 """
241 Wait until all the daemons appear in the FSMap, either assigned
242 MDS ranks or in the list of standbys
243 """
244 def get_daemon_names():
245 return [info['name'] for info in self.mds_cluster.status().get_all()]
246
247 if daemon_ids is None:
248 daemon_ids = self.mds_cluster.mds_ids
249
250 try:
251 self.wait_until_true(
252 lambda: set(daemon_ids) & set(get_daemon_names()) == set(daemon_ids),
253 timeout=30
254 )
255 except RuntimeError:
256 log.warn("Timeout waiting for daemons {0}, while we have {1}".format(
257 daemon_ids, get_daemon_names()
258 ))
259 raise
260
11fdf7f2
TL
261 def delete_mds_coredump(self, daemon_id):
262 # delete coredump file, otherwise teuthology.internal.coredump will
263 # catch it later and treat it as a failure.
264 p = self.mds_cluster.mds_daemons[daemon_id].remote.run(args=[
265 "sudo", "sysctl", "-n", "kernel.core_pattern"], stdout=StringIO())
266 core_dir = os.path.dirname(p.stdout.getvalue().strip())
267 if core_dir: # Non-default core_pattern with a directory in it
268 # We have seen a core_pattern that looks like it's from teuthology's coredump
269 # task, so proceed to clear out the core file
270 log.info("Clearing core from directory: {0}".format(core_dir))
271
272 # Verify that we see the expected single coredump
273 ls_proc = self.mds_cluster.mds_daemons[daemon_id].remote.run(args=[
274 "cd", core_dir, run.Raw('&&'),
275 "sudo", "ls", run.Raw('|'), "sudo", "xargs", "file"
276 ], stdout=StringIO())
277 cores = [l.partition(":")[0]
278 for l in ls_proc.stdout.getvalue().strip().split("\n")
279 if re.match(r'.*ceph-mds.* -i +{0}'.format(daemon_id), l)]
280
281 log.info("Enumerated cores: {0}".format(cores))
282 self.assertEqual(len(cores), 1)
283
284 log.info("Found core file {0}, deleting it".format(cores[0]))
285
286 self.mds_cluster.mds_daemons[daemon_id].remote.run(args=[
287 "cd", core_dir, run.Raw('&&'), "sudo", "rm", "-f", cores[0]
288 ])
7c673cae 289 else:
11fdf7f2 290 log.info("No core_pattern directory set, nothing to clear (internal.coredump not enabled?)")
81eedcae
TL
291
292 def _wait_subtrees(self, status, rank, test):
293 timeout = 30
294 pause = 2
295 test = sorted(test)
296 for i in range(timeout/pause):
297 subtrees = self.fs.mds_asok(["get", "subtrees"], mds_id=status.get_rank(self.fs.id, rank)['name'])
298 subtrees = filter(lambda s: s['dir']['path'].startswith('/'), subtrees)
299 filtered = sorted([(s['dir']['path'], s['auth_first']) for s in subtrees])
300 log.info("%s =?= %s", filtered, test)
301 if filtered == test:
302 # Confirm export_pin in output is correct:
303 for s in subtrees:
304 self.assertTrue(s['export_pin'] == s['auth_first'])
305 return subtrees
306 time.sleep(pause)
307 raise RuntimeError("rank {0} failed to reach desired subtree state", rank)