forked from operasoftware/cnpg-plugin-pgbackrest
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackup.go
More file actions
200 lines (177 loc) · 7.14 KB
/
Copy pathbackup.go
File metadata and controls
200 lines (177 loc) · 7.14 KB
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
/*
Copyright The CloudNativePG Contributors
Copyright 2025, Opera Norway AS
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 instance
import (
"context"
"fmt"
"path/filepath"
"time"
"github.com/cloudnative-pg/cloudnative-pg/pkg/postgres"
"github.com/cloudnative-pg/cnpg-i-machinery/pkg/pluginhelper/decoder"
"github.com/cloudnative-pg/cnpg-i/pkg/backup"
"github.com/cloudnative-pg/machinery/pkg/fileutils"
"github.com/cloudnative-pg/machinery/pkg/log"
pgTime "github.com/cloudnative-pg/machinery/pkg/postgres/time"
"sigs.k8s.io/controller-runtime/pkg/client"
pgbackrestv1 "github.com/operasoftware/cnpg-plugin-pgbackrest/api/v1"
"github.com/operasoftware/cnpg-plugin-pgbackrest/internal/cnpgi/common"
"github.com/operasoftware/cnpg-plugin-pgbackrest/internal/cnpgi/metadata"
"github.com/operasoftware/cnpg-plugin-pgbackrest/internal/cnpgi/operator/config"
pgbackrestBackup "github.com/operasoftware/cnpg-plugin-pgbackrest/internal/pgbackrest/backup"
"github.com/operasoftware/cnpg-plugin-pgbackrest/internal/pgbackrest/catalog"
pgbackrestCredentials "github.com/operasoftware/cnpg-plugin-pgbackrest/internal/pgbackrest/credentials"
"github.com/operasoftware/cnpg-plugin-pgbackrest/internal/pgbackrest/utils"
)
// BackupServiceImplementation is the implementation
// of the Backup CNPG capability
type BackupServiceImplementation struct {
Client client.Client
InstanceName string
PGDataPath string
backup.UnimplementedBackupServer
}
// GetCapabilities implements the BackupService interface
func (b BackupServiceImplementation) GetCapabilities(
_ context.Context, _ *backup.BackupCapabilitiesRequest,
) (*backup.BackupCapabilitiesResult, error) {
return &backup.BackupCapabilitiesResult{
Capabilities: []*backup.BackupCapability{
{
Type: &backup.BackupCapability_Rpc{
Rpc: &backup.BackupCapability_RPC{
Type: backup.BackupCapability_RPC_TYPE_BACKUP,
},
},
},
},
}, nil
}
// Backup implements the Backup interface
func (b BackupServiceImplementation) Backup(
ctx context.Context,
request *backup.BackupRequest,
) (*backup.BackupResult, error) {
contextLogger := log.FromContext(ctx)
contextLogger.Info("Starting backup")
backupConfig, err := decoder.DecodeBackupLenient(request.BackupDefinition)
if err != nil {
contextLogger.Error(err, "while getting backup definition")
return nil, err
}
configuration, err := config.NewFromClusterJSON(request.ClusterDefinition)
if err != nil {
return nil, err
}
var archive pgbackrestv1.Archive
if err := b.Client.Get(ctx, configuration.GetArchiveObjectKey(), &archive); err != nil {
contextLogger.Error(err, "while getting archive", "key", configuration.GetRecoveryArchiveObjectKey())
return nil, err
}
if err := fileutils.EnsureDirectoryExists(postgres.BackupTemporaryDirectory); err != nil {
contextLogger.Error(err, "Cannot create backup temporary directory", "err", err)
return nil, err
}
backupCmd := pgbackrestBackup.NewBackupCommand(
&archive.Spec.Configuration,
backupConfig.Spec.PluginConfiguration,
b.PGDataPath,
)
// We need to connect to PostgreSQL and to do that we need
// PGHOST (and the like) to be available
osEnvironment := utils.SanitizedEnviron()
caBundleEnvironment := common.GetRestoreCABundleEnv(&archive.Spec.Configuration)
env, err := pgbackrestCredentials.EnvSetBackupCloudCredentials(
ctx,
b.Client,
archive.Namespace,
&archive.Spec.Configuration,
common.MergeEnv(osEnvironment, caBundleEnvironment))
if err != nil {
contextLogger.Error(err, "while setting backup cloud credentials")
return nil, err
}
// pgbackrest stanza-create requires a primary PostgreSQL connection: it reads
// the live cluster's control data to initialize the stanza metadata in the
// repository. On a standby it fails with pgbackrest exit code 56
// ("unable to find primary cluster"), which aborts the whole backup. That
// makes target: prefer-standby / standby backups unusable (see issue #83).
//
// Skip stanza-create when this instance is a standby. This is safe: the
// stanza is created by the primary (its own backups + WAL archiving's
// CheckWalArchiveDestination run against the same repo), so by the time a
// standby backup runs the stanza already exists. We detect the role the same
// way PostgreSQL and CNPG itself do — the presence of standby.signal in
// PGDATA — so we need neither a database connection nor credentials here.
isStandby, err := instanceIsStandby(b.PGDataPath)
if err != nil {
contextLogger.Error(err, "while determining if instance is a standby")
return nil, err
}
if isStandby {
contextLogger.Info("Instance is a standby; skipping pgbackrest stanza-create " +
"(the stanza is initialized by the primary)")
} else {
if err = backupCmd.CreatePgbackrestStanza(ctx, configuration.Stanza, env); err != nil {
contextLogger.Error(err, "while initializing pgbackrest stanza")
return nil, err
}
}
backupName := fmt.Sprintf("backup-%v", pgTime.ToCompactISO8601(time.Now()))
if err = backupCmd.Take(
ctx,
backupName,
configuration.Stanza,
env,
postgres.BackupTemporaryDirectory,
); err != nil {
contextLogger.Error(err, "while taking backup")
return nil, err
}
executedBackupInfo, err := backupCmd.GetExecutedBackupInfo(
ctx,
backupName,
configuration.Stanza,
env)
if err != nil {
contextLogger.Error(err, "while getting executed backup info")
return nil, err
}
contextLogger.Info("Backup completed", "backup", executedBackupInfo.Backups[0].ID)
return &backup.BackupResult{
BackupId: executedBackupInfo.Backups[0].ID,
BackupName: executedBackupInfo.Backups[0].Annotations[catalog.BackupNameAnnotation],
StartedAt: executedBackupInfo.Backups[0].Time.Start,
StoppedAt: executedBackupInfo.Backups[0].Time.Stop,
BeginWal: executedBackupInfo.Backups[0].WAL.Start,
EndWal: executedBackupInfo.Backups[0].WAL.Stop,
BeginLsn: executedBackupInfo.Backups[0].LSN.Start,
EndLsn: executedBackupInfo.Backups[0].LSN.Stop,
InstanceId: b.InstanceName,
Online: true,
Metadata: map[string]string{
"version": metadata.Data.Version,
"name": metadata.Data.Name,
"displayName": metadata.Data.DisplayName,
},
}, nil
}
// instanceIsStandby reports whether the PostgreSQL instance rooted at pgDataPath
// is a standby (replica). It checks for the standby.signal file in PGDATA, which
// is the same signal PostgreSQL itself uses to start in standby mode and the same
// mechanism CloudNativePG uses to distinguish a replica from a primary. Using the
// signal file means we do not need a database connection or credentials at backup
// time to determine the role.
func instanceIsStandby(pgDataPath string) (bool, error) {
return fileutils.FileExists(filepath.Join(pgDataPath, "standby.signal"))
}