-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontainer.go
306 lines (267 loc) · 8.38 KB
/
container.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
298
299
300
301
302
303
304
305
306
package main
import (
"bytes"
"context"
"fmt"
"github.com/docker/docker/pkg/archive"
"io"
"io/ioutil"
"os"
"os/exec"
"strings"
"time"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/filters"
volumeType "github.com/docker/docker/api/types/volume"
"github.com/docker/docker/client"
"github.com/docker/go-connections/nat"
)
type ContainerController struct {
ctx context.Context //context for the docker client
cli *client.Client //docker client
dbContainersConfigs map[string]dbContainerConfig
}
// CreateImage will create an image given the creator id, port to expose (in the docker),
// name of the app, path for the tmp file, lang for the dockerfile and envs, if no error occurs
// the function will return the image name and image id
func (c ContainerController) CreateImage(creatorID, port int, name, branch, path, language string, envs []Env) (string, string, error) {
//check if the language is supported
var found bool
for _, l := range Langs {
if l == language {
found = true
break
}
}
//check if it's found
if !found {
return "", "", fmt.Errorf("language %s not supported, the supported langs are: %v", language, Langs)
}
//get the dockerfile
dockerfile, err := ioutil.ReadFile(fmt.Sprintf("dockerfiles/%s.dockerfile", language))
if err != nil {
return "", "", err
}
//set the env variables in a string with syntax: ENV key value
var envString string
for _, env := range envs {
envString += fmt.Sprintf("ENV %s %s\n", env.Key, env.Value)
}
//create the dockerfile
dockerfileWithEnvs := fmt.Sprintf(string(dockerfile), name, path, envString, port)
//set a random name for the dockerfile
dockerName := "ipaas-dockerfile_" + generateRandomString(10)
//create and write the propretary dockerfile to the repo
f, err := os.Create(path + "/" + dockerName)
if err != nil {
return "", "", err
}
if _, err := f.WriteString(dockerfileWithEnvs); err != nil {
return "", "", err
}
if err := f.Close(); err != nil {
return "", "", err
}
fmt.Println("dockerfile created")
//create a build context, is a tar with the temp repo,
//needed since we are not using the filesystem as a context
buildContext, err := archive.TarWithOptions(path, &archive.TarOptions{
NoLchown: true,
})
if err != nil {
return "", "", err
}
defer buildContext.Close()
fmt.Println("build the context:", &buildContext)
//create the name for the image <creatorID>-<name>-<branch>-<language>
imageName := []string{fmt.Sprintf("%d-%s-%s-%s", creatorID, name, branch, language)}
fmt.Println("image name:", imageName[0])
//create the image from the dockerfile
//we are setting some default labels and the flag -rm -f
//!should set memory and cpu limit
resp, err := c.cli.ImageBuild(c.ctx, buildContext, types.ImageBuildOptions{
Dockerfile: dockerName,
//Squash: true,
Tags: imageName,
Labels: map[string]string{
"creator": fmt.Sprintf("%d", creatorID),
"lang": language,
"name": name,
},
Remove: true,
ForceRemove: true,
})
if err != nil {
return "", "", err
}
//read the resp.Body, it's a way to wait for the image to be created
a, err := io.ReadAll(resp.Body)
err = resp.Body.Close()
if err != nil {
return "", "", err
}
fmt.Println("body:", string(a))
//find the id of the image just created
var out bytes.Buffer
cmd := exec.CommandContext(c.ctx, "docker", "images", "-q", imageName[0])
cmd.Stdout = &out
if err := cmd.Run(); err != nil {
return "", "", err
}
imageID := strings.Replace(out.String(), "\n", "", -1)
if !c.CheckIfImageCompiled(string(a)) {
return "", imageID, fmt.Errorf("image %s compiled incorrectly", imageName[0])
}
return imageName[0], imageID, nil
}
// CheckIfImageCompiled will check the output of the image build to see if the image was compiled correctly
func (c ContainerController) CheckIfImageCompiled(imageBuildOutput string) bool {
lines := strings.Split(imageBuildOutput, "\n")
return strings.Contains(lines[len(lines)-2], "Successfully tagged")
}
// RemoveImage removes an image given the image id
func (c ContainerController) RemoveImage(imageID string) error {
//remove the image
_, err := c.cli.ImageRemove(context.Background(), imageID, types.ImageRemoveOptions{
Force: true,
})
return err
}
// GetContainerExternalPort gets the first port opened by the container on the host machine,
func (c ContainerController) GetContainerExternalPort(id, containerPort string) (string, error) {
//same as docker inspect <id>
container, err := c.cli.ContainerInspect(c.ctx, id)
if err != nil {
return "", err
}
//from the network settings we get the port that the container is
//listening to internally and from there we get the host one
//!thecnically this should only be necessary for windows but for some "good practice" we will leave it here
i := 0
var natted []nat.PortBinding
for {
// the sleeps are for windows, when tested on linux they were not necesseary
time.Sleep(time.Second)
if i > 5 {
return "", fmt.Errorf("error getting the port of the container")
}
i++
//get the external port from the docker inspect command
natted = container.NetworkSettings.Ports[nat.Port(fmt.Sprintf("%s/tcp", containerPort))]
if len(natted) > 0 {
break
}
}
return natted[0].HostPort, nil
}
// FindVolume searchs a volume by name and returns a pointer to the volume (type volumeType.Volume) and an error.
// If the volume doesn't exist the volume pointer will be nil
func (c ContainerController) FindVolume(name string) (volume *types.Volume, err error) {
//get all the volumes
volumes, err := c.cli.VolumeList(context.Background(), filters.NewArgs())
if err != nil {
return nil, err
}
//search the volume with the same name
for _, v := range volumes.Volumes {
if v.Name == name {
return v, nil
}
}
return nil, nil
}
// EnsureVolume checks if a volume exists, if so returns false, the volume and an error.
// If it doesn't exist it will be created and the output will be true, the volume and an error
func (c ContainerController) EnsureVolume(name string) (created bool, volume *types.Volume, err error) {
//check if the volume exists (if it doesn't volume will be nil)
volume, err = c.FindVolume(name)
if err != nil {
return false, nil, err
}
if volume != nil {
return false, volume, nil
}
//create the volume given the context and the volume create body struct
vol, err := c.cli.VolumeCreate(c.ctx, volumeType.VolumeCreateBody{
Driver: "local",
Labels: map[string]string{"matricola": "18008", "type": "db", "dbType": "mysql"},
Name: name,
})
return true, &vol, err
}
// RemoveVolume deletes a volume
func (c ContainerController) RemoveVolume(name string) (removed bool, err error) {
//search the volume
vol, err := c.FindVolume(name)
if err != nil {
return false, err
}
if vol == nil {
return false, nil
}
//remove the volume
err = c.cli.VolumeRemove(context.Background(), name, true)
if err != nil {
return false, err
}
return true, nil
}
// DeleteContainer forcefully removes a container given the container id
func (c ContainerController) DeleteContainer(containerID string) error {
return c.cli.ContainerRemove(c.ctx, containerID, types.ContainerRemoveOptions{
Force: true,
})
}
func (c ContainerController) GetContainerLogs(containerID string) (string, error) {
reader, err := c.cli.ContainerLogs(c.ctx, containerID, types.ContainerLogsOptions{
ShowStdout: true,
ShowStderr: true,
Follow: true,
Tail: "all",
})
if err != nil {
return "", err
}
defer reader.Close()
logs, err := io.ReadAll(reader)
if err != nil {
return "", err
}
return string(logs), nil
}
func (c ContainerController) GetContainerStatus(id string) (string, error) {
container, err := c.cli.ContainerInspect(c.ctx, id)
if err != nil {
return "", err
}
return container.State.Status, nil
}
// NewContainerController creates a new controller
func NewContainerController() (*ContainerController, error) {
var err error
c := new(ContainerController)
c.ctx = context.Background()
//creating docker client from env
c.cli, err = client.NewClientWithOpts(client.FromEnv)
if err != nil {
return nil, err
}
c.dbContainersConfigs = map[string]dbContainerConfig{
"mysql": {
name: "mysql",
image: "mysql:8.0.28-oracle",
port: "3306",
},
"mariadb": {
name: "mariadb",
image: "mariadb:10.8.2-rc-focal",
port: "3306",
},
"mongodb": {
name: "mongodb",
image: "mongo:5.0.6",
port: "27017",
},
}
return c, nil
}