forked from decred/tumblebit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
signal.go
71 lines (60 loc) · 2.21 KB
/
signal.go
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
// Copyright (c) 2013-2014 The btcsuite developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package main
import (
"context"
"os"
"os/signal"
)
// shutdownRequestChannel is used to initiate shutdown from one of the
// subsystems using the same code paths as when an interrupt signal is received.
var shutdownRequestChannel = make(chan struct{})
// shutdownSignaled is closed whenever shutdown is invoked through an interrupt
// signal or from an JSON-RPC stop request. Any contexts created using
// withShutdownChannel are cancelled when this is closed.
var shutdownSignaled = make(chan struct{})
// signals defines the signals that are handled to do a clean shutdown.
// Conditional compilation is used to also include SIGTERM on Unix.
var signals = []os.Signal{os.Interrupt}
// withShutdownCancel creates a copy of a context that is cancelled whenever
// shutdown is invoked through an interrupt signal or from an JSON-RPC stop
// request.
func withShutdownCancel(ctx context.Context) context.Context {
ctx, cancel := context.WithCancel(ctx)
go func() {
<-shutdownSignaled
cancel()
}()
return ctx
}
// requestShutdown signals for starting the clean shutdown of the process
// through an internal component (such as through the JSON-RPC stop request).
func requestShutdown() {
shutdownRequestChannel <- struct{}{}
}
// shutdownListener listens for shutdown requests and cancels all contexts
// created from withShutdownCancel. This function never returns and is intended
// to be spawned in a new goroutine.
func shutdownListener() {
interruptChannel := make(chan os.Signal, 1)
signal.Notify(interruptChannel, signals...)
// Listen for the initial shutdown signal
select {
case sig := <-interruptChannel:
log.Infof("Received signal (%s). Shutting down...", sig)
case <-shutdownRequestChannel:
log.Info("Shutdown requested. Shutting down...")
}
// Cancel all contexts created from withShutdownCancel.
close(shutdownSignaled)
// Listen for any more shutdown signals and log that shutdown has already
// been signaled.
for {
select {
case <-interruptChannel:
case <-shutdownRequestChannel:
}
log.Info("Shutdown signaled. Already shutting down...")
}
}