|
| 1 | +import re |
| 2 | +import subprocess |
| 3 | +from abc import ABC |
| 4 | + |
| 5 | +from mwutil.exec import run_container_command |
| 6 | +from mwutil.local_config import MWUtilConfig |
| 7 | + |
| 8 | + |
| 9 | +def compile_path_template(config: MWUtilConfig, template: str) -> str: |
| 10 | + replacements = { |
| 11 | + "base": config.basedir.absolute(), |
| 12 | + "config": config.configdir.absolute(), |
| 13 | + "core": config.coredir.absolute(), |
| 14 | + "dumps": config.dumpdir.absolute(), |
| 15 | + } |
| 16 | + |
| 17 | + return template.format(**replacements) |
| 18 | + |
| 19 | +class FileWrapper(ABC): |
| 20 | + |
| 21 | + @staticmethod |
| 22 | + def from_path(config: MWUtilConfig, path_template: str) -> 'FileWrapper': |
| 23 | + path = compile_path_template(config, path_template) |
| 24 | + pattern = re.compile("^([A-Za-z0-9+.-]+)://") |
| 25 | + match = pattern.match(path) |
| 26 | + if not match: |
| 27 | + return HostFile(path) |
| 28 | + else: |
| 29 | + container_name = match.group(1) |
| 30 | + container_path = path[len(container_name) + 3:] |
| 31 | + return ContainerFile(container_name, container_path, config) |
| 32 | + |
| 33 | + def read(self): |
| 34 | + raise NotImplementedError("Subclasses must implement this method") |
| 35 | + |
| 36 | + def stream_to_stdout(self): |
| 37 | + raise NotImplementedError("Subclasses must implement this method") |
| 38 | + |
| 39 | + |
| 40 | +class HostFile(FileWrapper): |
| 41 | + def __init__(self, path: str): |
| 42 | + self.path = path |
| 43 | + |
| 44 | + def read(self): |
| 45 | + with open(self.path, 'r') as file: |
| 46 | + return file.read() |
| 47 | + |
| 48 | + def stream_to_stdout(self): |
| 49 | + subprocess.run(["cat", self.path], check=True) |
| 50 | + |
| 51 | +class ContainerFile(FileWrapper): |
| 52 | + def __init__(self, container_name: str, path: str, config: MWUtilConfig): |
| 53 | + self.container_name = container_name |
| 54 | + self.path = path |
| 55 | + self.config = config |
| 56 | + |
| 57 | + def read(self): |
| 58 | + result = run_container_command( |
| 59 | + self.config, |
| 60 | + ['cat', self.path], |
| 61 | + container_name=self.container_name, |
| 62 | + capture_output=True, |
| 63 | + text=True, |
| 64 | + exec_options=["-u", "root"] |
| 65 | + ) |
| 66 | + if result.returncode != 0: |
| 67 | + raise Exception(f"Failed to read file {self.path} from container {self.container_name}") |
| 68 | + return result.stdout |
| 69 | + |
| 70 | + def stream_to_stdout(self): |
| 71 | + run_container_command( |
| 72 | + self.config, |
| 73 | + ['cat', self.path], |
| 74 | + container_name=self.container_name, |
| 75 | + capture_output=False, |
| 76 | + text=True, |
| 77 | + exec_options=["-u", "root"] |
| 78 | + ) |
0 commit comments