-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathtimeout.go
More file actions
41 lines (33 loc) · 890 Bytes
/
Copy pathtimeout.go
File metadata and controls
41 lines (33 loc) · 890 Bytes
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
package check
import (
"fmt"
"os"
"os/signal"
"syscall"
"time"
)
var timeoutEnabled bool
// EnableTimeoutHandler starts the timeout and signal handler in a goroutine
func (c *Config) EnableTimeoutHandler() {
go HandleTimeout(c.Timeout)
}
// HandleTimeout is a helper for a goroutine, to wait for signals and timeout, and exit with a proper code
func HandleTimeout(timeout int) {
if timeoutEnabled {
// signal handling has already been set up
return
}
signals := make(chan os.Signal, 1)
signal.Notify(signals, os.Interrupt, syscall.SIGTERM, syscall.SIGHUP)
if timeout < 1 {
Exit(Unknown, fmt.Sprintf("Invalid timeout: %d", timeout))
}
timedOut := time.After(time.Duration(timeout) * time.Second)
timeoutEnabled = true
select {
case s := <-signals:
Exit(Unknown, fmt.Sprintf("Received signal: %s", s))
case <-timedOut:
Exit(Unknown, "Timeout reached")
}
}