-
Notifications
You must be signed in to change notification settings - Fork 261
/
archiver.go
301 lines (254 loc) · 9.81 KB
/
archiver.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
/*
Copyright The CloudNativePG Contributors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Package archiver manages the WAL archiving process
package archiver
import (
"context"
"fmt"
"math"
"os/exec"
"path"
"path/filepath"
"sync"
"time"
apiv1 "github.com/cloudnative-pg/cloudnative-pg/api/v1"
"github.com/cloudnative-pg/cloudnative-pg/pkg/fileutils"
"github.com/cloudnative-pg/cloudnative-pg/pkg/management/barman"
barmanCapabilities "github.com/cloudnative-pg/cloudnative-pg/pkg/management/barman/capabilities"
"github.com/cloudnative-pg/cloudnative-pg/pkg/management/barman/spool"
"github.com/cloudnative-pg/cloudnative-pg/pkg/management/execlog"
"github.com/cloudnative-pg/cloudnative-pg/pkg/management/log"
)
const (
// CheckEmptyWalArchiveFile is the name of the file in the PGDATA that,
// if present, requires the WAL archiver to check that the backup object
// store is empty.
CheckEmptyWalArchiveFile = ".check-empty-wal-archive"
)
// WALArchiver is a structure containing every info need to archive a set of WAL files
// using barman-cloud-wal-archive
type WALArchiver struct {
// The cluster for which we are archiving
cluster *apiv1.Cluster
// The spool of WAL files to be archived in parallel
spool *spool.WALSpool
// The environment that should be used to invoke barman-cloud-wal-archive
env []string
pgDataDirectory string
}
// WALArchiverResult contains the result of the archival of one WAL
type WALArchiverResult struct {
// The WAL that have been archived
WalName string
// If not nil, this is the error that has been detected
Err error
// The time when we started barman-cloud-wal-archive
StartTime time.Time
// The time when end barman-cloud-wal-archive ended
EndTime time.Time
}
// New creates a new WAL archiver
func New(
ctx context.Context,
cluster *apiv1.Cluster,
env []string,
spoolDirectory string,
pgDataDirectory string,
) (archiver *WALArchiver, err error) {
contextLog := log.FromContext(ctx)
var walArchiveSpool *spool.WALSpool
if walArchiveSpool, err = spool.New(spoolDirectory); err != nil {
contextLog.Info("Cannot initialize the WAL spool", "spoolDirectory", spoolDirectory)
return nil, fmt.Errorf("while creating spool directory: %w", err)
}
archiver = &WALArchiver{
cluster: cluster,
spool: walArchiveSpool,
env: env,
pgDataDirectory: pgDataDirectory,
}
return archiver, nil
}
// DeleteFromSpool checks if a WAL file is in the spool and, if it is, remove it
func (archiver *WALArchiver) DeleteFromSpool(walName string) (hasBeenDeleted bool, err error) {
var isContained bool
// this code assumes the wal-archive command is run at most once at each instant,
// given that PostgreSQL will call it sequentially without overlapping
isContained, err = archiver.spool.Contains(walName)
if !isContained || err != nil {
return false, err
}
return true, archiver.spool.Remove(walName)
}
// ArchiveList archives a list of WAL files in parallel
func (archiver *WALArchiver) ArchiveList(
ctx context.Context,
walNames []string,
options []string,
) (result []WALArchiverResult) {
contextLog := log.FromContext(ctx)
result = make([]WALArchiverResult, len(walNames))
var waitGroup sync.WaitGroup
for idx := range walNames {
waitGroup.Add(1)
go func(walIndex int) {
walStatus := &result[walIndex]
walStatus.WalName = walNames[walIndex]
walStatus.StartTime = time.Now()
walStatus.Err = archiver.Archive(walNames[walIndex], options)
walStatus.EndTime = time.Now()
if walStatus.Err == nil && walIndex != 0 {
walStatus.Err = archiver.spool.Touch(walNames[walIndex])
}
elapsedWalTime := walStatus.EndTime.Sub(walStatus.StartTime)
if walStatus.Err != nil {
contextLog.Warning(
"Failed archiving WAL: PostgreSQL will retry",
"walName", walStatus.WalName,
"startTime", walStatus.StartTime,
"endTime", walStatus.EndTime,
"elapsedWalTime", elapsedWalTime,
"error", walStatus.Err)
} else {
contextLog.Info(
"Archived WAL file",
"walName", walStatus.WalName,
"startTime", walStatus.StartTime,
"endTime", walStatus.EndTime,
"elapsedWalTime", elapsedWalTime)
}
waitGroup.Done()
}(idx)
}
waitGroup.Wait()
return result
}
// Archive archives a certain WAL file using barman-cloud-wal-archive.
// See archiveWALFileList for the meaning of the parameters
func (archiver *WALArchiver) Archive(walName string, baseOptions []string) error {
optionsLength := len(baseOptions)
if optionsLength >= math.MaxInt-1 {
return fmt.Errorf("can't archive wal file %v, options too long", walName)
}
options := make([]string, optionsLength, optionsLength+1)
copy(options, baseOptions)
options = append(options, walName)
log.Trace("Executing "+barmanCapabilities.BarmanCloudWalArchive,
"walName", walName,
"currentPrimary", archiver.cluster.Status.CurrentPrimary,
"targetPrimary", archiver.cluster.Status.TargetPrimary,
"options", options,
)
barmanCloudWalArchiveCmd := exec.Command(barmanCapabilities.BarmanCloudWalArchive, options...) // #nosec G204
barmanCloudWalArchiveCmd.Env = archiver.env
err := execlog.RunStreaming(barmanCloudWalArchiveCmd, barmanCapabilities.BarmanCloudWalArchive)
if err != nil {
log.Error(err, "Error invoking "+barmanCapabilities.BarmanCloudWalArchive,
"walName", walName,
"currentPrimary", archiver.cluster.Status.CurrentPrimary,
"targetPrimary", archiver.cluster.Status.TargetPrimary,
"options", options,
"exitCode", barmanCloudWalArchiveCmd.ProcessState.ExitCode(),
)
return fmt.Errorf("unexpected failure invoking %s: %w", barmanCapabilities.BarmanCloudWalArchive, err)
}
// Removes the `.check-empty-wal-archive` file inside PGDATA after the
// first successful archival of a WAL file.
filePath := path.Join(archiver.pgDataDirectory, CheckEmptyWalArchiveFile)
if err := fileutils.RemoveFile(filePath); err != nil {
return fmt.Errorf("error while deleting the check WAL file flag: %w", err)
}
return nil
}
// IsCheckWalArchiveFlagFilePresent returns true if the file CheckEmptyWalArchiveFile is present in the PGDATA directory
func (archiver *WALArchiver) IsCheckWalArchiveFlagFilePresent(ctx context.Context, pgDataDirectory string) bool {
contextLogger := log.FromContext(ctx)
filePath := filepath.Join(pgDataDirectory, CheckEmptyWalArchiveFile)
exists, err := fileutils.FileExists(filePath)
if err != nil {
contextLogger.Error(err, "error while checking for the existence of the CheckEmptyWalArchiveFile")
}
// If the check empty wal archive file doesn't exist this it's a no-op
if !exists {
contextLogger.Debug("WAL check flag file not found, skipping check")
return false
}
return exists
}
// CheckWalArchiveDestination checks if the destinationObjectStore is ready perform archiving.
// Based on this ticket in Barman https://github.com/EnterpriseDB/barman/issues/432
// and its implementation https://github.com/EnterpriseDB/barman/pull/443
// The idea here is to check ONLY if we're archiving the wal files for the first time in the bucket
// since in this case the command barman-cloud-check-wal-archive will fail if the bucket exist and
// contain wal files inside
func (archiver *WALArchiver) CheckWalArchiveDestination(ctx context.Context, options []string) error {
contextLogger := log.FromContext(ctx)
contextLogger.Info("barman-cloud-check-wal-archive checking the first wal")
// Check barman compatibility
capabilities, err := barmanCapabilities.CurrentCapabilities()
if err != nil {
return err
}
if !capabilities.HasCheckWalArchive {
contextLogger.Warning("barman-cloud-check-wal-archive cannot be used, is recommended to upgrade" +
" to version 2.18 or above.")
return nil
}
contextLogger.Trace("Executing "+barmanCapabilities.BarmanCloudCheckWalArchive,
"currentPrimary", archiver.cluster.Status.CurrentPrimary,
"targetPrimary", archiver.cluster.Status.TargetPrimary,
"options", options,
)
barmanCloudWalArchiveCmd := exec.Command(barmanCapabilities.BarmanCloudCheckWalArchive, options...) // #nosec G204
barmanCloudWalArchiveCmd.Env = archiver.env
err = execlog.RunStreaming(barmanCloudWalArchiveCmd, barmanCapabilities.BarmanCloudCheckWalArchive)
if err != nil {
contextLogger.Error(err, "Error invoking "+barmanCapabilities.BarmanCloudCheckWalArchive,
"currentPrimary", archiver.cluster.Status.CurrentPrimary,
"targetPrimary", archiver.cluster.Status.TargetPrimary,
"options", options,
"exitCode", barmanCloudWalArchiveCmd.ProcessState.ExitCode(),
)
return fmt.Errorf("unexpected failure invoking %s: %w", barmanCapabilities.BarmanCloudWalArchive, err)
}
contextLogger.Trace("barman-cloud-check-wal-archive command execution completed")
return nil
}
// BarmanCloudCheckWalArchiveOptions create the options needed for the `barman-cloud-check-wal-archive`
// command.
func (archiver *WALArchiver) BarmanCloudCheckWalArchiveOptions(
cluster *apiv1.Cluster,
clusterName string,
) ([]string, error) {
configuration := cluster.Spec.Backup.BarmanObjectStore
var options []string
if len(configuration.EndpointURL) > 0 {
options = append(
options,
"--endpoint-url",
configuration.EndpointURL)
}
options, err := barman.AppendCloudProviderOptionsFromConfiguration(options, configuration)
if err != nil {
return nil, err
}
serverName := clusterName
if len(configuration.ServerName) != 0 {
serverName = configuration.ServerName
}
options = append(
options,
configuration.DestinationPath,
serverName)
return options, nil
}