github.com/containers/podman/v4@v4.9.4/pkg/machine/cleanup.go (about)

     1  package machine
     2  
     3  import (
     4  	"os"
     5  	"os/signal"
     6  	"sync"
     7  	"syscall"
     8  
     9  	"github.com/sirupsen/logrus"
    10  )
    11  
    12  type CleanupCallback struct {
    13  	Funcs []func() error
    14  	mu    sync.Mutex
    15  }
    16  
    17  func (c *CleanupCallback) CleanIfErr(err *error) {
    18  	// Do not remove created files if the init is successful
    19  	if *err == nil {
    20  		return
    21  	}
    22  	c.clean()
    23  }
    24  
    25  func (c *CleanupCallback) CleanOnSignal() {
    26  	ch := make(chan os.Signal, 1)
    27  	signal.Notify(ch, os.Interrupt, syscall.SIGTERM)
    28  
    29  	_, ok := <-ch
    30  	if !ok {
    31  		return
    32  	}
    33  
    34  	c.clean()
    35  	os.Exit(1)
    36  }
    37  
    38  func (c *CleanupCallback) clean() {
    39  	c.mu.Lock()
    40  	// Claim exclusive usage by copy and resetting to nil
    41  	funcs := c.Funcs
    42  	c.Funcs = nil
    43  	c.mu.Unlock()
    44  
    45  	// Already claimed or none set
    46  	if funcs == nil {
    47  		return
    48  	}
    49  
    50  	// Cleanup functions can now exclusively be run
    51  	for _, cleanfunc := range funcs {
    52  		if err := cleanfunc(); err != nil {
    53  			logrus.Error(err)
    54  		}
    55  	}
    56  }
    57  
    58  func InitCleanup() CleanupCallback {
    59  	return CleanupCallback{
    60  		Funcs: []func() error{},
    61  	}
    62  }
    63  
    64  func (c *CleanupCallback) Add(anotherfunc func() error) {
    65  	c.mu.Lock()
    66  	c.Funcs = append(c.Funcs, anotherfunc)
    67  	c.mu.Unlock()
    68  }