From 70ca03b6fd387e70afd19ca5b4f29bb9c2479d7d Mon Sep 17 00:00:00 2001 From: Abiola Ibrahim Date: Sat, 14 Dec 2024 15:35:57 +0100 Subject: [PATCH] net: clear assets directory on startup (#1213) Signed-off-by: Abiola Ibrahim --- environment/vm/lima/limautil/files.go | 5 +++++ environment/vm/lima/limautil/instance.go | 17 +++++++++++++++++ environment/vm/lima/network.go | 8 ++++++++ 3 files changed, 30 insertions(+) diff --git a/environment/vm/lima/limautil/files.go b/environment/vm/lima/limautil/files.go index 0f33e34e7..11b0a4aad 100644 --- a/environment/vm/lima/limautil/files.go +++ b/environment/vm/lima/limautil/files.go @@ -19,3 +19,8 @@ const networkFile = "networks.yaml" func NetworkFile() string { return filepath.Join(config.LimaDir(), "_config", networkFile) } + +// NetworkAssetsDirecotry returns the directory for the generated network assets. +func NetworkAssetsDirectory() string { + return filepath.Join(config.LimaDir(), "_networks") +} diff --git a/environment/vm/lima/limautil/instance.go b/environment/vm/lima/limautil/instance.go index 99cf1ebe6..248f667fc 100644 --- a/environment/vm/lima/limautil/instance.go +++ b/environment/vm/lima/limautil/instance.go @@ -120,6 +120,23 @@ func Instances(ids ...string) ([]InstanceInfo, error) { return instances, nil } +// RunningInstances return Lima instances that are has a running status. +func RunningInstances() ([]InstanceInfo, error) { + allInstances, err := Instances() + if err != nil { + return nil, err + } + + var runningInstances []InstanceInfo + for _, instance := range allInstances { + if instance.Running() { + runningInstances = append(runningInstances, instance) + } + } + + return runningInstances, nil +} + func getRuntime(conf config.Config) string { var runtime string diff --git a/environment/vm/lima/network.go b/environment/vm/lima/network.go index 80b114e8e..df01f32d1 100644 --- a/environment/vm/lima/network.go +++ b/environment/vm/lima/network.go @@ -10,6 +10,7 @@ import ( "github.com/abiosoft/colima/embedded" "github.com/abiosoft/colima/environment/vm/lima/limautil" "github.com/abiosoft/colima/util" + "github.com/sirupsen/logrus" ) func (l *limaVM) writeNetworkFile() error { @@ -19,6 +20,13 @@ func (l *limaVM) writeNetworkFile() error { return fmt.Errorf("error reading embedded network config file: %w", err) } + // if there are no running instances, clear network directory + if instances, err := limautil.RunningInstances(); err == nil && len(instances) == 0 { + if err := os.RemoveAll(limautil.NetworkAssetsDirectory()); err != nil { + logrus.Warnln(fmt.Errorf("could not clear network assets directory: %w", err)) + } + } + if err := os.MkdirAll(filepath.Dir(networkFile), 0755); err != nil { return fmt.Errorf("error creating Lima config directory: %w", err) }