You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/engine/tests/test_startup_script_seed.py

114 lines
4.8 KiB
Python

"""First-install scripts survive seed refreshes without executing twice."""
import json
import shlex
import subprocess
import pytest
from virsh_panel.cloud_init import (
_read_seed_files, build_seed_iso, read_seed_network, replace_seed_network,
replace_seed_private_network, replace_seed_settings, validate_cloud_network,
)
from test_cloud_init import PUBLIC_KEY
def seed(script="", **kwargs):
return build_seed_iso(
"00000000-0000-4000-8000-000000000001", "first-boot",
"52:54:00:12:34:56",
validate_cloud_network("8.8.8.18/24", "8.8.8.1", ["1.1.1.1"], PUBLIC_KEY),
startup_script=script, **kwargs,
)
def config(image):
return json.loads(_read_seed_files(image)["user-data"].split(b"\n", 1)[1])
def materialize_runner(image, guest):
"""Run the emitted wrapper locally with paths confined to a temp guest."""
data = config(image)
for item in data["write_files"]:
if item["path"].startswith("/var/lib/virt-cloud/"):
path = guest / item["path"].removeprefix("/var/lib/virt-cloud/")
path.parent.mkdir(parents=True, exist_ok=True)
content = item["content"]
if item["path"].endswith("startup-runner.sh"):
content = content.replace("/var/lib/virt-cloud", str(guest))
path.write_text(content)
path.chmod(int(item["permissions"], 8))
return ["/bin/sh", str(guest / "startup-runner.sh")]
def test_script_is_data_in_seed_not_yaml_or_shell_interpolation(tmp_path):
script = '#!/bin/bash\r\nprintf "%s\\n" "中文: $HOME $(false)"\r\n'
data = config(seed(script, debian12_network_fix=True))
files = {item["path"]: item for item in data["write_files"]}
assert files["/var/lib/virt-cloud/startup.sh"]["content"] == script.replace("\r\n", "\n")
assert files["/var/lib/virt-cloud/startup.sh"]["permissions"] == "0600"
assert data["runcmd"] == [["/bin/sh", "/var/lib/virt-cloud/startup-runner.sh"]]
assert data["bootcmd"] # Debian early network setup remains intact.
assert not list(tmp_path.iterdir())
def test_blank_script_keeps_original_cloud_config():
data = config(seed())
assert "runcmd" not in data
assert not any("startup" in item["path"] for item in data["write_files"])
@pytest.mark.parametrize("script", [None, 123, "bad\x00script", "汉" * 10923])
def test_invalid_script_rejected_by_seed(script):
with pytest.raises(ValueError):
seed(script)
@pytest.mark.parametrize("result", [0, 17])
def test_success_and_failure_are_not_replayed_after_settings_refresh(tmp_path, result):
counter = tmp_path / "calls"
image = seed(f'echo called >> {shlex.quote(str(counter))}\necho script-output\nexit {result}\n')
guest = tmp_path / "guest"
command = materialize_runner(image, guest)
assert subprocess.run(command, check=False).returncode == result
assert (guest / "startup/exit-code").read_text() == f"{result}\n"
assert (guest / "startup/output.log").read_text() == "script-output\n"
updated = replace_seed_settings(image, hostname="updated-host")
assert _read_seed_files(updated)["meta-data"] != _read_seed_files(image)["meta-data"]
command = materialize_runner(updated, guest)
assert subprocess.run(command, check=False).returncode == 0
assert counter.read_text() == "called\n"
assert (guest / "startup/exit-code").read_text() == f"{result}\n"
def test_interrupted_script_attempt_is_not_automatically_replayed(tmp_path):
counter = tmp_path / "calls"
image = seed(f'echo called >> {shlex.quote(str(counter))}\nkill -TERM "$PPID"\n')
guest = tmp_path / "guest"
command = materialize_runner(image, guest)
assert subprocess.run(command, check=False).returncode != 0
assert (guest / "startup/started").is_dir()
assert not (guest / "startup/exit-code").exists()
assert subprocess.run(command, check=False).returncode == 0
assert counter.read_text() == "called\n"
def test_public_and_vpc_network_updates_preserve_script_and_runner():
image = seed("echo stable\n")
updated = replace_seed_network(image, "8.8.8.19/24", "8.8.8.1", ["8.8.8.8"])
attached = replace_seed_private_network(
updated, private_mac="52:54:00:12:34:57", private_ip_cidr="10.24.3.9/32",
private_routes=["10.24.0.0/16"],
)
detached = replace_seed_private_network(attached, private_mac=None, private_ip_cidr=None)
for changed in (updated, attached, detached):
assert config(changed) == config(image)
assert read_seed_network(detached)["public_ip_cidr"] == "8.8.8.19/24"
def test_maximum_escaped_script_round_trips_through_seed_settings():
# Control characters expand sixfold under ensure_ascii JSON serialization.
image = seed("\x01" * (32 * 1024))
changed = replace_seed_settings(image, hostname="updated-host")
assert config(changed)["write_files"][1]["content"] == "\x01" * (32 * 1024)