blob: fbd9fe9f3813d8dee512860e1190ef027093dee1 [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 Wilsonad108b92014-10-31 16:12:05 -040035// NormalizeURL is an internal function to be used by provider clients.
36//
37// It ensures that each endpoint URL has a closing `/`, as expected by
38// ServiceClient's methods.
Ash Wilsona8440642014-10-07 09:55:58 -040039func NormalizeURL(url string) string {
40 if !strings.HasSuffix(url, "/") {
41 return url + "/"
42 }
43 return url
44}