aboutsummaryrefslogtreecommitdiffstats
path: root/util/interrupt/cleaner.go
blob: 38c8425bae13870978a3813c74e156e0cf3742ed (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package interrupt

import (
	"fmt"
	"os"
	"os/signal"
	"sync"
	"syscall"
)

// CleanerFunc is a function to be executed when an interrupt trigger
type CleanerFunc func() error

// CancelFunc, if called, will disable the associated cleaner.
// This allow to create temporary cleaner. Be mindful though to not
// create too much of them as they are just disabled, not removed from
// memory.
type CancelFunc func()

type wrapper struct {
	f        CleanerFunc
	disabled bool
}

var mu sync.Mutex
var cleaners []*wrapper
var handlerCreated = false

// RegisterCleaner is responsible for registering a cleaner function.
// When a function is registered, the Signal watcher is started in a goroutine.
func RegisterCleaner(cleaner CleanerFunc) CancelFunc {
	mu.Lock()
	defer mu.Unlock()

	w := &wrapper{f: cleaner}

	cancel := func() {
		mu.Lock()
		defer mu.Unlock()
		w.disabled = true
	}

	// prepend to later execute then in reverse order
	cleaners = append([]*wrapper{w}, cleaners...)

	if handlerCreated {
		return cancel
	}

	handlerCreated = true
	go func() {
		ch := make(chan os.Signal, 1)
		signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM, os.Interrupt)
		<-ch
		// Prevent un-terminated ^C character in terminal
		fmt.Println()
		errl := clean()
		for _, err := range errl {
			_, _ = fmt.Fprintln(os.Stderr, err)
		}
		os.Exit(1)
	}()

	return cancel
}

// clean invokes all registered cleanup functions, and returns a list of errors, if they exist.
func clean() (errorList []error) {
	mu.Lock()
	defer mu.Unlock()

	for _, cleaner := range cleaners {
		if cleaner.disabled {
			continue
		}
		err := cleaner.f()
		if err != nil {
			errorList = append(errorList, err)
		}
	}
	cleaners = []*wrapper{}
	return
}