Skip to content

Commit

Permalink
Use serializable transactions
Browse files Browse the repository at this point in the history
  • Loading branch information
jrauh01 committed Nov 19, 2024
1 parent f22a408 commit 8435531
Showing 1 changed file with 18 additions and 4 deletions.
22 changes: 18 additions & 4 deletions pkg/metrics/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package metrics

import (
"context"
"database/sql"
"fmt"
"github.com/icinga/icinga-go-library/database"
schemav1 "github.com/icinga/icinga-kubernetes/pkg/schema/v1"
Expand Down Expand Up @@ -30,12 +31,17 @@ func (c *PrometheusConfig) Validate() error {
func SyncPrometheusConfig(ctx context.Context, db *database.DB, config *PrometheusConfig) error {
var configPairs []*schemav1.Config

tx, err := db.BeginTxx(ctx, &sql.TxOptions{Isolation: sql.LevelSerializable})
if err != nil {
return errors.Wrap(err, "cannot start transaction")
}

if config.Url != "" {
configPairs = append(configPairs, &schemav1.Config{Key: schemav1.ConfigKeyPrometheusUrl, Value: config.Url, Locked: "y"})

if config.Username != "" {
configPairs = append(configPairs, &schemav1.Config{Key: schemav1.ConfigKeyPrometheusUsername, Value: config.Username, Locked: "y"})
configPairs = append(configPairs, &schemav1.Config{Key: schemav1.ConfigKeyPrometheusPassword, Value: "", Locked: "y"})
configPairs = append(configPairs, &schemav1.Config{Key: schemav1.ConfigKeyPrometheusPassword, Value: config.Password, Locked: "y"})
} else {
var deleteKeys []schemav1.ConfigKey

Expand All @@ -49,7 +55,7 @@ func SyncPrometheusConfig(ctx context.Context, db *database.DB, config *Promethe
)

for _, key := range deleteKeys {
if _, err := db.ExecContext(ctx, deleteStmt, key); err != nil {
if _, err := tx.ExecContext(ctx, deleteStmt, key); err != nil {
return errors.Wrap(err, "cannot delete Prometheus credentials")
}
}
Expand All @@ -68,11 +74,19 @@ func SyncPrometheusConfig(ctx context.Context, db *database.DB, config *Promethe
}
}

stmt, _ := db.BuildUpsertStmt(&schemav1.Config{})
if _, err := db.NamedExecContext(ctx, stmt, configPairs); err != nil {
upsertStmt, _ := db.BuildUpsertStmt(&schemav1.Config{})

if _, err := tx.NamedExecContext(ctx, upsertStmt, configPairs); err != nil {
if err := tx.Rollback(); err != nil {
return errors.Wrap(err, "cannot rollback transaction")
}
return errors.Wrap(err, "cannot upsert Prometheus configuration")
}

if err := tx.Commit(); err != nil {
return errors.Wrap(err, "cannot commit transaction")
}

return nil
}

Expand Down

0 comments on commit 8435531

Please sign in to comment.