diff --git a/pkg/metrics/config.go b/pkg/metrics/config.go index e78827c..b55d543 100644 --- a/pkg/metrics/config.go +++ b/pkg/metrics/config.go @@ -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" @@ -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 @@ -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") } } @@ -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 }