forked from play-with-docker/play-with-docker
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dind.go
297 lines (263 loc) · 7.64 KB
/
dind.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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
package provisioner
import (
"bytes"
"fmt"
"io"
"log"
"net"
"net/http"
"path/filepath"
"strings"
lru "github.com/hashicorp/golang-lru"
"github.com/play-with-docker/play-with-docker/config"
"github.com/play-with-docker/play-with-docker/docker"
"github.com/play-with-docker/play-with-docker/id"
"github.com/play-with-docker/play-with-docker/pwd/types"
"github.com/play-with-docker/play-with-docker/router"
"github.com/play-with-docker/play-with-docker/storage"
)
type DinD struct {
factory docker.FactoryApi
storage storage.StorageApi
generator id.Generator
cache *lru.Cache
}
func NewDinD(generator id.Generator, f docker.FactoryApi, s storage.StorageApi) *DinD {
c, _ := lru.New(5000)
return &DinD{generator: generator, factory: f, storage: s, cache: c}
}
func checkHostnameExists(sessionId, hostname string, instances []*types.Instance) bool {
exists := false
for _, instance := range instances {
if instance.Hostname == hostname {
exists = true
break
}
}
return exists
}
func (d *DinD) InstanceNew(session *types.Session, conf types.InstanceConfig) (*types.Instance, error) {
if conf.ImageName == "" {
playground, err := d.storage.PlaygroundGet(session.PlaygroundId)
if err != nil {
return nil, err
}
conf.ImageName = playground.DefaultDinDInstanceImage
}
log.Printf("NewInstance - using image: [%s]\n", conf.ImageName)
if conf.Hostname == "" {
instances, err := d.storage.InstanceFindBySessionId(session.Id)
if err != nil {
return nil, err
}
var nodeName string
for i := 1; ; i++ {
nodeName = fmt.Sprintf("node%d", i)
exists := checkHostnameExists(session.Id, nodeName, instances)
if !exists {
break
}
}
conf.Hostname = nodeName
}
networks := []string{session.Id}
if config.Unsafe {
networks = append(networks, conf.Networks...)
}
containerName := fmt.Sprintf("%s_%s", session.Id[:8], d.generator.NewId())
opts := docker.CreateContainerOpts{
Image: conf.ImageName,
SessionId: session.Id,
ContainerName: containerName,
Hostname: conf.Hostname,
ServerCert: conf.ServerCert,
ServerKey: conf.ServerKey,
CACert: conf.CACert,
HostFQDN: conf.PlaygroundFQDN,
Privileged: conf.Privileged,
Networks: networks,
DindVolumeSize: conf.DindVolumeSize,
Envs: conf.Envs,
}
dockerClient, err := d.factory.GetForSession(session)
if err != nil {
return nil, err
}
if err := dockerClient.ContainerCreate(opts); err != nil {
return nil, err
}
ips, err := dockerClient.ContainerIPs(containerName)
if err != nil {
return nil, err
}
instance := &types.Instance{}
instance.Image = opts.Image
instance.IP = ips[session.Id]
instance.RoutableIP = instance.IP
instance.SessionId = session.Id
instance.Name = containerName
instance.Hostname = conf.Hostname
instance.Cert = conf.Cert
instance.Key = conf.Key
instance.ServerCert = conf.ServerCert
instance.ServerKey = conf.ServerKey
instance.CACert = conf.CACert
instance.Tls = conf.Tls
instance.ProxyHost = router.EncodeHost(session.Id, instance.RoutableIP, router.HostOpts{})
instance.SessionHost = session.Host
return instance, nil
}
func (d *DinD) getSession(sessionId string) (*types.Session, error) {
var session *types.Session
if s, found := d.cache.Get(sessionId); !found {
s, err := d.storage.SessionGet(sessionId)
if err != nil {
return nil, err
}
session = s
d.cache.Add(sessionId, s)
} else {
session = s.(*types.Session)
}
return session, nil
}
func (d *DinD) InstanceDelete(session *types.Session, instance *types.Instance) error {
dockerClient, err := d.factory.GetForSession(session)
if err != nil {
return err
}
err = dockerClient.ContainerDelete(instance.Name)
if err != nil && !strings.Contains(err.Error(), "No such container") {
return err
}
return nil
}
func (d *DinD) InstanceExec(instance *types.Instance, cmd []string) (int, error) {
session, err := d.getSession(instance.SessionId)
if err != nil {
return -1, err
}
dockerClient, err := d.factory.GetForSession(session)
if err != nil {
return -1, err
}
return dockerClient.Exec(instance.Name, cmd)
}
func (d *DinD) InstanceFSTree(instance *types.Instance) (io.Reader, error) {
session, err := d.getSession(instance.SessionId)
if err != nil {
return nil, err
}
dockerClient, err := d.factory.GetForSession(session)
if err != nil {
return nil, err
}
b := bytes.NewBuffer([]byte{})
if c, err := dockerClient.ExecAttach(instance.Name, []string{"bash", "-c", `tree --noreport -J $HOME`}, b); c > 0 {
log.Println(b.String())
return nil, fmt.Errorf("Error %d trying list directories", c)
} else if err != nil {
return nil, err
}
return b, nil
}
func (d *DinD) InstanceFile(instance *types.Instance, filePath string) (io.Reader, error) {
session, err := d.getSession(instance.SessionId)
if err != nil {
return nil, err
}
dockerClient, err := d.factory.GetForSession(session)
if err != nil {
return nil, err
}
return dockerClient.CopyFromContainer(instance.Name, filePath)
}
func (d *DinD) InstanceResizeTerminal(instance *types.Instance, rows, cols uint) error {
session, err := d.getSession(instance.SessionId)
if err != nil {
return err
}
dockerClient, err := d.factory.GetForSession(session)
if err != nil {
return err
}
return dockerClient.ContainerResize(instance.Name, rows, cols)
}
func (d *DinD) InstanceGetTerminal(instance *types.Instance) (net.Conn, error) {
session, err := d.getSession(instance.SessionId)
if err != nil {
return nil, err
}
dockerClient, err := d.factory.GetForSession(session)
if err != nil {
return nil, err
}
return dockerClient.CreateAttachConnection(instance.Name)
}
func (d *DinD) InstanceUploadFromUrl(instance *types.Instance, fileName, dest, url string) error {
log.Printf("Downloading file [%s]\n", url)
resp, err := http.Get(url)
if err != nil {
return fmt.Errorf("Could not download file [%s]. Error: %s\n", url, err)
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return fmt.Errorf("Could not download file [%s]. Status code: %d\n", url, resp.StatusCode)
}
session, err := d.getSession(instance.SessionId)
if err != nil {
return err
}
dockerClient, err := d.factory.GetForSession(session)
if err != nil {
return err
}
copyErr := dockerClient.CopyToContainer(instance.Name, dest, fileName, resp.Body)
if copyErr != nil {
return fmt.Errorf("Error while downloading file [%s]. Error: %s\n", url, copyErr)
}
return nil
}
func (d *DinD) getInstanceCWD(instance *types.Instance) (string, error) {
session, err := d.getSession(instance.SessionId)
if err != nil {
return "", err
}
dockerClient, err := d.factory.GetForSession(session)
if err != nil {
return "", err
}
b := bytes.NewBufferString("")
if c, err := dockerClient.ExecAttach(instance.Name, []string{"bash", "-c", `pwdx $(</var/run/cwd)`}, b); c > 0 {
return "", fmt.Errorf("Error %d trying to get CWD", c)
} else if err != nil {
return "", err
}
cwd := strings.TrimSpace(strings.Split(b.String(), ":")[1])
return cwd, nil
}
func (d *DinD) InstanceUploadFromReader(instance *types.Instance, fileName, dest string, reader io.Reader) error {
session, err := d.getSession(instance.SessionId)
if err != nil {
return err
}
dockerClient, err := d.factory.GetForSession(session)
if err != nil {
return err
}
var finalDest string
if filepath.IsAbs(dest) {
finalDest = dest
} else {
if cwd, err := d.getInstanceCWD(instance); err != nil {
return err
} else {
finalDest = fmt.Sprintf("%s/%s", cwd, dest)
}
}
copyErr := dockerClient.CopyToContainer(instance.Name, finalDest, fileName, reader)
if copyErr != nil {
return fmt.Errorf("Error while uploading file [%s]. Error: %s\n", fileName, copyErr)
}
return nil
}