Skip to content

Commit d8916b5

Browse files
committed
feat: added name change of duplicate vm
1 parent 83fa3fb commit d8916b5

File tree

1 file changed

+24
-8
lines changed

1 file changed

+24
-8
lines changed

backend/app/services/vm_service.py

Lines changed: 24 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -274,6 +274,20 @@ def _get_vm_or_404(session: Session, vm_id: str) -> VmORM:
274274
)
275275
return vm_record
276276

277+
@staticmethod
278+
def _get_duplicate_name(session: Session, vm_name: str) -> str:
279+
base_name = f"Duplicate of {vm_name}"
280+
search_pattern = f"{base_name}%"
281+
282+
statement = select(
283+
func.count(
284+
VmORM.id)).where(
285+
VmORM.name.like(search_pattern))
286+
count = session.exec(statement).one()
287+
if count == 0:
288+
return base_name
289+
return f"{base_name}({count})"
290+
277291
def get_vm_list():
278292
vm = Vm.get_all()
279293
return vm
@@ -485,21 +499,23 @@ def remove_all_recoverable_vms():
485499
def duplicate_vm(vm_id: str):
486500
with Session(engine) as session:
487501
vm_to_duplicate = VmService._get_vm_or_404(session, vm_id)
488-
duplicate_of_vm = VmORM(**vm_to_duplicate.model_dump())
489-
duplicate_of_vm.id = uuid.uuid4()
502+
duplicate_vm = VmORM(**vm_to_duplicate.model_dump())
503+
duplicate_vm.id = uuid.uuid4()
504+
duplicate_vm.name = VmService._get_duplicate_name(
505+
session, duplicate_vm.name)
490506

491-
src_path = VMS_DIR / vm_id / duplicate_of_vm.os
492-
dest_path = VMS_DIR / str(duplicate_of_vm.id)
507+
src_path = VMS_DIR / vm_id / duplicate_vm.os
508+
dest_path = VMS_DIR / str(duplicate_vm.id)
493509

494510
dest_path.mkdir(parents=True, exist_ok=True)
495-
copy(src_path, dest_path / duplicate_of_vm.os)
511+
copy(src_path, dest_path / duplicate_vm.os)
496512

497-
vm_xml = build_xml(VmCreateXML(**duplicate_of_vm.model_dump()))
513+
vm_xml = build_xml(VmCreateXML(**duplicate_vm.model_dump()))
498514

499515
try:
500516
conn = QEMUConfig.get_connection()
501517
conn.defineXML(vm_xml)
502-
session.add(duplicate_of_vm)
518+
session.add(duplicate_vm)
503519
session.commit()
504520
except Exception as e:
505521
if dest_path.exists():
@@ -509,4 +525,4 @@ def duplicate_vm(vm_id: str):
509525
detail=f"Failed to duplicate VM: {str(e)}"
510526
)
511527

512-
return Vm.get(str(duplicate_of_vm.id))
528+
return Vm.get(str(duplicate_vm.id))

0 commit comments

Comments
 (0)