-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmysql.go
113 lines (89 loc) · 2.44 KB
/
mysql.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 mysql
import (
"fmt"
"math/rand"
"os"
"strconv"
"time"
dockerinitiator "github.com/Storytel/go-docker-initiator"
v1 "github.com/opencontainers/image-spec/specs-go/v1"
)
// MysqlInstance contains the config for mysql instance
type MysqlInstance struct {
*dockerinitiator.Instance
project string
MysqlConfig
}
var (
DefaultImage = "mysql:5.7"
defaultCmd = []string{}
defaultExposedPort = "3306"
)
// MysqlConfig contains configs for mysql, User is automatically root
type MysqlConfig struct {
// Password is the mysql password for the standard user "root"
Password string
// DbName is the name of the database you want to create and connect to
DbName string
// ProbeTimeout specifies the timeout for the probing.
// A timeout results in a startup error, if left empty a default value is used
ProbeTimeout time.Duration
// Image specifies the image used for the Mysql docker instance.
// If left empty it will be set to DefaultImage
Image string
// Platform if you want to specify it. Can be nil.
Platform *v1.Platform
}
// Mysql starts up a mysql instance
func Mysql(config MysqlConfig) (*MysqlInstance, error) {
if config.ProbeTimeout == 0 {
config.ProbeTimeout = 10 * time.Second
}
if config.Image == "" {
config.Image = DefaultImage
}
i, err := dockerinitiator.CreateContainerWithPlatform(
dockerinitiator.ContainerConfig{
Image: config.Image,
Cmd: defaultCmd,
Env: []string{"MYSQL_ALLOW_EMPTY_PASSWORD=true", fmt.Sprintf("MYSQL_DATABASE=%s", config.DbName)},
ContainerPort: defaultExposedPort,
Tmpfs: map[string]string{
"/var/lib/mysql": "rw",
},
},
config.Platform,
MysqlProbe{
config,
})
if err != nil {
return nil, err
}
project := "__docker_initiator__project-" + strconv.Itoa(rand.Int())[:8]
mi := &MysqlInstance{
i,
project,
config,
}
if err = mi.Probe(mi.ProbeTimeout); err != nil {
return nil, err
}
return mi, nil
}
// Setenv sets the required variables for running against the emulator
func (mi *MysqlInstance) Setenv() error {
if err := os.Setenv("MYSQL_SERVER", mi.GetHost()); err != nil {
return err
}
if err := os.Setenv("MYSQL_USER", "root"); err != nil {
return err
}
if err := os.Setenv("MYSQL_PASSWORD", mi.Password); err != nil {
return err
}
return os.Setenv("MYSQL_DATABASE", mi.DbName)
}
// GetProject fetches the project for the mysql instance
func (mi *MysqlInstance) GetProject() string {
return mi.project
}