feat: separate instance display and resource names

dev
admin 2 months ago
parent a4b2ee923e
commit f8bf9cf171

@ -163,6 +163,7 @@ class Service(FakeVMService):
super().__init__()
self.create_failure = False
self.absent = False
self.absent_checks = []
self.vm.update(managed=True, os_source="iso")
def create_vm(self, spec):
@ -173,7 +174,10 @@ class Service(FakeVMService):
self.vm.update(uuid=spec["vm_uuid"], name=spec["name"])
return self.vm.copy()
def provisioning_absent(self, vm_uuid, name):
def provisioning_absent(self, vm_uuid, name, *, uuid_resources=False,
legacy_name_collision=False):
self.absent_checks.append(
(vm_uuid, name, uuid_resources, legacy_name_collision))
return self.absent
@ -1345,6 +1349,7 @@ def test_uncertain_creation_never_refunds_or_recreates(boundary):
assert failed.status_code == 502
assert failed.json()["status"] == "uncertain" and not failed.json()["safe_to_refund"]
record = json.loads(store.get("operation", "order-uncertain"))
assert record["resource_naming"] == "uuid-v1"
component = engine.registry.components["hk"]
scope = host_scope(component.manager.profile)
assert component.state.users.owns_vm(scope, record["vm_uuid"], 41)
@ -1356,11 +1361,45 @@ def test_uncertain_creation_never_refunds_or_recreates(boundary):
services["hk"].absent = True
operation = call(client, "GET", "/internal/v1/operations/order-uncertain").json()
assert operation["status"] == "failed" and operation["safe_to_refund"] is True
assert services["hk"].absent_checks[-1] == (
record["vm_uuid"], CREATE_BODY["name"], True, False)
assert not component.state.users.owns_vm(scope, record["vm_uuid"], 41)
assert component.store.get("vm_credential", f"{scope}.{record['vm_uuid']}") is None
assert component.store.list("ip_claim") == {}
def test_legacy_name_collision_operation_uses_legacy_absent_reconciliation(boundary):
client, _engine, store, _logs, services = boundary
call(client, "GET", "/internal/v1/hosts/hk/vms")
services["hk"].absent = True
legacy_vm_id = "00000000-0000-4000-8000-000000000002"
store.set("operation", "legacy-name-collision", json.dumps({
"operation_id": "legacy-name-collision",
"host_id": "hk",
"user_id": USER["user_id"],
"request_hash": "legacy",
"vm_uuid": legacy_vm_id,
"vm_name": CREATE_BODY["name"],
"kind": "create",
"resource": "vms",
"method": "POST",
"status": "uncertain",
"result": None,
"error": "虚拟机名称已存在",
"safe_to_refund": False,
"created_at": 1,
}))
operation = call(
client, "GET", "/internal/v1/operations/legacy-name-collision", USER,
).json()
assert operation["status"] == "failed"
assert operation["safe_to_refund"] is True
assert services["hk"].absent_checks[-1] == (
legacy_vm_id, CREATE_BODY["name"], False, True)
@pytest.mark.parametrize("payload", [{"name": "invalid"}, ["not-an-object"],
{**CREATE_BODY, "guest_ssh_key_id": 3}])
def test_rejected_create_has_durable_safe_failure_even_when_response_is_lost(boundary, payload):

@ -782,14 +782,14 @@ class VMServiceTests(unittest.TestCase):
with patch.object(self.service_module, "build_seed_iso", return_value=b"SEED", create=True):
return service.create_cloud_vm(spec, TEMPLATE_NAME)
def cloud_vm_with_real_seed(self):
def cloud_vm_with_real_seed(self, **changes):
"""Create a cloud VM and replace its stub seed with real NoCloud data."""
if importlib.util.find_spec("pycdlib") is None:
self.skipTest("pycdlib is not installed")
from virsh_panel.cloud_init import build_seed_iso, validate_cloud_network
service = self.cloud_service()
spec = self.cloud_spec()
spec = self.cloud_spec(**changes)
created = self.create_cloud_vm(service, spec)
domain = self.backend.domains[0]
root = domain.root
@ -884,9 +884,59 @@ class VMServiceTests(unittest.TestCase):
created = self.service.create_vm(self.spec(vm_uuid=requested_uuid))
self.assertEqual(created["uuid"], requested_uuid)
self.assertEqual(self.backend.domains[0].root.findtext("uuid"), requested_uuid)
resource_name = "vc-14d9bb2f65cd4406"
self.assertEqual(self.backend.domains[0].name(), resource_name)
self.assertIn(f"{resource_name}.qcow2", self.backend.pools["images"].volumes)
managed = self.backend.domains[0].root.find(
"./metadata/{urn:virsh-panel:1}managed")
self.assertEqual(managed.get("display-name"), "alma-test")
self.assertEqual(created["name"], "alma-test")
self.assertEqual(
self.service.list_vm_metadata([requested_uuid])[0]["name"], "alma-test")
self.assertEqual(
self.service.get_vm_state(requested_uuid)["name"], resource_name)
with self.assertRaisesRegex(self.error_type, "UUID"):
self.service.create_vm(self.spec(name="invalid-uuid", vm_uuid="not-a-uuid"))
def test_internal_resource_name_extends_past_domain_or_disk_collision(self):
vm_uuid = "14d9bb2f-65cd-4406-a377-90685c0690e4"
class NamedDomain:
def __init__(self, value):
self.value = value
def name(self):
return self.value
selected = self.service._select_internal_resource_name(
vm_uuid,
[NamedDomain("vc-14d9bb2f65cd4406")],
{"vc-14d9bb2f65cd4406a377.qcow2"},
)
self.assertEqual(selected, "vc-14d9bb2f65cd4406a3779068")
def test_legacy_name_collision_can_be_reconciled_without_own_artifacts(self):
self.service.create_vm(self.spec())
reserved_uuid = "14d9bb2f-65cd-4406-a377-90685c0690e4"
self.assertFalse(self.service.provisioning_absent(
reserved_uuid, "alma-test"))
self.assertTrue(self.service.provisioning_absent(
reserved_uuid, "alma-test", legacy_name_collision=True))
def test_uuid_resource_absence_checks_every_candidate_and_seed(self):
reserved_uuid = "14d9bb2f-65cd-4406-a377-90685c0690e4"
pool = self.backend.pools["images"]
candidate_disk = "vc-14d9bb2f65cd4406a377.qcow2"
pool.volumes[candidate_disk] = FakeVolume(pool, candidate_disk)
self.assertFalse(self.service.provisioning_absent(
reserved_uuid, "customer-label", uuid_resources=True))
del pool.volumes[candidate_disk]
self.assertTrue(self.service.provisioning_absent(
reserved_uuid, "customer-label", uuid_resources=True))
def test_unmanaged_vm_does_not_claim_an_os_or_ip(self):
vm = self.service.create_vm(self.spec())
domain = self.backend.domains[0]
@ -1016,6 +1066,7 @@ class VMServiceTests(unittest.TestCase):
self.assertGreater(int(balloon.find("stats").get("period")), 0)
self.assertEqual(root.find("./metadata/{urn:virsh-panel:1}managed").attrib,
{"version": "2", "disk-volume": "web.qcow2",
"display-name": "web",
"os-source": "iso", "install-iso": iso_name,
"created-at": vm["created_at"]})
self.assertIsNone(vm["os_name"])
@ -1619,6 +1670,33 @@ class VMServiceTests(unittest.TestCase):
self.assertEqual(created["credential_generation"],
f"panel-seed-{reserved_uuid}.iso")
self.assertEqual(created["disks"][0]["capacity_gib"], 20)
resource_name = f"vc-{uuid.UUID(reserved_uuid).hex[:16]}"
self.assertEqual(self.backend.domains[0].name(), resource_name)
self.assertIn(f"{resource_name}.qcow2", self.backend.pools["images"].volumes)
self.assertEqual(created["name"], "cloud-vm")
def test_uuid_backed_cloud_vms_can_share_a_display_name(self):
service = self.cloud_service()
first_uuid = "14d9bb2f-65cd-4406-a377-90685c0690e4"
second_uuid = "24d9bb2f-65cd-4406-a377-90685c0690e4"
first = self.create_cloud_vm(
service, self.cloud_spec(vm_uuid=first_uuid))
second = self.create_cloud_vm(service, self.cloud_spec(
vm_uuid=second_uuid,
public_ip_cidr="8.8.8.19/24",
))
self.assertEqual(first["name"], "cloud-vm")
self.assertEqual(second["name"], "cloud-vm")
resource_names = {domain.name() for domain in self.backend.domains}
self.assertEqual(resource_names, {
"vc-14d9bb2f65cd4406",
"vc-24d9bb2f65cd4406",
})
pool_names = set(self.backend.pools["images"].volumes)
self.assertIn("vc-14d9bb2f65cd4406.qcow2", pool_names)
self.assertIn("vc-24d9bb2f65cd4406.qcow2", pool_names)
def test_cloud_vm_accepts_almalinux_9_panel_template_volume(self):
service = self.cloud_service()
@ -1857,8 +1935,10 @@ class VMServiceTests(unittest.TestCase):
def test_cloud_vm_start_failure_undefines_domain_and_removes_new_volumes(self):
service = self.cloud_service()
self.backend.bridge_active = False
reserved_uuid = "14d9bb2f-65cd-4406-a377-90685c0690e4"
with self.assertRaises(self.error_type):
self.create_cloud_vm(service, self.cloud_spec())
self.create_cloud_vm(
service, self.cloud_spec(vm_uuid=reserved_uuid))
self.assertEqual(set(self.backend.pools["images"].volumes),
{TEMPLATE_NAME})
self.assertFalse(self.backend.domains)
@ -1984,8 +2064,12 @@ class VMServiceTests(unittest.TestCase):
self.assertNotIn("cloud-vm.qcow2", self.backend.deleted_volumes)
def test_reinstall_transport_error_after_start_preserves_both_disks(self):
service, created, spec, domain, old_seed_name = self.cloud_vm_with_real_seed()
reserved_uuid = "14d9bb2f-65cd-4406-a377-90685c0690e4"
service, created, spec, domain, old_seed_name = self.cloud_vm_with_real_seed(
vm_uuid=reserved_uuid)
pool = self.backend.pools["images"]
old_disk_name = domain.root.find(
"./metadata/{urn:virsh-panel:1}managed").get("disk-volume")
self.backend.fail_domain_create_after_start = True
result = service.reinstall_cloud_vm(
@ -1994,13 +2078,15 @@ class VMServiceTests(unittest.TestCase):
)
self.assertTrue(domain.isActive())
self.assertEqual(domain.name(), "vc-14d9bb2f65cd4406")
self.assertEqual(result["vm"]["name"], "cloud-vm")
self.assertIn("旧系统盘已保留", result["warning"])
self.assertIn("cloud-vm.qcow2", pool.volumes)
self.assertIn(old_disk_name, pool.volumes)
self.assertIn(old_seed_name, pool.volumes)
self.assertNotIn("cloud-vm.qcow2", self.backend.deleted_volumes)
self.assertNotIn(old_disk_name, self.backend.deleted_volumes)
self.assertNotEqual(
domain.root.find("./devices/disk[@device='disk']/source").get("file"),
pool.volumes["cloud-vm.qcow2"].path(),
pool.volumes[old_disk_name].path(),
)
def test_reinstall_old_disk_delete_failure_reports_warning_and_keeps_new_vm(self):

@ -1019,6 +1019,12 @@ class EngineApplication:
"actor_is_admin": bool(delegated.get("is_admin")),
"resource": resource, "method": method, "status": "running", "result": None,
"safe_to_refund": False, "created_at": int(time.time())}
if create:
# New PHP-backed creates always receive the reserved UUID below.
# Keep this durable marker so cleanup reconciliation checks the
# UUID-derived resource candidates, while old in-flight records
# continue to use their historical display-name disk convention.
record["resource_naming"] = "uuid-v1"
if resource.endswith("/service-resume"):
# Store only the allowlisted target-state option. It is needed to
# replay the exact same convergence request after a lost response;
@ -1236,7 +1242,12 @@ class EngineApplication:
if profile and not profile.get("key_locked"):
try:
absent = await asyncio.to_thread(self._service(profile).provisioning_absent,
operation["vm_uuid"], operation["vm_name"])
operation["vm_uuid"], operation["vm_name"],
uuid_resources=operation.get("resource_naming") == "uuid-v1",
legacy_name_collision=(
operation.get("resource_naming") is None
and operation.get("error") == "虚拟机名称已存在"
))
if absent:
await asyncio.to_thread(self._cleanup_absent_records, components,
profile, operation["vm_uuid"])

@ -35,6 +35,7 @@ LOG = logging.getLogger(__name__)
GIB = 1024**3
PANEL_NS = "urn:virsh-panel:1"
NAME_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,62}\Z")
INTERNAL_RESOURCE_PREFIX_LENGTHS = (16, 20, 24, 28, 32)
BRIDGE_NAME_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,14}\Z")
TEMPLATE_VOLUME_RE = re.compile(
r"panel-template-(?:alma(?:8|9|10)|debian(?:11|12|13)|"
@ -387,6 +388,44 @@ class VMService:
except ET.ParseError as exc:
raise VMError("宿主机返回的虚拟机配置 XML 无效", 502) from exc
@staticmethod
def _display_name(domain: Any, managed: ET.Element | None) -> str:
"""Return the customer label without exposing host resource names.
Older panel domains did not persist a separate label, so their
libvirt name remains the compatibility fallback.
"""
display_name = managed.get("display-name") if managed is not None else None
if isinstance(display_name, str) and NAME_RE.fullmatch(display_name):
return display_name
return domain.name()
@staticmethod
def _internal_resource_names(vm_uuid: str) -> tuple[str, ...]:
compact = uuidlib.UUID(vm_uuid).hex
return tuple(
f"vc-{compact[:length]}" for length in INTERNAL_RESOURCE_PREFIX_LENGTHS
)
@classmethod
def _select_internal_resource_name(
cls,
vm_uuid: str,
domains: list[Any],
volume_names: set[str],
) -> str:
"""Choose a short UUID-derived domain/disk stem without overwriting.
Sixteen hexadecimal digits are ample for routine host maintenance.
If an existing domain or volume has that prefix, progressively reveal
more of the UUID instead of falling back to a user-controlled name.
"""
domain_names = {domain.name() for domain in domains}
for candidate in cls._internal_resource_names(vm_uuid):
if candidate not in domain_names and f"{candidate}.qcow2" not in volume_names:
return candidate
raise VMError("虚拟机内部资源标识已被占用,请重试", 409)
@staticmethod
def _disk_rows(root: ET.Element) -> list[dict[str, Any]]:
rows: list[dict[str, Any]] = []
@ -467,7 +506,7 @@ class VMService:
autostart = False
return {
"uuid": domain.UUIDString(),
"name": domain.name(),
"name": self._display_name(domain, managed),
"state": STATES.get(info[0], "unknown"),
"vcpu": info[3],
"memory_mib": info[1] // 1024,
@ -558,7 +597,7 @@ class VMService:
autostart = False
return {
"uuid": domain.UUIDString(),
"name": domain.name(),
"name": self._display_name(domain, managed),
"vcpu": info[3],
"memory_mib": info[1] // 1024,
# Storage paths and volume names are host-internal details. The
@ -624,7 +663,14 @@ class VMService:
continue
return rows
def provisioning_absent(self, vm_uuid: str, name: str) -> bool:
def provisioning_absent(
self,
vm_uuid: str,
name: str,
*,
uuid_resources: bool = False,
legacy_name_collision: bool = False,
) -> bool:
"""Only certify refund safety after a fresh host/volume inventory.
Any connection failure, external disk collision or partial rollback is
@ -634,12 +680,28 @@ class VMService:
if not isinstance(name, str) or not NAME_RE.fullmatch(name):
return False
with self._connect() as conn:
if any(domain.UUIDString() == vm_uuid for domain in conn.listAllDomains(0)):
domains = conn.listAllDomains(0)
if any(domain.UUIDString() == vm_uuid for domain in domains):
return False
pool = self._active_pool(conn, self.storage_pool)
self._refresh_directory_pool(pool)
volumes = set(pool.listVolumes())
return not {f"{name}.qcow2", f"panel-seed-{vm_uuid}.iso"}.intersection(volumes)
seed_name = f"panel-seed-{vm_uuid}.iso"
if seed_name in volumes:
return False
if (legacy_name_collision and not uuid_resources
and any(domain.name() == name for domain in domains)):
# Legacy creates rejected a duplicate libvirt name before
# allocating either disk. Therefore a same-name domain with
# another UUID (and its same-name disk) predates this failed
# operation and must not keep a deterministic 409 uncertain
# forever. The operation UUID and seed were checked above.
return True
disk_names = (
{f"{candidate}.qcow2" for candidate in self._internal_resource_names(vm_uuid)}
if uuid_resources else {f"{name}.qcow2"}
)
return not disk_names.intersection(volumes)
def get_vm(self, uuid: str) -> dict[str, Any]:
with self._connect() as conn:
@ -808,7 +870,7 @@ class VMService:
iso_source: tuple[str, dict[str, str]], *,
install_phase: bool) -> str:
root = ET.Element("domain", type="kvm")
ET.SubElement(root, "name").text = spec["name"]
ET.SubElement(root, "name").text = spec.get("resource_name", spec["name"])
ET.SubElement(root, "uuid").text = vm_uuid
ET.SubElement(root, "memory", unit="MiB").text = str(spec["memory_mib"])
ET.SubElement(root, "vcpu", placement="static").text = str(spec["vcpu"])
@ -832,6 +894,7 @@ class VMService:
metadata = ET.SubElement(root, "metadata")
managed = ET.SubElement(metadata, f"{{{PANEL_NS}}}managed", version="2",
**{"disk-volume": disk_name})
managed.set("display-name", spec["name"])
if spec.get("created_at"):
managed.set("created-at", spec["created_at"])
if "iso" in spec:
@ -884,13 +947,14 @@ class VMService:
ET.SubElement(memballoon, "stats", period="10")
return ET.tostring(root, encoding="unicode")
def _rollback_new_vm(self, conn: Any, vm_uuid: str, name: str,
def _rollback_new_vm(self, conn: Any, vm_uuid: str, resource_name: str,
pool: Any, volume: Any, disk_name: str) -> bool:
"""Delete the new disk only after verifying its VM no longer exists."""
try:
domains = [domain for domain in conn.listAllDomains(0)
if domain.UUIDString() == vm_uuid]
if len(domains) > 1 or any(domain.name() != name for domain in domains):
if (len(domains) > 1
or any(domain.name() != resource_name for domain in domains)):
LOG.error("Cannot safely identify new domain %s during rollback", vm_uuid)
return False
for domain in domains:
@ -1989,7 +2053,12 @@ class VMService:
with _CREATE_LOCK, self._connect() as conn:
domains = conn.listAllDomains(0)
if any(domain.name() == validated["name"] for domain in domains):
uuid_resource_naming = requested_uuid is not None
vm_uuid = requested_uuid or str(uuidlib.uuid4())
if any(domain.UUIDString() == vm_uuid for domain in domains):
raise VMError("虚拟机 UUID 已存在", 409)
if (not uuid_resource_naming
and any(domain.name() == validated["name"] for domain in domains)):
raise VMError("虚拟机名称已存在", 409)
for domain in domains:
managed = self._vm_xml(domain).find(f"./metadata/{{{PANEL_NS}}}managed")
@ -2013,10 +2082,15 @@ class VMService:
raise VMError("虚拟磁盘不能小于云镜像模板的原始容量", 409)
if target_capacity > pool.info()[3]:
raise VMError("存储池剩余空间不足", 409)
vm_uuid = requested_uuid or str(uuidlib.uuid4())
disk_name = f"{validated['name']}.qcow2"
volume_names = set(pool.listVolumes())
resource_name = (
self._select_internal_resource_name(vm_uuid, domains, volume_names)
if uuid_resource_naming else validated["name"]
)
validated["resource_name"] = resource_name
disk_name = f"{resource_name}.qcow2"
seed_name = f"panel-seed-{vm_uuid}.iso"
if disk_name in pool.listVolumes() or seed_name in pool.listVolumes():
if disk_name in volume_names or seed_name in volume_names:
raise VMError("同名虚拟磁盘或配置盘已存在,不会覆盖", 409)
mac = self._mac_for_new_vm(conn)
try:
@ -2052,13 +2126,14 @@ class VMService:
except Exception as exc:
clean = True
for volume, volume_name in reversed(created):
if not self._rollback_new_vm(conn, vm_uuid, validated["name"],
if not self._rollback_new_vm(conn, vm_uuid, resource_name,
pool, volume, volume_name):
clean = False
break
if not clean:
raise VMError(
f"云虚拟机创建失败且回滚不完整;已保留相关文件,请检查 {validated['name']}",
"云虚拟机创建失败且回滚不完整;已保留相关文件,请检查内部资源 "
f"{resource_name}(显示名 {validated['name']})",
502,
) from exc
if isinstance(exc, VMError):
@ -2178,6 +2253,7 @@ class VMService:
or inactive_source is None
or inactive_source.get("bridge") != self.bridge_name):
raise VMError("关机后虚拟机配置已变化,重装已停止", 409)
display_name = self._display_name(domain, inactive_managed)
if self._owned_volume(conn, domain).name() != old_disk.name() or \
self._owned_seed_volume(conn, domain).name() != old_seed.name():
raise VMError("关机后存储卷已变化,重装已停止", 409)
@ -2188,7 +2264,7 @@ class VMService:
if disk_name in pool.listVolumes() or seed_name in pool.listVolumes():
raise VMError("新系统盘或配置盘名称冲突,已停止重装", 409)
try:
seed_data = build_seed_iso(seed_uuid, domain.name(), mac, network)
seed_data = build_seed_iso(seed_uuid, display_name, mac, network)
except ImportError as exc:
raise VMError("面板缺少 pycdlib,需安装 requirements.txt 中的依赖", 503) from exc
created: list[Any] = []
@ -2257,7 +2333,7 @@ class VMService:
phase("completed")
return {
"vm": {"uuid": vm_id,
"name": inactive_root.findtext("name") or vm_id,
"name": display_name,
"state": "running"},
"warning": "新系统可能已启动,但启动返回错误;旧系统盘已保留,"
"请检查虚拟机状态和存储卷后手工清理",
@ -2312,7 +2388,7 @@ class VMService:
vm_state = self._vm_dict(new_domain)
except Exception:
LOG.exception("VM %s started after reinstall, but its details could not be read", vm_id)
vm_state = {"uuid": vm_id, "name": inactive_root.findtext("name") or vm_id,
vm_state = {"uuid": vm_id, "name": display_name,
"state": "running"}
warnings.append("新系统已启动,但面板未能读取完整虚拟机状态,请检查宿主机")
result: dict[str, Any] = {"vm": vm_state, "credential_generation": seed_name}
@ -2334,7 +2410,13 @@ class VMService:
def _create_iso_vm(self, conn: Any, validated: dict[str, Any],
requested_uuid: str | None, iso_pool: Any,
iso_volume: Any) -> dict[str, Any]:
if any(domain.name() == validated["name"] for domain in conn.listAllDomains(0)):
domains = conn.listAllDomains(0)
uuid_resource_naming = requested_uuid is not None
vm_uuid = requested_uuid or str(uuidlib.uuid4())
if any(domain.UUIDString() == vm_uuid for domain in domains):
raise VMError("虚拟机 UUID 已存在", 409)
if (not uuid_resource_naming
and any(domain.name() == validated["name"] for domain in domains)):
raise VMError("虚拟机名称已存在", 409)
if conn.getInfo()[0] != "x86_64":
raise VMError("当前创建模板只支持 x86_64 宿主机", 422)
@ -2347,9 +2429,14 @@ class VMService:
if not network.isActive():
raise VMError("配置的虚拟网络未启动", 409)
vm_uuid = requested_uuid or str(uuidlib.uuid4())
disk_name = f"{validated['name']}.qcow2"
if disk_name in disk_pool.listVolumes():
volume_names = set(disk_pool.listVolumes())
resource_name = (
self._select_internal_resource_name(vm_uuid, domains, volume_names)
if uuid_resource_naming else validated["name"]
)
validated["resource_name"] = resource_name
disk_name = f"{resource_name}.qcow2"
if disk_name in volume_names:
raise VMError(f"磁盘文件 {disk_name} 已存在,不会覆盖现有数据", 409)
iso_source = self._volume_source(iso_pool, iso_volume)
volume = disk_pool.createXML(self._volume_xml(disk_name, validated["disk_gib"]), 0)
@ -2384,11 +2471,11 @@ class VMService:
self._enable_vm_autostart(domain)
return self._vm_dict(domain)
except Exception as exc:
if not self._rollback_new_vm(conn, vm_uuid, validated["name"],
if not self._rollback_new_vm(conn, vm_uuid, resource_name,
disk_pool, volume, disk_name):
raise VMError(
"创建失败且自动回滚不完整;为避免误删运行中磁盘,请检查宿主机中的"
f"虚拟机 {validated['name']} 和磁盘 {disk_name}", 502,
f"内部资源 {resource_name}(显示名 {validated['name']})和磁盘 {disk_name}", 502,
) from exc
raise

@ -442,6 +442,7 @@ final class CloudApiController
// period itself is still active.
$canOperate = $canDelete && $instance->serviceAvailable();
return array_merge(CloudInput::safeResult($spec), CloudInput::safeResult($vm), ['id' => (string) $instance->id, 'uuid' => $instance->uuid,
'name' => (string) $instance->name,
'user_id' => (int) $instance->user_id, 'owner_user_id' => (int) $instance->user_id,
'display_uuid' => $instance->uuid, 'host_id' => (int) $instance->host_id, 'region' => $host?->region ?? '',
'created_at' => $createdAt,

@ -3,6 +3,8 @@ namespace App\Services\Cloud;
final class CloudInput
{
private const INSTANCE_NAME_CODE_LENGTH = 6;
private const INSTANCE_NAME_CODE_ALPHABET = 'abcdefghjkmnpqrstuvwxyz23456789';
public const ROOT_PASSWORD_LENGTH = 32;
public const ROOT_PASSWORD_MIN_LENGTH = 12;
public const ROOT_PASSWORD_MAX_LENGTH = 128;
@ -50,6 +52,25 @@ final class CloudInput
return $value;
}
public static function optionalName($value): ?string
{
if ($value === null || $value === '') {
return null;
}
return self::name($value);
}
/** Generate a short, user-facing label; libvirt resources use their UUID. */
public static function generateInstanceName(): string
{
$code = '';
$maximum = strlen(self::INSTANCE_NAME_CODE_ALPHABET) - 1;
for ($index = 0; $index < self::INSTANCE_NAME_CODE_LENGTH; $index++) {
$code .= self::INSTANCE_NAME_CODE_ALPHABET[random_int(0, $maximum)];
}
return 'vm-' . $code;
}
public static function password($value): string
{
if ($value === null || $value === '') {

@ -87,10 +87,6 @@ final class CloudInstanceMetadata
if ($metadata !== []) {
$view['engine_metadata_version'] = self::VERSION;
}
$name = self::name($live['name'] ?? null);
if ($name !== null) {
$view['name'] = $name;
}
}
return $view;
}

@ -172,13 +172,12 @@ final class CloudInstancePageService
&& trim($live['state']) !== '';
$state = is_string($live['state'] ?? null) && trim($live['state']) !== ''
? trim($live['state']) : (string) ($snapshot['state'] ?? 'unknown');
$name = is_string($live['name'] ?? null) && trim($live['name']) !== ''
? trim($live['name']) : (string) ($snapshot['name'] ?? '');
return [
'id' => (string) $snapshot['id'],
'api_id' => (string) $snapshot['api_id'],
'uuid' => (string) $snapshot['uuid'],
'name' => $name,
// Engine resource names are UUID-derived implementation details.
'name' => (string) ($snapshot['name'] ?? ''),
'state' => $state,
'live_state_available' => $liveStateAvailable,
'instance_status' => (string) $snapshot['instance_status'],
@ -212,9 +211,7 @@ final class CloudInstancePageService
'id' => (string) $snapshot['id'],
'api_id' => (string) $snapshot['api_id'],
'uuid' => (string) $snapshot['uuid'],
'name' => $matches && is_string($live['name'] ?? null)
&& trim($live['name']) !== ''
? trim($live['name']) : (string) $snapshot['name'],
'name' => (string) $snapshot['name'],
'state' => $available ? trim($live['state']) : 'unknown',
'live_state_available' => $available,
];

@ -13,12 +13,16 @@ final class CloudOrderService
{
/** Unpaid provisioning invoices reserve finite stock for thirty minutes. */
public const PAYMENT_WINDOW_SECONDS = 1800;
private const AUTOMATIC_NAME_SCAN_LIMIT = 256;
public static function purchase(array $input, array $actor): CloudOrder
{
CloudInput::only($input, ['plan_id', 'source', 'template_id', 'guest_ssh_key_id',
'root_password', 'name', 'idempotency_key']);
$name = CloudInput::name($input['name'] ?? null);
$requestedName = CloudInput::optionalName($input['name'] ?? null);
// Missing, null and an empty field describe the same request. Keep the
// fingerprint stable without storing a generated name in the request.
$input['name'] = $requestedName ?? '';
$idempotency = $input['idempotency_key'] ?? '';
if (!is_string($idempotency) || preg_match('/^[A-Za-z0-9_.-]{16,128}$/D', $idempotency) !== 1) {
throw new CloudError('请提供 16 至 128 字符的请求幂等标识');
@ -34,7 +38,7 @@ final class CloudOrderService
$template = CloudInput::template($input['template_id'] ?? '');
ksort($input);
$requestHash = hash_hmac('sha256', json_encode($input, JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES), CloudSecrets::key('payload_key'));
return (new User())->getConnection()->transaction(function () use ($input, $actor, $planId, $source, $name, $template, $idempotency, $requestHash) {
return (new User())->getConnection()->transaction(function () use ($input, $actor, $planId, $source, $requestedName, $template, $idempotency, $requestHash) {
$user = User::where('id', $actor['user_id'])->lockForUpdate()->first();
if ($user === null || (int) $user->enable !== 1) {
throw new CloudError('账户不可用', 403);
@ -56,6 +60,9 @@ final class CloudOrderService
if ($active + $reserved >= $maximum) {
throw new CloudError('已达到账户虚拟机数量上限', 409);
}
// Generate only after an idempotency replay has been resolved, so
// retries return the original order and its original display name.
$name = $requestedName ?? self::automaticName($user);
$plan = Shop::where('id', $planId)->lockForUpdate()->first();
if ($plan === null || (int) $plan->status !== 1 || (int) $plan->stock === 0) {
throw new CloudError('套餐不可购买或已售罄', 409);
@ -106,6 +113,35 @@ final class CloudOrderService
}, 3);
}
private static function automaticName(User $user): string
{
$occupied = [];
foreach (CloudInstance::where('user_id', $user->id)
->where('status', '<>', 'deleted')->orderByDesc('id')
->limit(self::AUTOMATIC_NAME_SCAN_LIMIT)->pluck('name') as $name) {
if (is_string($name) && $name !== '') {
$occupied[$name] = true;
}
}
foreach (CloudOrder::where('user_id', $user->id)->whereIn('status',
['awaiting_payment', 'queued', 'running', 'uncertain'])
->orderByDesc('id')->limit(self::AUTOMATIC_NAME_SCAN_LIMIT)
->get(['spec_json']) as $order) {
$spec = json_decode((string) $order->spec_json, true);
$name = is_array($spec) ? ($spec['name'] ?? null) : null;
if (is_string($name) && $name !== '') {
$occupied[$name] = true;
}
}
for ($attempt = 0; $attempt < 32; $attempt++) {
$name = CloudInput::generateInstanceName();
if (!isset($occupied[$name])) {
return $name;
}
}
throw new CloudError('暂时无法生成唯一实例名称,请重试', 503);
}
/**
* Transfer a paid provisioning invoice into the worker queue.
*

@ -72,7 +72,7 @@
<section id="vm-config-step" class="deployment-step" aria-labelledby="deploy-config-title" aria-disabled="false">
<div class="deployment-step-heading"><span>4</span><h2 id="deploy-config-title">实例信息</h2></div>
<div class="form-grid">
<div class="field full"><label for="vm-name">实例名称 <span>*</span></label><input id="vm-name" name="name" type="text" required minlength="1" maxlength="63" pattern="[a-zA-Z0-9][a-zA-Z0-9._-]*" autocomplete="off" placeholder="例如 web-prod-01" /></div>
<div class="field full"><label for="vm-name">实例名称(可选)</label><input id="vm-name" name="name" type="text" maxlength="63" pattern="[a-zA-Z0-9][a-zA-Z0-9._-]*" autocomplete="off" placeholder="留空自动生成,例如 vm-k7m4p2" /><small>留空时由系统生成 vm- 加 6 位随机编码。</small></div>
<div class="cloud-fields full" id="vm-cloud-fields"><div class="form-grid vm-cloud-auth-fields"><div class="field full"><span class="ssh-key-picker-title">SSH 公钥(可选)</span><div id="vm-guest-ssh-key-cards" class="ssh-key-picker" role="group" aria-label="部署实例时选择 SSH 公钥">{if empty($cloud_deploy_ssh_keys)}<p class="muted">暂无公钥,可先到“公钥管理”添加。不选公钥也会生成强密码。</p>{else}{foreach $cloud_deploy_ssh_keys as $key}<button class="ssh-key-option" type="button" aria-pressed="false" data-key-id="{$key.id|escape:"html"}" aria-label="选择 SSH 公钥 {$key.name|escape:"html"},指纹 {$key.fingerprint|escape:"html"}"><i class="mdi mdi-key-variant ssh-key-choice-icon" aria-hidden="true"></i><span class="ssh-key-choice-copy"><strong class="ssh-key-choice-label">{$key.name|escape:"html"}</strong><small class="ssh-key-choice-fingerprint" title="{$key.fingerprint|escape:"html"}">{$key.fingerprint|escape:"html"}</small></span><span class="ssh-key-choice-check" aria-hidden="true">&#x2713;</span></button>{/foreach}{/if}</div><a id="vm-open-ssh-keys" class="ssh-key-picker-manage" href="/user/cloud/ssh-keys">管理我的公钥</a></div><div class="field full" id="vm-root-password-field"><label for="vm-root-password">初始 root 密码(可选)</label><input id="vm-root-password" name="root_password" type="password" maxlength="128" autocomplete="new-password" spellcheck="false" /><small>留空时生成 32 位完全随机密码;自行设置需为 12–128 位不含空格的英文可打印字符,包含大写、小写、数字和符号。</small></div></div></div>
</div>
</section>

@ -785,5 +785,24 @@ namespace {
&& CloudOrder::find($providerOrder->id)->status === 'queued'
&& CloudJob::where('order_id', $providerOrder->id)->count() === 1,
'Provider callback did not settle an opening invoice exactly once.');
// A blank optional label is normalized before hashing, but generated only
// for a genuinely new order. Replaying the same request with an explicit
// empty field must therefore return the original generated display name.
\App\Services\Config::$values['cloud_max_instances_per_user'] = 100;
$automaticInput = array_replace($input, [
'idempotency_key' => 'test-request-key-automatic-name',
]);
unset($automaticInput['name']);
$automatic = CloudOrderService::purchase($automaticInput, $actor);
$automaticReplay = CloudOrderService::purchase(
$automaticInput + ['name' => ''], $actor
);
$automaticSpec = json_decode((string) $automatic->spec_json, true,
flags: JSON_THROW_ON_ERROR);
$assert($automatic->id === $automaticReplay->id
&& preg_match('/^vm-[abcdefghjkmnpqrstuvwxyz23456789]{6}$/D',
(string) ($automaticSpec['name'] ?? '')) === 1,
'Blank instance names were not generated securely or idempotently.');
echo "Cloud SQLite purchase, provisioning, refund, ambiguity, quota and tenant checks passed (crypto double only).\n";
}

@ -87,14 +87,14 @@ $view = CloudInstanceMetadata::publicView([
'name' => 'database-name', 'disk_gib' => 20,
], $live);
$assert($view['id'] === '1' && $view['uuid'] === $firstUuid
&& $view['name'] === 'engine-name'
&& $view['name'] === 'database-name'
&& $view['public_ip_cidr'] === '203.0.113.18/28'
&& $view['os_source'] === 'cloud_template'
&& $view['os_name'] === 'AlmaLinux 10'
&& $view['login_name'] === 'root'
&& $view['engine_metadata_version'] === 1
&& $view['disk_gib'] === 42.5,
'Matching engine metadata was not exposed through the public allowlist.');
'Matching engine metadata was not exposed without replacing the database display name.');
$assert(array_keys($view['disks']) === [0, 1]
&& array_keys($view['disks'][0]) === ['capacity_gib']
&& !array_key_exists('state', $view)

@ -173,18 +173,20 @@ namespace {
&& !array_key_exists('renewal_price', $mutable),
'Detail status poll loaded static host, credential or renewal metadata.');
$status = CloudInstancePageService::status($managed,
['uuid' => $managed['uuid'], 'name' => 'foreign-vm', 'state' => 'running']);
['uuid' => $managed['uuid'], 'name' => 'vc-2222222222224222', 'state' => 'running']);
$assert($status['state'] === 'running' && $status['traffic_used_bytes'] === 500
&& $status['traffic_remaining_bytes'] === 1500
&& $status['name'] === 'foreign-vm'
&& $status['live_state_available'] === true,
'Lightweight status did not merge live state with the database billing snapshot.');
'Lightweight status did not merge live state while preserving the database display name.');
$unavailable = CloudInstancePageService::status($managed);
$assert($unavailable['state'] === 'unknown'
&& $unavailable['live_state_available'] === false,
'Unavailable hosts were presented as confirmed live power state.');
$power = CloudInstancePageService::powerStatus($managed,
['uuid' => $managed['uuid'], 'name' => 'foreign-vm', 'state' => 'running']);
['uuid' => $managed['uuid'], 'name' => 'vc-2222222222224222', 'state' => 'running']);
$assert($power['state'] === 'running' && $power['live_state_available'] === true
&& $power['name'] === 'foreign-vm'
&& !array_key_exists('traffic_quota_bytes', $power)
&& !array_key_exists('can_delete', $power),
'List polling returned detail-only billing or permission fields.');

@ -118,6 +118,11 @@ $assert(str_contains($statusApi, 'CloudInstancePageService::statusForActor')
&& str_contains($statusApi, ". '/state'")
&& str_contains($statusApi, 'hash_equals('),
'Single VM status must be owner scoped, UUID checked and avoid the full VM detail resource.');
$vmData = $section($api, 'private function vmData(', 'public function vms(');
$assert(str_contains($vmData, "'name' => (string) \$instance->name")
&& strpos($vmData, "'name' => (string) \$instance->name")
> strpos($vmData, 'CloudInput::safeResult($vm)'),
'Full VM responses must keep the database display name authoritative over engine resource names.');
$assert(str_contains($middleware, "\$path === '/api/v1/vms/page'")
&& str_contains($middleware, 'CloudAccess::actor(!$databaseOnly)'),
'Database-only VM pagination must not allocate a private-engine cloud session.');

@ -65,6 +65,13 @@ namespace {
'Generated guest passwords repeat or retain a fixed prefix.');
$assert(strlen(CloudInput::password('Aa1!' . str_repeat('x', 124))) === 128,
'Guest manual password bounds wrong.');
$automaticName = CloudInput::generateInstanceName();
$assert(preg_match('/^vm-[abcdefghjkmnpqrstuvwxyz23456789]{6}$/D',
$automaticName) === 1
&& CloudInput::optionalName(null) === null
&& CloudInput::optionalName('') === null
&& CloudInput::optionalName('customer-vm') === 'customer-vm',
'Optional or generated instance-name policy drifted.');
$safe = CloudInput::safeResult(['uuid' => 'test', 'generated_password' => 'never-save', 'nested' => ['private_key' => 'secret', 'name' => 'safe']]);
$assert($safe === ['uuid' => 'test', 'nested' => ['name' => 'safe']], 'Secret entered durable job output.');
echo "Cloud money, password, HMAC and ambiguity checks passed.\n";

@ -172,6 +172,11 @@ $assert($regionPosition !== false && $planPosition > $regionPosition && $sourceP
&& str_contains($clientScript, 'formBody.inert = false')
&& !str_contains($clientScript, 'body.iso_path ='),
'Deployment must select region, plan and a cloud image without exposing an installation-mode switch.');
$assert(str_contains($deployTemplate, '实例名称(可选)')
&& str_contains($deployTemplate, '留空自动生成,例如 vm-k7m4p2')
&& str_contains($deployTemplate, 'vm- 加 6 位随机编码')
&& !preg_match('/id="vm-name"[^>]*\srequired(?:\s|>)/', $deployTemplate),
'Deployment instance name must be optional and explain its short generated default.');
$planRendererStart = strpos($clientScript, 'function renderPlanPicker()');
$planRendererEnd = strpos($clientScript, 'async function selectRegion(', $planRendererStart);
$planRenderer = $planRendererStart === false || $planRendererEnd === false

Loading…
Cancel
Save