summaryrefslogtreecommitdiff
path: root/internal/io/signal/signal.go
blob: e94de424146c30b379adfb27c319a4c37aafcd7d (plain)
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
84
85
86
87
88
89
90
91
92
93
package signal

import (
	"context"
	"os"
	gosignal "os/signal"
	"syscall"
	"time"

	"github.com/mimecast/dtail/internal/config"
)

// InterruptChWithCancel returns a channel for "please print stats" signalling.
// It accepts a cancel function to properly shutdown when termination signals are received.
func InterruptChWithCancel(ctx context.Context, cancel context.CancelFunc) <-chan string {
	sigIntCh := make(chan os.Signal, 10)
	gosignal.Notify(sigIntCh, os.Interrupt)
	sigOtherCh := make(chan os.Signal, 10)
	gosignal.Notify(sigOtherCh, syscall.SIGHUP, syscall.SIGTERM, syscall.SIGQUIT)
	statsCh := make(chan string)

	go func() {
		for {
			select {
			case <-sigIntCh:
				select {
				case statsCh <- "Hint: Hit Ctrl+C again to exit":
					select {
					case <-sigIntCh:
						cancel()
						// Wait longer to allow MapReduce cleanup, then force exit if still running
						go func() {
							time.Sleep(5 * time.Second)
							os.Exit(0)
						}()
					case <-time.After(time.Second * time.Duration(config.InterruptTimeoutS)):
					}
				default:
					// Stats already printed.
				}
			case <-sigOtherCh:
				// Cancel context to allow graceful shutdown (MapReduce outfile cleanup, etc.)
				cancel()
				// Wait longer to allow MapReduce cleanup, then force exit if still running
				go func() {
					time.Sleep(5 * time.Second)
					os.Exit(0)
				}()
			case <-ctx.Done():
				return
			}
		}
	}()
	return statsCh
}

// InterruptCh returns a channel for "please print stats" signalling.
// Deprecated: Use InterruptChWithCancel for proper cleanup on termination signals.
func InterruptCh(ctx context.Context) <-chan string {
	sigIntCh := make(chan os.Signal, 10)
	gosignal.Notify(sigIntCh, os.Interrupt)
	sigOtherCh := make(chan os.Signal, 10)
	gosignal.Notify(sigOtherCh, syscall.SIGHUP, syscall.SIGTERM, syscall.SIGQUIT)
	statsCh := make(chan string)

	go func() {
		for {
			select {
			case <-sigIntCh:
				select {
				case statsCh <- "Hint: Hit Ctrl+C again to exit":
					select {
					case <-sigIntCh:
						os.Exit(0)
					case <-time.After(time.Second * time.Duration(config.InterruptTimeoutS)):
					}
				default:
					// Stats already printed.
				}
			case <-sigOtherCh:
				os.Exit(0)
			case <-ctx.Done():
				return
			}
		}
	}()
	return statsCh
}

// NoCh doesn't listen on a signal.
func NoCh(ctx context.Context) <-chan string {
	return make(chan string)
}