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 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453
|
package backrest
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"os/exec"
"strings"
"time"
"github.com/go-kit/log"
"github.com/go-kit/log/level"
"github.com/prometheus/client_golang/prometheus"
)
type setUpMetricValueFunType func(metric *prometheus.GaugeVec, value float64, labels ...string) error
type backupStruct struct {
backupLabel string
backupType string
backupTime time.Time
backupDuration float64
backupDelta int64
backupSize int64
backupRepoDelta int64
backupRepoDeltaMap *int64
backupRepoSize *int64
backupRepoSizeMap *int64
backupError *bool
backupAnnotation *annotation
backupBlockIncr string
backupReference []string
}
type lastBackupsStruct struct {
full backupStruct
diff backupStruct
incr backupStruct
}
var execCommand = exec.Command
const (
// https://golang.org/pkg/time/#Time.Format
layout = "2006-01-02 15:04:05"
fullLabel = "full"
diffLabel = "diff"
incrLabel = "incr"
)
func returnDefaultExecArgs() []string {
// Base exec arguments.
defaultArgs := []string{"info", "--output", "json"}
return defaultArgs
}
func returnConfigExecArgs(config, configIncludePath string) []string {
var configArgs []string
switch {
case config == "" && configIncludePath == "":
// Use default config and config-include-path (or define by env).
configArgs = []string{}
case config != "" && configIncludePath == "":
// Use custom config.
configArgs = []string{"--config", config}
case config == "" && configIncludePath != "":
// Use custom config-include-path.
configArgs = []string{"--config-include-path", configIncludePath}
default:
// Use custom config and config-include-path.
configArgs = []string{"--config", config, "--config-include-path", configIncludePath}
}
return configArgs
}
func returnStanzaExecArgs(stanza string) []string {
var stanzaArgs []string
switch {
case stanza == "":
// Stanza not set. No return parameters.
stanzaArgs = []string{}
default:
// Use specific stanza.
stanzaArgs = []string{"--stanza", stanza}
}
return stanzaArgs
}
// Option 'type' cannot be set multiple times for info command.
// It's pgBackRest restriction.
func returnBackupTypeExecArgs(backupType string) []string {
var backupTypeArgs []string
switch {
case backupType == "":
// Backup type not set. No return parameters.
backupTypeArgs = []string{}
default:
// Use specific backup type.
backupTypeArgs = []string{"--type", backupType}
}
return backupTypeArgs
}
func returnBackupSetExecArgs(backupSetLabel string) []string {
var backupSetLabelArgs []string
switch {
case backupSetLabel == "":
// Backup label not set. No return parameters.
backupSetLabelArgs = []string{}
default:
// Use specific backup label.
backupSetLabelArgs = []string{"--set", backupSetLabel}
}
return backupSetLabelArgs
}
func concatExecArgs(slices [][]string) []string {
tmp := []string{}
for _, s := range slices {
tmp = append(tmp, s...)
}
return tmp
}
func getAllInfoData(config, configIncludePath, stanza, backupType string, logger log.Logger) ([]byte, error) {
var backupLabel string
return getInfoData(config, configIncludePath, stanza, backupType, backupLabel, logger)
}
func getSpecificBackupInfoData(config, configIncludePath, stanza, backupLabel string, logger log.Logger) ([]byte, error) {
var backupType string
return getInfoData(config, configIncludePath, stanza, backupType, backupLabel, logger)
}
func getInfoData(config, configIncludePath, stanza, backupType, backupLabel string, logger log.Logger) ([]byte, error) {
app := "pgbackrest"
args := [][]string{
returnDefaultExecArgs(),
returnConfigExecArgs(config, configIncludePath),
returnStanzaExecArgs(stanza),
returnBackupTypeExecArgs(backupType),
}
if backupLabel != "" {
args = append(args, returnBackupSetExecArgs(backupLabel))
}
// Finally arguments for exec command.
concatArgs := concatExecArgs(args)
cmd := execCommand(app, concatArgs...)
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
err := cmd.Run()
// If stderr from pgBackRest is not empty,
// write message from pgBackRest to log.
if stderr.Len() > 0 {
level.Error(logger).Log(
"msg", "pgBackRest message",
"err", stderr.String(),
)
}
// If error occurs,
// return nil for stanza data.
if err != nil {
return nil, err
}
return stdout.Bytes(), err
}
func parseResult(output []byte) ([]stanza, error) {
var stanzas []stanza
err := json.Unmarshal(output, &stanzas)
return stanzas, err
}
func getPGVersion(id, repoKey int, dbList []db) string {
for _, db := range dbList {
if id == db.ID && repoKey == db.RepoKey {
return db.Version
}
}
return ""
}
func setUpMetricValue(metric *prometheus.GaugeVec, value float64, labels ...string) error {
metricVec, err := metric.GetMetricWithLabelValues(labels...)
if err != nil {
return err
}
// The situation should be handled by the prometheus libraries.
// But, anything is possible.
if metricVec == nil {
err := errors.New("metric is nil")
return err
}
metricVec.Set(value)
return nil
}
func compareLastBackups(backups *lastBackupsStruct, currentBackup backup, blockIncr string) {
currentBackupTime := time.Unix(currentBackup.Timestamp.Stop, 0)
curentBackupDuration := time.Unix(currentBackup.Timestamp.Stop, 0).Sub(time.Unix(currentBackup.Timestamp.Start, 0)).Seconds()
currentBackupLabel := currentBackup.Label
switch currentBackup.Type {
case "full":
if currentBackupTime.After(backups.full.backupTime) {
backups.full.backupTime = currentBackupTime
backups.full.backupLabel = currentBackupLabel
backups.full.backupDuration = curentBackupDuration
backups.full.backupDelta = currentBackup.Info.Delta
backups.full.backupSize = currentBackup.Info.Size
backups.full.backupRepoDelta = currentBackup.Info.Repository.Delta
backups.full.backupRepoDeltaMap = currentBackup.Info.Repository.DeltaMap
backups.full.backupRepoSize = currentBackup.Info.Repository.Size
backups.full.backupRepoSizeMap = currentBackup.Info.Repository.SizeMap
backups.full.backupError = currentBackup.Error
backups.full.backupAnnotation = currentBackup.Annotation
backups.full.backupBlockIncr = blockIncr
backups.full.backupReference = currentBackup.Reference
}
if currentBackupTime.After(backups.diff.backupTime) {
backups.diff.backupTime = currentBackupTime
backups.diff.backupLabel = currentBackupLabel
backups.diff.backupDuration = curentBackupDuration
backups.diff.backupDelta = currentBackup.Info.Delta
backups.diff.backupSize = currentBackup.Info.Size
backups.diff.backupRepoDelta = currentBackup.Info.Repository.Delta
backups.diff.backupRepoDeltaMap = currentBackup.Info.Repository.DeltaMap
backups.diff.backupRepoSize = currentBackup.Info.Repository.Size
backups.diff.backupRepoSizeMap = currentBackup.Info.Repository.SizeMap
backups.diff.backupError = currentBackup.Error
backups.diff.backupAnnotation = currentBackup.Annotation
backups.diff.backupBlockIncr = blockIncr
backups.diff.backupReference = currentBackup.Reference
}
if currentBackupTime.After(backups.incr.backupTime) {
backups.incr.backupTime = currentBackupTime
backups.incr.backupLabel = currentBackupLabel
backups.incr.backupDuration = curentBackupDuration
backups.incr.backupDelta = currentBackup.Info.Delta
backups.incr.backupSize = currentBackup.Info.Size
backups.incr.backupRepoDelta = currentBackup.Info.Repository.Delta
backups.incr.backupRepoDeltaMap = currentBackup.Info.Repository.DeltaMap
backups.incr.backupRepoSize = currentBackup.Info.Repository.Size
backups.incr.backupRepoSizeMap = currentBackup.Info.Repository.SizeMap
backups.incr.backupError = currentBackup.Error
backups.incr.backupAnnotation = currentBackup.Annotation
backups.incr.backupBlockIncr = blockIncr
backups.incr.backupReference = currentBackup.Reference
}
case "diff":
if currentBackupTime.After(backups.diff.backupTime) {
backups.diff.backupTime = currentBackupTime
backups.diff.backupLabel = currentBackupLabel
backups.diff.backupDuration = curentBackupDuration
backups.diff.backupDelta = currentBackup.Info.Delta
backups.diff.backupSize = currentBackup.Info.Size
backups.diff.backupRepoDelta = currentBackup.Info.Repository.Delta
backups.diff.backupRepoDeltaMap = currentBackup.Info.Repository.DeltaMap
backups.diff.backupRepoSize = currentBackup.Info.Repository.Size
backups.diff.backupRepoSizeMap = currentBackup.Info.Repository.SizeMap
backups.diff.backupError = currentBackup.Error
backups.diff.backupAnnotation = currentBackup.Annotation
backups.diff.backupBlockIncr = blockIncr
backups.diff.backupReference = currentBackup.Reference
}
if currentBackupTime.After(backups.incr.backupTime) {
backups.incr.backupTime = currentBackupTime
backups.incr.backupLabel = currentBackupLabel
backups.incr.backupDuration = curentBackupDuration
backups.incr.backupDelta = currentBackup.Info.Delta
backups.incr.backupSize = currentBackup.Info.Size
backups.incr.backupRepoDelta = currentBackup.Info.Repository.Delta
backups.incr.backupRepoDeltaMap = currentBackup.Info.Repository.DeltaMap
backups.incr.backupRepoSize = currentBackup.Info.Repository.Size
backups.incr.backupRepoSizeMap = currentBackup.Info.Repository.SizeMap
backups.incr.backupError = currentBackup.Error
backups.incr.backupAnnotation = currentBackup.Annotation
backups.incr.backupBlockIncr = blockIncr
backups.incr.backupReference = currentBackup.Reference
}
case "incr":
if currentBackupTime.After(backups.incr.backupTime) {
backups.incr.backupTime = currentBackupTime
backups.incr.backupLabel = currentBackupLabel
backups.incr.backupDuration = curentBackupDuration
backups.incr.backupDelta = currentBackup.Info.Delta
backups.incr.backupSize = currentBackup.Info.Size
backups.incr.backupRepoDelta = currentBackup.Info.Repository.Delta
backups.incr.backupRepoDeltaMap = currentBackup.Info.Repository.DeltaMap
backups.incr.backupRepoSize = currentBackup.Info.Repository.Size
backups.incr.backupRepoSizeMap = currentBackup.Info.Repository.SizeMap
backups.incr.backupError = currentBackup.Error
backups.incr.backupAnnotation = currentBackup.Annotation
backups.incr.backupBlockIncr = blockIncr
backups.incr.backupReference = currentBackup.Reference
}
}
}
func stanzaNotInExclude(stanza string, listExclude []string) bool {
// Check that exclude list is empty.
// If so, no excluding stanzas are set during startup.
if strings.Join(listExclude, "") != "" {
for _, val := range listExclude {
if val == stanza {
return false
}
}
}
return true
}
func getParsedSpecificBackupInfoData(config, configIncludePath, stanzaName, backupLabel string, logger log.Logger) ([]stanza, error) {
stanzaDataSpecific, err := getSpecificBackupInfoData(config, configIncludePath, stanzaName, backupLabel, logger)
if err != nil {
level.Error(logger).Log(
"msg", "Get data from pgBackRest failed",
"stanza", stanzaName,
"backup", backupLabel,
"err", err)
}
parseDataSpecific, err := parseResult(stanzaDataSpecific)
if err != nil {
level.Error(logger).Log(
"msg", "Parse JSON failed",
"stanza", stanzaName,
"backup", backupLabel,
"err", err)
}
return parseDataSpecific, err
}
func setUpMetric(metric *prometheus.GaugeVec, metricName string, value float64, setUpMetricValueFun setUpMetricValueFunType, logger log.Logger, labels ...string) {
level.Debug(logger).Log(
"msg", "Set up metric",
"metric", metricName,
"value", value,
"labels", strings.Join(labels, ","),
)
err := setUpMetricValueFun(metric, value, labels...)
if err != nil {
level.Error(logger).Log(
"msg", "Metric set up failed",
"metric", metricName,
"err", err,
)
}
}
// Reset all metrics.
func resetMetrics() {
resetStanzaMetrics()
resetRepoMetrics()
resetBackupMetrics()
resetLastBackupMetrics()
resetWALMetrics()
resetExporterMetrics()
}
func (backup backup) checkBackupIncremental() string {
// Block incremental map is used for block level backup.
// If one value from 'size-map' or 'delta-map' is nil, and other has correct value,
// it looks like a bug in pgBackRest.
// See https://github.com/pgbackrest/pgbackrest/blob/3feed389a2199454db68e446851323498b45db20/src/command/info/info.c#L459-L463
// Relation - backupInfoRepoSizeMap != NULL, where backupInfoRepoSizeMap is related to SizeMap (size-map).
if backup.Info.Repository.SizeMap != nil && backup.Info.Repository.DeltaMap != nil {
// The block incremental backup functionality is used.
return "y"
}
return "n"
}
func processSpecificBackupData(config, configIncludePath, stanzaName, backupLabel, backupType, metricName string, metric *prometheus.GaugeVec, setUpMetricValueFun setUpMetricValueFunType, logger log.Logger, addLabels ...string) {
var metricValue float64 = 0
parseStanzaDataSpecific, err := getParsedSpecificBackupInfoData(config, configIncludePath, stanzaName, backupLabel, logger)
if err != nil {
level.Error(logger).Log(
"msg", "Get data from pgBackRest failed",
"stanza", stanzaName,
"backup", backupLabel,
"err", err,
)
}
// In a normal situation, only one element with one backup should be returned.
// If more than one element or one backup is returned, there is may be a bug in pgBackRest.
// If it's not a bug, then this part will need to be refactoring.
// Use *[]struct() type for backup.DatabaseRef.
if (len(parseStanzaDataSpecific) != 0 && len(parseStanzaDataSpecific[0].Backup) != 0) &&
parseStanzaDataSpecific[0].Backup[0].DatabaseRef != nil {
metricValue = convertDatabaseRefPointerToFloat(parseStanzaDataSpecific[0].Backup[0].DatabaseRef)
} else {
level.Warn(logger).Log("msg", "No backup data returned",
"stanza", stanzaName,
"backup", backupLabel,
)
}
labels := append([]string{backupType, stanzaName}, addLabels...)
setUpMetric(
metric,
metricName,
metricValue,
setUpMetricValueFun,
logger,
labels...,
)
}
// processBackupReferencesCount processes the number of references to another backup (backup reference list).
func processBackupReferencesCount(backupReference []string, metricName string, metric *prometheus.GaugeVec, setUpMetricValueFun setUpMetricValueFunType, logger log.Logger, addLabels ...string) {
refListTotal, err := getBackupReferencesTotal(backupReference)
if err != nil {
level.Error(logger).Log(
"msg", "failed to get backup references",
"reference", strings.Join(backupReference, ","),
"err", err,
)
}
for refType, refCNT := range refListTotal {
setUpMetric(
metric,
metricName,
float64(refCNT),
setUpMetricValueFun,
logger,
append([]string{refType}, addLabels...)...,
)
}
}
// getBackupReferencesTotal counts the number of full, diff and incr backups.
func getBackupReferencesTotal(refList []string) (map[string]int, error) {
total := map[string]int{
fullLabel: 0,
diffLabel: 0,
incrLabel: 0,
}
if len(refList) == 0 {
return total, nil
}
for _, ref := range refList {
switch {
case strings.HasSuffix(ref, "F"):
total[fullLabel]++
case strings.HasSuffix(ref, "D"):
total[diffLabel]++
case strings.HasSuffix(ref, "I"):
total[incrLabel]++
default:
return total, fmt.Errorf("invalid backup name %s", ref)
}
}
return total, nil
}
|