Skip to content

Commit 37face9

Browse files
committed
fix
1 parent 97cc033 commit 37face9

File tree

10 files changed

+519
-86
lines changed

10 files changed

+519
-86
lines changed

pkg/console/service/condition_rule.go

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,6 @@ func updateConditionRuleUnsafe(ctx context.Context, name string, res *meshresour
9696
logger.Warnf("update %s condition failed with error: %s", name, err.Error())
9797
return err
9898
}
99-
logger.Infof("Condition route %s updated successfully", name)
10099
return nil
101100
}
102101

@@ -114,7 +113,6 @@ func CreateConditionRule(ctx context.Context, name string, res *meshresource.Con
114113
})
115114
}
116115

117-
// createConditionRuleUnsafe performs the actual creation without lock protection
118116
func createConditionRuleUnsafe(ctx context.Context, name string, res *meshresource.ConditionRouteResource) error {
119117
if err := ctx.ResourceManager().Add(res); err != nil {
120118
logger.Warnf("create %s condition failed with error: %s", name, err.Error())

pkg/console/service/configurator_rule.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -95,7 +95,7 @@ func DeleteConfigurator(ctx consolectx.Context, name string, mesh string) error
9595

9696
return lock.WithLock(ctx.AppContext(), lockKey, lockTimeout, func() error {
9797
if err := ctx.ResourceManager().DeleteByKey(meshresource.DynamicConfigKind, coremodel.BuildResourceKey(mesh, name)); err != nil {
98-
logger.Warnf("delete %s configurator failed with error: %s", name, err.Error())
98+
logger.Warnf("delete %s configurator failed with error: %s", name, err.Error())
9999
return err
100100
}
101101
return nil

pkg/console/service/tag_rule.go

Lines changed: 13 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -18,10 +18,8 @@
1818
package service
1919

2020
import (
21-
"fmt"
22-
"time"
23-
2421
consolectx "github.com/apache/dubbo-admin/pkg/console/context"
22+
"github.com/apache/dubbo-admin/pkg/core/lock"
2523
"github.com/apache/dubbo-admin/pkg/core/logger"
2624
"github.com/apache/dubbo-admin/pkg/core/manager"
2725
meshresource "github.com/apache/dubbo-admin/pkg/core/resource/apis/mesh/v1alpha1"
@@ -41,15 +39,14 @@ func GetTagRule(ctx consolectx.Context, name string, mesh string) (*meshresource
4139
}
4240

4341
func UpdateTagRule(ctx consolectx.Context, res *meshresource.TagRouteResource) error {
44-
lock := ctx.LockManager()
45-
if lock == nil {
42+
lockMgr := ctx.LockManager()
43+
if lockMgr == nil {
4644
return updateTagRuleUnsafe(ctx, res)
4745
}
4846

49-
lockKey := fmt.Sprintf("tag_route:%s:%s", res.Mesh, res.Name)
50-
lockTimeout := 30 * time.Second
47+
lockKey := lock.BuildTagRouteLockKey(res.Mesh, res.Name)
5148

52-
return lock.WithLock(ctx.AppContext(), lockKey, lockTimeout, func() error {
49+
return lockMgr.WithLock(ctx.AppContext(), lockKey, lock.DefaultLockTimeout, func() error {
5350
return updateTagRuleUnsafe(ctx, res)
5451
})
5552
}
@@ -64,15 +61,14 @@ func updateTagRuleUnsafe(ctx consolectx.Context, res *meshresource.TagRouteResou
6461
}
6562

6663
func CreateTagRule(ctx consolectx.Context, res *meshresource.TagRouteResource) error {
67-
lock := ctx.LockManager()
68-
if lock == nil {
64+
lockMgr := ctx.LockManager()
65+
if lockMgr == nil {
6966
return createTagRuleUnsafe(ctx, res)
7067
}
7168

72-
lockKey := fmt.Sprintf("tag_route:%s:%s", res.Mesh, res.Name)
73-
lockTimeout := 30 * time.Second
69+
lockKey := lock.BuildTagRouteLockKey(res.Mesh, res.Name)
7470

75-
return lock.WithLock(ctx.AppContext(), lockKey, lockTimeout, func() error {
71+
return lockMgr.WithLock(ctx.AppContext(), lockKey, lock.DefaultLockTimeout, func() error {
7672
return createTagRuleUnsafe(ctx, res)
7773
})
7874
}
@@ -87,15 +83,14 @@ func createTagRuleUnsafe(ctx consolectx.Context, res *meshresource.TagRouteResou
8783
}
8884

8985
func DeleteTagRule(ctx consolectx.Context, name string, mesh string) error {
90-
lock := ctx.LockManager()
91-
if lock == nil {
86+
lockMgr := ctx.LockManager()
87+
if lockMgr == nil {
9288
return ctx.ResourceManager().DeleteByKey(meshresource.TagRouteKind, coremodel.BuildResourceKey(mesh, name))
9389
}
9490

95-
lockKey := fmt.Sprintf("tag_route:%s:%s", mesh, name)
96-
lockTimeout := 30 * time.Second
91+
lockKey := lock.BuildTagRouteLockKey(mesh, name)
9792

98-
return lock.WithLock(ctx.AppContext(), lockKey, lockTimeout, func() error {
93+
return lockMgr.WithLock(ctx.AppContext(), lockKey, lock.DefaultLockTimeout, func() error {
9994
err := ctx.ResourceManager().DeleteByKey(meshresource.TagRouteKind, coremodel.BuildResourceKey(mesh, name))
10095
if err != nil {
10196
logger.Warnf("delete tag rule %s error: %v", name, err)

pkg/core/bootstrap/bootstrap.go

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -45,8 +45,7 @@ func Bootstrap(appCtx context.Context, cfg app.AdminConfig) (runtime.Runtime, er
4545
}
4646
// 2. initialize distributed lock
4747
if err := initDistributedLock(builder); err != nil {
48-
// Don't fail bootstrap if lock initialization fails
49-
logger.Warnf("Failed to initialize distributed lock: %v", err)
48+
return nil, errors.Wrap(err, "failed to initialize distributed lock")
5049
}
5150
// 3. initialize discovery
5251
if err := initializeResourceDiscovery(builder); err != nil {
@@ -94,6 +93,15 @@ func initResourceStore(cfg app.AdminConfig, builder *runtime.Builder) error {
9493
}
9594
return initAndActivateComponent(builder, comp)
9695
}
96+
97+
func initDistributedLock(builder *runtime.Builder) error {
98+
comp, err := runtime.ComponentRegistry().Get(lock.DistributedLockComponent)
99+
if err != nil {
100+
return err
101+
}
102+
return initAndActivateComponent(builder, comp)
103+
}
104+
97105
func initResourceManager(builder *runtime.Builder) error {
98106
comp, err := runtime.ComponentRegistry().ResourceManager()
99107
if err != nil {
@@ -153,10 +161,3 @@ func initAndActivateComponent(builder *runtime.Builder, comp runtime.Component)
153161
}
154162
return nil
155163
}
156-
func initDistributedLock(builder *runtime.Builder) error {
157-
comp, err := runtime.ComponentRegistry().Get(lock.DistributedLockComponent)
158-
if err != nil {
159-
return err
160-
}
161-
return initAndActivateComponent(builder, comp)
162-
}

pkg/core/lock/component.go

Lines changed: 21 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -19,13 +19,14 @@ package lock
1919

2020
import (
2121
"context"
22+
"gorm.io/gorm"
23+
"math"
2224
"time"
2325

2426
"github.com/pkg/errors"
2527

2628
"github.com/apache/dubbo-admin/pkg/core/logger"
2729
"github.com/apache/dubbo-admin/pkg/core/runtime"
28-
"github.com/apache/dubbo-admin/pkg/store/dbcommon"
2930
)
3031

3132
const (
@@ -49,48 +50,47 @@ func (c *Component) Type() runtime.ComponentType {
4950
}
5051

5152
// Order indicates the initialization order
52-
// Lock should be initialized after Store (Order 100) but before other services
53+
// Lock should be initialized after Store (Order math.MaxInt - 1)
54+
// Higher order values are initialized first, so we use math.MaxInt - 2
5355
func (c *Component) Order() int {
54-
return 90 // After Store, before Console
56+
return math.MaxInt - 2 // After Store, before other services
5557
}
5658

5759
// Init initializes the distributed lock component
5860
func (c *Component) Init(ctx runtime.BuilderContext) error {
59-
// Get the store component to access connection pool
61+
// Get the store component to access database connection
6062
storeComp, err := ctx.GetActivatedComponent(runtime.ResourceStore)
6163
if err != nil {
6264
return err
6365
}
6466

65-
// Try to extract connection pool from store component
66-
// We need to use type assertion with the proper interface
67-
type ConnectionPoolProvider interface {
68-
GetConnectionPool() *dbcommon.ConnectionPool
67+
// Try to extract database connection from store component
68+
// We use GetDB() interface to avoid circular dependency with dbcommon package
69+
type DBProvider interface {
70+
GetDB() *gorm.DB
6971
}
7072

71-
storeWithPool, ok := storeComp.(ConnectionPoolProvider)
73+
storeWithDB, ok := storeComp.(DBProvider)
7274
if !ok {
73-
// For memory store or other stores without connection pool
74-
logger.Warnf("Store component does not provide connection pool, distributed lock will not be available")
75+
// For memory store or other stores without database
76+
logger.Warnf("Store component does not provide database connection, distributed lock will not be available")
7577
return nil
7678
}
7779

78-
pool := storeWithPool.GetConnectionPool()
79-
if pool == nil {
80-
logger.Warnf("Connection pool is nil, distributed lock will not be available")
80+
db := storeWithDB.GetDB()
81+
if db == nil {
82+
logger.Warnf("Database connection is nil, distributed lock will not be available")
8183
return nil
8284
}
8385

84-
// Create GORM-based lock implementation using NewGormLock
85-
c.lock = NewGormLock(pool)
86+
// Create GORM-based lock implementation using NewGormLockFromDB
87+
c.lock = NewGormLockFromDB(db)
8688

8789
// Initialize the lock table
88-
db := pool.GetDB()
8990
if err := db.AutoMigrate(&LockRecord{}); err != nil {
9091
return errors.Wrap(err, "failed to migrate lock table")
9192
}
9293

93-
logger.Info("Distributed lock component initialized successfully")
9494
return nil
9595
}
9696

@@ -102,20 +102,17 @@ func (c *Component) Start(rt runtime.Runtime, stop <-chan struct{}) error {
102102
}
103103

104104
// Start background cleanup task
105-
ticker := time.NewTicker(5 * time.Minute) // Cleanup every 5 minutes
105+
ticker := time.NewTicker(DefaultCleanupInterval) // Cleanup every 5 minutes
106106
defer ticker.Stop()
107107

108-
logger.Info("Distributed lock cleanup task started")
109-
110108
for {
111109
select {
112110
case <-stop:
113-
logger.Info("Distributed lock cleanup task stopped")
114111
return nil
115112
case <-ticker.C:
116-
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
113+
ctx, cancel := context.WithTimeout(context.Background(), DefaultCleanupTimeout)
117114
if err := c.lock.CleanupExpiredLocks(ctx); err != nil {
118-
logger.Errorf("Failed to cleanup expired locks: %v", err)
115+
logger.Errorf("Failed to cleanup expired locks: %v", err)
119116
}
120117
cancel()
121118
}
@@ -136,7 +133,6 @@ func GetLockFromRuntime(rt runtime.Runtime) (Lock, error) {
136133

137134
lockComp, ok := comp.(*Component)
138135
if !ok {
139-
// 修正:使用标准错误处理
140136
return nil, errors.Errorf("component %s is not a valid lock component", DistributedLockComponent)
141137
}
142138

pkg/core/lock/const.go

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package lock
2+
3+
import "time"
4+
5+
const (
6+
// DefaultLockTimeout is the default timeout for distributed lock operations
7+
// This timeout applies to lock acquisition, renewal, and release operations
8+
DefaultLockTimeout = 30 * time.Second
9+
10+
// DefaultAutoRenewThreshold is the TTL threshold above which auto-renewal is enabled
11+
// Locks with TTL longer than this value will be automatically renewed
12+
DefaultAutoRenewThreshold = 10 * time.Second
13+
14+
// DefaultUnlockTimeout is the timeout for unlock operations in deferred cleanup
15+
DefaultUnlockTimeout = 5 * time.Second
16+
17+
// DefaultRenewTimeout is the timeout for lock renewal operations
18+
DefaultRenewTimeout = 5 * time.Second
19+
20+
// DefaultLockRetryInterval is the interval between lock acquisition retry attempts
21+
DefaultLockRetryInterval = 100 * time.Millisecond
22+
23+
// DefaultCleanupInterval is the interval for periodic expired lock cleanup
24+
DefaultCleanupInterval = 5 * time.Minute
25+
26+
// DefaultCleanupTimeout is the timeout for cleanup operations
27+
DefaultCleanupTimeout = 30 * time.Second
28+
)
29+
30+
// Lock key prefixes for different resource types
31+
const (
32+
// TagRouteKeyPrefix is the prefix for tag route lock keys
33+
TagRouteKeyPrefix = "tag_route"
34+
35+
// ConfiguratorRuleKeyPrefix is the prefix for configurator rule lock keys
36+
ConfiguratorRuleKeyPrefix = "configurator_rule"
37+
38+
// ConditionRuleKeyPrefix is the prefix for condition rule lock keys
39+
ConditionRuleKeyPrefix = "condition_rule"
40+
)

0 commit comments

Comments
 (0)