forked from fergusstrange/embedded-postgres
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathembedded_postgres.go
194 lines (156 loc) · 5.87 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
package embeddedpostgres
import (
"errors"
"fmt"
"log"
"net"
"os"
"os/exec"
"path/filepath"
"github.com/mholt/archiver"
)
// 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
}
// 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)
cacheLocator := defaultCacheLocator(versionStrategy)
remoteFetchStrategy := defaultRemoteFetchStrategy("https://repo1.maven.org", versionStrategy, cacheLocator)
return &EmbeddedPostgres{
config: config,
cacheLocator: cacheLocator,
remoteFetchStrategy: remoteFetchStrategy,
initDatabase: defaultInitDatabase,
createDatabase: defaultCreateDatabase,
started: false,
}
}
// Install will make filesystem modifications, retrieving and extracting the PostgreSQL binaries into the configured directory.
func (ep *EmbeddedPostgres) Install() error {
cacheLocation, exists := ep.cacheLocator()
if !exists {
if err := ep.remoteFetchStrategy(); err != nil {
return err
}
}
binaryExtractLocation := userLocationOrDefault(ep.config.runtimePath, cacheLocation)
if err := os.RemoveAll(binaryExtractLocation); err != nil {
return fmt.Errorf("unable to clean up directory %s with error: %s", binaryExtractLocation, err)
}
if err := archiver.NewTarXz().Unarchive(cacheLocation, binaryExtractLocation); err != nil {
return fmt.Errorf("unable to extract postgres archive %s to %s", cacheLocation, binaryExtractLocation)
}
if err := ep.initDatabase(binaryExtractLocation, ep.config.username, ep.config.password, ep.config.locale); err != nil {
return err
}
return nil
}
// CreateDatabase will issue the "CREATE DATABASE" command on a running server
func (ep *EmbeddedPostgres) CreateDatabase() error {
if !ep.started {
return errors.New("server is not started")
}
cacheLocation, _ := ep.cacheLocator()
binaryExtractLocation := userLocationOrDefault(ep.config.runtimePath, cacheLocation)
if err := ep.createDatabase(ep.config.port, ep.config.username, ep.config.password, ep.config.database); err != nil {
if stopErr := stopPostgres(binaryExtractLocation); stopErr != nil {
return fmt.Errorf("unable to stop database casused by error %s", err)
}
return err
}
return nil
}
func (ep *EmbeddedPostgres) IsStarted() bool {
return ep.started
}
// 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.
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
}
cacheLocation, _ := ep.cacheLocator()
binaryExtractLocation := userLocationOrDefault(ep.config.runtimePath, cacheLocation)
if err := startPostgres(binaryExtractLocation, ep.config); err != nil {
return err
}
ep.started = true
/*
commenting this out because I think it's screwing things up because the database has not yet been created.
if err := healthCheckDatabaseOrTimeout(ep.config); err != nil {
if stopErr := stopPostgres(binaryExtractLocation); stopErr != nil {
return fmt.Errorf("unable to stop database casused by error %s", err)
}
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 {
cacheLocation, exists := ep.cacheLocator()
if !exists || !ep.started {
return errors.New("server has not been started")
}
binaryExtractLocation := userLocationOrDefault(ep.config.runtimePath, cacheLocation)
if err := stopPostgres(binaryExtractLocation); err != nil {
return err
}
ep.started = false
return nil
}
func startPostgres(binaryExtractLocation string, config Config) error {
postgresBinary := filepath.Join(binaryExtractLocation, "bin/pg_ctl")
postgresProcess := exec.Command(postgresBinary, "start", "-w",
"-D", filepath.Join(binaryExtractLocation, "data"),
"-o", fmt.Sprintf(`"-p %d"`, config.port))
log.Println(postgresProcess.String())
postgresProcess.Stderr = os.Stderr
postgresProcess.Stdout = os.Stdout
if err := postgresProcess.Run(); err != nil {
return fmt.Errorf("could not start postgres using %s", postgresProcess.String())
}
return nil
}
func stopPostgres(binaryExtractLocation string) error {
postgresBinary := filepath.Join(binaryExtractLocation, "bin/pg_ctl")
postgresProcess := exec.Command(postgresBinary, "stop", "-w",
"-D", filepath.Join(binaryExtractLocation, "data"))
postgresProcess.Stderr = os.Stderr
postgresProcess.Stdout = os.Stdout
return postgresProcess.Run()
}
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 userLocationOrDefault(userLocation, cacheLocation string) string {
if userLocation != "" {
return userLocation
}
return filepath.Join(filepath.Dir(cacheLocation), "extracted")
}