From fe2e58e1a0bbf1cdf9fa45998c5b2a7f4328ef3e Mon Sep 17 00:00:00 2001 From: Daniel Jiang Date: Thu, 18 Oct 2018 19:02:33 +0800 Subject: [PATCH] Ignore duplication error when inserting config This commit mitigates the situation when more then one adminserver is deployed and there may be duplication error when they try to initialize the configuration to DB. Signed-off-by: Daniel Jiang --- src/common/dao/base.go | 6 ++++++ src/common/dao/config.go | 4 +++- src/common/dao/dao_test.go | 7 ++++++- 3 files changed, 15 insertions(+), 2 deletions(-) diff --git a/src/common/dao/base.go b/src/common/dao/base.go index f3d7a4ed1..4de0f8648 100644 --- a/src/common/dao/base.go +++ b/src/common/dao/base.go @@ -126,6 +126,12 @@ func GetOrmer() orm.Ormer { return globalOrm } +// isDupRecErr checks if the error is due to a duplication of record, currently this +// works only for pgSQL +func isDupRecErr(e error) bool { + return strings.Contains(e.Error(), "duplicate key value violates unique constraint") +} + // ClearTable is the shortcut for test cases, it should be called only in test cases. func ClearTable(table string) error { o := GetOrmer() diff --git a/src/common/dao/config.go b/src/common/dao/config.go index 98928e2ae..65ec6e195 100644 --- a/src/common/dao/config.go +++ b/src/common/dao/config.go @@ -18,6 +18,7 @@ import ( "github.com/goharbor/harbor/src/common" "github.com/goharbor/harbor/src/common/models" "github.com/goharbor/harbor/src/common/utils" + "github.com/goharbor/harbor/src/common/utils/log" ) // AuthModeCanBeModified determines whether auth mode can be @@ -60,7 +61,8 @@ func SaveConfigEntries(entries []models.ConfigEntry) error { tempEntry.Key = entry.Key tempEntry.Value = entry.Value created, _, err := o.ReadOrCreate(&tempEntry, "k") - if err != nil { + if err != nil && !isDupRecErr(err) { + log.Errorf("Error create configuration entry: %v", err) return err } if !created { diff --git a/src/common/dao/dao_test.go b/src/common/dao/dao_test.go index 4b2fd7bf2..1751897cf 100644 --- a/src/common/dao/dao_test.go +++ b/src/common/dao/dao_test.go @@ -15,6 +15,7 @@ package dao import ( + "fmt" "os" "testing" "time" @@ -1486,5 +1487,9 @@ func TestSaveConfigEntries(t *testing.T) { if findItem != 3 { t.Fatalf("Should update 3 configuration but only update %d", findItem) } - +} + +func TestIsDupRecError(t *testing.T) { + assert.True(t, isDupRecErr(fmt.Errorf("pq: duplicate key value violates unique constraint \"properties_k_key\""))) + assert.False(t, isDupRecErr(fmt.Errorf("other error"))) }