|
| 1 | +# Bob build tool |
| 2 | +# Copyright (C) 2024 Secunet Security Networks AG |
| 3 | +# |
| 4 | +# SPDX-License-Identifier: GPL-3.0-or-later |
| 5 | + |
| 6 | +from .errors import BuildError |
| 7 | +from .tty import stepExec, EXECUTED |
| 8 | +from .utils import hashFile |
| 9 | + |
| 10 | +import asyncio |
| 11 | +import concurrent.futures |
| 12 | +import fnmatch |
| 13 | +import gzip |
| 14 | +import hashlib |
| 15 | +import os |
| 16 | +import schema |
| 17 | +import signal |
| 18 | +import tarfile |
| 19 | +import tempfile |
| 20 | +import yaml |
| 21 | + |
| 22 | +class Bundler: |
| 23 | + def __init__(self, name, excludes): |
| 24 | + self.__name = name |
| 25 | + self.__bundleFile = os.path.join(os.getcwd(), self.__name) + ".tar" |
| 26 | + self.__excludes = excludes |
| 27 | + self.__tempDir = tempfile.TemporaryDirectory() |
| 28 | + self.__tempDirPath = os.path.join(self.__tempDir.name, self.__name) |
| 29 | + self.__bundled = {} |
| 30 | + |
| 31 | + if os.path.exists(self.__bundleFile): |
| 32 | + raise BuildError(f"Bundle {self.__bundleFile} already exists!") |
| 33 | + os.mkdir(self.__tempDirPath) |
| 34 | + |
| 35 | + def _bundle(self, workspace, bundleFile): |
| 36 | + def reset(tarinfo): |
| 37 | + tarinfo.uid = tarinfo.gid = 0 |
| 38 | + tarinfo.uname = tarinfo.gname = "root" |
| 39 | + tarinfo.mtime = 0 |
| 40 | + return tarinfo |
| 41 | + |
| 42 | + # Set default signal handler so that KeyboardInterrupt is raised. |
| 43 | + # Needed to gracefully handle ctrl+c. |
| 44 | + signal.signal(signal.SIGINT, signal.default_int_handler) |
| 45 | + |
| 46 | + try: |
| 47 | + files = [] |
| 48 | + for root, dirs, filenames in os.walk(workspace): |
| 49 | + for f in filenames: |
| 50 | + files.append(os.path.join(root, f)) |
| 51 | + files.sort() |
| 52 | + with open(bundleFile, 'wb') as outfile: |
| 53 | + with gzip.GzipFile(fileobj=outfile, mode='wb', mtime=0) as zipfile: |
| 54 | + with tarfile.open(fileobj=zipfile, mode="w:") as bundle: |
| 55 | + for f in files: |
| 56 | + bundle.add(f, arcname=os.path.relpath(f, workspace), |
| 57 | + recursive=False, filter=reset) |
| 58 | + digest = hashFile(bundleFile, hashlib.sha256).hex() |
| 59 | + |
| 60 | + except (tarfile.TarError, OSError) as e: |
| 61 | + raise BuildError("Cannot bundle workspace: " + str(e)) |
| 62 | + finally: |
| 63 | + # Restore signals to default so that Ctrl+C kills process. Needed |
| 64 | + # to prevent ugly backtraces when user presses ctrl+c. |
| 65 | + signal.signal(signal.SIGINT, signal.SIG_DFL) |
| 66 | + |
| 67 | + return ("ok", EXECUTED, digest) |
| 68 | + |
| 69 | + async def bundle(self, step, executor): |
| 70 | + for e in self.__excludes: |
| 71 | + if fnmatch.fnmatch(step.getPackage().getName(), e): return |
| 72 | + |
| 73 | + checkoutVariantId = step.getPackage().getCheckoutStep().getVariantId().hex() |
| 74 | + dest = os.path.join(self.__tempDirPath, step.getPackage().getRecipe().getName(), |
| 75 | + checkoutVariantId) |
| 76 | + os.makedirs(dest) |
| 77 | + bundleFile = os.path.join(dest, "bundle.tgz") |
| 78 | + |
| 79 | + loop = asyncio.get_event_loop() |
| 80 | + with stepExec(step, "BUNDLE", "{}".format(step.getWorkspacePath())) as a: |
| 81 | + try: |
| 82 | + msg, kind, digest = await loop.run_in_executor(executor, Bundler._bundle, |
| 83 | + self, step.getWorkspacePath(), bundleFile) |
| 84 | + a.setResult(msg, kind) |
| 85 | + except (concurrent.futures.CancelledError, concurrent.futures.process.BrokenProcessPool): |
| 86 | + raise BuildError("Upload of bundling interrupted.") |
| 87 | + |
| 88 | + self.__bundled[checkoutVariantId] = (step.getPackage().getRecipe().getName(), digest, bundleFile) |
| 89 | + |
| 90 | + def finalize(self): |
| 91 | + bundle = [] |
| 92 | + with tarfile.open(self.__bundleFile, "w") as bundle_tar: |
| 93 | + |
| 94 | + for vid, (package, digest, bundleFile) in sorted(self.__bundled.items()): |
| 95 | + bundle.append({vid : {"digestSHA256" : digest, |
| 96 | + "name" : package}}) |
| 97 | + print(f"add to bundle: {bundleFile}") |
| 98 | + bundle_tar.add(bundleFile, |
| 99 | + arcname=os.path.relpath(bundleFile, self.__tempDir.name)) |
| 100 | + |
| 101 | + bundleConfig = self.__name + ".yaml" |
| 102 | + bundleConfigPath = os.path.join(self.__tempDirPath, bundleConfig) |
| 103 | + with open(bundleConfigPath, "w") as f: |
| 104 | + yaml.dump(bundle, f, default_flow_style=False) |
| 105 | + bundle_tar.add(bundleConfigPath, arcname=os.path.join(self.__name, bundleConfig)) |
| 106 | + |
| 107 | +class Unbundler: |
| 108 | + BUNDLE_SCHEMA = schema.Schema([{ |
| 109 | + str : schema.Schema({ |
| 110 | + "name" : str, |
| 111 | + "digestSHA256" : str |
| 112 | + }) |
| 113 | + }]) |
| 114 | + |
| 115 | + def __init__(self, bundles): |
| 116 | + self.__bundles = bundles |
| 117 | + |
| 118 | + def getFromBundle(self, variantId): |
| 119 | + for bundleFile, items in self.__bundles.items(): |
| 120 | + for b in items: |
| 121 | + if variantId.hex() in b: |
| 122 | + data = b.get(variantId.hex()) |
| 123 | + return (bundleFile, os.path.join(os.path.dirname(bundleFile), data['name'], variantId.hex(), |
| 124 | + "bundle.tgz"), data['digestSHA256']) |
| 125 | + return None |
| 126 | + |
0 commit comments