File: finalcontext.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 (39 lines) | stat: -rw-r--r-- 1,305 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
// Package finalcontext is used by Vagrant to create a "final" context
// that we'll use after the real context has been cancelled. This lets us
// do some last minute cleanup that may require a context.
//
// For more detail in case that isn't clear: we use contexts everywhere
// for cancellation. Once cancelled, we may want to perform some cleanup,
// such as calling an RPC call to note we're cancelled. But this RPC itself
// requires a context and our context is already cancelled. We construct a
// "final" context that lets us do this.
package finalcontext

import (
	"context"
	"time"

	"github.com/hashicorp/go-hclog"

	"github.com/hashicorp/vagrant/internal/pkg/signalcontext"
)

// Context returns a final context. This context is set to timeout in
// some set amount of time (a few seconds) and will also cancel immediately
// if another interrupt is received.
func Context(log hclog.Logger) (context.Context, func()) {
	log.Warn("context cancelled, creating a final context to perform cleanup")

	ctx := context.Background()

	// Create a context that listens for another interrupt
	ctx, cancelSignal := signalcontext.WithInterrupt(ctx, log)

	// Create a timeout
	ctx, cancelTimeout := context.WithTimeout(ctx, 2*time.Second)

	return ctx, func() {
		cancelSignal()
		cancelTimeout()
	}
}