forked from juju/juju
/
worker.go
59 lines (49 loc) · 1.16 KB
/
worker.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
// Copyright 2014 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package terminationworker
import (
"os"
"os/signal"
"syscall"
"gopkg.in/juju/worker.v1"
"gopkg.in/tomb.v2"
jworker "github.com/juju/juju/worker"
)
// TerminationSignal is the signal that
// indicates the agent should terminate
// and uninstall itself.
//
// We do not use SIGTERM as SIGTERM is the
// default signal used to initiate a graceful
// shutdown.
const TerminationSignal = syscall.SIGABRT
type terminationWorker struct {
tomb tomb.Tomb
}
// NewWorker returns a worker that waits for a
// TerminationSignal signal, and then exits
// with worker.ErrTerminateAgent.
func NewWorker() worker.Worker {
var w terminationWorker
c := make(chan os.Signal, 1)
signal.Notify(c, TerminationSignal)
w.tomb.Go(func() error {
defer signal.Stop(c)
return w.loop(c)
})
return &w
}
func (w *terminationWorker) Kill() {
w.tomb.Kill(nil)
}
func (w *terminationWorker) Wait() error {
return w.tomb.Wait()
}
func (w *terminationWorker) loop(c <-chan os.Signal) (err error) {
select {
case <-c:
return jworker.ErrTerminateAgent
case <-w.tomb.Dying():
return tomb.ErrDying
}
}