Debian Codegraph @

tools/tests/gftest

raw symbols SCIP
1 #!/usr/bin/python3
2
3 from urllib.request import urlretrieve
4 from pathlib import Path
5 from copy import deepcopy
6 from xml.etree import ElementTree
7 import json
8 import os
9 import hashlib
10 import shutil
11 import libvirt
12 import sys
13 import click
14 from socketserver import TCPServer
15 from http.server import SimpleHTTPRequestHandler
16 import functools
17 from threading import Thread
18 import gnupg
19 import subprocess
20 import string
21 import time
22
23 libvirt.registerErrorHandler(lambda x, y: None, None)
24
25 class Config(object):
26 base = Path(sys.argv[0]).parent
27
28 def __init__(self, base, prefix, data):
29 self.base = base
30 self.prefix = prefix
31 self.data = data
32
33 @classmethod
34 def open(cls, name):
35 path = cls.base / name
36 base = path.expanduser()
37 file = base / 'config'
38 if not(file.exists()):
39 raise click.ClickException(f"'{file}' not found")
40 with open(file, 'r') as f:
41 data = json.load(f)
42 return cls(base, "", data)
43
44 @classmethod
45 def create(cls, name):
46 path = cls.base / name
47 base = path.expanduser()
48 file = base / 'config'
49 if base.exists():
50 raise click.ClickException(f"'{base}' already exists")
51 base.mkdir(parents = True, exist_ok = False)
52 return cls(base, "", {})
53
54 def copy(self, cfg, ctx = {}):
55 for item in cfg.base.iterdir():
56 shutil.copy(item, self.base / item.name)
57 with open(self.base / 'config', 'r') as f:
58 self.data = json.load(f)
59 if 'templates' in self.data:
60 for item in self.data.get('templates'):
61 self.render(self.base / item, ctx)
62 del self.data['templates']
63 self.save()
64
65 def render(self, path, ctx):
66 with open(path, 'r') as f:
67 tpl = string.Template(f.read())
68 data = tpl.substitute(ctx)
69 with open(path, 'w') as f:
70 f.write(data)
71
72 def save(self):
73 if len(self.prefix) > 0:
74 raise click.ClickException("Cannot save partial configuration")
75 with open(self.base / 'config', 'w') as f:
76 json.dump(self.data, f)
77
78 def delete(self):
79 if len(self.prefix) > 0:
80 raise click.ClickException("Cannot delete partial configuration")
81 for item in self.base.iterdir():
82 item.unlink()
83 self.base.rmdir()
84
85 def get(self, name, default = None):
86 data = self.data
87 for key in name.split('/'):
88 if type(data) is not dict:
89 raise click.ClickException(f"Invalid option '{name}'")
90 if key not in data:
91 if default is None:
92 raise click.ClickException(f"Option '{name}' not found")
93 data = default
94 break
95 data = data[key]
96 if type(data) is dict:
97 if len(self.prefix) > 0:
98 name = f'{self.prefix}/{name}'
99 data = Config(self.base, name, data)
100 return data
101
102 def set(self, name, value):
103 keys = name.split('/')
104 last = keys.pop()
105 data = self.data
106 for key in keys:
107 if type(data) is not dict:
108 raise click.ClickException(f"Invalid option '{name}'")
109 if key not in data:
110 data[key] = {}
111 data = data[key]
112 data[last] = value
113
114 class UserConfig(Config):
115 base = Path('~/.glusterfs/gftest')
116
117 class Image(object):
118 def __init__(self, cfg):
119 self.cfg = cfg
120 self.path = self.get_image(cfg.get('url'))
121
122 def get_key(self, gpg, url, fingerprint):
123 for key in gpg.list_keys():
124 if key['fingerprint'].lower() == fingerprint:
125 return
126 path, _ = urlretrieve(url)
127 try:
128 info = gpg.scan_keys(path)
129 if len(info) != 1:
130 raise click.ClickException("Unexpected number of keys")
131 if info[0]['fingerprint'].lower() != fingerprint:
132 raise click.ClickException("Unexpected key fingerprint")
133 with open(path, 'rb') as f:
134 data = f.read()
135 key = gpg.import_keys(data)
136 finally:
137 os.unlink(path)
138 if key.imported != 1:
139 raise click.ClickException("Key import failed")
140
141 def verify_signature(self, path, url, fingerprint):
142 click.echo("Validating checksum's signature...")
143 gpg = gnupg.GPG()
144 self.get_key(gpg, url, fingerprint)
145 with open(path, 'rb') as f:
146 ver = gpg.verify_file(f)
147 if not(ver.valid):
148 os.unlink(path)
149 raise click.ClickException("Invalid file signature")
150
151 def get_checksum(self, url, name):
152 base = Path('~/.glusterfs/cache').expanduser() / name
153 base.mkdir(parents = True, exist_ok = True)
154 path = base / 'checksums'
155 if not(path.exists()):
156 urlretrieve(self.cfg.get('checksums'), path)
157 key = self.cfg.get('key', False)
158 if key is not False:
159 fp = self.cfg.get('fingerprint').replace(' ', '').lower()
160 self.verify_signature(path, key, fp)
161 with open(path, 'r') as f:
162 for line in f.readlines():
163 data = line.strip().split()
164 if (len(data) == 2) and (data[1] == name):
165 return data[0].lower()
166 os.unlink(path)
167 raise click.ClickException("Image checksum not found")
168
169 def compute_checksum(self, path):
170 click.echo("Verifying VM image's checksum...")
171 sha256 = hashlib.sha256()
172 with open(path, 'rb') as f:
173 for chunk in iter(lambda: f.read(131072), b''):
174 sha256.update(chunk)
175 return sha256.hexdigest().lower()
176
177 def get_image(self, url):
178 name = url.split('/')[-1]
179 base = Path('~/.glusterfs/cache').expanduser() / name
180 base.mkdir(parents = True, exist_ok = True)
181 path = base / 'image.qcow2'
182 if not(path.exists()):
183 click.echo("Downloading VM image...")
184 urlretrieve(url, path)
185 cs = self.cfg.get('checksums', False)
186 if cs is not False:
187 cs = self.get_checksum(cs, url.split('/')[-1])
188 if self.compute_checksum(path) != cs:
189 os.unlink(path)
190 raise click.ClickException("Image checksum doesn't match")
191 return path
192
193 def create(self, path, size):
194 click.echo("Creating VM disk...")
195 path = path / 'image.qcow2'
196 subprocess.run([
197 'qemu-img',
198 'create',
199 '-q',
200 '-f', 'qcow2',
201 '-F', 'qcow2',
202 '-b', str(self.path),
203 str(path),
204 f'{size}G'
205 ], check = True)
206 return path
207
208 class HTTPRequestHandler(SimpleHTTPRequestHandler):
209 def __init__(self, handlers, *args, **kwargs):
210 self.handlers = handlers
211 super().__init__(*args, **kwargs)
212
213 def log_message(self, *args):
214 pass
215
216 def resolve_path(self, path):
217 items = path.split('?', 1)[0].split('/')
218 if (len(items) <= 1) or (items[1] not in self.handlers):
219 return None
220 path = '/'.join(items[2:])
221 return f'{self.handlers[items[1]]}/{path}'
222
223 def translate_path(self, path):
224 path = self.resolve_path(path)
225 if path is None:
226 path = '/file-not-found'
227 return path
228
229 def do_PUT(self):
230 path = self.resolve_path(self.path)
231 if path is None:
232 self.send_response(400)
233 msg = "Failed"
234 else:
235 length = int(self.headers['Content-Length'])
236 Path(path).parent.mkdir(parents = True, exist_ok = True)
237 with open(path, 'wb') as f:
238 while length > 0:
239 data = self.rfile.read(min(length, 131072))
240 f.write(data)
241 length -= len(data)
242 self.send_response(201)
243 msg = "Uploaded"
244 self.end_headers()
245 self.wfile.write(f"{msg}\n".encode('utf-8'))
246
247 class HTTPServer(object):
248 def __init__(self, handlers):
249 self.handlers = handlers
250
251 def __call__(self, *args, **kwargs):
252 return HTTPRequestHandler(self.handlers, *args, **kwargs)
253
254 def __enter__(self):
255 self.httpd = TCPServer(("127.0.0.1", 0), self)
256 self.port = self.httpd.server_address[1]
257 self.thread = Thread(target = self.server)
258 self.thread.start()
259 return self
260
261 def __exit__(self, exc_type, exc_value, exc_bt):
262 self.httpd.shutdown()
263 self.thread.join()
264
265 def server(self):
266 self.httpd.serve_forever()
267
268 class VM(object):
269 options = [
270 'UserKnownHostsFile=/dev/null',
271 'StrictHostKeyChecking=no',
272 'LogLevel=ERROR'
273 ]
274
275 def __init__(self, cfg, name, conn, dom):
276 self.cfg = cfg
277 self.name = name
278 self.conn = conn
279 self.dom = dom
280 self.network = cfg.get('vm/network')
281 self.prefix = '.'.join(self.network.split('.')[:-1])
282 self.host = f'{self.prefix}.2'
283
284 @classmethod
285 def install(cls, cfg, path, name, conn, timeout):
286 click.echo("Installing VM...")
287
288 with open(path, 'r') as f:
289 spec = f.read()
290
291 try:
292 dom = conn.defineXML(spec)
293 except libvirt.libvirtError as exc:
294 raise click.ClickException(f"Unable to create '{name}': {exc.get_error_message()}")
295
296 vm = cls(cfg, name, conn, dom)
297
298 try:
299 timeout = vm.start(timeout)
300 vm.wait(libvirt.VIR_DOMAIN_SHUTOFF, timeout)
301 except:
302 vm.kill(ignore = True)
303 vm.destroy(ignore = True)
304 raise
305
306 return vm
307
308 @classmethod
309 def create(cls, cfg, name, cpus, memory, disk, network, port, key, timeout):
310 pubkey = Path(key + '.pub').expanduser()
311 if not(pubkey.exists()):
312 raise click.ClickException(f"Public key '{pubkey}' not found")
313 with open(pubkey, 'r') as f:
314 pubkey = f.read()
315
316 conn = libvirt.open()
317 arch = cfg.get('arch', 'x86_64')
318 machine = cfg.get('machine', 'q35')
319 xml = conn.getDomainCapabilities(arch = arch, machine = machine, virttype = 'kvm')
320 data = ElementTree.fromstring(xml)
321 emulator = data.findtext('./path')
322
323 net = '.'.join(network.split('.')[:-1])
324
325 if cpus is None:
326 cpus = cfg.get('cpus', 2)
327 if memory is None:
328 memory = cfg.get('memory', 8)
329 if disk is None:
330 disk = cfg.get('disk', 20)
331
332 user = UserConfig.create(name)
333
334 try:
335 img = Image(cfg.get('image')).create(user.base, disk)
336
337 with HTTPServer({ 'config': user.base}) as httpd:
338 ctx = {
339 'vm_name': name,
340 'vm_arch': arch,
341 'vm_machine': machine,
342 'vm_emulator': emulator,
343 'vm_memory': memory,
344 'vm_cpus': cpus,
345 'vm_disk': img,
346 'vm_network': f'{net}.0/24',
347 'vm_key': pubkey,
348 'host_port': port,
349 'httpd_address': f'{net}.2:{httpd.port}',
350 'cloud_init_datasource': f'ds=nocloud-net;s=http://{net}.2:{httpd.port}/config/'
351 }
352 user.copy(cfg, ctx)
353 user.set('vm/network', f'{net}.0')
354 user.set('vm/port', port)
355 user.set('vm/key', str(key))
356 user.set('vm/cpus', str(cpus))
357 user.set('vm/memory', str(memory))
358 user.set('vm/disk', str(disk))
359 user.save()
360
361 return cls.install(user, user.base / cfg.get('domain'), name, conn, timeout)
362 except:
363 user.delete()
364 raise
365
366 @classmethod
367 def open(cls, name):
368 user = UserConfig.open(name)
369 conn = libvirt.open()
370 try:
371 dom = conn.lookupByName(name)
372 except libvirt.libvirtError as exc:
373 raise click.ClickException(f"Unable to access '{name}': {exc.get_error_message()}")
374 except:
375 raise click.ClickException(f"Unable to access '{name}'")
376 return cls(user, name, conn, dom)
377
378 def ping(self):
379 try:
380 print(self.run('uname -a', capture = True, error = False))
381 return True
382 except:
383 return False
384
385 def start(self, timeout):
386 try:
387 if self.dom.state()[0] == libvirt.VIR_DOMAIN_RUNNING:
388 return timeout
389 self.dom.create()
390 except libvirt.libvirtError as exc:
391 raise click.ClickException(f"Unable to start '{self.name}': {exc.get_error_message()}")
392 except:
393 raise click.ClickException(f"Unable to start '{self.name}'")
394
395 timeout = self.wait(libvirt.VIR_DOMAIN_RUNNING, timeout)
396
397 while True:
398 try:
399 iflist = self.dom.interfaceAddresses(libvirt.VIR_DOMAIN_INTERFACE_ADDRESSES_SRC_AGENT)
400 except:
401 iflist = []
402 for iface in iflist:
403 if 'addrs' not in iflist[iface]:
404 continue
405
406 addrs = iflist[iface]['addrs']
407 if addrs is None:
408 continue
409
410 for addr in addrs:
411 if 'addr' not in addr:
412 continue
413
414 addr = '.'.join(addr['addr'].split('.')[:-1])
415 if addr == self.prefix:
416 return timeout
417
418 if timeout <= 0:
419 raise click.ClickException(f"Timed out waiting for '{self.name}'")
420 time.sleep(0.2)
421 timeout -= 0.2
422
423 def stop(self, timeout):
424 try:
425 if self.dom.state()[0] == libvirt.VIR_DOMAIN_SHUTOFF:
426 return timeout
427 self.dom.shutdown()
428 except libvirt.libvirtError as exc:
429 raise click.ClickException(f"Unable to stop '{self.name}': {exc.get_error_message()}")
430 except:
431 raise click.ClickException(f"Unable to stop '{self.name}'")
432
433 return self.wait(libvirt.VIR_DOMAIN_SHUTOFF, timeout)
434
435 def kill(self, ignore = False):
436 try:
437 self.dom.destroy()
438 except libvirt.libvirtError as exc:
439 if not(ignore):
440 raise click.ClickException(f"Unable to kill '{self.name}': {exc.get_error_message()}")
441 except:
442 if not(ignore):
443 raise click.ClickException(f"Unable to kill '{self.name}'")
444
445 def destroy(self, ignore = False):
446 try:
447 self.dom.undefine()
448 self.cfg.delete()
449 except libvirt.libvirtError as exc:
450 if not(ignore):
451 raise click.ClickException(f"Unable to destroy '{self.name}': {exc.get_error_message()}")
452 except:
453 if not(ignore):
454 raise click.ClickException(f"Unable to destroy '{self.name}'")
455
456 def wait(self, state, timeout):
457 while self.dom.state()[0] != state:
458 if timeout <= 0:
459 raise click.ClickException(f"Timed out waiting for '{self.name}'")
460 time.sleep(0.2)
461 timeout -= 0.2
462 return timeout
463
464 def run(self, cmd, capture = False, error = True, ignore = False, env = None):
465 stdout = subprocess.PIPE if capture else None
466 stderr = None if error else subprocess.DEVNULL
467
468 cmdline = [
469 'ssh',
470 '-qt',
471 '-p', str(self.cfg.get('vm/port')),
472 '-i', self.cfg.get('vm/key')
473 ]
474 for opt in VM.options:
475 cmdline.extend(['-o', opt])
476 cmdline.append('[email protected]')
477 if env is not None:
478 cmdline.append('env')
479 cmdline.extend([f'{n}={env[n]}' for n in env])
480 cmdline.append(cmd)
481
482 proc = subprocess.run(cmdline, stdout = stdout, stderr = stderr, check = not(ignore), text = True, encoding = 'utf-8')
483 return proc.stdout
484
485 @click.group()
486 @click.version_option('0.1')
487 def gftest():
488 pass
489
490 @gftest.command()
491 @click.option('-k', '--key', default = '~/.ssh/id_rsa')
492 @click.option('-n', '--net', default = '192.168.254.0')
493 @click.option('-p', '--port', type = int, default = 2222)
494 @click.option('-t', '--template', default = 'centos7')
495 @click.option('-c', '--cpus', type = int)
496 @click.option('-m', '--memory', type = int)
497 @click.option('-d', '--disk', type = int)
498 @click.option('-o', '--timeout', type = int, default = 120)
499 @click.argument('name', required = True)
500 def create(key, net, port, template, cpus, memory, disk, timeout, name):
501 cfg = Config.open(template)
502 vm = VM.create(cfg.get('vm'), name, cpus, memory, disk, net, port, key, timeout)
503 click.echo("Restarting VM...")
504 try:
505 vm.start(45)
506 while not(vm.ping()):
507 time.sleep(1)
508 container = vm.cfg.get('containers/images/builder')
509 with HTTPServer({'config': vm.cfg.base}) as httpd:
510 click.echo("Creating builder container...")
511 vm.run(f'podman build --squash -t glusterfs/builder -f http://{vm.host}:{httpd.port}/config/{container} /root/')
512 except:
513 vm.kill(ignore = True)
514 vm.destroy(ignore = True)
515 raise
516
517 @gftest.command()
518 @click.argument('name', required = True)
519 def destroy(name):
520 vm = VM.open(name)
521 vm.kill(ignore = True)
522 vm.destroy(ignore = True)
523
524 @gftest.command()
525 @click.option('-t', '--timeout', type = int, default = 45)
526 @click.argument('name', required = True)
527 def poweron(timeout, name):
528 vm = VM.open(name)
529 timeout = vm.start(timeout)
530 while not(vm.ping()):
531 if timeout <= 0:
532 raise click.ClickException(f"Timed out waiting for '{self.name}'")
533 time.sleep(1)
534 timeout -= 1
535
536 @gftest.command()
537 @click.option('-t', '--timeout', type = int, default = 15)
538 @click.argument('name', required = True)
539 def shutdown(timeout, name):
540 VM.open(name).stop(timeout)
541
542 @gftest.command()
543 @click.argument('name', required = True)
544 def poweroff(name):
545 VM.open(name).kill()
546
547 @gftest.command()
548 @click.option('-c', '--commit', required = True)
549 @click.argument('name', required = True)
550 def build(commit, name):
551 subprocess.run(['git', 'update-server-info'], capture_output = True, check = True)
552 proc = subprocess.run(['git', 'rev-parse', '--show-toplevel'], capture_output = True, check = True, text = True, encoding = 'utf-8')
553 root = Path(proc.stdout.strip()) / '.git'
554 vm = VM.open(name)
555 vm.run('rm -rf /root/glusterfs')
556 try:
557 container = vm.cfg.get('containers/images/testing')
558 with HTTPServer({'config': vm.cfg.base, 'glusterfs': root}) as httpd:
559 vm.run(f'git clone http://{vm.host}:{httpd.port}/glusterfs /root/glusterfs')
560 vm.run(f'git -C /root/glusterfs checkout {commit}')
561 vm.run(f'podman build --squash -t glusterfs/testing -f http://{vm.host}:{httpd.port}/config/{container} /root/glusterfs')
562 except:
563 vm.run('rm -rf /root/glusterfs')
564 raise
565
566 @gftest.command()
567 @click.option('-s', '--space', type = int)
568 @click.option('-w', '--workers', type = int)
569 @click.argument('name', required = True)
570 def spawn(space, workers, name):
571 vm = VM.open(name)
572 if space is None:
573 space = vm.cfg.get('containers/space', 10)
574 if workers is None:
575 workers = vm.cfg.get('containers/workers', 8)
576 vm.run('modprobe zram')
577 zram = vm.run(f'zramctl -f -s {space * workers + 1}G', capture = True)
578 loop = vm.run(f'losetup -f --show {zram}', capture = True)
579 vm.run(f'pvcreate {loop}')
580 vm.run(f'vgcreate vg_{name} {loop}')
581 vm.run(f'lvcreate -l 100%FREE -Zn -T vg_{name}/tp')
582 for i in range(workers):
583 vm.run(f'lvcreate -V {space}G -T vg_{name}/tp -n lv_{name}_{i:02d}')
584 vm.run(f'mkfs.xfs -q -i size=512 /dev/vg_{name}/lv_{name}_{i:02d}')
585 vm.run(f'mkdir -p /mnt/mnt_{i:02d}')
586 vm.run(f'mount -o discard /dev/vg_{name}/lv_{name}_{i:02d} /mnt/mnt_{i:02d}')
587 vm.run(f'podman run -d --rm --privileged --name {name}{i:02d} --hostname {name}{i:02d} --tmpfs /tmp:exec -v /dev:/dev -v /mnt/mnt_{i:02d}:/d:Z glusterfs/testing /sbin/init')
588
589 @gftest.command()
590 @click.argument('name', required = True)
591 def kill(name):
592 vm = VM.open(name)
593 vm.run('podman rm -f --all')
594 vm.run('umount /mnt/mnt_*')
595 vm.run('rmdir /mnt/mnt_*')
596 vm.run('dmsetup remove_all')
597 vm.run('losetup -D')
598 vm.run('zramctl -r /dev/zram*', ignore = True)
599
600 @gftest.command()
601 @click.argument('name', required = True)
602 @click.argument('directory', type = click.Path(), required = True)
603 def run(name, directory):
604 vm = VM.open(name)
605 Path(directory).mkdir(parents = True, exist_ok = True)
606 with HTTPServer({'config': vm.cfg.base, 'run': directory}) as httpd:
607 env = {'HOST_URL': f'http://{vm.host}:{httpd.port}'}
608 vm.run('/root/glusterfs/tools/tests/regression', env = env)
609
610 @gftest.command()
611 @click.argument('name', required = True)
612 @click.argument('container', type = int, required = False)
613 def sh(name, container):
614 vm = VM.open(name)
615 with HTTPServer({'config': vm.cfg.base}) as httpd:
616 if container is None:
617 env = { 'HOST_URL': f'http://{vm.host}:{httpd.port}' }
618 vm.run('bash -ils', env = env, ignore = True)
619 else:
620 vm.run(f'podman exec -ti -e HOST_URL=http://{vm.host}:{httpd.port} {name}{container:02d} /bin/bash', ignore = True)
621
622 if __name__ == "__main__":
623 gftest()
624