aboutsummaryrefslogtreecommitdiffstats
path: root/util/interrupt/cleaner.go
blob: 75d6c390dbd2d530619ca620fa6a3d455e2866f2 (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
package interrupt

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

// Cleaner type refers to a function with no inputs that returns an error
type Cleaner func() error

var cleaners []Cleaner
var active = false

// RegisterCleaner is responsible for registering a cleaner function. When a function is registered, the Signal watcher is started in a goroutine.
func RegisterCleaner(f ...Cleaner) {
	for _, fn := range f {
		cleaners = append([]Cleaner{fn}, cleaners...)
		if !active {
			active = 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.Println(err)
				}
				os.Exit(1)
			}()
		}
	}
}

// clean invokes all registered cleanup functions, and returns a list of errors, if they exist.
func clean() (errorlist []error) {
	for _, f := range cleaners {
		err := f()
		if err != nil {
			errorlist = append(errorlist, err)
		}
	}
	cleaners = []Cleaner{}
	return
}