File: signals.go

package info (click to toggle)
mongo-tools 3.4.14-4
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 18,612 kB
  • sloc: python: 9,281; asm: 4,229; ansic: 1,606; sh: 817; makefile: 67; cpp: 59; lisp: 19
file content (56 lines) | stat: -rw-r--r-- 1,726 bytes parent folder | download
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
package signals

import (
	"github.com/mongodb/mongo-tools/common/log"
	"github.com/mongodb/mongo-tools/common/util"

	"os"
	"os/signal"
	"syscall"
)

// Handle is like HandleWithInterrupt but it doesn't take a finalizer and will
// exit immediately after the first signal is received.
func Handle() chan struct{} {
	return HandleWithInterrupt(nil)
}

// HandleWithInterrupt starts a goroutine which listens for SIGTERM, SIGINT, and
// SIGKILL and explicitly ignores SIGPIPE. It calls the finalizer function when
// the first signal is received and forcibly terminates the program after the
// second. If a nil function is provided, the program will exit after the first
// signal.
func HandleWithInterrupt(finalizer func()) chan struct{} {
	finishedChan := make(chan struct{})
	go handleSignals(finalizer, finishedChan)
	return finishedChan
}

func handleSignals(finalizer func(), finishedChan chan struct{}) {
	// explicitly ignore SIGPIPE; the tools should deal with write errors
	noopChan := make(chan os.Signal)
	signal.Notify(noopChan, syscall.SIGPIPE)

	log.Logv(log.DebugLow, "will listen for SIGTERM, SIGINT, and SIGKILL")
	sigChan := make(chan os.Signal, 2)
	signal.Notify(sigChan, syscall.SIGTERM, syscall.SIGINT, syscall.SIGKILL)
	defer signal.Stop(sigChan)
	if finalizer != nil {
		select {
		case sig := <-sigChan:
			// first signal use finalizer to terminate cleanly
			log.Logvf(log.Always, "signal '%s' received; attempting to shut down", sig)
			finalizer()
		case <-finishedChan:
			return
		}
	}
	select {
	case sig := <-sigChan:
		// second signal exits immediately
		log.Logvf(log.Always, "signal '%s' received; forcefully terminating", sig)
		os.Exit(util.ExitKill)
	case <-finishedChan:
		return
	}
}