-
Notifications
You must be signed in to change notification settings - Fork 198
/
container.go
92 lines (76 loc) · 1.81 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
package stapel
import (
"context"
"fmt"
"time"
"github.com/werf/lockgate"
"github.com/werf/logboek"
"github.com/werf/werf/pkg/docker"
"github.com/werf/werf/pkg/werf"
)
type container struct {
Name string
ImageName string
Volume string
}
func (c *container) Create(ctx context.Context) error {
name := fmt.Sprintf("--name=%s", c.Name)
volume := fmt.Sprintf("--volume=%s", c.Volume)
if exist, err := docker.ImageExist(ctx, c.ImageName); err != nil {
return err
} else if !exist {
if err := docker.CliPullWithRetries(ctx, c.ImageName); err != nil {
return err
}
}
return docker.CliCreate(ctx, name, volume, c.ImageName)
}
func (c *container) CreateIfNotExist(ctx context.Context) error {
exist, err := docker.ContainerExist(ctx, c.Name)
if err != nil {
return err
}
if !exist {
err := werf.WithHostLock(ctx, fmt.Sprintf("stapel.container.%s", c.Name), lockgate.AcquireOptions{Timeout: time.Second * 600}, func() error {
return logboek.Context(ctx).LogProcess("Creating container %s from image %s", c.Name, c.ImageName).DoError(func() error {
exist, err := docker.ContainerExist(ctx, c.Name)
if err != nil {
return err
}
if !exist {
if err := c.Create(ctx); err != nil {
return err
}
}
return nil
})
})
if err != nil {
return err
}
}
return nil
}
func (c *container) RmIfExist(ctx context.Context) error {
exist, err := docker.ContainerExist(ctx, c.Name)
if err != nil {
return err
}
if exist {
inspect, err := docker.ContainerInspect(ctx, c.Name)
if err != nil {
return err
}
if err := docker.CliRm(ctx, c.Name); err != nil {
return err
}
for _, m := range inspect.Mounts {
if m.Type == "volume" {
if err := docker.VolumeRm(ctx, m.Name, true); err != nil {
return err
}
}
}
}
return nil
}