-
Notifications
You must be signed in to change notification settings - Fork 1
/
vstart_runner.py
1762 lines (1459 loc) · 62.3 KB
/
vstart_runner.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
vstart_runner: override Filesystem and Mount interfaces to run a CephFSTestCase against a vstart
ceph instance instead of a packaged/installed cluster. Use this to turn around test cases
quickly during development.
Simple usage (assuming teuthology and ceph checked out in ~/git):
# Activate the teuthology virtualenv
source ~/git/teuthology/virtualenv/bin/activate
# Go into your ceph build directory
cd ~/git/ceph/build
# Invoke a test using this script
python ~/git/ceph/qa/tasks/vstart_runner.py --create tasks.cephfs.test_data_scan
Alternative usage:
# Alternatively, if you use different paths, specify them as follows:
LD_LIBRARY_PATH=`pwd`/lib PYTHONPATH=~/git/teuthology:~/git/ceph/qa:`pwd`/../src/pybind:`pwd`/lib/cython_modules/lib.3 python ~/git/ceph/qa/tasks/vstart_runner.py
# If you wish to drop to a python shell on failures, use --interactive:
python ~/git/ceph/qa/tasks/vstart_runner.py --interactive
# If you wish to run a named test case, pass it as an argument:
python ~/git/ceph/qa/tasks/vstart_runner.py tasks.cephfs.test_data_scan
# Also, you can create the cluster once and then run named test cases against it:
python ~/git/ceph/qa/tasks/vstart_runner.py --create-cluster-only
python ~/git/ceph/qa/tasks/vstart_runner.py tasks.mgr.dashboard.test_health
python ~/git/ceph/qa/tasks/vstart_runner.py tasks.mgr.dashboard.test_rgw
"""
from io import StringIO
from collections import defaultdict
import getpass
import signal
import tempfile
import threading
import datetime
import shutil
import re
import os
import time
import sys
import errno
from IPy import IP
import unittest
import platform
import logging
from unittest import suite, loader
from teuthology.orchestra.run import Raw, quote
from teuthology.orchestra.daemon import DaemonGroup
from teuthology.orchestra.remote import Remote
from teuthology.config import config as teuth_config
from teuthology.contextutil import safe_while
from teuthology.contextutil import MaxWhileTries
from teuthology.orchestra.run import CommandFailedError
try:
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
except:
pass
def init_log(log_level=logging.INFO):
global log
if log is not None:
del log
log = logging.getLogger(__name__)
global logpath
logpath = './vstart_runner.log'
handler = logging.FileHandler(logpath)
formatter = logging.Formatter(
fmt=u'%(asctime)s.%(msecs)03d %(levelname)s:%(name)s:%(message)s',
datefmt='%Y-%m-%dT%H:%M:%S')
handler.setFormatter(formatter)
log.addHandler(handler)
log.setLevel(log_level)
log = None
init_log()
def respawn_in_path(lib_path, python_paths):
execv_cmd = ['python']
if platform.system() == "Darwin":
lib_path_var = "DYLD_LIBRARY_PATH"
else:
lib_path_var = "LD_LIBRARY_PATH"
py_binary = os.environ.get("PYTHON", sys.executable)
if lib_path_var in os.environ:
if lib_path not in os.environ[lib_path_var]:
os.environ[lib_path_var] += ':' + lib_path
os.execvp(py_binary, execv_cmd + sys.argv)
else:
os.environ[lib_path_var] = lib_path
os.execvp(py_binary, execv_cmd + sys.argv)
for p in python_paths:
sys.path.insert(0, p)
# Let's use some sensible defaults
if os.path.exists("./CMakeCache.txt") and os.path.exists("./bin"):
# A list of candidate paths for each package we need
guesses = [
["~/git/teuthology", "~/scm/teuthology", "~/teuthology"],
["lib/cython_modules/lib.3"],
["../src/pybind"],
]
python_paths = []
# Up one level so that "tasks.foo.bar" imports work
python_paths.append(os.path.abspath(
os.path.join(os.path.dirname(os.path.realpath(__file__)), "..")
))
for package_guesses in guesses:
for g in package_guesses:
g_exp = os.path.abspath(os.path.expanduser(g))
if os.path.exists(g_exp):
python_paths.append(g_exp)
ld_path = os.path.join(os.getcwd(), "lib/")
print("Using guessed paths {0} {1}".format(ld_path, python_paths))
respawn_in_path(ld_path, python_paths)
try:
from tasks.ceph_manager import CephManager
from tasks.cephfs.fuse_mount import FuseMount
from tasks.cephfs.kernel_mount import KernelMount
from tasks.cephfs.filesystem import Filesystem, MDSCluster, CephCluster
from tasks.cephfs.mount import CephFSMount
from tasks.mgr.mgr_test_case import MgrCluster
from teuthology.task import interactive
except ImportError:
sys.stderr.write("***\nError importing packages, have you activated your teuthology virtualenv "
"and set PYTHONPATH to point to teuthology and ceph-qa-suite?\n***\n\n")
raise
# Must import after teuthology because of gevent monkey patching
import subprocess
if os.path.exists("./CMakeCache.txt"):
# Running in build dir of a cmake build
BIN_PREFIX = "./bin/"
SRC_PREFIX = "../src"
else:
# Running in src/ of an autotools build
BIN_PREFIX = "./"
SRC_PREFIX = "./"
def rm_nonascii_chars(var):
var = var.replace(b'\xe2\x80\x98', b'\'')
var = var.replace(b'\xe2\x80\x99', b'\'')
return var
class LocalRemoteProcess(object):
def __init__(self, args, subproc, check_status, stdout, stderr):
self.args = args
self.subproc = subproc
self.stdout = stdout
self.stderr = stderr
# this variable is meant for instance of this class named fuse_daemon.
# child process of the command launched with sudo must be killed,
# since killing parent process alone has no impact on the child
# process.
self.fuse_pid = -1
self.check_status = check_status
self.exitstatus = self.returncode = None
def wait(self):
if self.finished:
# Avoid calling communicate() on a dead process because it'll
# give you stick about std* already being closed
if self.check_status and self.exitstatus != 0:
raise CommandFailedError(self.args, self.exitstatus)
else:
return
out, err = self.subproc.communicate()
out, err = rm_nonascii_chars(out), rm_nonascii_chars(err)
if isinstance(self.stdout, StringIO):
self.stdout.write(out.decode(errors='ignore'))
elif self.stdout is None:
pass
else:
self.stdout.write(out)
if isinstance(self.stderr, StringIO):
self.stderr.write(err.decode(errors='ignore'))
elif self.stderr is None:
pass
else:
self.stderr.write(err)
self.exitstatus = self.returncode = self.subproc.returncode
if self.exitstatus != 0:
sys.stderr.write(out.decode())
sys.stderr.write(err.decode())
if self.check_status and self.exitstatus != 0:
raise CommandFailedError(self.args, self.exitstatus)
@property
def finished(self):
if self.exitstatus is not None:
return True
if self.subproc.poll() is not None:
out, err = self.subproc.communicate()
if isinstance(self.stdout, StringIO):
self.stdout.write(out.decode(errors='ignore'))
elif self.stdout is None:
pass
else:
self.stdout.write(out)
if isinstance(self.stderr, StringIO):
self.stderr.write(err.decode(errors='ignore'))
elif self.stderr is None:
pass
else:
self.stderr.write(err)
self.exitstatus = self.returncode = self.subproc.returncode
return True
else:
return False
def kill(self):
log.debug("kill ")
if self.subproc.pid and not self.finished:
log.debug("kill: killing pid {0} ({1})".format(
self.subproc.pid, self.args))
if self.fuse_pid != -1:
safe_kill(self.fuse_pid)
else:
safe_kill(self.subproc.pid)
else:
log.debug("kill: already terminated ({0})".format(self.args))
@property
def stdin(self):
class FakeStdIn(object):
def __init__(self, mount_daemon):
self.mount_daemon = mount_daemon
def close(self):
self.mount_daemon.kill()
return FakeStdIn(self)
class LocalRemote(object):
"""
Amusingly named class to present the teuthology RemoteProcess interface when we are really
running things locally for vstart
Run this inside your src/ dir!
"""
os = Remote.os
arch = Remote.arch
def __init__(self):
self.name = "local"
self.hostname = "localhost"
self.user = getpass.getuser()
def get_file(self, path, sudo, dest_dir):
tmpfile = tempfile.NamedTemporaryFile(delete=False).name
shutil.copy(path, tmpfile)
return tmpfile
# XXX: This method ignores the error raised when src and dst are
# holding same path. For teuthology, same path still represents
# different locations as they lie on different machines.
def put_file(self, src, dst, sudo=False):
try:
shutil.copy(src, dst)
except shutil.SameFileError:
pass
# XXX: accepts only two arugments to maintain compatibility with
# teuthology's mkdtemp.
def mkdtemp(self, suffix='', parentdir=None):
from tempfile import mkdtemp
# XXX: prefix had to be set without that this method failed against
# Python2.7 -
# > /usr/lib64/python2.7/tempfile.py(337)mkdtemp()
# -> file = _os.path.join(dir, prefix + name + suffix)
# (Pdb) p prefix
# None
return mkdtemp(suffix=suffix, prefix='', dir=parentdir)
def mktemp(self, suffix=None, parentdir=None):
"""
Make a remote temporary file
Returns: the path of the temp file created.
"""
from tempfile import mktemp
return mktemp(suffix=suffix, dir=parentdir)
def write_file(self, path, data, sudo=False, mode=None, owner=None,
mkdir=False, append=False):
"""
Write data to file
:param path: file path on host
:param data: str, binary or fileobj to be written
:param sudo: use sudo to write file, defaults False
:param mode: set file mode bits if provided
:param owner: set file owner if provided
:param mkdir: preliminary create the file directory, defaults False
:param append: append data to the file, defaults False
"""
dd = 'sudo dd' if sudo else 'dd'
args = dd + ' of=' + path
if append:
args += ' conv=notrunc oflag=append'
if mkdir:
mkdirp = 'sudo mkdir -p' if sudo else 'mkdir -p'
dirpath = os.path.dirname(path)
if dirpath:
args = mkdirp + ' ' + dirpath + '\n' + args
if mode:
chmod = 'sudo chmod' if sudo else 'chmod'
args += '\n' + chmod + ' ' + mode + ' ' + path
if owner:
chown = 'sudo chown' if sudo else 'chown'
args += '\n' + chown + ' ' + owner + ' ' + path
omit_sudo = False if sudo else True
self.run(args=args, stdin=data, omit_sudo=omit_sudo)
def sudo_write_file(self, path, data, **kwargs):
"""
Write data to file with sudo, for more info see `write_file()`.
"""
self.write_file(path, data, sudo=True, **kwargs)
def _perform_checks_and_return_list_of_args(self, args, omit_sudo):
# Since Python's shell simulation can only work when commands are
# provided as a list of argumensts...
if isinstance(args, str):
args = args.split()
# We'll let sudo be a part of command even omit flag says otherwise in
# cases of commands which can normally be ran only by root.
try:
if args[args.index('sudo') + 1] in ['-u', 'passwd', 'chown']:
omit_sudo = False
except ValueError:
pass
# Quotes wrapping a command argument don't work fine in Python's shell
# simulation if the arguments contains spaces too. E.g. '"ls"' is OK
# but "ls /" isn't.
errmsg = "Don't surround arguments commands by quotes if it " + \
"contains spaces.\nargs - %s" % (args)
for arg in args:
if isinstance(arg, Raw):
continue
if arg and (arg[0] in ['"', "'"] or arg[-1] in ['"', "'"]) and \
(arg.find(' ') != -1 and 0 < arg.find(' ') < len(arg) - 1):
raise RuntimeError(errmsg)
# ['sudo', '-u', 'user', '-s', 'path-to-shell', '-c', 'ls', 'a']
# and ['sudo', '-u', user, '-s', path_to_shell, '-c', 'ls a'] are
# treated differently by Python's shell simulation. Only latter has
# the desired effect.
errmsg = 'The entire command to executed as other user should be a ' +\
'single argument.\nargs - %s' % (args)
if 'sudo' in args and '-u' in args and '-c' in args and \
args.count('-c') == 1:
if args.index('-c') != len(args) - 2 and \
args[args.index('-c') + 2].find('-') == -1:
raise RuntimeError(errmsg)
if omit_sudo:
args = [a for a in args if a != "sudo"]
return args
# Wrapper to keep the interface exactly same as that of
# teuthology.remote.run.
def run(self, **kwargs):
return self._do_run(**kwargs)
# XXX: omit_sudo is set to True since using sudo can change the ownership
# of files which becomes problematic for following executions of
# vstart_runner.py.
def _do_run(self, args, check_status=True, wait=True, stdout=None,
stderr=None, cwd=None, stdin=None, logger=None, label=None,
env=None, timeout=None, omit_sudo=True):
args = self._perform_checks_and_return_list_of_args(args, omit_sudo)
# We have to use shell=True if any run.Raw was present, e.g. &&
shell = any([a for a in args if isinstance(a, Raw)])
# Filter out helper tools that don't exist in a vstart environment
args = [a for a in args if a not in ('adjust-ulimits',
'ceph-coverage')]
# Adjust binary path prefix if given a bare program name
if not isinstance(args[0], Raw) and "/" not in args[0]:
# If they asked for a bare binary name, and it exists
# in our built tree, use the one there.
local_bin = os.path.join(BIN_PREFIX, args[0])
if os.path.exists(local_bin):
args = [local_bin] + args[1:]
else:
log.debug("'{0}' is not a binary in the Ceph build dir".format(
args[0]
))
log.debug('> ' +
' '.join([str(a.value) if isinstance(a, Raw) else a for a in args]))
if shell:
subproc = subprocess.Popen(quote(args),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
stdin=subprocess.PIPE,
cwd=cwd,
env=env,
shell=True)
else:
# Sanity check that we've got a list of strings
for arg in args:
if not isinstance(arg, str):
raise RuntimeError("Oops, can't handle arg {0} type {1}".format(
arg, arg.__class__
))
subproc = subprocess.Popen(args,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
stdin=subprocess.PIPE,
cwd=cwd,
env=env)
if stdin:
# Hack: writing to stdin is not deadlock-safe, but it "always" works
# as long as the input buffer is "small"
if isinstance(stdin, str):
subproc.stdin.write(stdin.encode())
else:
subproc.stdin.write(stdin)
proc = LocalRemoteProcess(
args, subproc, check_status,
stdout, stderr
)
if wait:
proc.wait()
return proc
# XXX: for compatibility keep this method same as teuthology.orchestra.remote.sh
# BytesIO is being used just to keep things identical
def sh(self, script, **kwargs):
"""
Shortcut for run method.
Usage:
my_name = remote.sh('whoami')
remote_date = remote.sh('date')
"""
from io import BytesIO
if 'stdout' not in kwargs:
kwargs['stdout'] = BytesIO()
if 'args' not in kwargs:
kwargs['args'] = script
proc = self.run(**kwargs)
out = proc.stdout.getvalue()
if isinstance(out, bytes):
return out.decode()
else:
return out
class LocalDaemon(object):
def __init__(self, daemon_type, daemon_id):
self.daemon_type = daemon_type
self.daemon_id = daemon_id
self.controller = LocalRemote()
self.proc = None
@property
def remote(self):
return LocalRemote()
def running(self):
return self._get_pid() is not None
def check_status(self):
if self.proc:
return self.proc.poll()
def _get_pid(self):
"""
Return PID as an integer or None if not found
"""
ps_txt = self.controller.run(args=["ps", "ww", "-u"+str(os.getuid())],
stdout=StringIO()).\
stdout.getvalue().strip()
lines = ps_txt.split("\n")[1:]
for line in lines:
if line.find("ceph-{0} -i {1}".format(self.daemon_type, self.daemon_id)) != -1:
log.debug("Found ps line for daemon: {0}".format(line))
return int(line.split()[0])
if opt_log_ps_output:
log.debug("No match for {0} {1}: {2}".format(
self.daemon_type, self.daemon_id, ps_txt))
else:
log.debug("No match for {0} {1}".format(self.daemon_type,
self.daemon_id))
return None
def wait(self, timeout):
waited = 0
while self._get_pid() is not None:
if waited > timeout:
raise MaxWhileTries("Timed out waiting for daemon {0}.{1}".format(self.daemon_type, self.daemon_id))
time.sleep(1)
waited += 1
def stop(self, timeout=300):
if not self.running():
log.error('tried to stop a non-running daemon')
return
pid = self._get_pid()
log.debug("Killing PID {0} for {1}.{2}".format(pid, self.daemon_type, self.daemon_id))
os.kill(pid, signal.SIGTERM)
waited = 0
while pid is not None:
new_pid = self._get_pid()
if new_pid is not None and new_pid != pid:
log.debug("Killing new PID {0}".format(new_pid))
pid = new_pid
os.kill(pid, signal.SIGTERM)
if new_pid is None:
break
else:
if waited > timeout:
raise MaxWhileTries(
"Timed out waiting for daemon {0}.{1}".format(
self.daemon_type, self.daemon_id))
time.sleep(1)
waited += 1
self.wait(timeout=timeout)
def restart(self):
if self._get_pid() is not None:
self.stop()
self.proc = self.controller.run(args=[
os.path.join(BIN_PREFIX, "./ceph-{0}".format(self.daemon_type)),
"-i", self.daemon_id])
def signal(self, sig, silent=False):
if not self.running():
raise RuntimeError("Can't send signal to non-running daemon")
os.kill(self._get_pid(), sig)
if not silent:
log.debug("Sent signal {0} to {1}.{2}".format(sig, self.daemon_type, self.daemon_id))
def safe_kill(pid):
"""
os.kill annoyingly raises exception if process already dead. Ignore it.
"""
try:
return os.kill(pid, signal.SIGKILL)
except OSError as e:
if e.errno == errno.ESRCH:
# Raced with process termination
pass
else:
raise
def mon_in_localhost(config_path="./ceph.conf"):
"""
If the ceph cluster is using the localhost IP as mon host, will must disable ns unsharing
"""
with open(config_path) as f:
for line in f:
local = re.match(r'^\s*mon host\s*=\s*\[((v1|v2):127\.0\.0\.1:\d+,?)+\]', line)
if local:
return True
return False
class LocalKernelMount(KernelMount):
def __init__(self, ctx, test_dir, client_id=None,
client_keyring_path=None, client_remote=None,
hostfs_mntpt=None, cephfs_name=None, cephfs_mntpt=None,
brxnet=None):
super(LocalKernelMount, self).__init__(ctx=ctx, test_dir=test_dir,
client_id=client_id, client_keyring_path=client_keyring_path,
client_remote=LocalRemote(), hostfs_mntpt=hostfs_mntpt,
cephfs_name=cephfs_name, cephfs_mntpt=cephfs_mntpt, brxnet=brxnet)
@property
def config_path(self):
return "./ceph.conf"
def get_keyring_path(self):
# This is going to end up in a config file, so use an absolute path
# to avoid assumptions about daemons' pwd
keyring_path = "./client.{0}.keyring".format(self.client_id)
try:
os.stat(keyring_path)
except OSError:
return os.path.join(os.getcwd(), 'keyring')
else:
return keyring_path
def setupfs(self, name=None):
if name is None and self.fs is not None:
# Previous mount existed, reuse the old name
name = self.fs.name
self.fs = LocalFilesystem(self.ctx, name=name)
log.debug('Wait for MDS to reach steady state...')
self.fs.wait_for_daemons()
log.debug('Ready to start {}...'.format(type(self).__name__))
@property
def _prefix(self):
return BIN_PREFIX
def _asok_path(self):
# In teuthology, the asok is named after the PID of the ceph-fuse process, because it's
# run foreground. When running it daemonized however, the asok is named after
# the PID of the launching process, not the long running ceph-fuse process. Therefore
# we need to give an exact path here as the logic for checking /proc/ for which
# asok is alive does not work.
# Load the asok path from ceph.conf as vstart.sh now puts admin sockets
# in a tmpdir. All of the paths are the same, so no need to select
# based off of the service type.
d = "./out"
with open(self.config_path) as f:
for line in f:
asok_conf = re.search("^\s*admin\s+socket\s*=\s*(.*?)[^/]+$", line)
if asok_conf:
d = asok_conf.groups(1)[0]
break
path = "{0}/client.{1}.*.asok".format(d, self.client_id)
return path
def mount(self, mntopts=[], check_status=True, **kwargs):
self.update_attrs(**kwargs)
self.assert_and_log_minimum_mount_details()
if opt_use_ns:
self.using_namespace = True
self.setup_netns()
else:
self.using_namespace = False
if not self.cephfs_mntpt:
self.cephfs_mntpt = "/"
opts = 'norequire_active_mds'
if self.client_id:
opts += ',name=' + self.client_id
if self.client_keyring_path and self.client_id:
opts += ",secret=" + self.get_key_from_keyfile()
if self.config_path:
opts += ',conf=' + self.config_path
if self.cephfs_name:
opts += ",mds_namespace={0}".format(self.cephfs_name)
if mntopts:
opts += ',' + ','.join(mntopts)
stderr = StringIO()
try:
self.client_remote.run(args=['mkdir', '--', self.hostfs_mntpt],
timeout=(5*60), stderr=stderr)
except CommandFailedError:
if 'file exists' not in stderr.getvalue().lower():
raise
if self.cephfs_mntpt is None:
self.cephfs_mntpt = "/"
cmdargs = ['sudo']
if self.using_namespace:
cmdargs += ['nsenter',
'--net=/var/run/netns/{0}'.format(self.netns_name)]
cmdargs += ['./bin/mount.ceph', ':' + self.cephfs_mntpt,
self.hostfs_mntpt, '-v', '-o', opts]
mountcmd_stdout, mountcmd_stderr = StringIO(), StringIO()
try:
self.client_remote.run(args=cmdargs, timeout=(30*60),
omit_sudo=False, stdout=mountcmd_stdout,
stderr=mountcmd_stderr)
except CommandFailedError as e:
if check_status:
raise
else:
return (e, mountcmd_stdout.getvalue(),
mountcmd_stderr.getvalue())
stderr = StringIO()
try:
self.client_remote.run(args=['sudo', 'chmod', '1777',
self.hostfs_mntpt], stderr=stderr,
timeout=(5*60))
except CommandFailedError:
# the client does not have write permissions in cap it holds for
# the Ceph FS that was just mounted.
if 'permission denied' in stderr.getvalue().lower():
pass
self.mounted = True
def cleanup_netns(self):
if self.using_namespace:
super(type(self), self).cleanup_netns()
def _run_python(self, pyscript, py_version='python'):
"""
Override this to remove the daemon-helper prefix that is used otherwise
to make the process killable.
"""
return self.client_remote.run(args=[py_version, '-c', pyscript],
wait=False, stdout=StringIO())
class LocalFuseMount(FuseMount):
def __init__(self, ctx, test_dir, client_id, client_keyring_path=None,
client_remote=None, hostfs_mntpt=None, cephfs_name=None,
cephfs_mntpt=None, brxnet=None):
super(LocalFuseMount, self).__init__(ctx=ctx, client_config=None,
test_dir=test_dir, client_id=client_id,
client_keyring_path=client_keyring_path,
client_remote=LocalRemote(), hostfs_mntpt=hostfs_mntpt,
cephfs_name=cephfs_name, cephfs_mntpt=cephfs_mntpt, brxnet=brxnet)
@property
def config_path(self):
return "./ceph.conf"
def get_keyring_path(self):
# This is going to end up in a config file, so use an absolute path
# to avoid assumptions about daemons' pwd
return os.path.abspath("./client.{0}.keyring".format(self.client_id))
def setupfs(self, name=None):
if name is None and self.fs is not None:
# Previous mount existed, reuse the old name
name = self.fs.name
self.fs = LocalFilesystem(self.ctx, name=name)
log.debug('Wait for MDS to reach steady state...')
self.fs.wait_for_daemons()
log.debug('Ready to start {}...'.format(type(self).__name__))
@property
def _prefix(self):
return BIN_PREFIX
def _asok_path(self):
# In teuthology, the asok is named after the PID of the ceph-fuse process, because it's
# run foreground. When running it daemonized however, the asok is named after
# the PID of the launching process, not the long running ceph-fuse process. Therefore
# we need to give an exact path here as the logic for checking /proc/ for which
# asok is alive does not work.
# Load the asok path from ceph.conf as vstart.sh now puts admin sockets
# in a tmpdir. All of the paths are the same, so no need to select
# based off of the service type.
d = "./out"
with open(self.config_path) as f:
for line in f:
asok_conf = re.search("^\s*admin\s+socket\s*=\s*(.*?)[^/]+$", line)
if asok_conf:
d = asok_conf.groups(1)[0]
break
path = "{0}/client.{1}.*.asok".format(d, self.client_id)
return path
def mount(self, mntopts=[], check_status=True, **kwargs):
self.update_attrs(**kwargs)
self.assert_and_log_minimum_mount_details()
if opt_use_ns:
self.using_namespace = True
self.setup_netns()
else:
self.using_namespace = False
stderr = StringIO()
try:
self.client_remote.run(args=['mkdir', '-p', self.hostfs_mntpt],
stderr=stderr)
except CommandFailedError:
if 'file exists' not in stderr.getvalue().lower():
raise
def list_connections():
self.client_remote.run(
args=["mount", "-t", "fusectl", "/sys/fs/fuse/connections", "/sys/fs/fuse/connections"],
check_status=False
)
p = self.client_remote.run(args=["ls", "/sys/fs/fuse/connections"],
check_status=False, stdout=StringIO())
if p.exitstatus != 0:
log.warning("ls conns failed with {0}, assuming none".format(p.exitstatus))
return []
ls_str = p.stdout.getvalue().strip()
if ls_str:
return [int(n) for n in ls_str.split("\n")]
else:
return []
# Before starting ceph-fuse process, note the contents of
# /sys/fs/fuse/connections
pre_mount_conns = list_connections()
log.debug("Pre-mount connections: {0}".format(pre_mount_conns))
cmdargs = []
if self.using_namespace:
cmdargs = ['sudo', 'nsenter',
'--net=/var/run/netns/{0}'.format(self.netns_name),
'--setuid', str(os.getuid())]
cmdargs += [os.path.join(BIN_PREFIX, 'ceph-fuse'), self.hostfs_mntpt,
'-f']
if self.client_id is not None:
cmdargs += ["--id", self.client_id]
if self.client_keyring_path and self.client_id is not None:
cmdargs.extend(['-k', self.client_keyring_path])
if self.cephfs_name:
cmdargs += ["--client_fs=" + self.cephfs_name]
if self.cephfs_mntpt:
cmdargs += ["--client_mountpoint=" + self.cephfs_mntpt]
if os.getuid() != 0:
cmdargs += ["--client_die_on_failed_dentry_invalidate=false"]
if mntopts:
cmdargs += mntopts
mountcmd_stdout, mountcmd_stderr = StringIO(), StringIO()
self.fuse_daemon = self.client_remote.run(args=cmdargs, wait=False,
omit_sudo=False, stdout=mountcmd_stdout, stderr=mountcmd_stderr)
self._set_fuse_daemon_pid(check_status)
log.debug("Mounting client.{0} with pid "
"{1}".format(self.client_id, self.fuse_daemon.subproc.pid))
# Wait for the connection reference to appear in /sys
waited = 0
post_mount_conns = list_connections()
while len(post_mount_conns) <= len(pre_mount_conns):
if self.fuse_daemon.finished:
# Did mount fail? Raise the CommandFailedError instead of
# hitting the "failed to populate /sys/" timeout
try:
self.fuse_daemon.wait()
except CommandFailedError as e:
if check_status:
raise
else:
return (e, mountcmd_stdout.getvalue(),
mountcmd_stderr.getvalue())
time.sleep(1)
waited += 1
if waited > 30:
raise RuntimeError("Fuse mount failed to populate /sys/ after {0} seconds".format(
waited
))
post_mount_conns = list_connections()
log.debug("Post-mount connections: {0}".format(post_mount_conns))
# Record our fuse connection number so that we can use it when
# forcing an unmount
new_conns = list(set(post_mount_conns) - set(pre_mount_conns))
if len(new_conns) == 0:
raise RuntimeError("New fuse connection directory not found ({0})".format(new_conns))
elif len(new_conns) > 1:
raise RuntimeError("Unexpectedly numerous fuse connections {0}".format(new_conns))
else:
self._fuse_conn = new_conns[0]
self.gather_mount_info()
self.mounted = True
def _set_fuse_daemon_pid(self, check_status):
# NOTE: When a command <args> is launched with sudo, two processes are
# launched, one with sudo in <args> and other without. Make sure we
# get the PID of latter one.
try:
with safe_while(sleep=1, tries=15) as proceed:
while proceed():
try:
sock = self.find_admin_socket()
except (RuntimeError, CommandFailedError):
continue
self.fuse_daemon.fuse_pid = int(re.match(".*\.(\d+)\.asok$",
sock).group(1))
break
except MaxWhileTries:
if check_status:
raise
else:
pass
def cleanup_netns(self):
if self.using_namespace:
super(type(self), self).cleanup_netns()
def _run_python(self, pyscript, py_version='python'):
"""
Override this to remove the daemon-helper prefix that is used otherwise
to make the process killable.
"""
return self.client_remote.run(args=[py_version, '-c', pyscript],
wait=False, stdout=StringIO())
# XXX: this class has nothing to do with the Ceph daemon (ceph-mgr) of
# the same name.
class LocalCephManager(CephManager):
def __init__(self):
# Deliberately skip parent init, only inheriting from it to get
# util methods like osd_dump that sit on top of raw_cluster_cmd
self.controller = LocalRemote()
# A minority of CephManager fns actually bother locking for when
# certain teuthology tests want to run tasks in parallel
self.lock = threading.RLock()
self.log = lambda x: log.debug(x)
# Don't bother constructing a map of pools: it should be empty
# at test cluster start, and in any case it would be out of date
# in no time. The attribute needs to exist for some of the CephManager
# methods to work though.
self.pools = {}
def find_remote(self, daemon_type, daemon_id):
"""
daemon_type like 'mds', 'osd'
daemon_id like 'a', '0'
"""
return LocalRemote()
def run_ceph_w(self, watch_channel=None):
"""
:param watch_channel: Specifies the channel to be watched.
This can be 'cluster', 'audit', ...
:type watch_channel: str
"""
args = [os.path.join(BIN_PREFIX, "ceph"), "-w"]
if watch_channel is not None:
args.append("--watch-channel")
args.append(watch_channel)
proc = self.controller.run(args=args, wait=False, stdout=StringIO())
return proc
def run_cluster_cmd(self, **kwargs):
"""
Run a Ceph command and the object representing the process for the
command.
Accepts arguments same as teuthology.orchestra.remote.run().
"""
kwargs['args'] = [os.path.join(BIN_PREFIX,'ceph')]+list(kwargs['args'])
return self.controller.run(**kwargs)
def raw_cluster_cmd(self, *args, **kwargs) -> str:
"""
args like ["osd", "dump"}
return stdout string
"""
kwargs['args'] = args
if kwargs.get('stdout') is None:
kwargs['stdout'] = StringIO()
return self.run_cluster_cmd(**kwargs).stdout.getvalue()