|
| 1 | +import os |
| 2 | +import re |
| 3 | +import sys |
| 4 | +from glob import glob |
| 5 | +from hashlib import sha1 |
| 6 | + |
| 7 | +from dpdispatcher.machine import Machine |
| 8 | +from dpdispatcher.submission import Resources, Submission, Task |
| 9 | + |
| 10 | +if sys.version_info >= (3, 11): |
| 11 | + import tomllib |
| 12 | +else: |
| 13 | + import tomli as tomllib |
| 14 | +from typing import List, Optional |
| 15 | + |
| 16 | +from dargs import Argument |
| 17 | + |
| 18 | +from dpdispatcher.arginfo import machine_dargs, resources_dargs, task_dargs |
| 19 | + |
| 20 | +REGEX = r"(?m)^# /// (?P<type>[a-zA-Z0-9-]+)$\s(?P<content>(^#(| .*)$\s)+)^# ///$" |
| 21 | + |
| 22 | + |
| 23 | +def read_pep723(script: str) -> Optional[dict]: |
| 24 | + """Read a PEP 723 script metadata from a script string. |
| 25 | +
|
| 26 | + Parameters |
| 27 | + ---------- |
| 28 | + script : str |
| 29 | + Script content. |
| 30 | +
|
| 31 | + Returns |
| 32 | + ------- |
| 33 | + dict |
| 34 | + PEP 723 metadata. |
| 35 | + """ |
| 36 | + name = "script" |
| 37 | + matches = list( |
| 38 | + filter(lambda m: m.group("type") == name, re.finditer(REGEX, script)) |
| 39 | + ) |
| 40 | + if len(matches) > 1: |
| 41 | + # TODO: Add tests for scenarios where multiple script blocks are found |
| 42 | + raise ValueError(f"Multiple {name} blocks found") |
| 43 | + elif len(matches) == 1: |
| 44 | + content = "".join( |
| 45 | + line[2:] if line.startswith("# ") else line[1:] |
| 46 | + for line in matches[0].group("content").splitlines(keepends=True) |
| 47 | + ) |
| 48 | + return tomllib.loads(content) |
| 49 | + else: |
| 50 | + # TODO: Add tests for scenarios where no metadata is found |
| 51 | + return None |
| 52 | + |
| 53 | + |
| 54 | +def pep723_args() -> Argument: |
| 55 | + """Return the argument parser for PEP 723 metadata.""" |
| 56 | + machine_args = machine_dargs() |
| 57 | + machine_args.fold_subdoc = True |
| 58 | + machine_args.doc = "Machine configuration. See related documentation for details." |
| 59 | + resources_args = resources_dargs(detail_kwargs=False) |
| 60 | + resources_args.fold_subdoc = True |
| 61 | + resources_args.doc = ( |
| 62 | + "Resources configuration. See related documentation for details." |
| 63 | + ) |
| 64 | + task_args = task_dargs() |
| 65 | + command_arg = task_args["command"] |
| 66 | + command_arg.doc = ( |
| 67 | + "Python interpreter or launcher. No need to contain the Python script filename." |
| 68 | + ) |
| 69 | + command_arg.default = "python" |
| 70 | + command_arg.optional = True |
| 71 | + task_args["task_work_path"].doc += " Can be a glob pattern." |
| 72 | + task_args.name = "task_list" |
| 73 | + task_args.doc = "List of tasks to execute." |
| 74 | + task_args.repeat = True |
| 75 | + task_args.dtype = (list,) |
| 76 | + return Argument( |
| 77 | + "pep723", |
| 78 | + dtype=dict, |
| 79 | + doc="PEP 723 metadata", |
| 80 | + sub_fields=[ |
| 81 | + Argument( |
| 82 | + "work_base", |
| 83 | + dtype=str, |
| 84 | + optional=True, |
| 85 | + default="./", |
| 86 | + doc="Base directory for the work", |
| 87 | + ), |
| 88 | + Argument( |
| 89 | + "forward_common_files", |
| 90 | + dtype=List[str], |
| 91 | + optional=True, |
| 92 | + default=[], |
| 93 | + doc="Common files to forward to the remote machine", |
| 94 | + ), |
| 95 | + Argument( |
| 96 | + "backward_common_files", |
| 97 | + dtype=List[str], |
| 98 | + optional=True, |
| 99 | + default=[], |
| 100 | + doc="Common files to backward from the remote machine", |
| 101 | + ), |
| 102 | + machine_args, |
| 103 | + resources_args, |
| 104 | + task_args, |
| 105 | + ], |
| 106 | + ) |
| 107 | + |
| 108 | + |
| 109 | +def create_submission(metadata: dict, hash: str) -> Submission: |
| 110 | + """Create a Submission instance from a PEP 723 metadata. |
| 111 | +
|
| 112 | + Parameters |
| 113 | + ---------- |
| 114 | + metadata : dict |
| 115 | + PEP 723 metadata. |
| 116 | + hash : str |
| 117 | + Submission hash. |
| 118 | +
|
| 119 | + Returns |
| 120 | + ------- |
| 121 | + Submission |
| 122 | + Submission instance. |
| 123 | + """ |
| 124 | + base = pep723_args() |
| 125 | + metadata = base.normalize_value(metadata, trim_pattern="_*") |
| 126 | + base.check_value(metadata, strict=False) |
| 127 | + |
| 128 | + tasks = [] |
| 129 | + for task in metadata["task_list"]: |
| 130 | + task = task.copy() |
| 131 | + task["command"] += f" $REMOTE_ROOT/script_{hash}.py" |
| 132 | + task_work_path = os.path.join( |
| 133 | + metadata["machine"]["local_root"], |
| 134 | + metadata["work_base"], |
| 135 | + task["task_work_path"], |
| 136 | + ) |
| 137 | + if os.path.isdir(task_work_path): |
| 138 | + tasks.append(Task.load_from_dict(task)) |
| 139 | + elif glob(task_work_path): |
| 140 | + for file in glob(task_work_path): |
| 141 | + tasks.append(Task.load_from_dict({**task, "task_work_path": file})) |
| 142 | + # TODO: Add tests for scenarios where the task work path is a glob pattern |
| 143 | + else: |
| 144 | + # TODO: Add tests for scenarios where the task work path is not found |
| 145 | + raise FileNotFoundError(f"Task work path {task_work_path} not found.") |
| 146 | + return Submission( |
| 147 | + work_base=metadata["work_base"], |
| 148 | + forward_common_files=metadata["forward_common_files"], |
| 149 | + backward_common_files=metadata["backward_common_files"], |
| 150 | + machine=Machine.load_from_dict(metadata["machine"]), |
| 151 | + resources=Resources.load_from_dict(metadata["resources"]), |
| 152 | + task_list=tasks, |
| 153 | + ) |
| 154 | + |
| 155 | + |
| 156 | +def run_pep723(script: str): |
| 157 | + """Run a PEP 723 script. |
| 158 | +
|
| 159 | + Parameters |
| 160 | + ---------- |
| 161 | + script : str |
| 162 | + Script content. |
| 163 | + """ |
| 164 | + metadata = read_pep723(script) |
| 165 | + if metadata is None: |
| 166 | + raise ValueError("No PEP 723 metadata found.") |
| 167 | + dpdispatcher_metadata = metadata["tool"]["dpdispatcher"] |
| 168 | + script_hash = sha1(script.encode("utf-8")).hexdigest() |
| 169 | + submission = create_submission(dpdispatcher_metadata, script_hash) |
| 170 | + submission.machine.context.write_file(f"script_{script_hash}.py", script) |
| 171 | + # write script |
| 172 | + submission.run_submission() |
0 commit comments