forked from deis/builder
-
Notifications
You must be signed in to change notification settings - Fork 0
/
object.go
72 lines (66 loc) · 1.81 KB
/
object.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package storage
import (
"errors"
"fmt"
"time"
"github.com/docker/distribution/context"
storagedriver "github.com/docker/distribution/registry/storage/driver"
)
const (
noSuchKeyCode = "NoSuchKey"
octetStream = "application/octet-stream"
)
// ObjectExists determines whether the object in ${bucketName}/${objKey} exists, as reported by
// statter. Returns the following:
//
// - false, nil if statter succeeded and reported the object doesn't exist
// - false, err with the appropriate error if the statter failed
// - true, nil if the statter succeeded and reported the object exists
func ObjectExists(statter ObjectStatter, objKey string) (bool, error) {
_, err := statter.Stat(context.Background(), objKey)
if err != nil {
switch err := err.(type) {
case storagedriver.PathNotFoundError:
return false, nil
default:
return false, err
}
}
return true, nil
}
// WaitForObject checks statter for the object at ${bucketName}/${objKey} right away, then at
// every tick, then once when the timeout is up.
// Returns nil if it finds the object before or at timeout. Otherwise returns a non-nil error.
func WaitForObject(statter ObjectStatter, objKey string, tick, timeout time.Duration) error {
noExist := errors.New("object doesn't exist")
checker := func() error {
exists, err := ObjectExists(statter, objKey)
if err != nil {
return err
} else if exists {
return nil
} else {
return noExist
}
}
if err := checker(); err == nil {
return nil
}
ticker := time.NewTicker(tick)
defer ticker.Stop()
timer := time.NewTimer(timeout)
defer timer.Stop()
for {
select {
case <-ticker.C:
if err := checker(); err == nil {
return nil
}
case <-timer.C:
if err := checker(); err == nil {
return nil
}
return fmt.Errorf("Object %s didn't exist after %s", objKey, timeout)
}
}
}