This repository has been archived by the owner on Oct 11, 2023. It is now read-only.
/
client_factory.go
96 lines (79 loc) · 1.94 KB
/
client_factory.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package docker
import (
"fmt"
"sync"
"github.com/rancher/os/config"
"github.com/rancher/os/pkg/log"
"github.com/rancher/os/pkg/util"
dockerclient "github.com/docker/engine-api/client"
composeClient "github.com/docker/libcompose/docker/client"
"github.com/docker/libcompose/project"
"golang.org/x/net/context"
)
type ClientFactory struct {
userClient dockerclient.APIClient
systemClient dockerclient.APIClient
userOnce sync.Once
systemOnce sync.Once
}
func NewClientFactory(opts composeClient.Options) (project.ClientFactory, error) {
userOpts := opts
systemOpts := opts
userOpts.Host = config.DockerHost
systemOpts.Host = config.SystemDockerHost
userClient, err := composeClient.Create(userOpts)
if err != nil {
return nil, err
}
systemClient, err := composeClient.Create(systemOpts)
if err != nil {
return nil, err
}
return &ClientFactory{
userClient: userClient,
systemClient: systemClient,
}, nil
}
func (c *ClientFactory) Create(service project.Service) dockerclient.APIClient {
if IsSystemContainer(service.Config()) {
waitFor(&c.systemOnce, c.systemClient, config.SystemDockerHost)
return c.systemClient
}
waitFor(&c.userOnce, c.userClient, config.DockerHost)
return c.userClient
}
func waitFor(once *sync.Once, client dockerclient.APIClient, endpoint string) {
once.Do(func() {
err := ClientOK(endpoint, func() bool {
_, err := client.Info(context.Background())
return err == nil
})
if err != nil {
panic(err.Error())
}
})
}
func ClientOK(endpoint string, test func() bool) error {
backoff := util.Backoff{}
defer backoff.Close()
var err error
retry := false
for ok := range backoff.Start() {
if !ok {
err = fmt.Errorf("Timeout waiting for Docker at %s", endpoint)
break
}
if test() {
break
}
retry = true
log.Infof("Waiting for Docker at %s", endpoint)
}
if err != nil {
return err
}
if retry {
log.Infof("Connected to Docker at %s", endpoint)
}
return nil
}