| Jon Perritt | fa2c65e | 2014-10-02 20:32:43 -0500 | [diff] [blame] | 1 | package gophercloud | 
|  | 2 |  | 
|  | 3 | import ( | 
| Jamie Hannaford | f9b8bf5 | 2014-10-23 16:56:36 +0200 | [diff] [blame] | 4 | "errors" | 
| Ash Wilson | a844064 | 2014-10-07 09:55:58 -0400 | [diff] [blame] | 5 | "strings" | 
| Jon Perritt | fa2c65e | 2014-10-02 20:32:43 -0500 | [diff] [blame] | 6 | "time" | 
|  | 7 | ) | 
|  | 8 |  | 
| Jamie Hannaford | b280dea | 2014-10-24 15:14:06 +0200 | [diff] [blame] | 9 | // WaitFor polls a predicate function, once per second, up to a timeout limit. | 
| Ash Wilson | 03af57e | 2014-10-31 14:33:39 -0400 | [diff] [blame] | 10 | // 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 Hannaford | f9b8bf5 | 2014-10-23 16:56:36 +0200 | [diff] [blame] | 13 | func WaitFor(timeout int, predicate func() (bool, error)) error { | 
|  | 14 | start := time.Now().Second() | 
|  | 15 | for { | 
|  | 16 | // Force a 1s sleep | 
| Jon Perritt | fa2c65e | 2014-10-02 20:32:43 -0500 | [diff] [blame] | 17 | time.Sleep(1 * time.Second) | 
|  | 18 |  | 
| Jamie Hannaford | 3ac3aa7 | 2014-10-23 17:30:49 +0200 | [diff] [blame] | 19 | // 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 Hannaford | f9b8bf5 | 2014-10-23 16:56:36 +0200 | [diff] [blame] | 24 | // Execute the function | 
| Jon Perritt | fa2c65e | 2014-10-02 20:32:43 -0500 | [diff] [blame] | 25 | satisfied, err := predicate() | 
|  | 26 | if err != nil { | 
|  | 27 | return err | 
|  | 28 | } | 
|  | 29 | if satisfied { | 
|  | 30 | return nil | 
|  | 31 | } | 
|  | 32 | } | 
| Jon Perritt | fa2c65e | 2014-10-02 20:32:43 -0500 | [diff] [blame] | 33 | } | 
| Ash Wilson | a844064 | 2014-10-07 09:55:58 -0400 | [diff] [blame] | 34 |  | 
| Ash Wilson | 03af57e | 2014-10-31 14:33:39 -0400 | [diff] [blame] | 35 | // NormalizeURL ensures that each endpoint URL has a closing `/`, as expected | 
|  | 36 | // by ServiceClient. | 
| Ash Wilson | a844064 | 2014-10-07 09:55:58 -0400 | [diff] [blame] | 37 | func NormalizeURL(url string) string { | 
|  | 38 | if !strings.HasSuffix(url, "/") { | 
|  | 39 | return url + "/" | 
|  | 40 | } | 
|  | 41 | return url | 
|  | 42 | } |