Skip to content

Commit a008732

Browse files
committed
修复删除虚拟机后任务未结束
1 parent 7e1aa14 commit a008732

3 files changed

Lines changed: 116 additions & 1 deletion

File tree

backend/biz/host/repo/host.go

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ import (
2121
"github.com/chaitin/MonkeyCode/backend/db/model"
2222
"github.com/chaitin/MonkeyCode/backend/db/predicate"
2323
"github.com/chaitin/MonkeyCode/backend/db/projecttask"
24+
"github.com/chaitin/MonkeyCode/backend/db/task"
2425
"github.com/chaitin/MonkeyCode/backend/db/taskvirtualmachine"
2526
"github.com/chaitin/MonkeyCode/backend/db/teamgroup"
2627
"github.com/chaitin/MonkeyCode/backend/db/user"
@@ -610,6 +611,7 @@ func (h *HostRepo) CompleteCreateVirtualMachine(ctx context.Context, id string,
610611
func (h *HostRepo) DeleteVirtualMachine(ctx context.Context, uid uuid.UUID, hostID, id string, fn func(*db.VirtualMachine) error) error {
611612
return entx.WithTx2(ctx, h.db, func(tx *db.Tx) error {
612613
vm, err := tx.VirtualMachine.Query().
614+
WithTasks().
613615
Where(virtualmachine.ID(id)).
614616
Where(virtualmachine.UserID(uid)).
615617
First(ctx)
@@ -627,6 +629,27 @@ func (h *HostRepo) DeleteVirtualMachine(ctx context.Context, uid uuid.UUID, host
627629
return err
628630
}
629631

632+
taskIDs := make([]uuid.UUID, 0, len(vm.Edges.Tasks))
633+
for _, tk := range vm.Edges.Tasks {
634+
if tk == nil {
635+
continue
636+
}
637+
taskIDs = append(taskIDs, tk.ID)
638+
}
639+
if len(taskIDs) > 0 {
640+
_, err := tx.Task.Update().
641+
Where(
642+
task.IDIn(taskIDs...),
643+
task.StatusNotIn(consts.TaskStatusFinished, consts.TaskStatusError),
644+
).
645+
SetStatus(consts.TaskStatusFinished).
646+
SetCompletedAt(time.Now()).
647+
Save(ctx)
648+
if err != nil {
649+
return err
650+
}
651+
}
652+
630653
_, err = tx.VirtualMachine.Delete().Where(virtualmachine.ID(id)).Exec(ctx)
631654
if err != nil {
632655
return err

backend/biz/host/usecase/host.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -533,7 +533,7 @@ func (h *HostUsecase) CreateVM(ctx context.Context, user *domain.User, req *doma
533533

534534
// DeleteVM 删除虚拟机
535535
func (h *HostUsecase) DeleteVM(ctx context.Context, uid uuid.UUID, hostID, vmID string) error {
536-
h.logger.InfoContext(ctx, "delete vm", "vmID", vmID)
536+
h.logger.InfoContext(ctx, "delete vm", "vmID", vmID, "user_id", uid, "host_id", hostID)
537537
return h.repo.DeleteVirtualMachine(ctx, uid, hostID, vmID, func(vm *db.VirtualMachine) error {
538538
if err := h.taskflow.VirtualMachiner().Delete(ctx, &taskflow.DeleteVirtualMachineReq{
539539
UserID: uid.String(),

backend/biz/host/usecase/host_test.go

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ import (
2323
"github.com/chaitin/MonkeyCode/backend/db"
2424
"github.com/chaitin/MonkeyCode/backend/db/enttest"
2525
"github.com/chaitin/MonkeyCode/backend/domain"
26+
"github.com/chaitin/MonkeyCode/backend/pkg/delayqueue"
2627
"github.com/chaitin/MonkeyCode/backend/pkg/taskflow"
2728
)
2829

@@ -337,6 +338,97 @@ func TestHostUsecase_markRecycledTasksFinished(t *testing.T) {
337338
}
338339
}
339340

341+
func TestHostUsecase_DeleteVMFinishesBoundTasks(t *testing.T) {
342+
t.Parallel()
343+
344+
ctx := context.Background()
345+
client := enttest.Open(t, "sqlite3", "file:host-usecase-delete-vm-finish-task-test?mode=memory&cache=shared&_fk=1")
346+
defer client.Close()
347+
348+
userID := uuid.New()
349+
if _, err := client.User.Create().
350+
SetID(userID).
351+
SetName("tester").
352+
SetRole(consts.UserRoleIndividual).
353+
SetStatus(consts.UserStatusActive).
354+
Save(ctx); err != nil {
355+
t.Fatalf("create user: %v", err)
356+
}
357+
358+
hostID := "host-1"
359+
if _, err := client.Host.Create().
360+
SetID(hostID).
361+
SetUserID(userID).
362+
SetHostname("host").
363+
Save(ctx); err != nil {
364+
t.Fatalf("create host: %v", err)
365+
}
366+
367+
vmID := "vm-1"
368+
if _, err := client.VirtualMachine.Create().
369+
SetID(vmID).
370+
SetHostID(hostID).
371+
SetUserID(userID).
372+
SetName("vm").
373+
SetEnvironmentID("env-1").
374+
Save(ctx); err != nil {
375+
t.Fatalf("create vm: %v", err)
376+
}
377+
378+
taskID := uuid.New()
379+
if _, err := client.Task.Create().
380+
SetID(taskID).
381+
SetUserID(userID).
382+
SetKind(consts.TaskTypeDevelop).
383+
SetContent("content").
384+
SetStatus(consts.TaskStatusProcessing).
385+
Save(ctx); err != nil {
386+
t.Fatalf("create task: %v", err)
387+
}
388+
if _, err := client.TaskVirtualMachine.Create().
389+
SetID(uuid.New()).
390+
SetTaskID(taskID).
391+
SetVirtualmachineID(vmID).
392+
Save(ctx); err != nil {
393+
t.Fatalf("bind task vm: %v", err)
394+
}
395+
396+
i := do.New()
397+
do.ProvideValue(i, client)
398+
redisServer := miniredis.RunT(t)
399+
redisClient := redis.NewClient(&redis.Options{Addr: redisServer.Addr()})
400+
t.Cleanup(func() { _ = redisClient.Close() })
401+
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
402+
do.ProvideValue(i, &config.Config{})
403+
do.ProvideValue(i, logger)
404+
do.ProvideValue(i, redisClient)
405+
hostRepo, err := repo.NewHostRepo(i)
406+
if err != nil {
407+
t.Fatalf("new host repo: %v", err)
408+
}
409+
u := &HostUsecase{
410+
repo: hostRepo,
411+
taskflow: &preinsertTaskflowStub{vm: &preinsertVMCreateStub{db: client}},
412+
logger: logger,
413+
vmexpireQueue: delayqueue.NewVMExpireQueue(redisClient, logger),
414+
}
415+
416+
if err := u.DeleteVM(ctx, userID, hostID, vmID); err != nil {
417+
t.Fatalf("DeleteVM() error = %v", err)
418+
}
419+
420+
gotTask, err := client.Task.Get(ctx, taskID)
421+
if err != nil {
422+
t.Fatalf("query task: %v", err)
423+
}
424+
if gotTask.Status != consts.TaskStatusFinished {
425+
t.Fatalf("task status = %s, want %s", gotTask.Status, consts.TaskStatusFinished)
426+
}
427+
if gotTask.CompletedAt.IsZero() {
428+
t.Fatal("expected task completed_at to be set")
429+
}
430+
}
431+
340432
func TestHostUsecase_CreateVMPreinsertsVirtualMachineBeforeTaskflowCreate(t *testing.T) {
341433
t.Parallel()
342434

0 commit comments

Comments
 (0)