forked from fergusstrange/embedded-postgres
-
Notifications
You must be signed in to change notification settings - Fork 0
/
embedded_postgres.go
235 lines (186 loc) · 6.21 KB
/
embedded_postgres.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
package embeddedpostgres
import (
"errors"
"fmt"
"net"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
)
// EmbeddedPostgres maintains all configuration and runtime functions for maintaining the lifecycle of one Postgres process.
type EmbeddedPostgres struct {
config Config
cacheLocator CacheLocator
remoteFetchStrategy RemoteFetchStrategy
initDatabase initDatabase
createDatabase createDatabase
started bool
syncedLogger *syncedLogger
}
// NewDatabase creates a new EmbeddedPostgres struct that can be used to start and stop a Postgres process.
// When called with no parameters it will assume a default configuration state provided by the DefaultConfig method.
// When called with parameters the first Config parameter will be used for configuration.
func NewDatabase(config ...Config) *EmbeddedPostgres {
if len(config) < 1 {
return newDatabaseWithConfig(DefaultConfig())
}
return newDatabaseWithConfig(config[0])
}
func newDatabaseWithConfig(config Config) *EmbeddedPostgres {
versionStrategy := defaultVersionStrategy(
config,
runtime.GOOS,
runtime.GOARCH,
linuxMachineName,
shouldUseAlpineLinuxBuild,
)
cacheLocator := defaultCacheLocator(versionStrategy)
remoteFetchStrategy := defaultRemoteFetchStrategy(config.binaryRepositoryURL, versionStrategy, cacheLocator)
return &EmbeddedPostgres{
config: config,
cacheLocator: cacheLocator,
remoteFetchStrategy: remoteFetchStrategy,
initDatabase: defaultInitDatabase,
createDatabase: defaultCreateDatabase,
started: false,
}
}
// Start will try to start the configured Postgres process returning an error when there were any problems with invocation.
// If any error occurs Start will try to also Stop the Postgres process in order to not leave any sub-process running.
//
//nolint:funlen
func (ep *EmbeddedPostgres) Start() error {
if ep.started {
return errors.New("server is already started")
}
if err := ensurePortAvailable(ep.config.port); err != nil {
return err
}
logger, err := newSyncedLogger("", ep.config.logger)
if err != nil {
return errors.New("unable to create logger")
}
ep.syncedLogger = logger
cacheLocation, cacheExists := ep.cacheLocator()
if ep.config.runtimePath == "" {
ep.config.runtimePath = filepath.Join(filepath.Dir(cacheLocation), "extracted")
}
if ep.config.dataPath == "" {
ep.config.dataPath = filepath.Join(ep.config.runtimePath, "data")
}
if err := os.RemoveAll(ep.config.runtimePath); err != nil {
return fmt.Errorf("unable to clean up runtime directory %s with error: %s", ep.config.runtimePath, err)
}
if ep.config.binariesPath == "" {
ep.config.binariesPath = ep.config.runtimePath
}
_, binDirErr := os.Stat(filepath.Join(ep.config.binariesPath, "bin"))
if os.IsNotExist(binDirErr) {
if !cacheExists {
if err := ep.remoteFetchStrategy(); err != nil {
return err
}
}
if err := decompressTarXz(defaultTarReader, cacheLocation, ep.config.binariesPath); err != nil {
return err
}
}
if err := os.MkdirAll(ep.config.runtimePath, 0755); err != nil {
return fmt.Errorf("unable to create runtime directory %s with error: %s", ep.config.runtimePath, err)
}
reuseData := dataDirIsValid(ep.config.dataPath, ep.config.version)
if !reuseData {
if err := ep.cleanDataDirectoryAndInit(); err != nil {
return err
}
}
if err := startPostgres(ep); err != nil {
return err
}
if err := ep.syncedLogger.flush(); err != nil {
return err
}
ep.started = true
if !reuseData {
if err := ep.createDatabase(ep.config.port, ep.config.username, ep.config.password, ep.config.database); err != nil {
if stopErr := stopPostgres(ep); stopErr != nil {
return fmt.Errorf("unable to stop database casused by error %s", err)
}
return err
}
}
if err := healthCheckDatabaseOrTimeout(ep.config); err != nil {
if stopErr := stopPostgres(ep); stopErr != nil {
return fmt.Errorf("unable to stop database casused by error %s", err)
}
return err
}
return nil
}
func (ep *EmbeddedPostgres) cleanDataDirectoryAndInit() error {
if err := os.RemoveAll(ep.config.dataPath); err != nil {
return fmt.Errorf("unable to clean up data directory %s with error: %s", ep.config.dataPath, err)
}
if err := ep.initDatabase(ep.config.binariesPath, ep.config.runtimePath, ep.config.dataPath, ep.config.username, ep.config.password, ep.config.locale, ep.syncedLogger.file); err != nil {
return err
}
return nil
}
// Stop will try to stop the Postgres process gracefully returning an error when there were any problems.
func (ep *EmbeddedPostgres) Stop() error {
if !ep.started {
return errors.New("server has not been started")
}
if err := stopPostgres(ep); err != nil {
return err
}
ep.started = false
if err := ep.syncedLogger.flush(); err != nil {
return err
}
return nil
}
func startPostgres(ep *EmbeddedPostgres) error {
postgresBinary := filepath.Join(ep.config.binariesPath, "bin/pg_ctl")
postgresProcess := exec.Command(postgresBinary, "start", "-w",
"-D", ep.config.dataPath,
"-o", fmt.Sprintf(`"-p %d"`, ep.config.port))
postgresProcess.Stdout = ep.syncedLogger.file
postgresProcess.Stderr = ep.syncedLogger.file
if err := postgresProcess.Run(); err != nil {
return fmt.Errorf("could not start postgres using %s", postgresProcess.String())
}
return nil
}
func stopPostgres(ep *EmbeddedPostgres) error {
postgresBinary := filepath.Join(ep.config.binariesPath, "bin/pg_ctl")
postgresProcess := exec.Command(postgresBinary, "stop", "-w",
"-D", ep.config.dataPath)
postgresProcess.Stderr = ep.syncedLogger.file
postgresProcess.Stdout = ep.syncedLogger.file
if err := postgresProcess.Run(); err != nil {
return err
}
return nil
}
func ensurePortAvailable(port uint32) error {
conn, err := net.Listen("tcp", fmt.Sprintf("localhost:%d", port))
if err != nil {
return fmt.Errorf("process already listening on port %d", port)
}
if err := conn.Close(); err != nil {
return err
}
return nil
}
func dataDirIsValid(dataDir string, version PostgresVersion) bool {
pgVersion := filepath.Join(dataDir, "PG_VERSION")
d, err := os.ReadFile(pgVersion)
if err != nil {
return false
}
v := strings.TrimSuffix(string(d), "\n")
return strings.HasPrefix(string(version), v)
}