File size: 4,454 Bytes
0e239c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
"""Execute a staged command contract using a specified environment image."""
import argparse
import json
from pathlib import Path, PurePosixPath
import subprocess
import uuid
from common import ROOT, contained, load_task, sha256


def bind(source, target, read_only=False):
    source = Path(source).resolve()
    destination = PurePosixPath(target)
    if not source.exists() or "," in str(source) or "," in target:
        raise ValueError("Invalid mount source or target")
    if not destination.is_absolute() or ".." in destination.parts or str(destination) == "/":
        raise ValueError("Unsafe container mount target")
    return ["--mount", f"type=bind,source={source},target={destination}" + (",readonly" if read_only else "")]


def evaluate(directory, image, output, network=None):
    if not image or image.startswith("-"):
        raise ValueError("Invalid environment image")
    directory = Path(directory).resolve()
    output = Path(output).resolve()
    if output.exists():
        raise ValueError(f"Output already exists: {output}")
    if output.is_relative_to(ROOT) or ROOT.is_relative_to(output) or output.is_relative_to(directory) or directory.is_relative_to(output):
        raise ValueError("Evaluation output must remain outside the release and staged sources")
    preparation = json.loads((directory / "preparation.json").read_text())
    if sha256(directory / "contract.json") != preparation["contract_sha256"]:
        raise ValueError("Prepared contract changed")
    contract = json.loads((directory / "contract.json").read_text())
    if contract["kind"] != "command_contract":
        raise ValueError("Native contract adapters are not provided by this entry point")
    network = network or contract["network"]
    if network not in ("none", "bridge"):
        raise ValueError("Only none/bridge networks are supported")
    runtime_arguments = []
    task = load_task(preparation["instance_id"])
    task_root = contained(ROOT / "instances", task["instance_id"])
    runtime = task_root / "environment/runtime.json"
    if runtime.is_file():
        refs = {ref["path"]: ref for ref in task["artifacts"]}
        ref = refs.get("environment/runtime.json")
        if not ref or sha256(runtime) != ref["sha256"]:
            raise ValueError("Environment runtime contract changed")
        configuration = json.loads(runtime.read_text())
        if configuration["schema_version"] != 1 or not configuration.get("prepare_command"):
            raise ValueError("Unsupported environment runtime contract")
        runtime_arguments = ["--environment-setup", configuration["prepare_command"]]
    output.mkdir(parents=True)
    name = "crossswe-eval-" + uuid.uuid4().hex[:12]
    args = ["docker", "run", "--rm", "--platform", "linux/amd64", "--name", name, "--network", network,
            "--security-opt", "no-new-privileges"]
    for mount in json.loads((directory / "mounts.json").read_text()):
        args.extend(bind(mount["source"], mount["target"], mount["read_only"]))
    args.extend(bind(directory / "contract.json", "/crossswe/contract.json", True))
    args.extend(bind(ROOT / "scripts/run_contract.py", "/crossswe/run_contract.py", True))
    args.extend(bind(output, "/artifacts"))
    args.extend(["--entrypoint", "python3", image, "/crossswe/run_contract.py", "--contract", "/crossswe/contract.json", "--output-dir", "/artifacts", *runtime_arguments])
    try:
        with (output / "container.log").open("w") as log:
            code = subprocess.run(args, stdout=log, stderr=subprocess.STDOUT).returncode
    except BaseException:
        subprocess.run(["docker", "rm", "--force", name], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
        raise
    (output / "execution.json").write_text(json.dumps({"instance_id": contract["instance_id"], "world": preparation["world"],
        "image": image, "network": network, "exit_code": code, "contract_sha256": preparation["contract_sha256"]}, indent=2) + "\n")
    return code


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--evaluation-dir", type=Path, required=True)
    parser.add_argument("--image", required=True)
    parser.add_argument("--output-dir", type=Path, required=True)
    parser.add_argument("--network", choices=["none", "bridge"])
    args = parser.parse_args()
    raise SystemExit(evaluate(args.evaluation_dir, args.image, args.output_dir, args.network))