blob: 8fa4cafd4d3d4632fb60c15c3f0c2d23f5953250 [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.
Ash Wilson03af57e2014-10-31 14:33:39 -040010// It usually does this to wait for a resource to transition to a certain state.
11// Resource packages will wrap this in a more convenient function that's
12// specific to a certain resource, but it can also be useful on its own.
Jamie Hannafordf9b8bf52014-10-23 16:56:36 +020013func WaitFor(timeout int, predicate func() (bool, error)) error {
14 start := time.Now().Second()
15 for {
16 // Force a 1s sleep
Jon Perrittfa2c65e2014-10-02 20:32:43 -050017 time.Sleep(1 * time.Second)
18
Jamie Hannaford3ac3aa72014-10-23 17:30:49 +020019 // If a timeout is set, and that's been exceeded, shut it down
20 if timeout >= 0 && time.Now().Second()-start >= timeout {
21 return errors.New("A timeout occurred")
22 }
23
Jamie Hannafordf9b8bf52014-10-23 16:56:36 +020024 // Execute the function
Jon Perrittfa2c65e2014-10-02 20:32:43 -050025 satisfied, err := predicate()
26 if err != nil {
27 return err
28 }
29 if satisfied {
30 return nil
31 }
32 }
Jon Perrittfa2c65e2014-10-02 20:32:43 -050033}
Ash Wilsona8440642014-10-07 09:55:58 -040034
Ash Wilson03af57e2014-10-31 14:33:39 -040035// NormalizeURL ensures that each endpoint URL has a closing `/`, as expected
36// by ServiceClient.
Ash Wilsona8440642014-10-07 09:55:58 -040037func NormalizeURL(url string) string {
38 if !strings.HasSuffix(url, "/") {
39 return url + "/"
40 }
41 return url
42}