packer-plugin-xenserver/builder/xenserver/interruptible_wait.go

87 lines
1.9 KiB
Go
Raw Normal View History

2014-12-09 04:42:16 -06:00
package xenserver
import (
"github.com/mitchellh/multistep"
"time"
)
type InterruptibleWait struct {
Timeout time.Duration
// optional:
2014-12-09 05:17:35 -06:00
Predicate func() (result bool, err error)
2014-12-09 04:42:16 -06:00
PredicateInterval time.Duration
}
2014-12-09 05:17:35 -06:00
type TimeoutError struct{}
2014-12-09 04:42:16 -06:00
func (err TimeoutError) Error() string {
return "Timed out"
}
2014-12-09 05:17:35 -06:00
type InterruptedError struct{}
2014-12-09 04:42:16 -06:00
func (err InterruptedError) Error() string {
return "Interrupted"
}
type PredicateResult struct {
complete bool
2014-12-09 05:17:35 -06:00
err error
2014-12-09 04:42:16 -06:00
}
/* Wait waits for up to Timeout duration, checking an optional Predicate every PredicateInterval duration.
The first run of Predicate is immediately after Wait is called.
If the command is interrupted by the user, then an InterruptedError is returned.
If Predicate is not nil, a timeout leads to TimeoutError being returned, and a successful Predicate run leads to nil being returned.
If Predicate is nil, a timeout is not an error, and nil is returned.
*/
2014-12-09 04:42:16 -06:00
func (wait InterruptibleWait) Wait(state multistep.StateBag) error {
predicateResult := make(chan PredicateResult, 1)
stopWaiting := make(chan struct{})
defer close(stopWaiting)
if wait.Predicate != nil {
go func() {
for {
if complete, err := wait.Predicate(); err != nil || complete {
predicateResult <- PredicateResult{complete, err}
return
}
select {
case <-time.After(wait.PredicateInterval):
continue
case <-stopWaiting:
return
}
2014-12-09 04:42:16 -06:00
}
}()
}
2014-12-09 04:42:16 -06:00
timeout := time.After(wait.Timeout)
for {
// wait for either install to complete/error,
// an interrupt to come through, or a timeout to occur
if _, ok := state.GetOk(multistep.StateCancelled); ok {
return InterruptedError{}
}
2014-12-09 04:42:16 -06:00
select {
case result := <-predicateResult:
return result.err
case <-time.After(1 * time.Second):
continue
2014-12-09 04:42:16 -06:00
case <-timeout:
if wait.Predicate != nil {
return TimeoutError{}
} else {
return nil
}
2014-12-09 04:42:16 -06:00
}
}
}