-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathengine.go
246 lines (203 loc) · 5.83 KB
/
engine.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
package pgengine
import (
"database/sql"
"errors"
"fmt"
"os"
"os/exec"
"path"
"strconv"
"strings"
"time"
"github.com/google/uuid"
_ "github.com/jackc/pgx/v4/stdlib"
)
type ConnectionOption string
const (
ConnectionOptionDatabase ConnectionOption = "dbname"
)
type ConnectionOptions map[ConnectionOption]string
func (c ConnectionOptions) With(option ConnectionOption, value string) ConnectionOptions {
clone := make(ConnectionOptions)
for k, v := range c {
clone[k] = v
}
clone[option] = value
return clone
}
func (c ConnectionOptions) ToDSN() string {
var pairs []string
for k, v := range c {
pairs = append(pairs, fmt.Sprintf("%s%s%s", k, "=", v))
}
return strings.Join(pairs, " ")
}
type Engine struct {
superuser string
// for cleanup purposes
process *os.Process
dbPath string
sockPath string
}
const (
defaultPort = 5432
defaultSuperuser = "postgres"
defaultMaxConnAttemptsAtStartup = 10
defaultWaitBetweenStartupConnAttempt = time.Second
)
var (
defaultServerConfiguration = map[string]string{
"log_checkpoints": "false",
}
)
// StartEngine starts a postgres instance. This is useful for testing, where Postgres databases need to be spun up.
// "postgres" must be on the system's PATH, and the binary must be located in a directory containing "initdb"
func StartEngine() (*Engine, error) {
postgresPath, err := exec.LookPath("postgres")
if err != nil {
return nil, errors.New("postgres executable not found in path")
}
return StartEngineUsingPgDir(path.Dir(postgresPath))
}
func StartEngineUsingPgDir(pgDir string) (_ *Engine, retErr error) {
dbPath, err := os.MkdirTemp("", "postgresql-")
if err != nil {
return nil, err
}
sockPath, err := os.MkdirTemp("", "pgsock-")
if err != nil {
return nil, err
}
if err := initDB(path.Join(pgDir, "initdb"), dbPath, defaultSuperuser); err != nil {
return nil, err
}
process, err := startServer(path.Join(pgDir, "postgres"), dbPath, sockPath, defaultServerConfiguration)
if err != nil {
// Cleanup temporary directories that were created
os.RemoveAll(dbPath)
os.RemoveAll(sockPath)
return nil, err
}
pgEngine := &Engine{
superuser: defaultSuperuser,
dbPath: dbPath,
sockPath: sockPath,
process: process,
}
defer func() {
if retErr != nil {
pgEngine.Close()
}
}()
if err := pgEngine.waitTillServingTraffic(defaultMaxConnAttemptsAtStartup, defaultWaitBetweenStartupConnAttempt); err != nil {
return nil, fmt.Errorf("waiting till server can serve traffic: %w", err)
}
return pgEngine, nil
}
func initDB(initDbPath, dbPath, superuser string) error {
cmd := exec.Command(initDbPath, []string{
"-U", superuser,
"-D", dbPath,
"-A", "trust",
}...)
output, err := cmd.CombinedOutput()
if err != nil {
outputStr := string(output)
var tip string
line := strings.Repeat("=", 95)
if strings.Contains(outputStr, "request for a shared memory segment exceeded your kernel's SHMALL parameter") {
tip = line + "\n Run 'sudo sysctl -w kern.sysv.shmall=16777216' to solve this issue \n" + line + "\n"
} else if strings.Contains(outputStr, "could not create shared memory segment: No space left on device") {
tip = line + "\n Use the ipcs and ipcrm commands to clear the shared memory \n" + line + "\n"
}
return fmt.Errorf("error running initdb: %w\n%s\n%s", err, outputStr, tip)
}
return nil
}
func startServer(pgBinaryPath, dbPath, sockPath string, configuration map[string]string) (*os.Process, error) {
opts := []string{
"-D", dbPath,
"-k", sockPath,
"-p", strconv.Itoa(defaultPort),
"-h", "",
}
for k, v := range configuration {
opts = append(opts, "-c", fmt.Sprintf("%s=%s", k, v))
}
cmd := exec.Command(pgBinaryPath, opts...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Start(); err != nil {
return nil, fmt.Errorf("starting postgres server instance: %w", err)
}
return cmd.Process, nil
}
func (e *Engine) waitTillServingTraffic(maxAttempts int, timeBetweenAttempts time.Duration) error {
var mostRecentErr error
for i := 0; i < maxAttempts; i++ {
mostRecentErr = e.testIfInstanceServingTraffic()
if mostRecentErr == nil {
return nil
}
time.Sleep(timeBetweenAttempts)
}
return fmt.Errorf("unable to establish connection to postgres instance. most recent error: %w", mostRecentErr)
}
func (e *Engine) testIfInstanceServingTraffic() error {
db, err := sql.Open("pgx", e.GetPostgresDatabaseDSN())
if err != nil {
return err
}
if err := db.Ping(); err != nil {
db.Close()
return err
}
return db.Close()
}
func (e *Engine) GetPostgresDatabaseConnOpts() ConnectionOptions {
result := make(map[ConnectionOption]string)
result[ConnectionOptionDatabase] = "postgres"
result["host"] = e.sockPath
result["user"] = e.superuser
result["port"] = strconv.Itoa(defaultPort)
result["sslmode"] = "disable"
return result
}
func (e *Engine) GetPostgresDatabaseDSN() string {
return e.GetPostgresDatabaseConnOpts().ToDSN()
}
func (e *Engine) Close() error {
// Make best effort attempt to clean up everything
e.process.Signal(os.Interrupt)
e.process.Wait()
os.RemoveAll(e.dbPath)
os.RemoveAll(e.dbPath)
return nil
}
func (e *Engine) CreateDatabase() (*DB, error) {
uuid, err := uuid.NewRandom()
if err != nil {
return nil, fmt.Errorf("generating uuid: %w", err)
}
testDBName := fmt.Sprintf("pgtestdb_%v", uuid.String())
testDb, err := e.CreateDatabaseWithName(testDBName)
if err != nil {
return nil, err
}
return testDb, err
}
func (e *Engine) CreateDatabaseWithName(name string) (*DB, error) {
dsn := e.GetPostgresDatabaseConnOpts().With(ConnectionOptionDatabase, "postgres").ToDSN()
db, err := sql.Open("pgx", dsn)
if err != nil {
return nil, err
}
defer db.Close()
_, err = db.Exec(fmt.Sprintf("CREATE DATABASE \"%s\"", name))
if err != nil {
return nil, err
}
return &DB{
connOpts: e.GetPostgresDatabaseConnOpts().With(ConnectionOptionDatabase, name),
}, nil
}