-
Notifications
You must be signed in to change notification settings - Fork 0
/
sig.go
71 lines (59 loc) · 1.48 KB
/
sig.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 2014 Simon Zimmermann. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
// Package util/sig is simple sig trap closer
package sig
import (
"io"
"os"
"os/signal"
"syscall"
"time"
"github.com/simonz05/util/log"
)
// TODO remove Cleanup
type Cleanup func() error
func TrapCloser(cl io.Closer, cleanups ...Cleanup) {
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGINT, syscall.SIGKILL, syscall.SIGTERM, syscall.SIGHUP)
go func() {
for {
rawSig := <-c
sig, ok := rawSig.(syscall.Signal)
if !ok {
log.Fatal("not a unix signal")
}
switch {
case sig == syscall.SIGHUP:
log.Print("SIGHUP: restart process")
err := RestartProcess()
if err != nil {
log.Fatal("failed to restart: " + err.Error())
}
case sig == syscall.SIGINT || sig == syscall.SIGKILL || sig == syscall.SIGTERM:
log.Print("shutting down")
donec := make(chan bool)
go func() {
for _, cb := range cleanups {
if err := cb(); err != nil {
log.Error(err)
}
}
if err := cl.Close(); err != nil {
log.Fatalf("Error shutting down: %v", err)
}
donec <- true
}()
select {
case <-donec:
log.Printf("shutdown")
os.Exit(0)
case <-time.After(5 * time.Second):
log.Fatal("Timeout shutting down. Exiting uncleanly.")
}
default:
log.Fatal("Received another signal, should not happen.")
}
}
}()
}