forked from play-with-docker/play-with-docker
-
Notifications
You must be signed in to change notification settings - Fork 0
/
local_cached_factory.go
113 lines (98 loc) · 2.28 KB
/
local_cached_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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
package docker
import (
"context"
"fmt"
"log"
"sync"
"time"
client "docker.io/go-docker"
"github.com/play-with-docker/play-with-docker/pwd/types"
"github.com/play-with-docker/play-with-docker/storage"
)
type localCachedFactory struct {
rw sync.Mutex
irw sync.Mutex
sessionClient DockerApi
instanceClients map[string]*instanceEntry
storage storage.StorageApi
}
type instanceEntry struct {
rw sync.Mutex
client DockerApi
}
func (f *localCachedFactory) GetForSession(session *types.Session) (DockerApi, error) {
f.rw.Lock()
defer f.rw.Unlock()
if f.sessionClient != nil {
if err := f.check(f.sessionClient.GetClient()); err == nil {
return f.sessionClient, nil
} else {
f.sessionClient.GetClient().Close()
}
}
c, err := client.NewEnvClient()
if err != nil {
return nil, err
}
err = f.check(c)
if err != nil {
return nil, err
}
d := NewDocker(c)
f.sessionClient = d
return f.sessionClient, nil
}
func (f *localCachedFactory) GetForInstance(instance *types.Instance) (DockerApi, error) {
key := instance.Name
f.irw.Lock()
c, found := f.instanceClients[key]
if !found {
c := &instanceEntry{}
f.instanceClients[key] = c
}
c = f.instanceClients[key]
f.irw.Unlock()
c.rw.Lock()
defer c.rw.Unlock()
if c.client != nil {
if err := f.check(c.client.GetClient()); err == nil {
return c.client, nil
} else {
c.client.GetClient().Close()
}
}
dc, err := NewClient(instance, "l2:443")
if err != nil {
return nil, err
}
err = f.check(dc)
if err != nil {
return nil, err
}
dockerClient := NewDocker(dc)
c.client = dockerClient
return dockerClient, nil
}
func (f *localCachedFactory) check(c *client.Client) error {
ok := false
for i := 0; i < 5; i++ {
_, err := c.Ping(context.Background())
if err != nil {
log.Printf("Connection to [%s] has failed, maybe instance is not ready yet, sleeping and retrying in 1 second. Try #%d. Got: %v\n", c.DaemonHost(), i+1, err)
time.Sleep(time.Second)
continue
}
ok = true
break
}
if !ok {
return fmt.Errorf("Connection to docker daemon was not established.")
}
return nil
}
func NewLocalCachedFactory(s storage.StorageApi) *localCachedFactory {
return &localCachedFactory{
instanceClients: make(map[string]*instanceEntry),
storage: s,
}
}