@ -139,6 +139,10 @@ class HostBody(HostScanBody):
default_network : str = Field ( default = " default " , min_length = 1 , max_length = 128 )
region : str = Field ( default = " " , max_length = 64 ,
pattern = r " ^[^ \ x00- \ x1f \ x7f]*$ " )
public_pool_cidr : str = Field ( default = " " , max_length = 18 )
public_gateway : str = Field ( default = " " , max_length = 15 )
public_dns_servers : list [ str ] = Field ( default_factory = list , max_length = 4 )
public_reserved_ips : list [ str ] = Field ( default_factory = list , max_length = 254 )
def profile ( self ) - > HostProfile :
return HostProfile (
@ -151,6 +155,10 @@ class HostBody(HostScanBody):
iso_pool = self . iso_pool ,
default_network = self . default_network ,
region = self . region ,
public_pool_cidr = self . public_pool_cidr ,
public_gateway = self . public_gateway ,
public_dns_servers = self . public_dns_servers ,
public_reserved_ips = self . public_reserved_ips ,
)
@ -176,9 +184,9 @@ class CreateCloudBody(BaseModel):
disk_gib : int = Field ( ge = 1 , le = 4096 )
network : str = Field ( min_length = 1 , max_length = 128 )
template_id : str = Field ( min_length = 1 , max_length = 80 )
public_ip_cidr : str = Field ( min_length= 3 , max_length = 64 )
gateway : str = Field ( min_length= 7 , max_length = 64 )
dns_servers : list [ str ] = Field ( min_length= 1 , max_length = 4 )
public_ip_cidr : str = Field ( default= " " , max_length = 64 )
gateway : str = Field ( default= " " , max_length = 64 )
dns_servers : list [ str ] = Field ( default_factory= list , max_length = 4 )
guest_ssh_public_key : str = Field ( default = " " , max_length = 16384 )
guest_ssh_key_id : int | None = Field ( default = None , ge = 1 )
root_password : SecretStr | None = None
@ -222,8 +230,15 @@ def _public_host(profile: dict | None) -> dict:
" iso_pool " , " default_network " , " private_key_configured " ,
" private_key_encrypted " , " key_locked " , " private_key_passphrase_saved " ,
)
return { " configured " : True , * * { key : profile [ key ] for key in keys if key in profile } ,
" region " : profile . get ( " region " , " " ) }
return {
" configured " : True ,
* * { key : profile [ key ] for key in keys if key in profile } ,
" region " : profile . get ( " region " , " " ) ,
" public_pool_cidr " : profile . get ( " public_pool_cidr " , " " ) ,
" public_gateway " : profile . get ( " public_gateway " , " " ) ,
" public_dns_servers " : profile . get ( " public_dns_servers " , [ ] ) ,
" public_reserved_ips " : profile . get ( " public_reserved_ips " , [ ] ) ,
}
def _peer ( request : Request ) - > str :
@ -330,6 +345,125 @@ def create_app(
# nonce. The in-memory fallback is only for injected, database-free tests.
test_credentials : dict [ str , str ] = { }
def ip_claim_key ( profile : dict , address : str ) - > str :
return f " { host_scope ( profile ) } . { address } "
def insert_public_ip_claim ( profile : dict , address : str , vm_id : str ) - > bool :
if data_store is None :
return True
claim = json . dumps ( { " vm_uuid " : vm_id , " reserved_at " : int ( time . time ( ) ) } ,
separators = ( " , " , " : " ) )
return data_store . insert ( " ip_claim " , ip_claim_key ( profile , address ) , claim )
def allocate_public_ip ( profile : dict , service : VMService ,
vm_id : str ) - > str :
""" Choose and reserve a public IP, including across panel processes.
Claims remain after a successful create and are released on panel VM
deletion . A claim from an uncertain create is retained rather than
risking reuse of an address whose guest may still exist .
"""
try :
network = ipaddress . IPv4Network ( profile [ " public_pool_cidr " ] , strict = True )
gateway = ipaddress . IPv4Address ( profile [ " public_gateway " ] )
if ( network . prefixlen != 24 or not network . network_address . is_global
or not network . broadcast_address . is_global
or gateway not in network
or gateway in ( network . network_address , network . broadcast_address ) ) :
raise ValueError ( " Invalid host public IPv4 pool " )
blocked = { network . network_address , network . broadcast_address , gateway }
for value in ( * profile . get ( " public_reserved_ips " , [ ] ) ,
* profile . get ( " public_dns_servers " , [ ] ) ) :
address = ipaddress . ip_address ( value )
if isinstance ( address , ipaddress . IPv4Address ) and address in network :
blocked . add ( address )
try :
host_address = ipaddress . ip_address ( profile [ " host " ] )
except ValueError :
host_address = None
if isinstance ( host_address , ipaddress . IPv4Address ) and host_address in network :
blocked . add ( host_address )
except ( KeyError , TypeError , ValueError ) as exc :
raise VMError ( " 宿主机公网地址池配置损坏,请管理员重新保存设置 " , 500 ) from exc
# Include all libvirt-visible panel IPs, regardless of VM ownership.
# VMService also checks duplicates under its own create lock.
for existing_vm in service . list_vms ( ) :
configured = existing_vm . get ( " public_ip_cidr " )
if isinstance ( configured , str ) :
try :
address = ipaddress . IPv4Address ( configured . split ( " / " , 1 ) [ 0 ] )
except ValueError :
continue
if address in network :
blocked . add ( address )
scope_prefix = f " { host_scope ( profile ) } . "
if data_store is not None :
for key in data_store . list ( " ip_claim " ) :
if key . startswith ( scope_prefix ) :
try :
address = ipaddress . IPv4Address ( key [ len ( scope_prefix ) : ] )
except ValueError :
continue
if address in network :
blocked . add ( address )
for address in network . hosts ( ) :
if address in blocked :
continue
if not insert_public_ip_claim ( profile , str ( address ) , vm_id ) :
continue
return f " { address } / { network . prefixlen } "
raise VMError ( " 公网 /24 地址池中没有可分配的 IP, 请检查已用和保留地址 " , 409 )
def claim_explicit_public_ip ( profile : dict , public_ip_cidr : str ,
vm_id : str ) - > None :
if data_store is None :
return
try :
address = str ( ipaddress . IPv4Interface ( public_ip_cidr ) . ip )
except ( TypeError , ValueError ) :
# The libvirt create path returns the detailed input error.
return
if not insert_public_ip_claim ( profile , address , vm_id ) :
raise VMError ( " 该公网 IP 已被面板中的虚拟机或创建任务占用 " , 409 )
def release_public_ip_claim ( profile : dict , public_ip_cidr : str ,
vm_id : str ) - > None :
if data_store is None :
return
try :
address = str ( ipaddress . IPv4Interface ( public_ip_cidr ) . ip )
key = ip_claim_key ( profile , address )
except ( TypeError , ValueError , KeyError ) :
return
raw = data_store . get ( " ip_claim " , key )
if raw is None :
return
try :
claim = json . loads ( raw )
except ( TypeError , ValueError ) :
LOG . error ( " Could not parse public IP claim for %s " , key )
return
if isinstance ( claim , dict ) and claim . get ( " vm_uuid " ) == vm_id :
data_store . delete ( " ip_claim " , key )
def release_vm_public_ip_claims ( profile : dict , vm_id : str ) - > None :
if data_store is None :
return
prefix = f " { host_scope ( profile ) } . "
for key , raw in data_store . list ( " ip_claim " ) . items ( ) :
if not key . startswith ( prefix ) :
continue
try :
claim = json . loads ( raw )
except ( TypeError , ValueError ) :
LOG . error ( " Could not parse public IP claim for %s " , key )
continue
if isinstance ( claim , dict ) and claim . get ( " vm_uuid " ) == vm_id :
data_store . delete ( " ip_claim " , key )
def credential_key ( profile : dict , vm_id : str ) - > str :
try :
canonical_id = str ( uuid . UUID ( vm_id ) )
@ -1125,7 +1259,12 @@ def create_app(
@app.get ( " /api/v1/resources " )
def resources ( _session : Session = Depends ( require_approved ) ) :
return current_service ( ) . resources ( )
profile = current_profile ( )
return {
* * new_service ( profile ) . resources ( ) ,
" public_pool_cidr " : profile . get ( " public_pool_cidr " , " " ) ,
" public_pool_enabled " : bool ( profile . get ( " public_pool_cidr " ) ) ,
}
@app.get ( " /api/v1/vm-templates " )
def list_templates ( _session : Session = Depends ( require_approved ) ) :
@ -1321,6 +1460,19 @@ def create_app(
password_hash = hash_root_password ( root_password )
except ValueError as exc :
raise HTTPException ( status_code = 422 , detail = str ( exc ) ) from exc
auto_public_ip = bool ( profile . get ( " public_pool_cidr " ) )
if auto_public_ip and ( body . public_ip_cidr or body . gateway or body . dns_servers ) :
raise HTTPException (
status_code = 422 ,
detail = " 宿主机已配置公网地址池,创建时不能手动指定 IP、网关或 DNS " ,
)
if not auto_public_ip and not (
body . public_ip_cidr and body . gateway and body . dns_servers
) :
raise HTTPException (
status_code = 422 ,
detail = " 宿主机尚未配置公网地址池,请手动填写 IP、网关和 DNS " ,
)
record = templates . get ( template_scope ( profile ) , body . template_id )
spec = body . model_dump ( exclude = {
" source " , " template_id " , " root_password " , " guest_ssh_key_id " ,
@ -1331,14 +1483,28 @@ def create_app(
spec [ " root_password_hash " ] = password_hash
requested_uuid = str ( uuid . uuid4 ( ) )
spec [ " vm_uuid " ] = requested_uuid
if owner_id is not None :
state . users . assign_vm ( host_scope ( profile ) , requested_uuid , owner_id )
service = new_service ( profile )
allocated_ip = " "
owner_assigned = False
try :
if auto_public_ip :
allocated_ip = allocate_public_ip (
profile , service , requested_uuid ,
)
spec [ " public_ip_cidr " ] = allocated_ip
spec [ " gateway " ] = profile [ " public_gateway " ]
spec [ " dns_servers " ] = list ( profile [ " public_dns_servers " ] )
else :
claim_explicit_public_ip ( profile , body . public_ip_cidr , requested_uuid )
allocated_ip = body . public_ip_cidr
if owner_id is not None :
state . users . assign_vm ( host_scope ( profile ) , requested_uuid , owner_id )
owner_assigned = True
save_credential ( profile , requested_uuid ,
" ssh_key " if public_key else " password " ,
f " panel-seed- { requested_uuid } .iso " ,
root_password or None )
vm = new_service ( profile ) . create_cloud_vm ( spec , record [ " volume_name " ] )
vm = service. create_cloud_vm ( spec , record [ " volume_name " ] )
except Exception as exc :
# An incomplete libvirt rollback may have left the guest
# behind. Keep its credential in that exceptional case so
@ -1350,8 +1516,16 @@ def create_app(
delete_credential ( profile , requested_uuid )
except DatabaseError :
LOG . exception ( " Could not remove unused VM credential for %s " , requested_uuid )
if owner_id is not None :
state . users . delete_vm_owner ( host_scope ( profile ) , requested_uuid )
if owner_assigned :
try :
state . users . delete_vm_owner ( host_scope ( profile ) , requested_uuid )
except DatabaseError :
LOG . exception ( " Could not remove unused VM owner for %s " , requested_uuid )
if allocated_ip :
try :
release_public_ip_claim ( profile , allocated_ip , requested_uuid )
except DatabaseError :
LOG . exception ( " Could not release unused public IP claim for %s " , requested_uuid )
raise
vm = verified_created_vm ( profile , vm , requested_uuid )
else :
@ -1588,6 +1762,11 @@ def create_app(
except DatabaseError :
LOG . exception ( " Could not remove credential for deleted VM %s " , result [ " uuid " ] )
result = { * * result , " warning " : " 虚拟机已删除,但数据库中的登录凭据或归属记录未能完全清理;请检查数据库状态 " }
try :
release_vm_public_ip_claims ( profile , result [ " uuid " ] )
except DatabaseError :
LOG . exception ( " Could not release public IP claim for deleted VM %s " , result [ " uuid " ] )
result = { * * result , " warning " : " 虚拟机已删除,但公网 IP 占用记录未能清理;请检查数据库状态 " }
LOG . info (
" vm deleted: uuid= %s delete_disks= %s admin= %s " ,
result . get ( " uuid " ) , delete_disks , _session . username ,