45 lines
1.3 KiB
Go
45 lines
1.3 KiB
Go
package app
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"time"
|
|
|
|
"github.com/Nwflower/reims-go/internal/networkmsg"
|
|
)
|
|
|
|
type networkTransaction struct {
|
|
prepareHost func() error
|
|
commitConfig func() error
|
|
rollbackConfig func() error
|
|
rollbackHost func() error
|
|
}
|
|
|
|
// networkRollback 保证取消创建或操作超时后,恢复命令仍有独立且有界的执行时间。
|
|
func networkRollback(ctx context.Context, restore func(context.Context) error) func() error {
|
|
return func() error {
|
|
recoveryCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Minute)
|
|
defer cancel()
|
|
return restore(recoveryCtx)
|
|
}
|
|
}
|
|
|
|
// 通道准备失败时不触碰虚拟机配置;提交失败时恢复配置和原通道。
|
|
func runNetworkTransaction(change networkTransaction) (restored bool, err error) {
|
|
if err := change.prepareHost(); err != nil {
|
|
if restoreErr := change.rollbackHost(); restoreErr != nil {
|
|
return false, networkmsg.Error("host_rollback", errors.Join(err, restoreErr))
|
|
}
|
|
return true, networkmsg.Error("switch_unchanged", err)
|
|
}
|
|
if err := change.commitConfig(); err != nil {
|
|
configErr := change.rollbackConfig()
|
|
hostErr := change.rollbackHost()
|
|
if configErr != nil || hostErr != nil {
|
|
return false, errors.Join(err, configErr, hostErr)
|
|
}
|
|
return true, networkmsg.Error("switch_rolled_back", err)
|
|
}
|
|
return false, nil
|
|
}
|