Skip to content

Commit 2066761

Browse files
author
Peter Jönsson
committed
Add wait function
1 parent aa303a9 commit 2066761

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

wait.go

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
package gopherstack
2+
3+
import (
4+
"fmt"
5+
"log"
6+
"time"
7+
)
8+
9+
// waitForAsyncJob simply blocks until the the asynchronous job has
10+
// executed or has timed out.
11+
func WaitForAsyncJob(jobId string, client *CloudStackClient, timeout time.Duration) error {
12+
done := make(chan struct{})
13+
defer close(done)
14+
15+
result := make(chan error, 1)
16+
go func() {
17+
attempts := 0
18+
for {
19+
attempts += 1
20+
21+
log.Printf("Checking async job status... (attempt: %d)", attempts)
22+
status, err := client.QueryAsyncJobResult(jobId)
23+
if err != nil {
24+
result <- err
25+
return
26+
}
27+
28+
// check what the real state will be.
29+
if status == 1 {
30+
result <- nil
31+
return
32+
}
33+
34+
// Wait 3 seconds in between
35+
time.Sleep(3 * time.Second)
36+
37+
// Verify we shouldn't exit
38+
select {
39+
case <-done:
40+
// We finished, so just exit the goroutine
41+
return
42+
default:
43+
// Keep going
44+
}
45+
}
46+
}()
47+
48+
log.Printf("Waiting for up to %d seconds for async job %s", timeout, jobId)
49+
select {
50+
case err := <-result:
51+
return err
52+
case <-time.After(timeout):
53+
err := fmt.Errorf("Timeout while waiting to for async job to finish")
54+
return err
55+
}
56+
}

0 commit comments

Comments
 (0)