File: signalcontext.go

package info (click to toggle)
vagrant 2.3.7%2Bgit20230731.5fc64cde%2Bdfsg-3
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 17,616 kB
  • sloc: ruby: 111,820; sh: 462; makefile: 123; ansic: 34; lisp: 1
file content (42 lines) | stat: -rw-r--r-- 1,186 bytes parent folder | download | duplicates (3)
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
package signalcontext

import (
	"context"
	"os"
	"os/signal"

	"github.com/hashicorp/go-hclog"
)

// WithInterrupt returns a Context that is done when an interrupt signal is received.
// It also returns a closer function that should be deferred for proper cleanup.
func WithInterrupt(ctx context.Context, log hclog.Logger) (context.Context, func()) {
	log.Trace("starting interrupt listener for context cancellation")

	// Create the cancellable context that we'll use when we receive an interrupt
	ctx, cancel := context.WithCancel(ctx)

	// Create the signal channel and cancel the context when we get a signal
	ch := make(chan os.Signal, 1)
	signal.Notify(ch, os.Interrupt)
	go func() {
		log.Trace("interrupt listener goroutine started")

		select {
		case <-ch:
			log.Warn("interrupt received, cancelling context")
			cancel()
		case <-ctx.Done():
			log.Warn("context cancelled, stopping interrupt listener loop")
			return
		}
	}()

	// Return the context and a closer that cancels the context and also
	// stops any signals from coming to our channel.
	return ctx, func() {
		log.Trace("stopping signal listeners and cancelling the context")
		signal.Stop(ch)
		cancel()
	}
}