]> git.sesse.net Git - bcachefs-tools-debian/blob - tests/util.py
b6e05e3a97d2696f1f06369fc64bd1746bc37f4f
[bcachefs-tools-debian] / tests / util.py
1 #!/usr/bin/python3
2
3 import os
4 import pytest
5 import re
6 import subprocess
7 import sys
8 import tempfile
9 import threading
10 import time
11
12 from pathlib import Path
13
14 DIR = Path('..')
15 BCH_PATH = DIR / 'bcachefs'
16
17 VPAT = re.compile(r'ERROR SUMMARY: (\d+) errors from (\d+) contexts')
18
19 class ValgrindFailedError(Exception):
20     def __init__(self, log):
21         self.log = log
22
23 def check_valgrind(logfile):
24     log = logfile.read().decode('utf-8')
25     m = VPAT.search(log)
26     assert m is not None, 'Internal error: valgrind log did not match.'
27
28     errors = int(m.group(1))
29     if errors > 0:
30         raise ValgrindFailedError(log)
31
32 def run(cmd, *args, valgrind=False, check=False):
33     """Run an external program via subprocess, optionally with valgrind.
34
35     This subprocess wrapper will capture the stdout and stderr. If valgrind is
36     requested, it will be checked for errors and raise a
37     ValgrindFailedError if there's a problem.
38     """
39     cmds = [cmd] + list(args)
40
41     if valgrind:
42         vout = tempfile.NamedTemporaryFile()
43         vcmd = ['valgrind',
44                '--leak-check=full',
45                '--log-file={}'.format(vout.name)]
46         cmds = vcmd + cmds
47
48     print("Running '{}'".format(cmds))
49     res = subprocess.run(cmds, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
50                          encoding='utf-8', check=check)
51
52     if valgrind:
53         check_valgrind(vout)
54
55     return res
56
57 def run_bch(*args, **kwargs):
58     """Wrapper to run the bcachefs binary specifically."""
59     cmds = [BCH_PATH] + list(args)
60     return run(*cmds, **kwargs)
61
62 def sparse_file(lpath, size):
63     """Construct a sparse file of the specified size.
64
65     This is typically used to create device files for bcachefs.
66     """
67     path = Path(lpath)
68     f = path.touch(mode = 0o600, exist_ok = False)
69     os.truncate(path, size)
70
71     return path
72
73 def device_1g(tmpdir):
74     """Default 1g sparse file for use with bcachefs."""
75     path = tmpdir / 'dev-1g'
76     return sparse_file(path, 1024**3)
77
78 def format_1g(tmpdir):
79     """Format a default filesystem on a 1g device."""
80     dev = device_1g(tmpdir)
81     run_bch('format', dev, check=True)
82     return dev
83
84 def mountpoint(tmpdir):
85     """Construct a mountpoint "mnt" for tests."""
86     path = Path(tmpdir) / 'mnt'
87     path.mkdir(mode = 0o700)
88     return path
89
90 class Timestamp:
91     '''Context manager to assist in verifying timestamps.
92
93     Records the range of times which would be valid for an encoded operation to
94     use.
95
96     FIXME: The kernel code is currently using CLOCK_REALTIME_COARSE, but python
97     didn't expose this time API (yet).  Probably the kernel shouldn't be using
98     _COARSE anyway, but this might lead to occasional errors.
99
100     To make sure this doesn't happen, we sleep a fraction of a second in an
101     attempt to guarantee containment.
102
103     N.B. this might be better tested by overriding the clock used in bcachefs.
104
105     '''
106     def __init__(self):
107         self.start = None
108         self.end = None
109
110     def __enter__(self):
111         self.start = time.clock_gettime(time.CLOCK_REALTIME)
112         time.sleep(0.1)
113         return self
114
115     def __exit__(self, type, value, traceback):
116         time.sleep(0.1)
117         self.end = time.clock_gettime(time.CLOCK_REALTIME)
118
119     def contains(self, test):
120         '''True iff the test time is within the range.'''
121         return self.start <= test <= self.end
122
123 class FuseError(Exception):
124     def __init__(self, msg):
125         self.msg = msg
126
127 class BFuse(threading.Thread):
128     '''bcachefs fuse runner.
129
130     This class runs bcachefs in fusemount mode, and waits until the mount has
131     reached a point suitable for testing the filesystem.
132
133     bcachefs is run under valgrind by default, and is checked for errors.
134     '''
135
136     def __init__(self, dev, mnt):
137         threading.Thread.__init__(self)
138         self.dev = dev
139         self.mnt = mnt
140         self.ready = threading.Event()
141         self.proc = None
142         self.returncode = None
143         self.stdout = None
144         self.stderr = None
145         self.vout = None
146
147     def run(self):
148         """Background thread which runs "bcachefs fusemount" under valgrind"""
149
150         vout = tempfile.NamedTemporaryFile()
151         cmd = [ 'valgrind',
152                 '--leak-check=full',
153                 '--log-file={}'.format(vout.name),
154                 BCH_PATH,
155                 'fusemount', '-f', self.dev, self.mnt]
156
157         print("Running {}".format(cmd))
158
159         err = tempfile.TemporaryFile()
160         self.proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=err,
161                                      encoding='utf-8')
162
163         out1 = self.expect(self.proc.stdout, r'^Fuse mount initialized.$')
164         self.ready.set()
165
166         print("Waiting for process.")
167         (out2, _) = self.proc.communicate()
168         print("Process exited.")
169
170         self.stdout = out1 + out2
171         self.stderr = err.read()
172         self.returncode = self.proc.returncode
173         self.vout = vout
174
175     def expect(self, pipe, regex):
176         """Wait for the child process to mount."""
177
178         c = re.compile(regex)
179
180         out = ""
181         for line in pipe:
182             print('Expect line "{}"'.format(line.rstrip()))
183             out += line
184             if c.match(line):
185                 print("Matched.")
186                 return out
187
188         raise FuseError('stdout did not contain regex "{}"'.format(regex))
189
190     def mount(self):
191         print("Starting fuse thread.")
192         self.start()
193         self.ready.wait()
194         print("Fuse is mounted.")
195
196     def unmount(self, timeout=None):
197         print("Unmounting fuse.")
198         run("fusermount3", "-zu", self.mnt)
199         print("Waiting for thread to exit.")
200
201         self.join(timeout)
202         if self.isAlive():
203             self.proc.kill()
204             self.join()
205
206         check_valgrind(self.vout)
207
208     def verify(self):
209         assert self.returncode == 0
210         assert len(self.stdout) > 0
211         assert len(self.stderr) == 0
212
213 def have_fuse():
214     res = run(BCH_PATH, 'fusemount', valgrind=False)
215     return "Please supply a mountpoint." in res.stdout