From 1c483f82570239c49830d54ba8345ffdb2f59b71 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Fri, 9 Aug 2024 15:20:31 -0700 Subject: [PATCH 01/12] Use an abstract lock layer to allow distributed lock between multiple Gitea instances --- custom/conf/app.example.ini | 6 ++ go.mod | 3 + go.sum | 7 ++ modules/globallock/lock.go | 128 ++++++++++++++++++++++++++++ modules/globallock/lock_test.go | 26 ++++++ modules/setting/gloabl_lock.go | 37 ++++++++ modules/setting/global_lock_test.go | 35 ++++++++ modules/setting/setting.go | 1 + modules/sync/exclusive_pool.go | 69 --------------- modules/sync/status_pool.go | 57 ------------- modules/sync/status_pool_test.go | 31 ------- services/cron/cron.go | 4 - services/cron/tasks.go | 12 ++- services/pull/check.go | 14 ++- services/pull/merge.go | 25 +++++- services/pull/pull.go | 19 +++-- services/pull/update.go | 13 ++- services/repository/transfer.go | 37 +++++--- services/wiki/wiki.go | 31 +++++-- 19 files changed, 361 insertions(+), 194 deletions(-) create mode 100644 modules/globallock/lock.go create mode 100644 modules/globallock/lock_test.go create mode 100644 modules/setting/gloabl_lock.go create mode 100644 modules/setting/global_lock_test.go delete mode 100644 modules/sync/exclusive_pool.go delete mode 100644 modules/sync/status_pool.go delete mode 100644 modules/sync/status_pool_test.go diff --git a/custom/conf/app.example.ini b/custom/conf/app.example.ini index adec5aff3655..0f70a1a3d040 100644 --- a/custom/conf/app.example.ini +++ b/custom/conf/app.example.ini @@ -2713,3 +2713,9 @@ LEVEL = Info ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; storage type ;STORAGE_TYPE = local + +;[global_lock] +;; Lock service type, could be memory or redis +;SERVICE_TYPE = memory +;; Ignored for the "memory" type. For "redis" use something like `redis://127.0.0.1:6379/0` +;SERVICE_CONN_STR = diff --git a/go.mod b/go.mod index f5c189893f4d..1d05a1cec665 100644 --- a/go.mod +++ b/go.mod @@ -201,6 +201,7 @@ require ( github.com/go-openapi/strfmt v0.23.0 // indirect github.com/go-openapi/swag v0.23.0 // indirect github.com/go-openapi/validate v0.24.0 // indirect + github.com/go-redsync/redsync/v4 v4.13.0 // indirect github.com/go-webauthn/x v0.1.9 // indirect github.com/goccy/go-json v0.10.3 // indirect github.com/golang-jwt/jwt/v4 v4.5.0 // indirect @@ -218,7 +219,9 @@ require ( github.com/gorilla/mux v1.8.1 // indirect github.com/gorilla/securecookie v1.1.2 // indirect github.com/h2non/parth v0.0.0-20190131123155-b4df798d6542 // indirect + github.com/hashicorp/errwrap v1.1.0 // indirect github.com/hashicorp/go-cleanhttp v0.5.2 // indirect + github.com/hashicorp/go-multierror v1.1.1 // indirect github.com/hashicorp/go-retryablehttp v0.7.7 // indirect github.com/hashicorp/hcl v1.0.0 // indirect github.com/imdario/mergo v0.3.16 // indirect diff --git a/go.sum b/go.sum index f1780fada798..0882d6be225a 100644 --- a/go.sum +++ b/go.sum @@ -342,6 +342,8 @@ github.com/go-openapi/swag v0.23.0/go.mod h1:esZ8ITTYEsH1V2trKHjAN8Ai7xHb8RV+YSZ github.com/go-openapi/validate v0.24.0 h1:LdfDKwNbpB6Vn40xhTdNZAnfLECL81w+VX3BumrGD58= github.com/go-openapi/validate v0.24.0/go.mod h1:iyeX1sEufmv3nPbBdX3ieNviWnOZaJ1+zquzJEf2BAQ= github.com/go-redis/redis v6.15.2+incompatible/go.mod h1:NAIEuMOZ/fxfXJIrKDQDz8wamY7mA7PouImQ2Jvg6kA= +github.com/go-redsync/redsync/v4 v4.13.0 h1:49X6GJfnbLGaIpBBREM/zA4uIMDXKAh1NDkvQ1EkZKA= +github.com/go-redsync/redsync/v4 v4.13.0/go.mod h1:HMW4Q224GZQz6x1Xc7040Yfgacukdzu7ifTDAKiyErQ= github.com/go-sql-driver/mysql v1.4.1/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w= github.com/go-sql-driver/mysql v1.8.1 h1:LedoTUt/eveggdHS9qUFC1EFSa8bU2+1pZjSRpvNJ1Y= github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg= @@ -449,10 +451,15 @@ github.com/h2non/gock v1.2.0 h1:K6ol8rfrRkUOefooBC8elXoaNGYkpp7y2qcxGG6BzUE= github.com/h2non/gock v1.2.0/go.mod h1:tNhoxHYW2W42cYkYb1WqzdbYIieALC99kpYr7rH/BQk= github.com/h2non/parth v0.0.0-20190131123155-b4df798d6542 h1:2VTzZjLZBgl62/EtslCrtky5vbi9dd7HrQPQIx6wqiw= github.com/h2non/parth v0.0.0-20190131123155-b4df798d6542/go.mod h1:Ow0tF8D4Kplbc8s8sSb3V2oUCygFHVp8gC3Dn6U4MNI= +github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= +github.com/hashicorp/errwrap v1.1.0 h1:OxrOeh75EUXMY8TBjag2fzXGZ40LB6IKw45YeGUDY2I= +github.com/hashicorp/errwrap v1.1.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= github.com/hashicorp/go-cleanhttp v0.5.2 h1:035FKYIWjmULyFRBKPs8TBQoi0x6d9G4xc9neXJWAZQ= github.com/hashicorp/go-cleanhttp v0.5.2/go.mod h1:kO/YDlP8L1346E6Sodw+PrpBSV4/SoxCXGY6BqNFT48= github.com/hashicorp/go-hclog v1.6.3 h1:Qr2kF+eVWjTiYmU7Y31tYlP1h0q/X3Nl3tPGdaB11/k= github.com/hashicorp/go-hclog v1.6.3/go.mod h1:W4Qnvbt70Wk/zYJryRzDRU/4r0kIg0PVHBcfoyhpF5M= +github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo= +github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM= github.com/hashicorp/go-retryablehttp v0.7.7 h1:C8hUCYzor8PIfXHa4UrZkU4VvK8o9ISHxT2Q8+VepXU= github.com/hashicorp/go-retryablehttp v0.7.7/go.mod h1:pkQpWZeYWskR+D1tR2O5OcBFOxfA7DoAO6xtkuQnHTk= github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k= diff --git a/modules/globallock/lock.go b/modules/globallock/lock.go new file mode 100644 index 000000000000..52a097e54471 --- /dev/null +++ b/modules/globallock/lock.go @@ -0,0 +1,128 @@ +// Copyright 2023 The Gitea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package globallock + +import ( + "context" + "sync" + "time" + + "code.gitea.io/gitea/modules/nosql" + "code.gitea.io/gitea/modules/setting" + + redsync "github.com/go-redsync/redsync/v4" + goredis "github.com/go-redsync/redsync/v4/redis/goredis/v9" +) + +type Locker interface { + Lock() error + TryLock() (bool, error) + Unlock() (bool, error) +} + +type LockService interface { + GetLock(name string) Locker +} + +type memoryLock struct { + mutex sync.Mutex +} + +func (r *memoryLock) Lock() error { + r.mutex.Lock() + return nil +} + +func (r *memoryLock) TryLock() (bool, error) { + return r.mutex.TryLock(), nil +} + +func (r *memoryLock) Unlock() (bool, error) { + r.mutex.Unlock() + return true, nil +} + +var _ Locker = &memoryLock{} + +type memoryLockService struct { + syncMap sync.Map +} + +var _ LockService = &memoryLockService{} + +func newMemoryLockService() *memoryLockService { + return &memoryLockService{ + syncMap: sync.Map{}, + } +} + +func (l *memoryLockService) GetLock(name string) Locker { + v, _ := l.syncMap.LoadOrStore(name, &memoryLock{}) + return v.(*memoryLock) +} + +type redisLockService struct { + rs *redsync.Redsync +} + +var _ LockService = &redisLockService{} + +func newRedisLockService(connection string) *redisLockService { + client := nosql.GetManager().GetRedisClient(connection) + + pool := goredis.NewPool(client) + + // Create an instance of redisync to be used to obtain a mutual exclusion + // lock. + rs := redsync.New(pool) + + return &redisLockService{ + rs: rs, + } +} + +type redisLock struct { + mutex *redsync.Mutex +} + +func (r *redisLockService) GetLock(name string) Locker { + return &redisLock{mutex: r.rs.NewMutex(name)} +} + +func (r *redisLock) Lock() error { + return r.mutex.Lock() +} + +func (r *redisLock) TryLock() (bool, error) { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond) + defer cancel() + if err := r.mutex.LockContext(ctx); err != nil { + return false, err + } + return true, nil +} + +func (r *redisLock) Unlock() (bool, error) { + return r.mutex.Unlock() +} + +var ( + syncOnce sync.Once + lockService LockService +) + +func getLockService() LockService { + syncOnce.Do(func() { + if setting.GlobalLock.ServiceType == "redis" { + lockService = newRedisLockService(setting.GlobalLock.ServiceConnStr) + } else { + lockService = newMemoryLockService() + } + }) + return lockService +} + +func GetLock(name string) Locker { + return getLockService().GetLock(name) +} diff --git a/modules/globallock/lock_test.go b/modules/globallock/lock_test.go new file mode 100644 index 000000000000..0052057e460f --- /dev/null +++ b/modules/globallock/lock_test.go @@ -0,0 +1,26 @@ +// Copyright 2024 The Gitea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package globallock + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func Test_Lock(t *testing.T) { + locker := GetLock("test") + assert.NoError(t, locker.Lock()) + locker.Unlock() + + locked1, err1 := locker.TryLock() + assert.NoError(t, err1) + assert.True(t, locked1) + + locked2, err2 := locker.TryLock() + assert.NoError(t, err2) + assert.False(t, locked2) + + locker.Unlock() +} diff --git a/modules/setting/gloabl_lock.go b/modules/setting/gloabl_lock.go new file mode 100644 index 000000000000..a7802a9df1f7 --- /dev/null +++ b/modules/setting/gloabl_lock.go @@ -0,0 +1,37 @@ +// Copyright 2024 The Gitea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package setting + +import ( + "code.gitea.io/gitea/modules/log" + "code.gitea.io/gitea/modules/nosql" +) + +// GlobalLock represents configuration of global lock +var GlobalLock = struct { + ServiceType string + ServiceConnStr string +}{ + ServiceType: "memory", +} + +func loadGlobalLockFrom(rootCfg ConfigProvider) { + sec := rootCfg.Section("global_lock") + GlobalLock.ServiceType = sec.Key("SERVICE_TYPE").MustString("memory") + switch GlobalLock.ServiceType { + case "memory": + case "redis": + connStr := sec.Key("SERVICE_CONN_STR").String() + if connStr == "" { + log.Fatal("SERVICE_CONN_STR is empty for redis") + } + u := nosql.ToRedisURI(connStr) + if u == nil { + log.Fatal("SERVICE_CONN_STR %s is not a valid redis connection string", connStr) + } + GlobalLock.ServiceConnStr = connStr + default: + log.Fatal("Unknown sync lock service type: %s", GlobalLock.ServiceType) + } +} diff --git a/modules/setting/global_lock_test.go b/modules/setting/global_lock_test.go new file mode 100644 index 000000000000..5eeb275523a7 --- /dev/null +++ b/modules/setting/global_lock_test.go @@ -0,0 +1,35 @@ +// Copyright 2024 The Gitea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package setting + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestLoadGlobalLockConfig(t *testing.T) { + t.Run("DefaultGlobalLockConfig", func(t *testing.T) { + iniStr := `` + cfg, err := NewConfigProviderFromData(iniStr) + assert.NoError(t, err) + + loadGlobalLockFrom(cfg) + assert.EqualValues(t, "memory", GlobalLock.ServiceType) + }) + + t.Run("RedisGlobalLockConfig", func(t *testing.T) { + iniStr := ` +[global_lock] +SERVICE_TYPE = redis +SERVICE_CONN_STR = addrs=127.0.0.1:6379 db=0 +` + cfg, err := NewConfigProviderFromData(iniStr) + assert.NoError(t, err) + + loadGlobalLockFrom(cfg) + assert.EqualValues(t, "redis", GlobalLock.ServiceType) + assert.EqualValues(t, "addrs=127.0.0.1:6379 db=0", GlobalLock.ServiceConnStr) + }) +} diff --git a/modules/setting/setting.go b/modules/setting/setting.go index b4f913cdae1c..c93d199b1b63 100644 --- a/modules/setting/setting.go +++ b/modules/setting/setting.go @@ -147,6 +147,7 @@ func loadCommonSettingsFrom(cfg ConfigProvider) error { loadGitFrom(cfg) loadMirrorFrom(cfg) loadMarkupFrom(cfg) + loadGlobalLockFrom(cfg) loadOtherFrom(cfg) return nil } diff --git a/modules/sync/exclusive_pool.go b/modules/sync/exclusive_pool.go deleted file mode 100644 index fbfc1f22924c..000000000000 --- a/modules/sync/exclusive_pool.go +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright 2016 The Gogs Authors. All rights reserved. -// SPDX-License-Identifier: MIT - -package sync - -import ( - "sync" -) - -// ExclusivePool is a pool of non-identical instances -// that only one instance with same identity is in the pool at a time. -// In other words, only instances with different identities can be in -// the pool the same time. If another instance with same identity tries -// to get into the pool, it hangs until previous instance left the pool. -// -// This pool is particularly useful for performing tasks on same resource -// on the file system in different goroutines. -type ExclusivePool struct { - lock sync.Mutex - - // pool maintains locks for each instance in the pool. - pool map[string]*sync.Mutex - - // count maintains the number of times an instance with same identity checks in - // to the pool, and should be reduced to 0 (removed from map) by checking out - // with same number of times. - // The purpose of count is to delete lock when count down to 0 and recycle memory - // from map object. - count map[string]int -} - -// NewExclusivePool initializes and returns a new ExclusivePool object. -func NewExclusivePool() *ExclusivePool { - return &ExclusivePool{ - pool: make(map[string]*sync.Mutex), - count: make(map[string]int), - } -} - -// CheckIn checks in an instance to the pool and hangs while instance -// with same identity is using the lock. -func (p *ExclusivePool) CheckIn(identity string) { - p.lock.Lock() - - lock, has := p.pool[identity] - if !has { - lock = &sync.Mutex{} - p.pool[identity] = lock - } - p.count[identity]++ - - p.lock.Unlock() - lock.Lock() -} - -// CheckOut checks out an instance from the pool and releases the lock -// to let other instances with same identity to grab the lock. -func (p *ExclusivePool) CheckOut(identity string) { - p.lock.Lock() - defer p.lock.Unlock() - - p.pool[identity].Unlock() - if p.count[identity] == 1 { - delete(p.pool, identity) - delete(p.count, identity) - } else { - p.count[identity]-- - } -} diff --git a/modules/sync/status_pool.go b/modules/sync/status_pool.go deleted file mode 100644 index 6f075d54b79d..000000000000 --- a/modules/sync/status_pool.go +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright 2016 The Gogs Authors. All rights reserved. -// SPDX-License-Identifier: MIT - -package sync - -import ( - "sync" - - "code.gitea.io/gitea/modules/container" -) - -// StatusTable is a table maintains true/false values. -// -// This table is particularly useful for un/marking and checking values -// in different goroutines. -type StatusTable struct { - lock sync.RWMutex - pool container.Set[string] -} - -// NewStatusTable initializes and returns a new StatusTable object. -func NewStatusTable() *StatusTable { - return &StatusTable{ - pool: make(container.Set[string]), - } -} - -// StartIfNotRunning sets value of given name to true if not already in pool. -// Returns whether set value was set to true -func (p *StatusTable) StartIfNotRunning(name string) bool { - p.lock.Lock() - added := p.pool.Add(name) - p.lock.Unlock() - return added -} - -// Start sets value of given name to true in the pool. -func (p *StatusTable) Start(name string) { - p.lock.Lock() - p.pool.Add(name) - p.lock.Unlock() -} - -// Stop sets value of given name to false in the pool. -func (p *StatusTable) Stop(name string) { - p.lock.Lock() - p.pool.Remove(name) - p.lock.Unlock() -} - -// IsRunning checks if value of given name is set to true in the pool. -func (p *StatusTable) IsRunning(name string) bool { - p.lock.RLock() - exists := p.pool.Contains(name) - p.lock.RUnlock() - return exists -} diff --git a/modules/sync/status_pool_test.go b/modules/sync/status_pool_test.go deleted file mode 100644 index e2e48862f581..000000000000 --- a/modules/sync/status_pool_test.go +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright 2017 The Gitea Authors. All rights reserved. -// SPDX-License-Identifier: MIT - -package sync - -import ( - "testing" - - "github.com/stretchr/testify/assert" -) - -func Test_StatusTable(t *testing.T) { - table := NewStatusTable() - - assert.False(t, table.IsRunning("xyz")) - - table.Start("xyz") - assert.True(t, table.IsRunning("xyz")) - - assert.False(t, table.StartIfNotRunning("xyz")) - assert.True(t, table.IsRunning("xyz")) - - table.Stop("xyz") - assert.False(t, table.IsRunning("xyz")) - - assert.True(t, table.StartIfNotRunning("xyz")) - assert.True(t, table.IsRunning("xyz")) - - table.Stop("xyz") - assert.False(t, table.IsRunning("xyz")) -} diff --git a/services/cron/cron.go b/services/cron/cron.go index 3c5737e3718f..1d803ed96daf 100644 --- a/services/cron/cron.go +++ b/services/cron/cron.go @@ -11,7 +11,6 @@ import ( "code.gitea.io/gitea/modules/graceful" "code.gitea.io/gitea/modules/process" - "code.gitea.io/gitea/modules/sync" "code.gitea.io/gitea/modules/translation" "github.com/go-co-op/gocron" @@ -19,9 +18,6 @@ import ( var scheduler = gocron.NewScheduler(time.Local) -// Prevent duplicate running tasks. -var taskStatusTable = sync.NewStatusTable() - // NewContext begins cron tasks // Each cron task is run within the shutdown context as a running server // AtShutdown the cron server is stopped diff --git a/services/cron/tasks.go b/services/cron/tasks.go index f8a7444c49e5..48d1fbcd53c4 100644 --- a/services/cron/tasks.go +++ b/services/cron/tasks.go @@ -14,6 +14,7 @@ import ( "code.gitea.io/gitea/models/db" system_model "code.gitea.io/gitea/models/system" user_model "code.gitea.io/gitea/models/user" + "code.gitea.io/gitea/modules/globallock" "code.gitea.io/gitea/modules/graceful" "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/process" @@ -73,7 +74,12 @@ func (t *Task) Run() { // RunWithUser will run the task incrementing the cron counter at the time with User func (t *Task) RunWithUser(doer *user_model.User, config Config) { - if !taskStatusTable.StartIfNotRunning(t.Name) { + lock := globallock.GetLock(fmt.Sprintf("cron_tasks_%s", t.Name)) + if success, err := lock.TryLock(); err != nil { + log.Error("Unable to lock cron task %s Error: %v", t.Name, err) + return + } else if !success { + // get lock failed, so that there must be another task are running. return } t.lock.Lock() @@ -83,7 +89,9 @@ func (t *Task) RunWithUser(doer *user_model.User, config Config) { t.ExecTimes++ t.lock.Unlock() defer func() { - taskStatusTable.Stop(t.Name) + if _, err := lock.Unlock(); err != nil { + log.Error("Unable to unlock cron task %s Error: %v", t.Name, err) + } }() graceful.GetManager().RunWithShutdownContext(func(baseCtx context.Context) { defer func() { diff --git a/services/pull/check.go b/services/pull/check.go index 7d93ff7a8a4b..eef5137c4c20 100644 --- a/services/pull/check.go +++ b/services/pull/check.go @@ -21,6 +21,7 @@ import ( user_model "code.gitea.io/gitea/models/user" "code.gitea.io/gitea/modules/git" "code.gitea.io/gitea/modules/gitrepo" + "code.gitea.io/gitea/modules/globallock" "code.gitea.io/gitea/modules/graceful" "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/process" @@ -334,8 +335,17 @@ func handler(items ...string) []string { } func testPR(id int64) { - pullWorkingPool.CheckIn(fmt.Sprint(id)) - defer pullWorkingPool.CheckOut(fmt.Sprint(id)) + lock := globallock.GetLock(getPullWorkingLockKey(id)) + if err := lock.Lock(); err != nil { + log.Error("lock.Lock(): %v", err) + return + } + defer func() { + if _, err := lock.Unlock(); err != nil { + log.Error("lock.Unlock: %v", err) + } + }() + ctx, _, finished := process.GetManager().AddContext(graceful.GetManager().HammerContext(), fmt.Sprintf("Test PR[%d] from patch checking queue", id)) defer finished() diff --git a/services/pull/merge.go b/services/pull/merge.go index e19292c31ca9..91743cb4bb1b 100644 --- a/services/pull/merge.go +++ b/services/pull/merge.go @@ -23,6 +23,7 @@ import ( user_model "code.gitea.io/gitea/models/user" "code.gitea.io/gitea/modules/cache" "code.gitea.io/gitea/modules/git" + "code.gitea.io/gitea/modules/globallock" "code.gitea.io/gitea/modules/httplib" "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/references" @@ -169,8 +170,16 @@ func Merge(ctx context.Context, pr *issues_model.PullRequest, doer *user_model.U return fmt.Errorf("unable to load head repo: %w", err) } - pullWorkingPool.CheckIn(fmt.Sprint(pr.ID)) - defer pullWorkingPool.CheckOut(fmt.Sprint(pr.ID)) + lock := globallock.GetLock(getPullWorkingLockKey(pr.ID)) + if err := lock.Lock(); err != nil { + log.Error("lock.Lock(): %v", err) + return fmt.Errorf("lock.Lock: %w", err) + } + defer func() { + if _, err := lock.Unlock(); err != nil { + log.Error("lock.Unlock: %v", err) + } + }() prUnit, err := pr.BaseRepo.GetUnit(ctx, unit.TypePullRequests) if err != nil { @@ -483,8 +492,16 @@ func CheckPullBranchProtections(ctx context.Context, pr *issues_model.PullReques // MergedManually mark pr as merged manually func MergedManually(ctx context.Context, pr *issues_model.PullRequest, doer *user_model.User, baseGitRepo *git.Repository, commitID string) error { - pullWorkingPool.CheckIn(fmt.Sprint(pr.ID)) - defer pullWorkingPool.CheckOut(fmt.Sprint(pr.ID)) + lock := globallock.GetLock(getPullWorkingLockKey(pr.ID)) + if err := lock.Lock(); err != nil { + log.Error("lock.Lock(): %v", err) + return fmt.Errorf("lock.Lock: %w", err) + } + defer func() { + if _, err := lock.Unlock(); err != nil { + log.Error("lock.Unlock: %v", err) + } + }() if err := db.WithTx(ctx, func(ctx context.Context) error { if err := pr.LoadBaseRepo(ctx); err != nil { diff --git a/services/pull/pull.go b/services/pull/pull.go index e69c842a2d4b..cec78bc8f4a1 100644 --- a/services/pull/pull.go +++ b/services/pull/pull.go @@ -25,20 +25,21 @@ import ( "code.gitea.io/gitea/modules/container" "code.gitea.io/gitea/modules/git" "code.gitea.io/gitea/modules/gitrepo" + "code.gitea.io/gitea/modules/globallock" "code.gitea.io/gitea/modules/graceful" "code.gitea.io/gitea/modules/json" "code.gitea.io/gitea/modules/log" repo_module "code.gitea.io/gitea/modules/repository" "code.gitea.io/gitea/modules/setting" - "code.gitea.io/gitea/modules/sync" "code.gitea.io/gitea/modules/util" gitea_context "code.gitea.io/gitea/services/context" issue_service "code.gitea.io/gitea/services/issue" notify_service "code.gitea.io/gitea/services/notify" ) -// TODO: use clustered lock (unique queue? or *abuse* cache) -var pullWorkingPool = sync.NewExclusivePool() +func getPullWorkingLockKey(prID int64) string { + return fmt.Sprintf("pull_working_%d", prID) +} // NewPullRequest creates new pull request with labels for repository. func NewPullRequest(ctx context.Context, repo *repo_model.Repository, issue *issues_model.Issue, labelIDs []int64, uuids []string, pr *issues_model.PullRequest, assigneeIDs []int64) error { @@ -202,8 +203,16 @@ func NewPullRequest(ctx context.Context, repo *repo_model.Repository, issue *iss // ChangeTargetBranch changes the target branch of this pull request, as the given user. func ChangeTargetBranch(ctx context.Context, pr *issues_model.PullRequest, doer *user_model.User, targetBranch string) (err error) { - pullWorkingPool.CheckIn(fmt.Sprint(pr.ID)) - defer pullWorkingPool.CheckOut(fmt.Sprint(pr.ID)) + lock := globallock.GetLock(getPullWorkingLockKey(pr.ID)) + if err := lock.Lock(); err != nil { + log.Error("lock.Lock(): %v", err) + return fmt.Errorf("lock.Lock: %w", err) + } + defer func() { + if _, err := lock.Unlock(); err != nil { + log.Error("lock.Unlock(): %v", err) + } + }() // Current target branch is already the same if pr.BaseBranch == targetBranch { diff --git a/services/pull/update.go b/services/pull/update.go index a7fd81421e9b..208c309d2adc 100644 --- a/services/pull/update.go +++ b/services/pull/update.go @@ -14,6 +14,7 @@ import ( "code.gitea.io/gitea/models/unit" user_model "code.gitea.io/gitea/models/user" "code.gitea.io/gitea/modules/git" + "code.gitea.io/gitea/modules/globallock" "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/repository" ) @@ -25,8 +26,16 @@ func Update(ctx context.Context, pr *issues_model.PullRequest, doer *user_model. return fmt.Errorf("update of agit flow pull request's head branch is unsupported") } - pullWorkingPool.CheckIn(fmt.Sprint(pr.ID)) - defer pullWorkingPool.CheckOut(fmt.Sprint(pr.ID)) + lock := globallock.GetLock(getPullWorkingLockKey(pr.ID)) + if err := lock.Lock(); err != nil { + log.Error("lock.Lock(): %v", err) + return fmt.Errorf("lock.Lock: %w", err) + } + defer func() { + if _, err := lock.Unlock(); err != nil { + log.Error("lock.Unlock: %v", err) + } + }() diffCount, err := GetDiverging(ctx, pr) if err != nil { diff --git a/services/repository/transfer.go b/services/repository/transfer.go index 9e0ff7ae1405..000598f56765 100644 --- a/services/repository/transfer.go +++ b/services/repository/transfer.go @@ -17,16 +17,16 @@ import ( access_model "code.gitea.io/gitea/models/perm/access" repo_model "code.gitea.io/gitea/models/repo" user_model "code.gitea.io/gitea/models/user" + "code.gitea.io/gitea/modules/globallock" "code.gitea.io/gitea/modules/log" repo_module "code.gitea.io/gitea/modules/repository" - "code.gitea.io/gitea/modules/sync" "code.gitea.io/gitea/modules/util" notify_service "code.gitea.io/gitea/services/notify" ) -// repoWorkingPool represents a working pool to order the parallel changes to the same repository -// TODO: use clustered lock (unique queue? or *abuse* cache) -var repoWorkingPool = sync.NewExclusivePool() +func getRepoWorkingLockKey(repoID int64) string { + return fmt.Sprintf("repo_working_%d", repoID) +} // TransferOwnership transfers all corresponding setting from old user to new one. func TransferOwnership(ctx context.Context, doer, newOwner *user_model.User, repo *repo_model.Repository, teams []*organization.Team) error { @@ -41,12 +41,20 @@ func TransferOwnership(ctx context.Context, doer, newOwner *user_model.User, rep oldOwner := repo.Owner - repoWorkingPool.CheckIn(fmt.Sprint(repo.ID)) + lock := globallock.GetLock(getRepoWorkingLockKey(repo.ID)) + if err := lock.Lock(); err != nil { + log.Error("lock.Lock(): %v", err) + return fmt.Errorf("lock.Lock: %w", err) + } + defer func() { + if _, err := lock.Unlock(); err != nil { + log.Error("lock.Unlock: %v", err) + } + }() + if err := transferOwnership(ctx, doer, newOwner.Name, repo); err != nil { - repoWorkingPool.CheckOut(fmt.Sprint(repo.ID)) return err } - repoWorkingPool.CheckOut(fmt.Sprint(repo.ID)) newRepo, err := repo_model.GetRepositoryByID(ctx, repo.ID) if err != nil { @@ -346,12 +354,21 @@ func ChangeRepositoryName(ctx context.Context, doer *user_model.User, repo *repo // repo so that we can atomically rename the repo path and updates the // local copy's origin accordingly. - repoWorkingPool.CheckIn(fmt.Sprint(repo.ID)) + lock := globallock.GetLock(getRepoWorkingLockKey(repo.ID)) + if err := lock.Lock(); err != nil { + log.Error("lock.Lock(): %v", err) + return fmt.Errorf("lock.Lock: %w", err) + } + + defer func() { + if _, err := lock.Unlock(); err != nil { + log.Error("lock.Unlock: %v", err) + } + }() + if err := changeRepositoryName(ctx, repo, newRepoName); err != nil { - repoWorkingPool.CheckOut(fmt.Sprint(repo.ID)) return err } - repoWorkingPool.CheckOut(fmt.Sprint(repo.ID)) repo.Name = newRepoName notify_service.RenameRepository(ctx, doer, repo, oldRepoName) diff --git a/services/wiki/wiki.go b/services/wiki/wiki.go index fdcc5feefa7e..da0cb2e06629 100644 --- a/services/wiki/wiki.go +++ b/services/wiki/wiki.go @@ -18,19 +18,20 @@ import ( user_model "code.gitea.io/gitea/models/user" "code.gitea.io/gitea/modules/git" "code.gitea.io/gitea/modules/gitrepo" + "code.gitea.io/gitea/modules/globallock" "code.gitea.io/gitea/modules/log" repo_module "code.gitea.io/gitea/modules/repository" - "code.gitea.io/gitea/modules/sync" "code.gitea.io/gitea/modules/util" asymkey_service "code.gitea.io/gitea/services/asymkey" repo_service "code.gitea.io/gitea/services/repository" ) -// TODO: use clustered lock (unique queue? or *abuse* cache) -var wikiWorkingPool = sync.NewExclusivePool() - const DefaultRemote = "origin" +func getWikiWorkingLockKey(repoID int64) string { + return fmt.Sprintf("wiki_working_%d", repoID) +} + // InitWiki initializes a wiki for repository, // it does nothing when repository already has wiki. func InitWiki(ctx context.Context, repo *repo_model.Repository) error { @@ -89,8 +90,15 @@ func updateWikiPage(ctx context.Context, doer *user_model.User, repo *repo_model if err = validateWebPath(newWikiName); err != nil { return err } - wikiWorkingPool.CheckIn(fmt.Sprint(repo.ID)) - defer wikiWorkingPool.CheckOut(fmt.Sprint(repo.ID)) + lock := globallock.GetLock(getWikiWorkingLockKey(repo.ID)) + if err := lock.Lock(); err != nil { + return err + } + defer func() { + if _, err := lock.Unlock(); err != nil { + log.Error("lock.Unlock: %v", err) + } + }() if err = InitWiki(ctx, repo); err != nil { return fmt.Errorf("InitWiki: %w", err) @@ -250,8 +258,15 @@ func DeleteWikiPage(ctx context.Context, doer *user_model.User, repo *repo_model return err } - wikiWorkingPool.CheckIn(fmt.Sprint(repo.ID)) - defer wikiWorkingPool.CheckOut(fmt.Sprint(repo.ID)) + lock := globallock.GetLock(getWikiWorkingLockKey(repo.ID)) + if err := lock.Lock(); err != nil { + return err + } + defer func() { + if _, err := lock.Unlock(); err != nil { + log.Error("lock.Unlock: %v", err) + } + }() if err = InitWiki(ctx, repo); err != nil { return fmt.Errorf("InitWiki: %w", err) From 5141395f7a04c4a0de6cde58ad60188f27cd0e94 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Sun, 18 Aug 2024 13:04:14 -0700 Subject: [PATCH 02/12] Fix go tidy --- assets/go-licenses.json | 15 +++++++++++++++ go.mod | 2 +- go.sum | 12 ++++++++++++ 3 files changed, 28 insertions(+), 1 deletion(-) diff --git a/assets/go-licenses.json b/assets/go-licenses.json index 1b6c2d9e7863..ccce3e331428 100644 --- a/assets/go-licenses.json +++ b/assets/go-licenses.json @@ -489,6 +489,11 @@ "path": "github.com/go-ldap/ldap/v3/LICENSE", "licenseText": "The MIT License (MIT)\n\nCopyright (c) 2011-2015 Michael Mitton (mmitton@gmail.com)\nPortions copyright (c) 2015-2016 go-ldap Authors\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n" }, + { + "name": "github.com/go-redsync/redsync/v4", + "path": "github.com/go-redsync/redsync/v4/LICENSE", + "licenseText": "Copyright (c) 2023, Mahmud Ridwan\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n* Redistributions of source code must retain the above copyright notice, this\n list of conditions and the following disclaimer.\n\n* Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and/or other materials provided with the distribution.\n\n* Neither the name of the Redsync nor the names of its\n contributors may be used to endorse or promote products derived from\n this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n" + }, { "name": "github.com/go-sql-driver/mysql", "path": "github.com/go-sql-driver/mysql/LICENSE", @@ -624,11 +629,21 @@ "path": "github.com/gorilla/sessions/LICENSE", "licenseText": "Copyright (c) 2023 The Gorilla Authors. All rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\n\n\t * Redistributions of source code must retain the above copyright\nnotice, this list of conditions and the following disclaimer.\n\t * Redistributions in binary form must reproduce the above\ncopyright notice, this list of conditions and the following disclaimer\nin the documentation and/or other materials provided with the\ndistribution.\n\t * Neither the name of Google Inc. nor the names of its\ncontributors may be used to endorse or promote products derived from\nthis software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\nOWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\nTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n" }, + { + "name": "github.com/hashicorp/errwrap", + "path": "github.com/hashicorp/errwrap/LICENSE", + "licenseText": "Mozilla Public License, version 2.0\n\n1. Definitions\n\n1.1. “Contributor”\n\n means each individual or legal entity that creates, contributes to the\n creation of, or owns Covered Software.\n\n1.2. “Contributor Version”\n\n means the combination of the Contributions of others (if any) used by a\n Contributor and that particular Contributor’s Contribution.\n\n1.3. “Contribution”\n\n means Covered Software of a particular Contributor.\n\n1.4. “Covered Software”\n\n means Source Code Form to which the initial Contributor has attached the\n notice in Exhibit A, the Executable Form of such Source Code Form, and\n Modifications of such Source Code Form, in each case including portions\n thereof.\n\n1.5. “Incompatible With Secondary Licenses”\n means\n\n a. that the initial Contributor has attached the notice described in\n Exhibit B to the Covered Software; or\n\n b. that the Covered Software was made available under the terms of version\n 1.1 or earlier of the License, but not also under the terms of a\n Secondary License.\n\n1.6. “Executable Form”\n\n means any form of the work other than Source Code Form.\n\n1.7. “Larger Work”\n\n means a work that combines Covered Software with other material, in a separate\n file or files, that is not Covered Software.\n\n1.8. “License”\n\n means this document.\n\n1.9. “Licensable”\n\n means having the right to grant, to the maximum extent possible, whether at the\n time of the initial grant or subsequently, any and all of the rights conveyed by\n this License.\n\n1.10. “Modifications”\n\n means any of the following:\n\n a. any file in Source Code Form that results from an addition to, deletion\n from, or modification of the contents of Covered Software; or\n\n b. any new file in Source Code Form that contains any Covered Software.\n\n1.11. “Patent Claims” of a Contributor\n\n means any patent claim(s), including without limitation, method, process,\n and apparatus claims, in any patent Licensable by such Contributor that\n would be infringed, but for the grant of the License, by the making,\n using, selling, offering for sale, having made, import, or transfer of\n either its Contributions or its Contributor Version.\n\n1.12. “Secondary License”\n\n means either the GNU General Public License, Version 2.0, the GNU Lesser\n General Public License, Version 2.1, the GNU Affero General Public\n License, Version 3.0, or any later versions of those licenses.\n\n1.13. “Source Code Form”\n\n means the form of the work preferred for making modifications.\n\n1.14. “You” (or “Your”)\n\n means an individual or a legal entity exercising rights under this\n License. For legal entities, “You” includes any entity that controls, is\n controlled by, or is under common control with You. For purposes of this\n definition, “control” means (a) the power, direct or indirect, to cause\n the direction or management of such entity, whether by contract or\n otherwise, or (b) ownership of more than fifty percent (50%) of the\n outstanding shares or beneficial ownership of such entity.\n\n\n2. License Grants and Conditions\n\n2.1. Grants\n\n Each Contributor hereby grants You a world-wide, royalty-free,\n non-exclusive license:\n\n a. under intellectual property rights (other than patent or trademark)\n Licensable by such Contributor to use, reproduce, make available,\n modify, display, perform, distribute, and otherwise exploit its\n Contributions, either on an unmodified basis, with Modifications, or as\n part of a Larger Work; and\n\n b. under Patent Claims of such Contributor to make, use, sell, offer for\n sale, have made, import, and otherwise transfer either its Contributions\n or its Contributor Version.\n\n2.2. Effective Date\n\n The licenses granted in Section 2.1 with respect to any Contribution become\n effective for each Contribution on the date the Contributor first distributes\n such Contribution.\n\n2.3. Limitations on Grant Scope\n\n The licenses granted in this Section 2 are the only rights granted under this\n License. No additional rights or licenses will be implied from the distribution\n or licensing of Covered Software under this License. Notwithstanding Section\n 2.1(b) above, no patent license is granted by a Contributor:\n\n a. for any code that a Contributor has removed from Covered Software; or\n\n b. for infringements caused by: (i) Your and any other third party’s\n modifications of Covered Software, or (ii) the combination of its\n Contributions with other software (except as part of its Contributor\n Version); or\n\n c. under Patent Claims infringed by Covered Software in the absence of its\n Contributions.\n\n This License does not grant any rights in the trademarks, service marks, or\n logos of any Contributor (except as may be necessary to comply with the\n notice requirements in Section 3.4).\n\n2.4. Subsequent Licenses\n\n No Contributor makes additional grants as a result of Your choice to\n distribute the Covered Software under a subsequent version of this License\n (see Section 10.2) or under the terms of a Secondary License (if permitted\n under the terms of Section 3.3).\n\n2.5. Representation\n\n Each Contributor represents that the Contributor believes its Contributions\n are its original creation(s) or it has sufficient rights to grant the\n rights to its Contributions conveyed by this License.\n\n2.6. Fair Use\n\n This License is not intended to limit any rights You have under applicable\n copyright doctrines of fair use, fair dealing, or other equivalents.\n\n2.7. Conditions\n\n Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in\n Section 2.1.\n\n\n3. Responsibilities\n\n3.1. Distribution of Source Form\n\n All distribution of Covered Software in Source Code Form, including any\n Modifications that You create or to which You contribute, must be under the\n terms of this License. You must inform recipients that the Source Code Form\n of the Covered Software is governed by the terms of this License, and how\n they can obtain a copy of this License. You may not attempt to alter or\n restrict the recipients’ rights in the Source Code Form.\n\n3.2. Distribution of Executable Form\n\n If You distribute Covered Software in Executable Form then:\n\n a. such Covered Software must also be made available in Source Code Form,\n as described in Section 3.1, and You must inform recipients of the\n Executable Form how they can obtain a copy of such Source Code Form by\n reasonable means in a timely manner, at a charge no more than the cost\n of distribution to the recipient; and\n\n b. You may distribute such Executable Form under the terms of this License,\n or sublicense it under different terms, provided that the license for\n the Executable Form does not attempt to limit or alter the recipients’\n rights in the Source Code Form under this License.\n\n3.3. Distribution of a Larger Work\n\n You may create and distribute a Larger Work under terms of Your choice,\n provided that You also comply with the requirements of this License for the\n Covered Software. If the Larger Work is a combination of Covered Software\n with a work governed by one or more Secondary Licenses, and the Covered\n Software is not Incompatible With Secondary Licenses, this License permits\n You to additionally distribute such Covered Software under the terms of\n such Secondary License(s), so that the recipient of the Larger Work may, at\n their option, further distribute the Covered Software under the terms of\n either this License or such Secondary License(s).\n\n3.4. Notices\n\n You may not remove or alter the substance of any license notices (including\n copyright notices, patent notices, disclaimers of warranty, or limitations\n of liability) contained within the Source Code Form of the Covered\n Software, except that You may alter any license notices to the extent\n required to remedy known factual inaccuracies.\n\n3.5. Application of Additional Terms\n\n You may choose to offer, and to charge a fee for, warranty, support,\n indemnity or liability obligations to one or more recipients of Covered\n Software. However, You may do so only on Your own behalf, and not on behalf\n of any Contributor. You must make it absolutely clear that any such\n warranty, support, indemnity, or liability obligation is offered by You\n alone, and You hereby agree to indemnify every Contributor for any\n liability incurred by such Contributor as a result of warranty, support,\n indemnity or liability terms You offer. You may include additional\n disclaimers of warranty and limitations of liability specific to any\n jurisdiction.\n\n4. Inability to Comply Due to Statute or Regulation\n\n If it is impossible for You to comply with any of the terms of this License\n with respect to some or all of the Covered Software due to statute, judicial\n order, or regulation then You must: (a) comply with the terms of this License\n to the maximum extent possible; and (b) describe the limitations and the code\n they affect. Such description must be placed in a text file included with all\n distributions of the Covered Software under this License. Except to the\n extent prohibited by statute or regulation, such description must be\n sufficiently detailed for a recipient of ordinary skill to be able to\n understand it.\n\n5. Termination\n\n5.1. The rights granted under this License will terminate automatically if You\n fail to comply with any of its terms. However, if You become compliant,\n then the rights granted under this License from a particular Contributor\n are reinstated (a) provisionally, unless and until such Contributor\n explicitly and finally terminates Your grants, and (b) on an ongoing basis,\n if such Contributor fails to notify You of the non-compliance by some\n reasonable means prior to 60 days after You have come back into compliance.\n Moreover, Your grants from a particular Contributor are reinstated on an\n ongoing basis if such Contributor notifies You of the non-compliance by\n some reasonable means, this is the first time You have received notice of\n non-compliance with this License from such Contributor, and You become\n compliant prior to 30 days after Your receipt of the notice.\n\n5.2. If You initiate litigation against any entity by asserting a patent\n infringement claim (excluding declaratory judgment actions, counter-claims,\n and cross-claims) alleging that a Contributor Version directly or\n indirectly infringes any patent, then the rights granted to You by any and\n all Contributors for the Covered Software under Section 2.1 of this License\n shall terminate.\n\n5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user\n license agreements (excluding distributors and resellers) which have been\n validly granted by You or Your distributors under this License prior to\n termination shall survive termination.\n\n6. Disclaimer of Warranty\n\n Covered Software is provided under this License on an “as is” basis, without\n warranty of any kind, either expressed, implied, or statutory, including,\n without limitation, warranties that the Covered Software is free of defects,\n merchantable, fit for a particular purpose or non-infringing. The entire\n risk as to the quality and performance of the Covered Software is with You.\n Should any Covered Software prove defective in any respect, You (not any\n Contributor) assume the cost of any necessary servicing, repair, or\n correction. This disclaimer of warranty constitutes an essential part of this\n License. No use of any Covered Software is authorized under this License\n except under this disclaimer.\n\n7. Limitation of Liability\n\n Under no circumstances and under no legal theory, whether tort (including\n negligence), contract, or otherwise, shall any Contributor, or anyone who\n distributes Covered Software as permitted above, be liable to You for any\n direct, indirect, special, incidental, or consequential damages of any\n character including, without limitation, damages for lost profits, loss of\n goodwill, work stoppage, computer failure or malfunction, or any and all\n other commercial damages or losses, even if such party shall have been\n informed of the possibility of such damages. This limitation of liability\n shall not apply to liability for death or personal injury resulting from such\n party’s negligence to the extent applicable law prohibits such limitation.\n Some jurisdictions do not allow the exclusion or limitation of incidental or\n consequential damages, so this exclusion and limitation may not apply to You.\n\n8. Litigation\n\n Any litigation relating to this License may be brought only in the courts of\n a jurisdiction where the defendant maintains its principal place of business\n and such litigation shall be governed by laws of that jurisdiction, without\n reference to its conflict-of-law provisions. Nothing in this Section shall\n prevent a party’s ability to bring cross-claims or counter-claims.\n\n9. Miscellaneous\n\n This License represents the complete agreement concerning the subject matter\n hereof. If any provision of this License is held to be unenforceable, such\n provision shall be reformed only to the extent necessary to make it\n enforceable. Any law or regulation which provides that the language of a\n contract shall be construed against the drafter shall not be used to construe\n this License against a Contributor.\n\n\n10. Versions of the License\n\n10.1. New Versions\n\n Mozilla Foundation is the license steward. Except as provided in Section\n 10.3, no one other than the license steward has the right to modify or\n publish new versions of this License. Each version will be given a\n distinguishing version number.\n\n10.2. Effect of New Versions\n\n You may distribute the Covered Software under the terms of the version of\n the License under which You originally received the Covered Software, or\n under the terms of any subsequent version published by the license\n steward.\n\n10.3. Modified Versions\n\n If you create software not governed by this License, and you want to\n create a new license for such software, you may create and use a modified\n version of this License if you rename the license and remove any\n references to the name of the license steward (except to note that such\n modified license differs from this License).\n\n10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses\n If You choose to distribute Source Code Form that is Incompatible With\n Secondary Licenses under the terms of this version of the License, the\n notice described in Exhibit B of this License must be attached.\n\nExhibit A - Source Code Form License Notice\n\n This Source Code Form is subject to the\n terms of the Mozilla Public License, v.\n 2.0. If a copy of the MPL was not\n distributed with this file, You can\n obtain one at\n http://mozilla.org/MPL/2.0/.\n\nIf it is not possible or desirable to put the notice in a particular file, then\nYou may include the notice in a location (such as a LICENSE file in a relevant\ndirectory) where a recipient would be likely to look for such a notice.\n\nYou may add additional accurate notices of copyright ownership.\n\nExhibit B - “Incompatible With Secondary Licenses” Notice\n\n This Source Code Form is “Incompatible\n With Secondary Licenses”, as defined by\n the Mozilla Public License, v. 2.0.\n\n" + }, { "name": "github.com/hashicorp/go-cleanhttp", "path": "github.com/hashicorp/go-cleanhttp/LICENSE", "licenseText": "Mozilla Public License, version 2.0\n\n1. Definitions\n\n1.1. \"Contributor\"\n\n means each individual or legal entity that creates, contributes to the\n creation of, or owns Covered Software.\n\n1.2. \"Contributor Version\"\n\n means the combination of the Contributions of others (if any) used by a\n Contributor and that particular Contributor's Contribution.\n\n1.3. \"Contribution\"\n\n means Covered Software of a particular Contributor.\n\n1.4. \"Covered Software\"\n\n means Source Code Form to which the initial Contributor has attached the\n notice in Exhibit A, the Executable Form of such Source Code Form, and\n Modifications of such Source Code Form, in each case including portions\n thereof.\n\n1.5. \"Incompatible With Secondary Licenses\"\n means\n\n a. that the initial Contributor has attached the notice described in\n Exhibit B to the Covered Software; or\n\n b. that the Covered Software was made available under the terms of\n version 1.1 or earlier of the License, but not also under the terms of\n a Secondary License.\n\n1.6. \"Executable Form\"\n\n means any form of the work other than Source Code Form.\n\n1.7. \"Larger Work\"\n\n means a work that combines Covered Software with other material, in a\n separate file or files, that is not Covered Software.\n\n1.8. \"License\"\n\n means this document.\n\n1.9. \"Licensable\"\n\n means having the right to grant, to the maximum extent possible, whether\n at the time of the initial grant or subsequently, any and all of the\n rights conveyed by this License.\n\n1.10. \"Modifications\"\n\n means any of the following:\n\n a. any file in Source Code Form that results from an addition to,\n deletion from, or modification of the contents of Covered Software; or\n\n b. any new file in Source Code Form that contains any Covered Software.\n\n1.11. \"Patent Claims\" of a Contributor\n\n means any patent claim(s), including without limitation, method,\n process, and apparatus claims, in any patent Licensable by such\n Contributor that would be infringed, but for the grant of the License,\n by the making, using, selling, offering for sale, having made, import,\n or transfer of either its Contributions or its Contributor Version.\n\n1.12. \"Secondary License\"\n\n means either the GNU General Public License, Version 2.0, the GNU Lesser\n General Public License, Version 2.1, the GNU Affero General Public\n License, Version 3.0, or any later versions of those licenses.\n\n1.13. \"Source Code Form\"\n\n means the form of the work preferred for making modifications.\n\n1.14. \"You\" (or \"Your\")\n\n means an individual or a legal entity exercising rights under this\n License. For legal entities, \"You\" includes any entity that controls, is\n controlled by, or is under common control with You. For purposes of this\n definition, \"control\" means (a) the power, direct or indirect, to cause\n the direction or management of such entity, whether by contract or\n otherwise, or (b) ownership of more than fifty percent (50%) of the\n outstanding shares or beneficial ownership of such entity.\n\n\n2. License Grants and Conditions\n\n2.1. Grants\n\n Each Contributor hereby grants You a world-wide, royalty-free,\n non-exclusive license:\n\n a. under intellectual property rights (other than patent or trademark)\n Licensable by such Contributor to use, reproduce, make available,\n modify, display, perform, distribute, and otherwise exploit its\n Contributions, either on an unmodified basis, with Modifications, or\n as part of a Larger Work; and\n\n b. under Patent Claims of such Contributor to make, use, sell, offer for\n sale, have made, import, and otherwise transfer either its\n Contributions or its Contributor Version.\n\n2.2. Effective Date\n\n The licenses granted in Section 2.1 with respect to any Contribution\n become effective for each Contribution on the date the Contributor first\n distributes such Contribution.\n\n2.3. Limitations on Grant Scope\n\n The licenses granted in this Section 2 are the only rights granted under\n this License. No additional rights or licenses will be implied from the\n distribution or licensing of Covered Software under this License.\n Notwithstanding Section 2.1(b) above, no patent license is granted by a\n Contributor:\n\n a. for any code that a Contributor has removed from Covered Software; or\n\n b. for infringements caused by: (i) Your and any other third party's\n modifications of Covered Software, or (ii) the combination of its\n Contributions with other software (except as part of its Contributor\n Version); or\n\n c. under Patent Claims infringed by Covered Software in the absence of\n its Contributions.\n\n This License does not grant any rights in the trademarks, service marks,\n or logos of any Contributor (except as may be necessary to comply with\n the notice requirements in Section 3.4).\n\n2.4. Subsequent Licenses\n\n No Contributor makes additional grants as a result of Your choice to\n distribute the Covered Software under a subsequent version of this\n License (see Section 10.2) or under the terms of a Secondary License (if\n permitted under the terms of Section 3.3).\n\n2.5. Representation\n\n Each Contributor represents that the Contributor believes its\n Contributions are its original creation(s) or it has sufficient rights to\n grant the rights to its Contributions conveyed by this License.\n\n2.6. Fair Use\n\n This License is not intended to limit any rights You have under\n applicable copyright doctrines of fair use, fair dealing, or other\n equivalents.\n\n2.7. Conditions\n\n Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in\n Section 2.1.\n\n\n3. Responsibilities\n\n3.1. Distribution of Source Form\n\n All distribution of Covered Software in Source Code Form, including any\n Modifications that You create or to which You contribute, must be under\n the terms of this License. You must inform recipients that the Source\n Code Form of the Covered Software is governed by the terms of this\n License, and how they can obtain a copy of this License. You may not\n attempt to alter or restrict the recipients' rights in the Source Code\n Form.\n\n3.2. Distribution of Executable Form\n\n If You distribute Covered Software in Executable Form then:\n\n a. such Covered Software must also be made available in Source Code Form,\n as described in Section 3.1, and You must inform recipients of the\n Executable Form how they can obtain a copy of such Source Code Form by\n reasonable means in a timely manner, at a charge no more than the cost\n of distribution to the recipient; and\n\n b. You may distribute such Executable Form under the terms of this\n License, or sublicense it under different terms, provided that the\n license for the Executable Form does not attempt to limit or alter the\n recipients' rights in the Source Code Form under this License.\n\n3.3. Distribution of a Larger Work\n\n You may create and distribute a Larger Work under terms of Your choice,\n provided that You also comply with the requirements of this License for\n the Covered Software. If the Larger Work is a combination of Covered\n Software with a work governed by one or more Secondary Licenses, and the\n Covered Software is not Incompatible With Secondary Licenses, this\n License permits You to additionally distribute such Covered Software\n under the terms of such Secondary License(s), so that the recipient of\n the Larger Work may, at their option, further distribute the Covered\n Software under the terms of either this License or such Secondary\n License(s).\n\n3.4. Notices\n\n You may not remove or alter the substance of any license notices\n (including copyright notices, patent notices, disclaimers of warranty, or\n limitations of liability) contained within the Source Code Form of the\n Covered Software, except that You may alter any license notices to the\n extent required to remedy known factual inaccuracies.\n\n3.5. Application of Additional Terms\n\n You may choose to offer, and to charge a fee for, warranty, support,\n indemnity or liability obligations to one or more recipients of Covered\n Software. However, You may do so only on Your own behalf, and not on\n behalf of any Contributor. You must make it absolutely clear that any\n such warranty, support, indemnity, or liability obligation is offered by\n You alone, and You hereby agree to indemnify every Contributor for any\n liability incurred by such Contributor as a result of warranty, support,\n indemnity or liability terms You offer. You may include additional\n disclaimers of warranty and limitations of liability specific to any\n jurisdiction.\n\n4. Inability to Comply Due to Statute or Regulation\n\n If it is impossible for You to comply with any of the terms of this License\n with respect to some or all of the Covered Software due to statute,\n judicial order, or regulation then You must: (a) comply with the terms of\n this License to the maximum extent possible; and (b) describe the\n limitations and the code they affect. Such description must be placed in a\n text file included with all distributions of the Covered Software under\n this License. Except to the extent prohibited by statute or regulation,\n such description must be sufficiently detailed for a recipient of ordinary\n skill to be able to understand it.\n\n5. Termination\n\n5.1. The rights granted under this License will terminate automatically if You\n fail to comply with any of its terms. However, if You become compliant,\n then the rights granted under this License from a particular Contributor\n are reinstated (a) provisionally, unless and until such Contributor\n explicitly and finally terminates Your grants, and (b) on an ongoing\n basis, if such Contributor fails to notify You of the non-compliance by\n some reasonable means prior to 60 days after You have come back into\n compliance. Moreover, Your grants from a particular Contributor are\n reinstated on an ongoing basis if such Contributor notifies You of the\n non-compliance by some reasonable means, this is the first time You have\n received notice of non-compliance with this License from such\n Contributor, and You become compliant prior to 30 days after Your receipt\n of the notice.\n\n5.2. If You initiate litigation against any entity by asserting a patent\n infringement claim (excluding declaratory judgment actions,\n counter-claims, and cross-claims) alleging that a Contributor Version\n directly or indirectly infringes any patent, then the rights granted to\n You by any and all Contributors for the Covered Software under Section\n 2.1 of this License shall terminate.\n\n5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user\n license agreements (excluding distributors and resellers) which have been\n validly granted by You or Your distributors under this License prior to\n termination shall survive termination.\n\n6. Disclaimer of Warranty\n\n Covered Software is provided under this License on an \"as is\" basis,\n without warranty of any kind, either expressed, implied, or statutory,\n including, without limitation, warranties that the Covered Software is free\n of defects, merchantable, fit for a particular purpose or non-infringing.\n The entire risk as to the quality and performance of the Covered Software\n is with You. Should any Covered Software prove defective in any respect,\n You (not any Contributor) assume the cost of any necessary servicing,\n repair, or correction. This disclaimer of warranty constitutes an essential\n part of this License. No use of any Covered Software is authorized under\n this License except under this disclaimer.\n\n7. Limitation of Liability\n\n Under no circumstances and under no legal theory, whether tort (including\n negligence), contract, or otherwise, shall any Contributor, or anyone who\n distributes Covered Software as permitted above, be liable to You for any\n direct, indirect, special, incidental, or consequential damages of any\n character including, without limitation, damages for lost profits, loss of\n goodwill, work stoppage, computer failure or malfunction, or any and all\n other commercial damages or losses, even if such party shall have been\n informed of the possibility of such damages. This limitation of liability\n shall not apply to liability for death or personal injury resulting from\n such party's negligence to the extent applicable law prohibits such\n limitation. Some jurisdictions do not allow the exclusion or limitation of\n incidental or consequential damages, so this exclusion and limitation may\n not apply to You.\n\n8. Litigation\n\n Any litigation relating to this License may be brought only in the courts\n of a jurisdiction where the defendant maintains its principal place of\n business and such litigation shall be governed by laws of that\n jurisdiction, without reference to its conflict-of-law provisions. Nothing\n in this Section shall prevent a party's ability to bring cross-claims or\n counter-claims.\n\n9. Miscellaneous\n\n This License represents the complete agreement concerning the subject\n matter hereof. If any provision of this License is held to be\n unenforceable, such provision shall be reformed only to the extent\n necessary to make it enforceable. Any law or regulation which provides that\n the language of a contract shall be construed against the drafter shall not\n be used to construe this License against a Contributor.\n\n\n10. Versions of the License\n\n10.1. New Versions\n\n Mozilla Foundation is the license steward. Except as provided in Section\n 10.3, no one other than the license steward has the right to modify or\n publish new versions of this License. Each version will be given a\n distinguishing version number.\n\n10.2. Effect of New Versions\n\n You may distribute the Covered Software under the terms of the version\n of the License under which You originally received the Covered Software,\n or under the terms of any subsequent version published by the license\n steward.\n\n10.3. Modified Versions\n\n If you create software not governed by this License, and you want to\n create a new license for such software, you may create and use a\n modified version of this License if you rename the license and remove\n any references to the name of the license steward (except to note that\n such modified license differs from this License).\n\n10.4. Distributing Source Code Form that is Incompatible With Secondary\n Licenses If You choose to distribute Source Code Form that is\n Incompatible With Secondary Licenses under the terms of this version of\n the License, the notice described in Exhibit B of this License must be\n attached.\n\nExhibit A - Source Code Form License Notice\n\n This Source Code Form is subject to the\n terms of the Mozilla Public License, v.\n 2.0. If a copy of the MPL was not\n distributed with this file, You can\n obtain one at\n http://mozilla.org/MPL/2.0/.\n\nIf it is not possible or desirable to put the notice in a particular file,\nthen You may include the notice in a location (such as a LICENSE file in a\nrelevant directory) where a recipient would be likely to look for such a\nnotice.\n\nYou may add additional accurate notices of copyright ownership.\n\nExhibit B - \"Incompatible With Secondary Licenses\" Notice\n\n This Source Code Form is \"Incompatible\n With Secondary Licenses\", as defined by\n the Mozilla Public License, v. 2.0.\n\n" }, + { + "name": "github.com/hashicorp/go-multierror", + "path": "github.com/hashicorp/go-multierror/LICENSE", + "licenseText": "Mozilla Public License, version 2.0\n\n1. Definitions\n\n1.1. “Contributor”\n\n means each individual or legal entity that creates, contributes to the\n creation of, or owns Covered Software.\n\n1.2. “Contributor Version”\n\n means the combination of the Contributions of others (if any) used by a\n Contributor and that particular Contributor’s Contribution.\n\n1.3. “Contribution”\n\n means Covered Software of a particular Contributor.\n\n1.4. “Covered Software”\n\n means Source Code Form to which the initial Contributor has attached the\n notice in Exhibit A, the Executable Form of such Source Code Form, and\n Modifications of such Source Code Form, in each case including portions\n thereof.\n\n1.5. “Incompatible With Secondary Licenses”\n means\n\n a. that the initial Contributor has attached the notice described in\n Exhibit B to the Covered Software; or\n\n b. that the Covered Software was made available under the terms of version\n 1.1 or earlier of the License, but not also under the terms of a\n Secondary License.\n\n1.6. “Executable Form”\n\n means any form of the work other than Source Code Form.\n\n1.7. “Larger Work”\n\n means a work that combines Covered Software with other material, in a separate\n file or files, that is not Covered Software.\n\n1.8. “License”\n\n means this document.\n\n1.9. “Licensable”\n\n means having the right to grant, to the maximum extent possible, whether at the\n time of the initial grant or subsequently, any and all of the rights conveyed by\n this License.\n\n1.10. “Modifications”\n\n means any of the following:\n\n a. any file in Source Code Form that results from an addition to, deletion\n from, or modification of the contents of Covered Software; or\n\n b. any new file in Source Code Form that contains any Covered Software.\n\n1.11. “Patent Claims” of a Contributor\n\n means any patent claim(s), including without limitation, method, process,\n and apparatus claims, in any patent Licensable by such Contributor that\n would be infringed, but for the grant of the License, by the making,\n using, selling, offering for sale, having made, import, or transfer of\n either its Contributions or its Contributor Version.\n\n1.12. “Secondary License”\n\n means either the GNU General Public License, Version 2.0, the GNU Lesser\n General Public License, Version 2.1, the GNU Affero General Public\n License, Version 3.0, or any later versions of those licenses.\n\n1.13. “Source Code Form”\n\n means the form of the work preferred for making modifications.\n\n1.14. “You” (or “Your”)\n\n means an individual or a legal entity exercising rights under this\n License. For legal entities, “You” includes any entity that controls, is\n controlled by, or is under common control with You. For purposes of this\n definition, “control” means (a) the power, direct or indirect, to cause\n the direction or management of such entity, whether by contract or\n otherwise, or (b) ownership of more than fifty percent (50%) of the\n outstanding shares or beneficial ownership of such entity.\n\n\n2. License Grants and Conditions\n\n2.1. Grants\n\n Each Contributor hereby grants You a world-wide, royalty-free,\n non-exclusive license:\n\n a. under intellectual property rights (other than patent or trademark)\n Licensable by such Contributor to use, reproduce, make available,\n modify, display, perform, distribute, and otherwise exploit its\n Contributions, either on an unmodified basis, with Modifications, or as\n part of a Larger Work; and\n\n b. under Patent Claims of such Contributor to make, use, sell, offer for\n sale, have made, import, and otherwise transfer either its Contributions\n or its Contributor Version.\n\n2.2. Effective Date\n\n The licenses granted in Section 2.1 with respect to any Contribution become\n effective for each Contribution on the date the Contributor first distributes\n such Contribution.\n\n2.3. Limitations on Grant Scope\n\n The licenses granted in this Section 2 are the only rights granted under this\n License. No additional rights or licenses will be implied from the distribution\n or licensing of Covered Software under this License. Notwithstanding Section\n 2.1(b) above, no patent license is granted by a Contributor:\n\n a. for any code that a Contributor has removed from Covered Software; or\n\n b. for infringements caused by: (i) Your and any other third party’s\n modifications of Covered Software, or (ii) the combination of its\n Contributions with other software (except as part of its Contributor\n Version); or\n\n c. under Patent Claims infringed by Covered Software in the absence of its\n Contributions.\n\n This License does not grant any rights in the trademarks, service marks, or\n logos of any Contributor (except as may be necessary to comply with the\n notice requirements in Section 3.4).\n\n2.4. Subsequent Licenses\n\n No Contributor makes additional grants as a result of Your choice to\n distribute the Covered Software under a subsequent version of this License\n (see Section 10.2) or under the terms of a Secondary License (if permitted\n under the terms of Section 3.3).\n\n2.5. Representation\n\n Each Contributor represents that the Contributor believes its Contributions\n are its original creation(s) or it has sufficient rights to grant the\n rights to its Contributions conveyed by this License.\n\n2.6. Fair Use\n\n This License is not intended to limit any rights You have under applicable\n copyright doctrines of fair use, fair dealing, or other equivalents.\n\n2.7. Conditions\n\n Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in\n Section 2.1.\n\n\n3. Responsibilities\n\n3.1. Distribution of Source Form\n\n All distribution of Covered Software in Source Code Form, including any\n Modifications that You create or to which You contribute, must be under the\n terms of this License. You must inform recipients that the Source Code Form\n of the Covered Software is governed by the terms of this License, and how\n they can obtain a copy of this License. You may not attempt to alter or\n restrict the recipients’ rights in the Source Code Form.\n\n3.2. Distribution of Executable Form\n\n If You distribute Covered Software in Executable Form then:\n\n a. such Covered Software must also be made available in Source Code Form,\n as described in Section 3.1, and You must inform recipients of the\n Executable Form how they can obtain a copy of such Source Code Form by\n reasonable means in a timely manner, at a charge no more than the cost\n of distribution to the recipient; and\n\n b. You may distribute such Executable Form under the terms of this License,\n or sublicense it under different terms, provided that the license for\n the Executable Form does not attempt to limit or alter the recipients’\n rights in the Source Code Form under this License.\n\n3.3. Distribution of a Larger Work\n\n You may create and distribute a Larger Work under terms of Your choice,\n provided that You also comply with the requirements of this License for the\n Covered Software. If the Larger Work is a combination of Covered Software\n with a work governed by one or more Secondary Licenses, and the Covered\n Software is not Incompatible With Secondary Licenses, this License permits\n You to additionally distribute such Covered Software under the terms of\n such Secondary License(s), so that the recipient of the Larger Work may, at\n their option, further distribute the Covered Software under the terms of\n either this License or such Secondary License(s).\n\n3.4. Notices\n\n You may not remove or alter the substance of any license notices (including\n copyright notices, patent notices, disclaimers of warranty, or limitations\n of liability) contained within the Source Code Form of the Covered\n Software, except that You may alter any license notices to the extent\n required to remedy known factual inaccuracies.\n\n3.5. Application of Additional Terms\n\n You may choose to offer, and to charge a fee for, warranty, support,\n indemnity or liability obligations to one or more recipients of Covered\n Software. However, You may do so only on Your own behalf, and not on behalf\n of any Contributor. You must make it absolutely clear that any such\n warranty, support, indemnity, or liability obligation is offered by You\n alone, and You hereby agree to indemnify every Contributor for any\n liability incurred by such Contributor as a result of warranty, support,\n indemnity or liability terms You offer. You may include additional\n disclaimers of warranty and limitations of liability specific to any\n jurisdiction.\n\n4. Inability to Comply Due to Statute or Regulation\n\n If it is impossible for You to comply with any of the terms of this License\n with respect to some or all of the Covered Software due to statute, judicial\n order, or regulation then You must: (a) comply with the terms of this License\n to the maximum extent possible; and (b) describe the limitations and the code\n they affect. Such description must be placed in a text file included with all\n distributions of the Covered Software under this License. Except to the\n extent prohibited by statute or regulation, such description must be\n sufficiently detailed for a recipient of ordinary skill to be able to\n understand it.\n\n5. Termination\n\n5.1. The rights granted under this License will terminate automatically if You\n fail to comply with any of its terms. However, if You become compliant,\n then the rights granted under this License from a particular Contributor\n are reinstated (a) provisionally, unless and until such Contributor\n explicitly and finally terminates Your grants, and (b) on an ongoing basis,\n if such Contributor fails to notify You of the non-compliance by some\n reasonable means prior to 60 days after You have come back into compliance.\n Moreover, Your grants from a particular Contributor are reinstated on an\n ongoing basis if such Contributor notifies You of the non-compliance by\n some reasonable means, this is the first time You have received notice of\n non-compliance with this License from such Contributor, and You become\n compliant prior to 30 days after Your receipt of the notice.\n\n5.2. If You initiate litigation against any entity by asserting a patent\n infringement claim (excluding declaratory judgment actions, counter-claims,\n and cross-claims) alleging that a Contributor Version directly or\n indirectly infringes any patent, then the rights granted to You by any and\n all Contributors for the Covered Software under Section 2.1 of this License\n shall terminate.\n\n5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user\n license agreements (excluding distributors and resellers) which have been\n validly granted by You or Your distributors under this License prior to\n termination shall survive termination.\n\n6. Disclaimer of Warranty\n\n Covered Software is provided under this License on an “as is” basis, without\n warranty of any kind, either expressed, implied, or statutory, including,\n without limitation, warranties that the Covered Software is free of defects,\n merchantable, fit for a particular purpose or non-infringing. The entire\n risk as to the quality and performance of the Covered Software is with You.\n Should any Covered Software prove defective in any respect, You (not any\n Contributor) assume the cost of any necessary servicing, repair, or\n correction. This disclaimer of warranty constitutes an essential part of this\n License. No use of any Covered Software is authorized under this License\n except under this disclaimer.\n\n7. Limitation of Liability\n\n Under no circumstances and under no legal theory, whether tort (including\n negligence), contract, or otherwise, shall any Contributor, or anyone who\n distributes Covered Software as permitted above, be liable to You for any\n direct, indirect, special, incidental, or consequential damages of any\n character including, without limitation, damages for lost profits, loss of\n goodwill, work stoppage, computer failure or malfunction, or any and all\n other commercial damages or losses, even if such party shall have been\n informed of the possibility of such damages. This limitation of liability\n shall not apply to liability for death or personal injury resulting from such\n party’s negligence to the extent applicable law prohibits such limitation.\n Some jurisdictions do not allow the exclusion or limitation of incidental or\n consequential damages, so this exclusion and limitation may not apply to You.\n\n8. Litigation\n\n Any litigation relating to this License may be brought only in the courts of\n a jurisdiction where the defendant maintains its principal place of business\n and such litigation shall be governed by laws of that jurisdiction, without\n reference to its conflict-of-law provisions. Nothing in this Section shall\n prevent a party’s ability to bring cross-claims or counter-claims.\n\n9. Miscellaneous\n\n This License represents the complete agreement concerning the subject matter\n hereof. If any provision of this License is held to be unenforceable, such\n provision shall be reformed only to the extent necessary to make it\n enforceable. Any law or regulation which provides that the language of a\n contract shall be construed against the drafter shall not be used to construe\n this License against a Contributor.\n\n\n10. Versions of the License\n\n10.1. New Versions\n\n Mozilla Foundation is the license steward. Except as provided in Section\n 10.3, no one other than the license steward has the right to modify or\n publish new versions of this License. Each version will be given a\n distinguishing version number.\n\n10.2. Effect of New Versions\n\n You may distribute the Covered Software under the terms of the version of\n the License under which You originally received the Covered Software, or\n under the terms of any subsequent version published by the license\n steward.\n\n10.3. Modified Versions\n\n If you create software not governed by this License, and you want to\n create a new license for such software, you may create and use a modified\n version of this License if you rename the license and remove any\n references to the name of the license steward (except to note that such\n modified license differs from this License).\n\n10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses\n If You choose to distribute Source Code Form that is Incompatible With\n Secondary Licenses under the terms of this version of the License, the\n notice described in Exhibit B of this License must be attached.\n\nExhibit A - Source Code Form License Notice\n\n This Source Code Form is subject to the\n terms of the Mozilla Public License, v.\n 2.0. If a copy of the MPL was not\n distributed with this file, You can\n obtain one at\n http://mozilla.org/MPL/2.0/.\n\nIf it is not possible or desirable to put the notice in a particular file, then\nYou may include the notice in a location (such as a LICENSE file in a relevant\ndirectory) where a recipient would be likely to look for such a notice.\n\nYou may add additional accurate notices of copyright ownership.\n\nExhibit B - “Incompatible With Secondary Licenses” Notice\n\n This Source Code Form is “Incompatible\n With Secondary Licenses”, as defined by\n the Mozilla Public License, v. 2.0.\n" + }, { "name": "github.com/hashicorp/go-retryablehttp", "path": "github.com/hashicorp/go-retryablehttp/LICENSE", diff --git a/go.mod b/go.mod index 1d05a1cec665..69695fa17873 100644 --- a/go.mod +++ b/go.mod @@ -49,6 +49,7 @@ require ( github.com/go-git/go-billy/v5 v5.5.0 github.com/go-git/go-git/v5 v5.12.0 github.com/go-ldap/ldap/v3 v3.4.6 + github.com/go-redsync/redsync/v4 v4.13.0 github.com/go-sql-driver/mysql v1.8.1 github.com/go-swagger/go-swagger v0.31.0 github.com/go-testfixtures/testfixtures/v3 v3.11.0 @@ -201,7 +202,6 @@ require ( github.com/go-openapi/strfmt v0.23.0 // indirect github.com/go-openapi/swag v0.23.0 // indirect github.com/go-openapi/validate v0.24.0 // indirect - github.com/go-redsync/redsync/v4 v4.13.0 // indirect github.com/go-webauthn/x v0.1.9 // indirect github.com/goccy/go-json v0.10.3 // indirect github.com/golang-jwt/jwt/v4 v4.5.0 // indirect diff --git a/go.sum b/go.sum index 0882d6be225a..510ef8479de1 100644 --- a/go.sum +++ b/go.sum @@ -342,6 +342,12 @@ github.com/go-openapi/swag v0.23.0/go.mod h1:esZ8ITTYEsH1V2trKHjAN8Ai7xHb8RV+YSZ github.com/go-openapi/validate v0.24.0 h1:LdfDKwNbpB6Vn40xhTdNZAnfLECL81w+VX3BumrGD58= github.com/go-openapi/validate v0.24.0/go.mod h1:iyeX1sEufmv3nPbBdX3ieNviWnOZaJ1+zquzJEf2BAQ= github.com/go-redis/redis v6.15.2+incompatible/go.mod h1:NAIEuMOZ/fxfXJIrKDQDz8wamY7mA7PouImQ2Jvg6kA= +github.com/go-redis/redis v6.15.9+incompatible h1:K0pv1D7EQUjfyoMql+r/jZqCLizCGKFlFgcHWWmHQjg= +github.com/go-redis/redis v6.15.9+incompatible/go.mod h1:NAIEuMOZ/fxfXJIrKDQDz8wamY7mA7PouImQ2Jvg6kA= +github.com/go-redis/redis/v7 v7.4.1 h1:PASvf36gyUpr2zdOUS/9Zqc80GbM+9BDyiJSJDDOrTI= +github.com/go-redis/redis/v7 v7.4.1/go.mod h1:JDNMw23GTyLNC4GZu9njt15ctBQVn7xjRfnwdHj/Dcg= +github.com/go-redis/redis/v8 v8.11.5 h1:AcZZR7igkdvfVmQTPnu9WE37LRrO/YrBH5zWyjDC0oI= +github.com/go-redis/redis/v8 v8.11.5/go.mod h1:gREzHqY1hg6oD9ngVRbLStwAWKhA0FEgq8Jd4h5lpwo= github.com/go-redsync/redsync/v4 v4.13.0 h1:49X6GJfnbLGaIpBBREM/zA4uIMDXKAh1NDkvQ1EkZKA= github.com/go-redsync/redsync/v4 v4.13.0/go.mod h1:HMW4Q224GZQz6x1Xc7040Yfgacukdzu7ifTDAKiyErQ= github.com/go-sql-driver/mysql v1.4.1/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w= @@ -399,6 +405,8 @@ github.com/golang/snappy v0.0.1/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEW github.com/golang/snappy v0.0.2/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= github.com/golang/snappy v0.0.4 h1:yAGX7huGHXlcLOEtBnF4w7FQwA26wojNCwOYAEhLjQM= github.com/golang/snappy v0.0.4/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/gomodule/redigo v1.8.9 h1:Sl3u+2BI/kk+VEatbj0scLdrFhjPmbxOc1myhDP41ws= +github.com/gomodule/redigo v1.8.9/go.mod h1:7ArFNvsTjH8GMMzB4uy1snslv2BwmginuMs06a1uzZE= github.com/google/btree v1.1.2 h1:xf4v41cLI2Z6FxbKm+8Bu+m8ifhj15JuZ9sa0jZCMUU= github.com/google/btree v1.1.2/go.mod h1:qOPhT0dTNdNzV6Z/lhRX0YXUafgPLFUh+gZMl761Gm4= github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= @@ -681,6 +689,8 @@ github.com/quasoft/websspi v1.1.2/go.mod h1:HmVdl939dQ0WIXZhyik+ARdI03M6bQzaSEKc github.com/rcrowley/go-metrics v0.0.0-20190826022208-cac0b30c2563/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4= github.com/redis/go-redis/v9 v9.6.0 h1:NLck+Rab3AOTHw21CGRpvQpgTrAU4sgdCswqGtlhGRA= github.com/redis/go-redis/v9 v9.6.0/go.mod h1:hdY0cQFCN4fnSYT6TkisLufl/4W5UIXyv0b/CLO2V2M= +github.com/redis/rueidis v1.0.19 h1:s65oWtotzlIFN8eMPhyYwxlwLR1lUdhza2KtWprKYSo= +github.com/redis/rueidis v1.0.19/go.mod h1:8B+r5wdnjwK3lTFml5VtxjzGOQAC+5UmujoD12pDrEo= github.com/remyoudompheng/bigfft v0.0.0-20200410134404-eec4a21b6bb0 h1:OdAsTTz6OkFY5QxjkYwrChwuRruF69c169dPK26NUlk= github.com/remyoudompheng/bigfft v0.0.0-20200410134404-eec4a21b6bb0/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= github.com/rhysd/actionlint v1.7.1 h1:WJaDzyT1StBWVKGSsZPYnbV0HF9Y9/vD6KFdZQL42qE= @@ -772,6 +782,8 @@ github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +github.com/stvp/tempredis v0.0.0-20181119212430-b82af8480203 h1:QVqDTf3h2WHt08YuiTGPZLls0Wq99X9bWd0Q5ZSBesM= +github.com/stvp/tempredis v0.0.0-20181119212430-b82af8480203/go.mod h1:oqN97ltKNihBbwlX8dLpwxCl3+HnXKV/R0e+sRLd9C8= github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8= github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU= github.com/syndtr/goleveldb v1.0.0 h1:fBdIW9lB4Iz0n9khmH8w27SJ3QEJ7+IgjPEwGSZiFdE= From b0f67104eecb41185fb9e1517ddf56a3b3434dd0 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Sun, 18 Aug 2024 15:35:07 -0700 Subject: [PATCH 03/12] Revert changes about status table --- modules/sync/status_pool.go | 57 ++++++++++++++++++++++++++++++++ modules/sync/status_pool_test.go | 31 +++++++++++++++++ services/cron/cron.go | 3 ++ services/cron/tasks.go | 12 ++----- 4 files changed, 93 insertions(+), 10 deletions(-) create mode 100644 modules/sync/status_pool.go create mode 100644 modules/sync/status_pool_test.go diff --git a/modules/sync/status_pool.go b/modules/sync/status_pool.go new file mode 100644 index 000000000000..6f075d54b79d --- /dev/null +++ b/modules/sync/status_pool.go @@ -0,0 +1,57 @@ +// Copyright 2016 The Gogs Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package sync + +import ( + "sync" + + "code.gitea.io/gitea/modules/container" +) + +// StatusTable is a table maintains true/false values. +// +// This table is particularly useful for un/marking and checking values +// in different goroutines. +type StatusTable struct { + lock sync.RWMutex + pool container.Set[string] +} + +// NewStatusTable initializes and returns a new StatusTable object. +func NewStatusTable() *StatusTable { + return &StatusTable{ + pool: make(container.Set[string]), + } +} + +// StartIfNotRunning sets value of given name to true if not already in pool. +// Returns whether set value was set to true +func (p *StatusTable) StartIfNotRunning(name string) bool { + p.lock.Lock() + added := p.pool.Add(name) + p.lock.Unlock() + return added +} + +// Start sets value of given name to true in the pool. +func (p *StatusTable) Start(name string) { + p.lock.Lock() + p.pool.Add(name) + p.lock.Unlock() +} + +// Stop sets value of given name to false in the pool. +func (p *StatusTable) Stop(name string) { + p.lock.Lock() + p.pool.Remove(name) + p.lock.Unlock() +} + +// IsRunning checks if value of given name is set to true in the pool. +func (p *StatusTable) IsRunning(name string) bool { + p.lock.RLock() + exists := p.pool.Contains(name) + p.lock.RUnlock() + return exists +} diff --git a/modules/sync/status_pool_test.go b/modules/sync/status_pool_test.go new file mode 100644 index 000000000000..e2e48862f581 --- /dev/null +++ b/modules/sync/status_pool_test.go @@ -0,0 +1,31 @@ +// Copyright 2017 The Gitea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package sync + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func Test_StatusTable(t *testing.T) { + table := NewStatusTable() + + assert.False(t, table.IsRunning("xyz")) + + table.Start("xyz") + assert.True(t, table.IsRunning("xyz")) + + assert.False(t, table.StartIfNotRunning("xyz")) + assert.True(t, table.IsRunning("xyz")) + + table.Stop("xyz") + assert.False(t, table.IsRunning("xyz")) + + assert.True(t, table.StartIfNotRunning("xyz")) + assert.True(t, table.IsRunning("xyz")) + + table.Stop("xyz") + assert.False(t, table.IsRunning("xyz")) +} diff --git a/services/cron/cron.go b/services/cron/cron.go index 1d803ed96daf..56f8012b8e59 100644 --- a/services/cron/cron.go +++ b/services/cron/cron.go @@ -11,6 +11,7 @@ import ( "code.gitea.io/gitea/modules/graceful" "code.gitea.io/gitea/modules/process" + "code.gitea.io/gitea/modules/sync" "code.gitea.io/gitea/modules/translation" "github.com/go-co-op/gocron" @@ -18,6 +19,8 @@ import ( var scheduler = gocron.NewScheduler(time.Local) +var taskStatusTable = sync.NewStatusTable() + // NewContext begins cron tasks // Each cron task is run within the shutdown context as a running server // AtShutdown the cron server is stopped diff --git a/services/cron/tasks.go b/services/cron/tasks.go index 48d1fbcd53c4..f8a7444c49e5 100644 --- a/services/cron/tasks.go +++ b/services/cron/tasks.go @@ -14,7 +14,6 @@ import ( "code.gitea.io/gitea/models/db" system_model "code.gitea.io/gitea/models/system" user_model "code.gitea.io/gitea/models/user" - "code.gitea.io/gitea/modules/globallock" "code.gitea.io/gitea/modules/graceful" "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/process" @@ -74,12 +73,7 @@ func (t *Task) Run() { // RunWithUser will run the task incrementing the cron counter at the time with User func (t *Task) RunWithUser(doer *user_model.User, config Config) { - lock := globallock.GetLock(fmt.Sprintf("cron_tasks_%s", t.Name)) - if success, err := lock.TryLock(); err != nil { - log.Error("Unable to lock cron task %s Error: %v", t.Name, err) - return - } else if !success { - // get lock failed, so that there must be another task are running. + if !taskStatusTable.StartIfNotRunning(t.Name) { return } t.lock.Lock() @@ -89,9 +83,7 @@ func (t *Task) RunWithUser(doer *user_model.User, config Config) { t.ExecTimes++ t.lock.Unlock() defer func() { - if _, err := lock.Unlock(); err != nil { - log.Error("Unable to unlock cron task %s Error: %v", t.Name, err) - } + taskStatusTable.Stop(t.Name) }() graceful.GetManager().RunWithShutdownContext(func(baseCtx context.Context) { defer func() { From 1748ba82caf9edf5182eed0267bc4188b32a7af9 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Sun, 18 Aug 2024 15:36:48 -0700 Subject: [PATCH 04/12] Revert unnecessary change --- services/cron/cron.go | 1 + 1 file changed, 1 insertion(+) diff --git a/services/cron/cron.go b/services/cron/cron.go index 56f8012b8e59..3c5737e3718f 100644 --- a/services/cron/cron.go +++ b/services/cron/cron.go @@ -19,6 +19,7 @@ import ( var scheduler = gocron.NewScheduler(time.Local) +// Prevent duplicate running tasks. var taskStatusTable = sync.NewStatusTable() // NewContext begins cron tasks From 0c3c1a324c79ba27d0b6dd5354441a421f6a9c57 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Mon, 19 Aug 2024 11:17:07 -0700 Subject: [PATCH 05/12] refactor the names and add remove locker --- modules/globallock/lock.go | 25 ++++++++++----- modules/globallock/lock_test.go | 55 ++++++++++++++++++++++++++++----- services/pull/check.go | 6 ++-- services/pull/merge.go | 12 +++---- services/pull/pull.go | 6 ++-- services/pull/update.go | 6 ++-- services/repository/transfer.go | 12 +++---- services/wiki/wiki.go | 12 +++---- 8 files changed, 91 insertions(+), 43 deletions(-) diff --git a/modules/globallock/lock.go b/modules/globallock/lock.go index 52a097e54471..a106f3c8d80f 100644 --- a/modules/globallock/lock.go +++ b/modules/globallock/lock.go @@ -16,13 +16,14 @@ import ( ) type Locker interface { - Lock() error - TryLock() (bool, error) - Unlock() (bool, error) + Lock() error // lock the resource and block until it is unlocked by the holder + TryLock() (bool, error) // try to lock the resource and return immediately, first return value indicates if the lock was successful + Unlock() (bool, error) // only lock with no error and TryLock returned true with no error can be unlocked } type LockService interface { - GetLock(name string) Locker + GetLocker(name string) Locker // create or get a locker by name, RemoveLocker should be called after the locker is no longer needed + RemoveLocker(name string) // remove a locker by name from the pool. This should be invoked affect locker is no longer needed, i.e. a pull request merged or closed } type memoryLock struct { @@ -57,11 +58,15 @@ func newMemoryLockService() *memoryLockService { } } -func (l *memoryLockService) GetLock(name string) Locker { +func (l *memoryLockService) GetLocker(name string) Locker { v, _ := l.syncMap.LoadOrStore(name, &memoryLock{}) return v.(*memoryLock) } +func (l *memoryLockService) RemoveLocker(name string) { + l.syncMap.Delete(name) +} + type redisLockService struct { rs *redsync.Redsync } @@ -86,10 +91,14 @@ type redisLock struct { mutex *redsync.Mutex } -func (r *redisLockService) GetLock(name string) Locker { +func (r *redisLockService) GetLocker(name string) Locker { return &redisLock{mutex: r.rs.NewMutex(name)} } +func (r *redisLockService) RemoveLocker(name string) { + // Do nothing +} + func (r *redisLock) Lock() error { return r.mutex.Lock() } @@ -123,6 +132,6 @@ func getLockService() LockService { return lockService } -func GetLock(name string) Locker { - return getLockService().GetLock(name) +func GetLocker(name string) Locker { + return getLockService().GetLocker(name) } diff --git a/modules/globallock/lock_test.go b/modules/globallock/lock_test.go index 0052057e460f..99b26d08aaf6 100644 --- a/modules/globallock/lock_test.go +++ b/modules/globallock/lock_test.go @@ -10,17 +10,56 @@ import ( ) func Test_Lock(t *testing.T) { - locker := GetLock("test") - assert.NoError(t, locker.Lock()) - locker.Unlock() + locker1 := GetLocker("test2") + assert.NoError(t, locker1.Lock()) + unlocked, err := locker1.Unlock() + assert.NoError(t, err) + assert.True(t, unlocked) - locked1, err1 := locker.TryLock() + locker2 := GetLocker("test2") + assert.NoError(t, locker2.Lock()) + + locked1, err1 := locker2.TryLock() + assert.NoError(t, err1) + assert.False(t, locked1) + + locker2.Unlock() + + locked2, err2 := locker2.TryLock() + assert.NoError(t, err2) + assert.True(t, locked2) + + locker2.Unlock() +} + +func Test_Lock_Redis(t *testing.T) { + if os.Getenv("CI") == "" { + t.Skip("Skip test for local development") + } + + lockService = newRedisLockService("redis://redis") + + redisPool := + locker1 := GetLocker("test1") + assert.NoError(t, locker1.Lock()) + unlocked, err := locker1.Unlock() + assert.NoError(t, err) + assert.True(t, unlocked) + + locker2 := GetLocker("test1") + assert.NoError(t, locker2.Lock()) + + locked1, err1 := locker2.TryLock() assert.NoError(t, err1) - assert.True(t, locked1) + assert.False(t, locked1) + + locker2.Unlock() - locked2, err2 := locker.TryLock() + locked2, err2 := locker2.TryLock() assert.NoError(t, err2) - assert.False(t, locked2) + assert.True(t, locked2) + + locker2.Unlock() - locker.Unlock() + redisPool.Close() } diff --git a/services/pull/check.go b/services/pull/check.go index eef5137c4c20..efc504ec07b6 100644 --- a/services/pull/check.go +++ b/services/pull/check.go @@ -335,13 +335,13 @@ func handler(items ...string) []string { } func testPR(id int64) { - lock := globallock.GetLock(getPullWorkingLockKey(id)) - if err := lock.Lock(); err != nil { + locker := globallock.GetLocker(getPullWorkingLockKey(id)) + if err := locker.Lock(); err != nil { log.Error("lock.Lock(): %v", err) return } defer func() { - if _, err := lock.Unlock(); err != nil { + if _, err := locker.Unlock(); err != nil { log.Error("lock.Unlock: %v", err) } }() diff --git a/services/pull/merge.go b/services/pull/merge.go index 91743cb4bb1b..629f94f025b7 100644 --- a/services/pull/merge.go +++ b/services/pull/merge.go @@ -170,13 +170,13 @@ func Merge(ctx context.Context, pr *issues_model.PullRequest, doer *user_model.U return fmt.Errorf("unable to load head repo: %w", err) } - lock := globallock.GetLock(getPullWorkingLockKey(pr.ID)) - if err := lock.Lock(); err != nil { + locker := globallock.GetLocker(getPullWorkingLockKey(pr.ID)) + if err := locker.Lock(); err != nil { log.Error("lock.Lock(): %v", err) return fmt.Errorf("lock.Lock: %w", err) } defer func() { - if _, err := lock.Unlock(); err != nil { + if _, err := locker.Unlock(); err != nil { log.Error("lock.Unlock: %v", err) } }() @@ -492,13 +492,13 @@ func CheckPullBranchProtections(ctx context.Context, pr *issues_model.PullReques // MergedManually mark pr as merged manually func MergedManually(ctx context.Context, pr *issues_model.PullRequest, doer *user_model.User, baseGitRepo *git.Repository, commitID string) error { - lock := globallock.GetLock(getPullWorkingLockKey(pr.ID)) - if err := lock.Lock(); err != nil { + locker := globallock.GetLocker(getPullWorkingLockKey(pr.ID)) + if err := locker.Lock(); err != nil { log.Error("lock.Lock(): %v", err) return fmt.Errorf("lock.Lock: %w", err) } defer func() { - if _, err := lock.Unlock(); err != nil { + if _, err := locker.Unlock(); err != nil { log.Error("lock.Unlock: %v", err) } }() diff --git a/services/pull/pull.go b/services/pull/pull.go index cec78bc8f4a1..9df8285af281 100644 --- a/services/pull/pull.go +++ b/services/pull/pull.go @@ -203,13 +203,13 @@ func NewPullRequest(ctx context.Context, repo *repo_model.Repository, issue *iss // ChangeTargetBranch changes the target branch of this pull request, as the given user. func ChangeTargetBranch(ctx context.Context, pr *issues_model.PullRequest, doer *user_model.User, targetBranch string) (err error) { - lock := globallock.GetLock(getPullWorkingLockKey(pr.ID)) - if err := lock.Lock(); err != nil { + locker := globallock.GetLocker(getPullWorkingLockKey(pr.ID)) + if err := locker.Lock(); err != nil { log.Error("lock.Lock(): %v", err) return fmt.Errorf("lock.Lock: %w", err) } defer func() { - if _, err := lock.Unlock(); err != nil { + if _, err := locker.Unlock(); err != nil { log.Error("lock.Unlock(): %v", err) } }() diff --git a/services/pull/update.go b/services/pull/update.go index 208c309d2adc..d1c6bd65d70b 100644 --- a/services/pull/update.go +++ b/services/pull/update.go @@ -26,13 +26,13 @@ func Update(ctx context.Context, pr *issues_model.PullRequest, doer *user_model. return fmt.Errorf("update of agit flow pull request's head branch is unsupported") } - lock := globallock.GetLock(getPullWorkingLockKey(pr.ID)) - if err := lock.Lock(); err != nil { + locker := globallock.GetLocker(getPullWorkingLockKey(pr.ID)) + if err := locker.Lock(); err != nil { log.Error("lock.Lock(): %v", err) return fmt.Errorf("lock.Lock: %w", err) } defer func() { - if _, err := lock.Unlock(); err != nil { + if _, err := locker.Unlock(); err != nil { log.Error("lock.Unlock: %v", err) } }() diff --git a/services/repository/transfer.go b/services/repository/transfer.go index e3313046945f..c1b94fb54546 100644 --- a/services/repository/transfer.go +++ b/services/repository/transfer.go @@ -42,13 +42,13 @@ func TransferOwnership(ctx context.Context, doer, newOwner *user_model.User, rep oldOwner := repo.Owner - lock := globallock.GetLock(getRepoWorkingLockKey(repo.ID)) - if err := lock.Lock(); err != nil { + locker := globallock.GetLocker(getRepoWorkingLockKey(repo.ID)) + if err := locker.Lock(); err != nil { log.Error("lock.Lock(): %v", err) return fmt.Errorf("lock.Lock: %w", err) } defer func() { - if _, err := lock.Unlock(); err != nil { + if _, err := locker.Unlock(); err != nil { log.Error("lock.Unlock: %v", err) } }() @@ -371,14 +371,14 @@ func ChangeRepositoryName(ctx context.Context, doer *user_model.User, repo *repo // repo so that we can atomically rename the repo path and updates the // local copy's origin accordingly. - lock := globallock.GetLock(getRepoWorkingLockKey(repo.ID)) - if err := lock.Lock(); err != nil { + locker := globallock.GetLocker(getRepoWorkingLockKey(repo.ID)) + if err := locker.Lock(); err != nil { log.Error("lock.Lock(): %v", err) return fmt.Errorf("lock.Lock: %w", err) } defer func() { - if _, err := lock.Unlock(); err != nil { + if _, err := locker.Unlock(); err != nil { log.Error("lock.Unlock: %v", err) } }() diff --git a/services/wiki/wiki.go b/services/wiki/wiki.go index da0cb2e06629..59f896658a79 100644 --- a/services/wiki/wiki.go +++ b/services/wiki/wiki.go @@ -90,12 +90,12 @@ func updateWikiPage(ctx context.Context, doer *user_model.User, repo *repo_model if err = validateWebPath(newWikiName); err != nil { return err } - lock := globallock.GetLock(getWikiWorkingLockKey(repo.ID)) - if err := lock.Lock(); err != nil { + locker := globallock.GetLocker(getWikiWorkingLockKey(repo.ID)) + if err := locker.Lock(); err != nil { return err } defer func() { - if _, err := lock.Unlock(); err != nil { + if _, err := locker.Unlock(); err != nil { log.Error("lock.Unlock: %v", err) } }() @@ -258,12 +258,12 @@ func DeleteWikiPage(ctx context.Context, doer *user_model.User, repo *repo_model return err } - lock := globallock.GetLock(getWikiWorkingLockKey(repo.ID)) - if err := lock.Lock(); err != nil { + locker := globallock.GetLocker(getWikiWorkingLockKey(repo.ID)) + if err := locker.Lock(); err != nil { return err } defer func() { - if _, err := lock.Unlock(); err != nil { + if _, err := locker.Unlock(); err != nil { log.Error("lock.Unlock: %v", err) } }() From 35daeceb0448774f161fb7a0e8c4c6d2e6c51634 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Mon, 26 Aug 2024 10:10:51 -0700 Subject: [PATCH 06/12] use globallock lock --- modules/globallock/lock.go | 137 -------------------------------- modules/globallock/lock_test.go | 65 --------------- services/pull/check.go | 12 +-- services/pull/merge.go | 20 ++--- services/pull/pull.go | 10 +-- services/pull/update.go | 10 +-- services/repository/transfer.go | 23 ++---- services/wiki/wiki.go | 20 ++--- 8 files changed, 29 insertions(+), 268 deletions(-) delete mode 100644 modules/globallock/lock.go delete mode 100644 modules/globallock/lock_test.go diff --git a/modules/globallock/lock.go b/modules/globallock/lock.go deleted file mode 100644 index a106f3c8d80f..000000000000 --- a/modules/globallock/lock.go +++ /dev/null @@ -1,137 +0,0 @@ -// Copyright 2023 The Gitea Authors. All rights reserved. -// SPDX-License-Identifier: MIT - -package globallock - -import ( - "context" - "sync" - "time" - - "code.gitea.io/gitea/modules/nosql" - "code.gitea.io/gitea/modules/setting" - - redsync "github.com/go-redsync/redsync/v4" - goredis "github.com/go-redsync/redsync/v4/redis/goredis/v9" -) - -type Locker interface { - Lock() error // lock the resource and block until it is unlocked by the holder - TryLock() (bool, error) // try to lock the resource and return immediately, first return value indicates if the lock was successful - Unlock() (bool, error) // only lock with no error and TryLock returned true with no error can be unlocked -} - -type LockService interface { - GetLocker(name string) Locker // create or get a locker by name, RemoveLocker should be called after the locker is no longer needed - RemoveLocker(name string) // remove a locker by name from the pool. This should be invoked affect locker is no longer needed, i.e. a pull request merged or closed -} - -type memoryLock struct { - mutex sync.Mutex -} - -func (r *memoryLock) Lock() error { - r.mutex.Lock() - return nil -} - -func (r *memoryLock) TryLock() (bool, error) { - return r.mutex.TryLock(), nil -} - -func (r *memoryLock) Unlock() (bool, error) { - r.mutex.Unlock() - return true, nil -} - -var _ Locker = &memoryLock{} - -type memoryLockService struct { - syncMap sync.Map -} - -var _ LockService = &memoryLockService{} - -func newMemoryLockService() *memoryLockService { - return &memoryLockService{ - syncMap: sync.Map{}, - } -} - -func (l *memoryLockService) GetLocker(name string) Locker { - v, _ := l.syncMap.LoadOrStore(name, &memoryLock{}) - return v.(*memoryLock) -} - -func (l *memoryLockService) RemoveLocker(name string) { - l.syncMap.Delete(name) -} - -type redisLockService struct { - rs *redsync.Redsync -} - -var _ LockService = &redisLockService{} - -func newRedisLockService(connection string) *redisLockService { - client := nosql.GetManager().GetRedisClient(connection) - - pool := goredis.NewPool(client) - - // Create an instance of redisync to be used to obtain a mutual exclusion - // lock. - rs := redsync.New(pool) - - return &redisLockService{ - rs: rs, - } -} - -type redisLock struct { - mutex *redsync.Mutex -} - -func (r *redisLockService) GetLocker(name string) Locker { - return &redisLock{mutex: r.rs.NewMutex(name)} -} - -func (r *redisLockService) RemoveLocker(name string) { - // Do nothing -} - -func (r *redisLock) Lock() error { - return r.mutex.Lock() -} - -func (r *redisLock) TryLock() (bool, error) { - ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond) - defer cancel() - if err := r.mutex.LockContext(ctx); err != nil { - return false, err - } - return true, nil -} - -func (r *redisLock) Unlock() (bool, error) { - return r.mutex.Unlock() -} - -var ( - syncOnce sync.Once - lockService LockService -) - -func getLockService() LockService { - syncOnce.Do(func() { - if setting.GlobalLock.ServiceType == "redis" { - lockService = newRedisLockService(setting.GlobalLock.ServiceConnStr) - } else { - lockService = newMemoryLockService() - } - }) - return lockService -} - -func GetLocker(name string) Locker { - return getLockService().GetLocker(name) -} diff --git a/modules/globallock/lock_test.go b/modules/globallock/lock_test.go deleted file mode 100644 index 99b26d08aaf6..000000000000 --- a/modules/globallock/lock_test.go +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright 2024 The Gitea Authors. All rights reserved. -// SPDX-License-Identifier: MIT - -package globallock - -import ( - "testing" - - "github.com/stretchr/testify/assert" -) - -func Test_Lock(t *testing.T) { - locker1 := GetLocker("test2") - assert.NoError(t, locker1.Lock()) - unlocked, err := locker1.Unlock() - assert.NoError(t, err) - assert.True(t, unlocked) - - locker2 := GetLocker("test2") - assert.NoError(t, locker2.Lock()) - - locked1, err1 := locker2.TryLock() - assert.NoError(t, err1) - assert.False(t, locked1) - - locker2.Unlock() - - locked2, err2 := locker2.TryLock() - assert.NoError(t, err2) - assert.True(t, locked2) - - locker2.Unlock() -} - -func Test_Lock_Redis(t *testing.T) { - if os.Getenv("CI") == "" { - t.Skip("Skip test for local development") - } - - lockService = newRedisLockService("redis://redis") - - redisPool := - locker1 := GetLocker("test1") - assert.NoError(t, locker1.Lock()) - unlocked, err := locker1.Unlock() - assert.NoError(t, err) - assert.True(t, unlocked) - - locker2 := GetLocker("test1") - assert.NoError(t, locker2.Lock()) - - locked1, err1 := locker2.TryLock() - assert.NoError(t, err1) - assert.False(t, locked1) - - locker2.Unlock() - - locked2, err2 := locker2.TryLock() - assert.NoError(t, err2) - assert.True(t, locked2) - - locker2.Unlock() - - redisPool.Close() -} diff --git a/services/pull/check.go b/services/pull/check.go index efc504ec07b6..9bb63f58a09c 100644 --- a/services/pull/check.go +++ b/services/pull/check.go @@ -335,18 +335,14 @@ func handler(items ...string) []string { } func testPR(id int64) { - locker := globallock.GetLocker(getPullWorkingLockKey(id)) - if err := locker.Lock(); err != nil { + ctx, releaser, err := globallock.Lock(graceful.GetManager().HammerContext(), getPullWorkingLockKey(id)) + if err != nil { log.Error("lock.Lock(): %v", err) return } - defer func() { - if _, err := locker.Unlock(); err != nil { - log.Error("lock.Unlock: %v", err) - } - }() + defer releaser() - ctx, _, finished := process.GetManager().AddContext(graceful.GetManager().HammerContext(), fmt.Sprintf("Test PR[%d] from patch checking queue", id)) + ctx, _, finished := process.GetManager().AddContext(ctx, fmt.Sprintf("Test PR[%d] from patch checking queue", id)) defer finished() pr, err := issues_model.GetPullRequestByID(ctx, id) diff --git a/services/pull/merge.go b/services/pull/merge.go index d91c06a18fd2..a69a1d3e63ab 100644 --- a/services/pull/merge.go +++ b/services/pull/merge.go @@ -170,16 +170,12 @@ func Merge(ctx context.Context, pr *issues_model.PullRequest, doer *user_model.U return fmt.Errorf("unable to load head repo: %w", err) } - locker := globallock.GetLocker(getPullWorkingLockKey(pr.ID)) - if err := locker.Lock(); err != nil { + ctx, releaser, err := globallock.Lock(ctx, getPullWorkingLockKey(pr.ID)) + if err != nil { log.Error("lock.Lock(): %v", err) return fmt.Errorf("lock.Lock: %w", err) } - defer func() { - if _, err := locker.Unlock(); err != nil { - log.Error("lock.Unlock: %v", err) - } - }() + defer releaser() prUnit, err := pr.BaseRepo.GetUnit(ctx, unit.TypePullRequests) if err != nil { @@ -496,16 +492,12 @@ func CheckPullBranchProtections(ctx context.Context, pr *issues_model.PullReques // MergedManually mark pr as merged manually func MergedManually(ctx context.Context, pr *issues_model.PullRequest, doer *user_model.User, baseGitRepo *git.Repository, commitID string) error { - locker := globallock.GetLocker(getPullWorkingLockKey(pr.ID)) - if err := locker.Lock(); err != nil { + ctx, releaser, err := globallock.Lock(ctx, getPullWorkingLockKey(pr.ID)) + if err != nil { log.Error("lock.Lock(): %v", err) return fmt.Errorf("lock.Lock: %w", err) } - defer func() { - if _, err := locker.Unlock(); err != nil { - log.Error("lock.Unlock: %v", err) - } - }() + defer releaser() if err := db.WithTx(ctx, func(ctx context.Context) error { if err := pr.LoadBaseRepo(ctx); err != nil { diff --git a/services/pull/pull.go b/services/pull/pull.go index 9df8285af281..0cbba9cf8a65 100644 --- a/services/pull/pull.go +++ b/services/pull/pull.go @@ -203,16 +203,12 @@ func NewPullRequest(ctx context.Context, repo *repo_model.Repository, issue *iss // ChangeTargetBranch changes the target branch of this pull request, as the given user. func ChangeTargetBranch(ctx context.Context, pr *issues_model.PullRequest, doer *user_model.User, targetBranch string) (err error) { - locker := globallock.GetLocker(getPullWorkingLockKey(pr.ID)) - if err := locker.Lock(); err != nil { + ctx, releaser, err := globallock.Lock(ctx, getPullWorkingLockKey(pr.ID)) + if err != nil { log.Error("lock.Lock(): %v", err) return fmt.Errorf("lock.Lock: %w", err) } - defer func() { - if _, err := locker.Unlock(); err != nil { - log.Error("lock.Unlock(): %v", err) - } - }() + defer releaser() // Current target branch is already the same if pr.BaseBranch == targetBranch { diff --git a/services/pull/update.go b/services/pull/update.go index d1c6bd65d70b..cd57f522a3cb 100644 --- a/services/pull/update.go +++ b/services/pull/update.go @@ -26,16 +26,12 @@ func Update(ctx context.Context, pr *issues_model.PullRequest, doer *user_model. return fmt.Errorf("update of agit flow pull request's head branch is unsupported") } - locker := globallock.GetLocker(getPullWorkingLockKey(pr.ID)) - if err := locker.Lock(); err != nil { + ctx, releaser, err := globallock.Lock(ctx, getPullWorkingLockKey(pr.ID)) + if err != nil { log.Error("lock.Lock(): %v", err) return fmt.Errorf("lock.Lock: %w", err) } - defer func() { - if _, err := locker.Unlock(); err != nil { - log.Error("lock.Unlock: %v", err) - } - }() + defer releaser() diffCount, err := GetDiverging(ctx, pr) if err != nil { diff --git a/services/repository/transfer.go b/services/repository/transfer.go index c1b94fb54546..597b4ebcc4a4 100644 --- a/services/repository/transfer.go +++ b/services/repository/transfer.go @@ -42,16 +42,12 @@ func TransferOwnership(ctx context.Context, doer, newOwner *user_model.User, rep oldOwner := repo.Owner - locker := globallock.GetLocker(getRepoWorkingLockKey(repo.ID)) - if err := locker.Lock(); err != nil { + ctx, releaser, err := globallock.Lock(ctx, getRepoWorkingLockKey(repo.ID)) + if err != nil { log.Error("lock.Lock(): %v", err) return fmt.Errorf("lock.Lock: %w", err) } - defer func() { - if _, err := locker.Unlock(); err != nil { - log.Error("lock.Unlock: %v", err) - } - }() + defer releaser() if err := transferOwnership(ctx, doer, newOwner.Name, repo); err != nil { return err @@ -368,20 +364,15 @@ func ChangeRepositoryName(ctx context.Context, doer *user_model.User, repo *repo oldRepoName := repo.Name // Change repository directory name. We must lock the local copy of the - // repo so that we can atomically rename the repo path and updates the + // repo so that we can automatically rename the repo path and updates the // local copy's origin accordingly. - locker := globallock.GetLocker(getRepoWorkingLockKey(repo.ID)) - if err := locker.Lock(); err != nil { + ctx, releaser, err := globallock.Lock(ctx, getRepoWorkingLockKey(repo.ID)) + if err != nil { log.Error("lock.Lock(): %v", err) return fmt.Errorf("lock.Lock: %w", err) } - - defer func() { - if _, err := locker.Unlock(); err != nil { - log.Error("lock.Unlock: %v", err) - } - }() + defer releaser() if err := changeRepositoryName(ctx, repo, newRepoName); err != nil { return err diff --git a/services/wiki/wiki.go b/services/wiki/wiki.go index 59f896658a79..f392b9bd482e 100644 --- a/services/wiki/wiki.go +++ b/services/wiki/wiki.go @@ -90,15 +90,11 @@ func updateWikiPage(ctx context.Context, doer *user_model.User, repo *repo_model if err = validateWebPath(newWikiName); err != nil { return err } - locker := globallock.GetLocker(getWikiWorkingLockKey(repo.ID)) - if err := locker.Lock(); err != nil { + ctx, releaser, err := globallock.Lock(ctx, getWikiWorkingLockKey(repo.ID)) + if err != nil { return err } - defer func() { - if _, err := locker.Unlock(); err != nil { - log.Error("lock.Unlock: %v", err) - } - }() + defer releaser() if err = InitWiki(ctx, repo); err != nil { return fmt.Errorf("InitWiki: %w", err) @@ -258,15 +254,11 @@ func DeleteWikiPage(ctx context.Context, doer *user_model.User, repo *repo_model return err } - locker := globallock.GetLocker(getWikiWorkingLockKey(repo.ID)) - if err := locker.Lock(); err != nil { + ctx, releaser, err := globallock.Lock(ctx, getWikiWorkingLockKey(repo.ID)) + if err != nil { return err } - defer func() { - if _, err := locker.Unlock(); err != nil { - log.Error("lock.Unlock: %v", err) - } - }() + defer releaser() if err = InitWiki(ctx, repo); err != nil { return fmt.Errorf("InitWiki: %w", err) From fe9efa90f86c88f38fdb15ae1a9dc309662c69f6 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Mon, 26 Aug 2024 10:26:24 -0700 Subject: [PATCH 07/12] finish the global lock init --- modules/globallock/globallock.go | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/modules/globallock/globallock.go b/modules/globallock/globallock.go index 707d169f05c6..5f69b5bf1204 100644 --- a/modules/globallock/globallock.go +++ b/modules/globallock/globallock.go @@ -6,14 +6,22 @@ package globallock import ( "context" "sync" + + "code.gitea.io/gitea/modules/setting" ) var ( defaultLocker Locker initOnce sync.Once initFunc = func() { - // TODO: read the setting and initialize the default locker. - // Before implementing this, don't use it. + switch setting.GlobalLock.ServiceType { + case "redis": + defaultLocker = NewRedisLocker(setting.GlobalLock.ServiceConnStr) + case "memory": + fallthrough + default: + defaultLocker = NewMemoryLocker() + } } // define initFunc as a variable to make it possible to change it in tests ) From 4bf86e959475873841a1554bd5a6ccc2feb7e8e5 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Mon, 26 Aug 2024 10:37:31 -0700 Subject: [PATCH 08/12] Follow the old logic --- services/repository/transfer.go | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/services/repository/transfer.go b/services/repository/transfer.go index 597b4ebcc4a4..ec644f3f3a5b 100644 --- a/services/repository/transfer.go +++ b/services/repository/transfer.go @@ -47,11 +47,12 @@ func TransferOwnership(ctx context.Context, doer, newOwner *user_model.User, rep log.Error("lock.Lock(): %v", err) return fmt.Errorf("lock.Lock: %w", err) } - defer releaser() if err := transferOwnership(ctx, doer, newOwner.Name, repo); err != nil { + releaser() return err } + releaser() newRepo, err := repo_model.GetRepositoryByID(ctx, repo.ID) if err != nil { @@ -372,11 +373,12 @@ func ChangeRepositoryName(ctx context.Context, doer *user_model.User, repo *repo log.Error("lock.Lock(): %v", err) return fmt.Errorf("lock.Lock: %w", err) } - defer releaser() if err := changeRepositoryName(ctx, repo, newRepoName); err != nil { + releaser() return err } + releaser() repo.Name = newRepoName notify_service.RenameRepository(ctx, doer, repo, oldRepoName) From 1e1d6e947e7959bf577e8d0d4c2032409e3d39a1 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Tue, 27 Aug 2024 21:15:32 -0700 Subject: [PATCH 09/12] Use lockCtx when necessary --- services/pull/merge.go | 25 +++++++++++++------------ services/repository/transfer.go | 8 ++++---- 2 files changed, 17 insertions(+), 16 deletions(-) diff --git a/services/pull/merge.go b/services/pull/merge.go index a69a1d3e63ab..f15132a37cfc 100644 --- a/services/pull/merge.go +++ b/services/pull/merge.go @@ -170,13 +170,6 @@ func Merge(ctx context.Context, pr *issues_model.PullRequest, doer *user_model.U return fmt.Errorf("unable to load head repo: %w", err) } - ctx, releaser, err := globallock.Lock(ctx, getPullWorkingLockKey(pr.ID)) - if err != nil { - log.Error("lock.Lock(): %v", err) - return fmt.Errorf("lock.Lock: %w", err) - } - defer releaser() - prUnit, err := pr.BaseRepo.GetUnit(ctx, unit.TypePullRequests) if err != nil { log.Error("pr.BaseRepo.GetUnit(unit.TypePullRequests): %v", err) @@ -189,11 +182,18 @@ func Merge(ctx context.Context, pr *issues_model.PullRequest, doer *user_model.U return models.ErrInvalidMergeStyle{ID: pr.BaseRepo.ID, Style: mergeStyle} } + lockCtx, releaser, err := globallock.Lock(ctx, getPullWorkingLockKey(pr.ID)) + if err != nil { + log.Error("lock.Lock(): %v", err) + return fmt.Errorf("lock.Lock: %w", err) + } + defer func() { go AddTestPullRequestTask(doer, pr.BaseRepo.ID, pr.BaseBranch, false, "", "") }() - _, err = doMergeAndPush(ctx, pr, doer, mergeStyle, expectedHeadCommitID, message, repo_module.PushTriggerPRMergeToBase) + _, err = doMergeAndPush(lockCtx, pr, doer, mergeStyle, expectedHeadCommitID, message, repo_module.PushTriggerPRMergeToBase) + releaser() if err != nil { return err } @@ -492,14 +492,13 @@ func CheckPullBranchProtections(ctx context.Context, pr *issues_model.PullReques // MergedManually mark pr as merged manually func MergedManually(ctx context.Context, pr *issues_model.PullRequest, doer *user_model.User, baseGitRepo *git.Repository, commitID string) error { - ctx, releaser, err := globallock.Lock(ctx, getPullWorkingLockKey(pr.ID)) + lockCtx, releaser, err := globallock.Lock(ctx, getPullWorkingLockKey(pr.ID)) if err != nil { log.Error("lock.Lock(): %v", err) return fmt.Errorf("lock.Lock: %w", err) } - defer releaser() - if err := db.WithTx(ctx, func(ctx context.Context) error { + err = db.WithTx(lockCtx, func(ctx context.Context) error { if err := pr.LoadBaseRepo(ctx); err != nil { return err } @@ -549,7 +548,9 @@ func MergedManually(ctx context.Context, pr *issues_model.PullRequest, doer *use return fmt.Errorf("SetMerged failed") } return nil - }); err != nil { + }) + releaser() + if err != nil { return err } diff --git a/services/repository/transfer.go b/services/repository/transfer.go index ec644f3f3a5b..aff900bda0dd 100644 --- a/services/repository/transfer.go +++ b/services/repository/transfer.go @@ -42,13 +42,13 @@ func TransferOwnership(ctx context.Context, doer, newOwner *user_model.User, rep oldOwner := repo.Owner - ctx, releaser, err := globallock.Lock(ctx, getRepoWorkingLockKey(repo.ID)) + lockCtx, releaser, err := globallock.Lock(ctx, getRepoWorkingLockKey(repo.ID)) if err != nil { log.Error("lock.Lock(): %v", err) return fmt.Errorf("lock.Lock: %w", err) } - if err := transferOwnership(ctx, doer, newOwner.Name, repo); err != nil { + if err := transferOwnership(lockCtx, doer, newOwner.Name, repo); err != nil { releaser() return err } @@ -368,13 +368,13 @@ func ChangeRepositoryName(ctx context.Context, doer *user_model.User, repo *repo // repo so that we can automatically rename the repo path and updates the // local copy's origin accordingly. - ctx, releaser, err := globallock.Lock(ctx, getRepoWorkingLockKey(repo.ID)) + lockCtx, releaser, err := globallock.Lock(ctx, getRepoWorkingLockKey(repo.ID)) if err != nil { log.Error("lock.Lock(): %v", err) return fmt.Errorf("lock.Lock: %w", err) } - if err := changeRepositoryName(ctx, repo, newRepoName); err != nil { + if err := changeRepositoryName(lockCtx, repo, newRepoName); err != nil { releaser() return err } From 8e09e01ef6a752b85f3686a7337862e038627e69 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Tue, 27 Aug 2024 23:35:32 -0700 Subject: [PATCH 10/12] Use correct ctx usage --- services/pull/merge.go | 12 ++++++------ services/repository/transfer.go | 12 ++++++------ 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/services/pull/merge.go b/services/pull/merge.go index f15132a37cfc..735c5e3df960 100644 --- a/services/pull/merge.go +++ b/services/pull/merge.go @@ -182,7 +182,7 @@ func Merge(ctx context.Context, pr *issues_model.PullRequest, doer *user_model.U return models.ErrInvalidMergeStyle{ID: pr.BaseRepo.ID, Style: mergeStyle} } - lockCtx, releaser, err := globallock.Lock(ctx, getPullWorkingLockKey(pr.ID)) + ctx, releaser, err := globallock.Lock(ctx, getPullWorkingLockKey(pr.ID)) if err != nil { log.Error("lock.Lock(): %v", err) return fmt.Errorf("lock.Lock: %w", err) @@ -192,8 +192,8 @@ func Merge(ctx context.Context, pr *issues_model.PullRequest, doer *user_model.U go AddTestPullRequestTask(doer, pr.BaseRepo.ID, pr.BaseBranch, false, "", "") }() - _, err = doMergeAndPush(lockCtx, pr, doer, mergeStyle, expectedHeadCommitID, message, repo_module.PushTriggerPRMergeToBase) - releaser() + _, err = doMergeAndPush(ctx, pr, doer, mergeStyle, expectedHeadCommitID, message, repo_module.PushTriggerPRMergeToBase) + ctx = releaser() if err != nil { return err } @@ -492,13 +492,13 @@ func CheckPullBranchProtections(ctx context.Context, pr *issues_model.PullReques // MergedManually mark pr as merged manually func MergedManually(ctx context.Context, pr *issues_model.PullRequest, doer *user_model.User, baseGitRepo *git.Repository, commitID string) error { - lockCtx, releaser, err := globallock.Lock(ctx, getPullWorkingLockKey(pr.ID)) + ctx, releaser, err := globallock.Lock(ctx, getPullWorkingLockKey(pr.ID)) if err != nil { log.Error("lock.Lock(): %v", err) return fmt.Errorf("lock.Lock: %w", err) } - err = db.WithTx(lockCtx, func(ctx context.Context) error { + err = db.WithTx(ctx, func(ctx context.Context) error { if err := pr.LoadBaseRepo(ctx); err != nil { return err } @@ -549,7 +549,7 @@ func MergedManually(ctx context.Context, pr *issues_model.PullRequest, doer *use } return nil }) - releaser() + ctx = releaser() if err != nil { return err } diff --git a/services/repository/transfer.go b/services/repository/transfer.go index aff900bda0dd..fa129e76c316 100644 --- a/services/repository/transfer.go +++ b/services/repository/transfer.go @@ -42,17 +42,17 @@ func TransferOwnership(ctx context.Context, doer, newOwner *user_model.User, rep oldOwner := repo.Owner - lockCtx, releaser, err := globallock.Lock(ctx, getRepoWorkingLockKey(repo.ID)) + ctx, releaser, err := globallock.Lock(ctx, getRepoWorkingLockKey(repo.ID)) if err != nil { log.Error("lock.Lock(): %v", err) return fmt.Errorf("lock.Lock: %w", err) } - if err := transferOwnership(lockCtx, doer, newOwner.Name, repo); err != nil { + if err := transferOwnership(ctx, doer, newOwner.Name, repo); err != nil { releaser() return err } - releaser() + ctx = releaser() newRepo, err := repo_model.GetRepositoryByID(ctx, repo.ID) if err != nil { @@ -368,17 +368,17 @@ func ChangeRepositoryName(ctx context.Context, doer *user_model.User, repo *repo // repo so that we can automatically rename the repo path and updates the // local copy's origin accordingly. - lockCtx, releaser, err := globallock.Lock(ctx, getRepoWorkingLockKey(repo.ID)) + ctx, releaser, err := globallock.Lock(ctx, getRepoWorkingLockKey(repo.ID)) if err != nil { log.Error("lock.Lock(): %v", err) return fmt.Errorf("lock.Lock: %w", err) } - if err := changeRepositoryName(lockCtx, repo, newRepoName); err != nil { + if err := changeRepositoryName(ctx, repo, newRepoName); err != nil { releaser() return err } - releaser() + ctx = releaser() repo.Name = newRepoName notify_service.RenameRepository(ctx, doer, repo, oldRepoName) From 860f3ec5a56177fab2cb4f0d5229e0bed952c063 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Thu, 29 Aug 2024 11:04:31 -0700 Subject: [PATCH 11/12] Follow global lock refactor --- services/pull/check.go | 3 ++- services/pull/merge.go | 8 ++++---- services/pull/pull.go | 2 +- services/pull/update.go | 2 +- services/repository/transfer.go | 8 ++++---- services/wiki/wiki.go | 4 ++-- 6 files changed, 14 insertions(+), 13 deletions(-) diff --git a/services/pull/check.go b/services/pull/check.go index 9bb63f58a09c..ce212f7d83be 100644 --- a/services/pull/check.go +++ b/services/pull/check.go @@ -335,7 +335,8 @@ func handler(items ...string) []string { } func testPR(id int64) { - ctx, releaser, err := globallock.Lock(graceful.GetManager().HammerContext(), getPullWorkingLockKey(id)) + ctx := graceful.GetManager().HammerContext() + releaser, err := globallock.Lock(ctx, getPullWorkingLockKey(id)) if err != nil { log.Error("lock.Lock(): %v", err) return diff --git a/services/pull/merge.go b/services/pull/merge.go index 735c5e3df960..f94861a14e90 100644 --- a/services/pull/merge.go +++ b/services/pull/merge.go @@ -182,7 +182,7 @@ func Merge(ctx context.Context, pr *issues_model.PullRequest, doer *user_model.U return models.ErrInvalidMergeStyle{ID: pr.BaseRepo.ID, Style: mergeStyle} } - ctx, releaser, err := globallock.Lock(ctx, getPullWorkingLockKey(pr.ID)) + releaser, err := globallock.Lock(ctx, getPullWorkingLockKey(pr.ID)) if err != nil { log.Error("lock.Lock(): %v", err) return fmt.Errorf("lock.Lock: %w", err) @@ -193,7 +193,7 @@ func Merge(ctx context.Context, pr *issues_model.PullRequest, doer *user_model.U }() _, err = doMergeAndPush(ctx, pr, doer, mergeStyle, expectedHeadCommitID, message, repo_module.PushTriggerPRMergeToBase) - ctx = releaser() + releaser() if err != nil { return err } @@ -492,7 +492,7 @@ func CheckPullBranchProtections(ctx context.Context, pr *issues_model.PullReques // MergedManually mark pr as merged manually func MergedManually(ctx context.Context, pr *issues_model.PullRequest, doer *user_model.User, baseGitRepo *git.Repository, commitID string) error { - ctx, releaser, err := globallock.Lock(ctx, getPullWorkingLockKey(pr.ID)) + releaser, err := globallock.Lock(ctx, getPullWorkingLockKey(pr.ID)) if err != nil { log.Error("lock.Lock(): %v", err) return fmt.Errorf("lock.Lock: %w", err) @@ -549,7 +549,7 @@ func MergedManually(ctx context.Context, pr *issues_model.PullRequest, doer *use } return nil }) - ctx = releaser() + releaser() if err != nil { return err } diff --git a/services/pull/pull.go b/services/pull/pull.go index 0cbba9cf8a65..154ff6c5c685 100644 --- a/services/pull/pull.go +++ b/services/pull/pull.go @@ -203,7 +203,7 @@ func NewPullRequest(ctx context.Context, repo *repo_model.Repository, issue *iss // ChangeTargetBranch changes the target branch of this pull request, as the given user. func ChangeTargetBranch(ctx context.Context, pr *issues_model.PullRequest, doer *user_model.User, targetBranch string) (err error) { - ctx, releaser, err := globallock.Lock(ctx, getPullWorkingLockKey(pr.ID)) + releaser, err := globallock.Lock(ctx, getPullWorkingLockKey(pr.ID)) if err != nil { log.Error("lock.Lock(): %v", err) return fmt.Errorf("lock.Lock: %w", err) diff --git a/services/pull/update.go b/services/pull/update.go index cd57f522a3cb..311ffc2442dc 100644 --- a/services/pull/update.go +++ b/services/pull/update.go @@ -26,7 +26,7 @@ func Update(ctx context.Context, pr *issues_model.PullRequest, doer *user_model. return fmt.Errorf("update of agit flow pull request's head branch is unsupported") } - ctx, releaser, err := globallock.Lock(ctx, getPullWorkingLockKey(pr.ID)) + releaser, err := globallock.Lock(ctx, getPullWorkingLockKey(pr.ID)) if err != nil { log.Error("lock.Lock(): %v", err) return fmt.Errorf("lock.Lock: %w", err) diff --git a/services/repository/transfer.go b/services/repository/transfer.go index fa129e76c316..b731d570eb50 100644 --- a/services/repository/transfer.go +++ b/services/repository/transfer.go @@ -42,7 +42,7 @@ func TransferOwnership(ctx context.Context, doer, newOwner *user_model.User, rep oldOwner := repo.Owner - ctx, releaser, err := globallock.Lock(ctx, getRepoWorkingLockKey(repo.ID)) + releaser, err := globallock.Lock(ctx, getRepoWorkingLockKey(repo.ID)) if err != nil { log.Error("lock.Lock(): %v", err) return fmt.Errorf("lock.Lock: %w", err) @@ -52,7 +52,7 @@ func TransferOwnership(ctx context.Context, doer, newOwner *user_model.User, rep releaser() return err } - ctx = releaser() + releaser() newRepo, err := repo_model.GetRepositoryByID(ctx, repo.ID) if err != nil { @@ -368,7 +368,7 @@ func ChangeRepositoryName(ctx context.Context, doer *user_model.User, repo *repo // repo so that we can automatically rename the repo path and updates the // local copy's origin accordingly. - ctx, releaser, err := globallock.Lock(ctx, getRepoWorkingLockKey(repo.ID)) + releaser, err := globallock.Lock(ctx, getRepoWorkingLockKey(repo.ID)) if err != nil { log.Error("lock.Lock(): %v", err) return fmt.Errorf("lock.Lock: %w", err) @@ -378,7 +378,7 @@ func ChangeRepositoryName(ctx context.Context, doer *user_model.User, repo *repo releaser() return err } - ctx = releaser() + releaser() repo.Name = newRepoName notify_service.RenameRepository(ctx, doer, repo, oldRepoName) diff --git a/services/wiki/wiki.go b/services/wiki/wiki.go index f392b9bd482e..7a0419aea7c7 100644 --- a/services/wiki/wiki.go +++ b/services/wiki/wiki.go @@ -90,7 +90,7 @@ func updateWikiPage(ctx context.Context, doer *user_model.User, repo *repo_model if err = validateWebPath(newWikiName); err != nil { return err } - ctx, releaser, err := globallock.Lock(ctx, getWikiWorkingLockKey(repo.ID)) + releaser, err := globallock.Lock(ctx, getWikiWorkingLockKey(repo.ID)) if err != nil { return err } @@ -254,7 +254,7 @@ func DeleteWikiPage(ctx context.Context, doer *user_model.User, repo *repo_model return err } - ctx, releaser, err := globallock.Lock(ctx, getWikiWorkingLockKey(repo.ID)) + releaser, err := globallock.Lock(ctx, getWikiWorkingLockKey(repo.ID)) if err != nil { return err } From aa51a8c023280bf5739cd48d4712663ab63f0602 Mon Sep 17 00:00:00 2001 From: Jason Song Date: Fri, 30 Aug 2024 10:33:45 +0800 Subject: [PATCH 12/12] fix: always defer release --- services/pull/merge.go | 3 ++- services/repository/transfer.go | 4 ++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/services/pull/merge.go b/services/pull/merge.go index f94861a14e90..a3fbe4f627b0 100644 --- a/services/pull/merge.go +++ b/services/pull/merge.go @@ -187,7 +187,7 @@ func Merge(ctx context.Context, pr *issues_model.PullRequest, doer *user_model.U log.Error("lock.Lock(): %v", err) return fmt.Errorf("lock.Lock: %w", err) } - + defer releaser() defer func() { go AddTestPullRequestTask(doer, pr.BaseRepo.ID, pr.BaseBranch, false, "", "") }() @@ -497,6 +497,7 @@ func MergedManually(ctx context.Context, pr *issues_model.PullRequest, doer *use log.Error("lock.Lock(): %v", err) return fmt.Errorf("lock.Lock: %w", err) } + defer releaser() err = db.WithTx(ctx, func(ctx context.Context) error { if err := pr.LoadBaseRepo(ctx); err != nil { diff --git a/services/repository/transfer.go b/services/repository/transfer.go index b731d570eb50..7ad6b46fa4ce 100644 --- a/services/repository/transfer.go +++ b/services/repository/transfer.go @@ -47,9 +47,9 @@ func TransferOwnership(ctx context.Context, doer, newOwner *user_model.User, rep log.Error("lock.Lock(): %v", err) return fmt.Errorf("lock.Lock: %w", err) } + defer releaser() if err := transferOwnership(ctx, doer, newOwner.Name, repo); err != nil { - releaser() return err } releaser() @@ -373,9 +373,9 @@ func ChangeRepositoryName(ctx context.Context, doer *user_model.User, repo *repo log.Error("lock.Lock(): %v", err) return fmt.Errorf("lock.Lock: %w", err) } + defer releaser() if err := changeRepositoryName(ctx, repo, newRepoName); err != nil { - releaser() return err } releaser()