/
worker.go
60 lines (49 loc) · 1.11 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
60
// Copyright 2014 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package terminationworker
import (
"os"
"os/signal"
"syscall"
"launchpad.net/tomb"
"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
// NewWorker returns a worker that wais for a
type terminationWorker struct {
tomb tomb.Tomb
}
// TerminationSignal signal and exits with
// ErrTerminateAgent.
func NewWorker() worker.Worker {
u := &terminationWorker{}
go func() {
defer u.tomb.Done()
u.tomb.Kill(u.loop())
}()
return u
}
func (u *terminationWorker) Kill() {
u.tomb.Kill(nil)
}
func (u *terminationWorker) Wait() error {
return u.tomb.Wait()
}
func (u *terminationWorker) loop() (err error) {
c := make(chan os.Signal, 1)
signal.Notify(c, TerminationSignal)
defer signal.Stop(c)
select {
case <-c:
return worker.ErrTerminateAgent
case <-u.tomb.Dying():
return nil
}
}