mirror of
https://github.com/containers/podman.git
synced 2025-08-06 19:44:14 +08:00

If init fails, or if a SIGINT is sent during init, podman machine should remove all files and configs created during the init. This includes config jsons, image files, ssh id's, and system connections. On Windows, the VM instances are also unregistered. Signed-off-by: Ashley Cui <acui@redhat.com>
69 lines
1.1 KiB
Go
69 lines
1.1 KiB
Go
package machine
|
|
|
|
import (
|
|
"os"
|
|
"os/signal"
|
|
"sync"
|
|
"syscall"
|
|
|
|
"github.com/sirupsen/logrus"
|
|
)
|
|
|
|
type CleanupCallback struct {
|
|
Funcs []func() error
|
|
mu sync.Mutex
|
|
}
|
|
|
|
func (c *CleanupCallback) CleanIfErr(err *error) {
|
|
// Do not remove created files if the init is successful
|
|
if *err == nil {
|
|
return
|
|
}
|
|
c.clean()
|
|
}
|
|
|
|
func (c *CleanupCallback) CleanOnSignal() {
|
|
ch := make(chan os.Signal, 1)
|
|
signal.Notify(ch, os.Interrupt, syscall.SIGTERM)
|
|
|
|
_, ok := <-ch
|
|
if !ok {
|
|
return
|
|
}
|
|
|
|
c.clean()
|
|
os.Exit(1)
|
|
}
|
|
|
|
func (c *CleanupCallback) clean() {
|
|
c.mu.Lock()
|
|
// Claim exclusive usage by copy and resetting to nil
|
|
funcs := c.Funcs
|
|
c.Funcs = nil
|
|
c.mu.Unlock()
|
|
|
|
// Already claimed or none set
|
|
if funcs == nil {
|
|
return
|
|
}
|
|
|
|
// Cleanup functions can now exclusively be run
|
|
for _, cleanfunc := range funcs {
|
|
if err := cleanfunc(); err != nil {
|
|
logrus.Error(err)
|
|
}
|
|
}
|
|
}
|
|
|
|
func InitCleanup() CleanupCallback {
|
|
return CleanupCallback{
|
|
Funcs: []func() error{},
|
|
}
|
|
}
|
|
|
|
func (c *CleanupCallback) Add(anotherfunc func() error) {
|
|
c.mu.Lock()
|
|
c.Funcs = append(c.Funcs, anotherfunc)
|
|
c.mu.Unlock()
|
|
}
|