-
Notifications
You must be signed in to change notification settings - Fork 1
/
postgres.go
390 lines (297 loc) · 8.62 KB
/
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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
package main
import (
"bytes"
"fmt"
"io"
"os"
"os/exec"
"sync"
"time"
_ "github.com/lib/pq"
log "github.com/sirupsen/logrus"
)
// DBConf stores information about the database backend
type DBConf struct {
host string
port int
user string
password string
database string
caCert string
sslMode string
clientCert string
clientKey string
}
// Basebackup function:
// - gets an identical copy of the pg database (pg_data)
// - verifies the backup
// - tars the copy
// - compresses the encrypted file
// - gets the key and encrypts the tar file
// - puts the encrypted and compressed file in S3
func (db DBConf) basebackup(sb s3Backend, publicKeyPath string) error {
log.Info("Basebackup started")
today := time.Now().Format("20060102150405")
destDir := "db-backup"
dbURI := buildConnInfo(db)
cmd := exec.Command("pg_basebackup", dbURI, "-F", "p", "-D", destDir)
var errMsg bytes.Buffer
cmd.Stderr = &errMsg
err := cmd.Run()
if err != nil {
return err
}
log.Debugf("Backup command successfully executed in directory: %v", destDir)
cmd = exec.Command("pg_verifybackup", destDir)
cmd.Stderr = &errMsg
err = cmd.Run()
if err != nil {
return err
}
log.Debug("Verify backup command successfully executed")
cmd = exec.Command("tar", "-cvf", destDir+".tar", destDir)
cmd.Stderr = &errMsg
err = cmd.Run()
if err != nil {
return err
}
log.Debugf("%v.tar file created", destDir)
fileName := today + "-" + db.database + ".enc"
wg := sync.WaitGroup{}
wr, err := sb.NewFileWriter(fileName, &wg)
if err != nil {
return fmt.Errorf("Could not open backup file for writing: %s", err)
}
log.Debugf("Backup file %v ready for writing", fileName)
privateKey, publicKeyList, err := getKeys(publicKeyPath)
if err != nil {
return fmt.Errorf("Could not retrieve public key or generate private key: %s", err)
}
log.Debug("Public key retrieved and private key successfully created")
e, err := newEncryptor(publicKeyList, privateKey, wr)
if err != nil {
return fmt.Errorf("Could not initialize encryptor: %s", err)
}
log.Debug("Encryption initialized")
c, err := newCompressor(e)
if err != nil {
return fmt.Errorf("Could not initialize compressor: %s", err)
}
log.Debug("Compression initialized")
sourceFileName := destDir + ".tar"
data, err := os.ReadFile(sourceFileName)
if err != nil {
log.Errorf("Error in reading source data: %v", err)
}
_, err = c.Write(data)
if err != nil {
log.Errorf("Error in writer: %v", err)
}
err = c.Close()
if err != nil {
log.Errorf("Could not close compressor: %v", err)
}
if err := e.Close(); err != nil {
log.Errorf("Could not close encryptor: %v", err)
}
err = wr.Close()
if err != nil {
log.Errorf("Could not close destination file: %v", err)
}
wg.Wait()
log.Info("Backup data are compressed and encrypted")
return nil
}
func (db DBConf) dump(sb s3Backend, publicKeyPath string) error {
log.Info("Dump backup started")
today := time.Now().Format("20060102150405")
dbURI := buildConnInfo(db)
cmd := exec.Command("pg_dump", dbURI, "-xF", "tar")
var out bytes.Buffer
cmd.Stdout = &out
var errMsg bytes.Buffer
cmd.Stderr = &errMsg
err := cmd.Run()
if err != nil {
return err
}
log.Debug("Dump command successfully executed")
wg := sync.WaitGroup{}
dumpFile := today + "-" + db.database + ".sqldump"
wr, err := sb.NewFileWriter(dumpFile, &wg)
if err != nil {
return fmt.Errorf("Could not open backup file for writing: %s", err)
}
log.Debugf("Dump file %v ready for writing", dumpFile)
privateKey, publicKeyList, err := getKeys(publicKeyPath)
if err != nil {
return fmt.Errorf("Could not retrieve public key or generate private key: %s", err)
}
log.Debug("Public key retrieved and private key successfully created")
e, err := newEncryptor(publicKeyList, privateKey, wr)
if err != nil {
return fmt.Errorf("Could not initialize encryptor: %s", err)
}
log.Debug("Encryption initialized")
c, err := newCompressor(e)
if err != nil {
return fmt.Errorf("Could not initialize compressor: %s", err)
}
log.Debug("Compression initialized")
_, err = c.Write(out.Bytes())
if err != nil {
return fmt.Errorf("Could not encrypt/write: %s", err)
}
if err := c.Close(); err != nil {
log.Errorf("Could not close compressor: %v", err)
}
if err := e.Close(); err != nil {
log.Errorf("Could not close encryptor: %v", err)
}
if err := wr.Close(); err != nil {
log.Errorf("Could not close destination file: %v", err)
}
wg.Wait()
log.Info("Dump data are compressed and encrypted")
return nil
}
// BasebackupUnpack function:
// - gets the key to decrypt the pg_data
// - decrypts and decompress the data
// - untar the data
// - puts the db copy in the running container
func (db DBConf) baseBackupUnpack(sb s3Backend, privateKeyPath, backupTar, c4ghPassword string) error {
log.Info("Unpacking basebackup data started")
localTar, err := os.Create("/home/backup.tar")
if err != nil {
log.Errorf("Error in creating file: %v", err)
}
log.Debug("File created")
fr, err := sb.NewFileReader(backupTar)
if err != nil {
return err
}
defer fr.Close()
log.Debug("Data ready for unpacking")
privateKey, err := getPrivateKey(privateKeyPath, c4ghPassword)
if err != nil {
return fmt.Errorf("Could not retrieve private key: %s", err)
}
log.Debug("Private key retrieved")
r, err := newDecryptor(privateKey, fr)
if err != nil {
return fmt.Errorf("Could not initialise decryptor: %s", err)
}
log.Debug("Decryption initialized")
d, err := newDecompressor(r)
if err != nil {
return fmt.Errorf("Could not initialise decompressor: %s", err)
}
log.Debug("Decompression initialized")
_, err = io.Copy(localTar, d)
if err != nil {
return fmt.Errorf("Error in copying file: %s", err)
}
log.Debug("Data copied")
cmd := exec.Command("tar", "-xvf", "/home/backup.tar", "--directory", "/home/")
var errMsg bytes.Buffer
cmd.Stderr = &errMsg
err = cmd.Run()
if err != nil {
return err
}
log.Debug("Untar file completed")
err = d.Close()
if err != nil {
log.Errorf("Could not close decompressor: %v", err)
}
if err := r.Close(); err != nil {
log.Errorf("Could not close decryptor: %v", err)
}
log.Info("Data copied succesfully")
return nil
}
func (db DBConf) restore(sb s3Backend, privateKeyPath, sqlDump, c4ghPassword string) error {
log.Info("Start importing dump file")
fr, err := sb.NewFileReader(sqlDump)
if err != nil {
return err
}
defer fr.Close()
log.Debug("Read dump file")
privateKey, err := getPrivateKey(privateKeyPath, c4ghPassword)
if err != nil {
return fmt.Errorf("Could not retrieve private key: %s", err)
}
log.Debug("Private key retrieved")
r, err := newDecryptor(privateKey, fr)
if err != nil {
return fmt.Errorf("Could not initialise decryptor: %s", err)
}
log.Debug("Decryption initialized")
d, err := newDecompressor(r)
if err != nil {
return fmt.Errorf("Could not initialise decompressor: %s", err)
}
log.Debug("Decompression initialized")
data, err := io.ReadAll(d)
if err != nil {
return fmt.Errorf("Could not read all data: %s", err)
}
if err := d.Close(); err != nil {
log.Errorf("Could not close decompressor: %v", err)
}
if err := r.Close(); err != nil {
log.Errorf("Could not close decryptor: %v", err)
}
log.Debug("Data read successfully")
dbURI := fmt.Sprintf("--dbname=postgresql://%s:%s@%s:%d/%s", db.user, db.password, db.host, db.port, db.database)
cmd := exec.Command("pg_restore", dbURI)
var in bytes.Buffer
cmd.Stdin = &in
in.Write(data)
var errMsg bytes.Buffer
cmd.Stderr = &errMsg
err = cmd.Run()
if err != nil {
return err
}
log.Debug("Importing dump data finished")
return nil
}
// buildConnInfo builds a connection string for the database
func buildConnInfo(db DBConf) string {
dbURI := fmt.Sprintf("--dbname=postgresql://%s:%s@%s:%d/%s", db.user, db.password, db.host, db.port, db.database)
var certsRequired bool
log.Debugf("Postgres sslmode is set to: %v", db.sslMode)
switch db.sslMode {
case "allow":
certsRequired = false
dbURI += fmt.Sprintf("?sslmode=%s", db.sslMode)
case "disable":
certsRequired = false
dbURI += fmt.Sprintf("?sslmode=%s", db.sslMode)
case "prefer":
certsRequired = false
case "require":
certsRequired = true
case "verify-ca":
certsRequired = true
case "verify-full":
certsRequired = true
}
if certsRequired {
log.Debug("Certificates required for postgres connection")
dbURI += fmt.Sprintf("?sslmode=%s", db.sslMode)
if db.caCert != "" {
dbURI += fmt.Sprintf("&sslrootcert=%s", db.caCert)
}
if db.clientCert != "" {
dbURI += fmt.Sprintf("&sslcert=%s", db.clientCert)
}
if db.clientKey != "" {
dbURI += fmt.Sprintf("&sslkey=%s", db.clientKey)
}
}
return dbURI
}