blob: 7f5ead7d8ff8e429c294b923d2624d9e4d8cd4a4 [file] [log] [blame]
Jon Perrittfa2c65e2014-10-02 20:32:43 -05001package gophercloud
2
3import (
Jamie Hannafordf9b8bf52014-10-23 16:56:36 +02004 "errors"
Ash Wilsona8440642014-10-07 09:55:58 -04005 "strings"
Jon Perrittfa2c65e2014-10-02 20:32:43 -05006 "time"
7)
8
Jamie Hannafordb280dea2014-10-24 15:14:06 +02009// WaitFor polls a predicate function, once per second, up to a timeout limit.
10// It usually does this to wait for the resource to transition to a certain state.
Jamie Hannafordf9b8bf52014-10-23 16:56:36 +020011func WaitFor(timeout int, predicate func() (bool, error)) error {
12 start := time.Now().Second()
13 for {
14 // Force a 1s sleep
Jon Perrittfa2c65e2014-10-02 20:32:43 -050015 time.Sleep(1 * time.Second)
16
Jamie Hannaford3ac3aa72014-10-23 17:30:49 +020017 // If a timeout is set, and that's been exceeded, shut it down
18 if timeout >= 0 && time.Now().Second()-start >= timeout {
19 return errors.New("A timeout occurred")
20 }
21
Jamie Hannafordf9b8bf52014-10-23 16:56:36 +020022 // Execute the function
Jon Perrittfa2c65e2014-10-02 20:32:43 -050023 satisfied, err := predicate()
24 if err != nil {
25 return err
26 }
27 if satisfied {
28 return nil
29 }
30 }
Jon Perrittfa2c65e2014-10-02 20:32:43 -050031}
Ash Wilsona8440642014-10-07 09:55:58 -040032
33// NormalizeURL ensures that each endpoint URL has a closing `/`, as expected by ServiceClient.
34func NormalizeURL(url string) string {
35 if !strings.HasSuffix(url, "/") {
36 return url + "/"
37 }
38 return url
39}
Jamie Hannafordee049ec2014-10-22 17:02:55 +020040
41// BuildQuery constructs the query section of a URI from a map.
42func BuildQuery(params map[string]string) string {
43 if len(params) == 0 {
44 return ""
45 }
46
47 query := "?"
48 for k, v := range params {
49 query += k + "=" + v + "&"
50 }
51 query = query[:len(query)-1]
52 return query
53}