Skip to content

Commit 8253eda

Browse files
committed
truncate
1 parent a2cae37 commit 8253eda

2 files changed

Lines changed: 17 additions & 8 deletions

File tree

cmd/vm/handler.go

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ import (
2020
"github.com/projecteru2/cocoon/console"
2121
"github.com/projecteru2/cocoon/hypervisor"
2222
"github.com/projecteru2/cocoon/hypervisor/cloudhypervisor"
23+
"github.com/projecteru2/cocoon/network"
2324
"github.com/projecteru2/cocoon/types"
2425
"github.com/projecteru2/cocoon/utils"
2526
)
@@ -286,10 +287,14 @@ func (h Handler) createVM(cmd *cobra.Command, image string) (context.Context, *c
286287
return nil, nil, fmt.Errorf("generate VM ID: %w", err)
287288
}
288289

289-
var networkConfigs []*types.NetworkConfig
290+
var (
291+
networkConfigs []*types.NetworkConfig
292+
netProvider network.Network
293+
)
290294
nics, _ := cmd.Flags().GetInt("nics")
291295
if nics > 0 {
292-
netProvider, initErr := cmdcore.InitNetwork(conf)
296+
var initErr error
297+
netProvider, initErr = cmdcore.InitNetwork(conf)
293298
if initErr != nil {
294299
return nil, nil, fmt.Errorf("init network: %w", initErr)
295300
}
@@ -301,11 +306,8 @@ func (h Handler) createVM(cmd *cobra.Command, image string) (context.Context, *c
301306

302307
info, createErr := hyper.Create(ctx, vmID, vmCfg, storageConfigs, networkConfigs, bootCfg)
303308
if createErr != nil {
304-
// Rollback network if Create fails.
305-
if nics > 0 {
306-
if netProvider, initErr := cmdcore.InitNetwork(conf); initErr == nil {
307-
_, _ = netProvider.Delete(ctx, []string{vmID})
308-
}
309+
if netProvider != nil {
310+
_, _ = netProvider.Delete(ctx, []string{vmID})
309311
}
310312
return nil, nil, fmt.Errorf("create VM: %w", createErr)
311313
}

hypervisor/cloudhypervisor/create.go

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -107,9 +107,16 @@ func (ch *CloudHypervisor) prepareOCI(ctx context.Context, vmID string, vmCfg *t
107107
cowPath := ch.conf.CHVMCOWRawPath(vmID)
108108

109109
// Create sparse COW file (equivalent to truncate -s <size>).
110-
if err := os.Truncate(cowPath, vmCfg.Storage); err != nil {
110+
// os.Truncate requires the file to exist; create it first.
111+
f, err := os.Create(cowPath) //nolint:gosec
112+
if err != nil {
113+
return nil, fmt.Errorf("create COW: %w", err)
114+
}
115+
if err := f.Truncate(vmCfg.Storage); err != nil {
116+
_ = f.Close()
111117
return nil, fmt.Errorf("truncate COW: %w", err)
112118
}
119+
_ = f.Close()
113120
// mkfs.ext4
114121
if out, err := exec.CommandContext(ctx, //nolint:gosec
115122
"mkfs.ext4", "-F", "-m", "0", "-q",

0 commit comments

Comments
 (0)