forked from jen20/riviera
-
Notifications
You must be signed in to change notification settings - Fork 0
/
basic_runner.go
104 lines (89 loc) · 1.88 KB
/
basic_runner.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package test
import (
"log"
"sync"
"sync/atomic"
)
type runState int32
const (
stateIdle runState = iota
stateRunning
stateCancelling
)
type basicRunner struct {
Steps []Step
cancelCh chan struct{}
doneCh chan struct{}
state runState
l sync.Mutex
}
func (b *basicRunner) Run(state AzureStateBag) {
b.l.Lock()
if b.state != stateIdle {
panic("already running")
}
// Seed the random name generator
reseed()
cancelCh := make(chan struct{})
doneCh := make(chan struct{})
b.cancelCh = cancelCh
b.doneCh = doneCh
b.state = stateRunning
b.l.Unlock()
defer func() {
b.l.Lock()
b.cancelCh = nil
b.doneCh = nil
b.state = stateIdle
close(doneCh)
b.l.Unlock()
}()
// This goroutine listens for cancels and puts the StateCancelled key
// as quickly as possible into the state bag to mark it.
go func() {
select {
case <-cancelCh:
// Flag cancel and wait for finish
state.Put(StateCancelled, true)
<-doneCh
case <-doneCh:
}
}()
for _, step := range b.Steps {
// We also check for cancellation here since we can't be sure
// the goroutine that is running to set it actually ran.
if runState(atomic.LoadInt32((*int32)(&b.state))) == stateCancelling {
state.Put(StateCancelled, true)
break
}
action := step.Run(state)
defer step.Cleanup(state)
if _, ok := state.GetOk(StateCancelled); ok {
break
}
if action == Halt {
log.Println("[INFO] Halt requested by current step")
state.Put(StateHalted, true)
break
}
}
}
func (b *basicRunner) Cancel() {
b.l.Lock()
switch b.state {
case stateIdle:
// Not running, so Cancel is... done.
b.l.Unlock()
return
case stateRunning:
// Running, so mark that we cancelled and set the state
close(b.cancelCh)
b.state = stateCancelling
fallthrough
case stateCancelling:
// Already cancelling, so just wait until we're done
ch := b.doneCh
b.l.Unlock()
<-ch
}
}