|
| 1 | +/* |
| 2 | + * Licensed to the Apache Software Foundation (ASF) under one or more |
| 3 | + * contributor license agreements. See the NOTICE file distributed with |
| 4 | + * this work for additional information regarding copyright ownership. |
| 5 | + * The ASF licenses this file to You under the Apache License, Version 2.0 |
| 6 | + * (the "License"); you may not use this file except in compliance with |
| 7 | + * the License. You may obtain a copy of the License at |
| 8 | + * |
| 9 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | + * |
| 11 | + * Unless required by applicable law or agreed to in writing, software |
| 12 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | + * See the License for the specific language governing permissions and |
| 15 | + * limitations under the License. |
| 16 | + */ |
| 17 | + |
| 18 | +package dbcommon |
| 19 | + |
| 20 | +import ( |
| 21 | + "database/sql" |
| 22 | + "fmt" |
| 23 | + "sync" |
| 24 | + "time" |
| 25 | + |
| 26 | + "gorm.io/gorm" |
| 27 | + |
| 28 | + storecfg "github.com/apache/dubbo-admin/pkg/config/store" |
| 29 | + "github.com/apache/dubbo-admin/pkg/core/logger" |
| 30 | +) |
| 31 | + |
| 32 | +var ( |
| 33 | + // pools stores all connection pools indexed by a unique key (storeType:address) |
| 34 | + pools = make(map[string]*ConnectionPool) |
| 35 | + // poolsMutex protects concurrent access to the pools map |
| 36 | + poolsMutex sync.RWMutex |
| 37 | +) |
| 38 | + |
| 39 | +// ConnectionPoolConfig defines connection pool configuration |
| 40 | +type ConnectionPoolConfig struct { |
| 41 | + MaxIdleConns int // Maximum number of idle connections |
| 42 | + MaxOpenConns int // Maximum number of open connections |
| 43 | + ConnMaxLifetime time.Duration // Maximum lifetime of a connection |
| 44 | + ConnMaxIdleTime time.Duration // Maximum idle time of a connection |
| 45 | +} |
| 46 | + |
| 47 | +// ConnectionPool manages database connections with connection pooling |
| 48 | +type ConnectionPool struct { |
| 49 | + db *gorm.DB |
| 50 | + sqlDB *sql.DB |
| 51 | + address string |
| 52 | + storeType storecfg.Type |
| 53 | + mu sync.RWMutex |
| 54 | + refCount int // Reference counter for the number of stores using this pool |
| 55 | + closeOnce sync.Once // Ensure Close is called only once |
| 56 | + closed bool // Track if the pool is closed |
| 57 | +} |
| 58 | + |
| 59 | +// GetOrCreatePool returns or creates a connection pool for the given store type and address |
| 60 | +// It implements a singleton pattern with reference counting to allow pool reuse across multiple stores |
| 61 | +// If a pool already exists for the same storeType and address, it increments the reference count and returns the existing pool |
| 62 | +// Otherwise, it creates a new pool with the provided dialector |
| 63 | +func GetOrCreatePool(dialector gorm.Dialector, storeType storecfg.Type, address string, config *ConnectionPoolConfig) (*ConnectionPool, error) { |
| 64 | + if storeType == storecfg.Memory { |
| 65 | + return nil, fmt.Errorf("memory pool store is no need to create connection pool") |
| 66 | + } |
| 67 | + |
| 68 | + poolKey := fmt.Sprintf("%s:%s", storeType, address) |
| 69 | + |
| 70 | + poolsMutex.Lock() |
| 71 | + defer poolsMutex.Unlock() |
| 72 | + |
| 73 | + // Check if pool already exists |
| 74 | + if existingPool, exists := pools[poolKey]; exists { |
| 75 | + // Increment reference count when reusing existing pool |
| 76 | + existingPool.refCount++ |
| 77 | + logger.Infof("Reusing %s connection pool: address=%s, refCount=%d", storeType, address, existingPool.refCount) |
| 78 | + return existingPool, nil |
| 79 | + } |
| 80 | + |
| 81 | + // Create new pool |
| 82 | + if config == nil { |
| 83 | + config = DefaultConnectionPoolConfig() |
| 84 | + } |
| 85 | + |
| 86 | + pool, err := NewConnectionPool(dialector, storeType, address, config) |
| 87 | + if err != nil { |
| 88 | + return nil, err |
| 89 | + } |
| 90 | + |
| 91 | + // Store the pool |
| 92 | + pools[poolKey] = pool |
| 93 | + logger.Infof("%s connection pool created successfully: address=%s, maxIdleConns=%d, maxOpenConns=%d", |
| 94 | + storeType, address, config.MaxIdleConns, config.MaxOpenConns) |
| 95 | + |
| 96 | + return pool, nil |
| 97 | +} |
| 98 | + |
| 99 | +// RemovePool removes a pool from the global registry |
| 100 | +// This should only be called when the pool's reference count reaches zero |
| 101 | +func RemovePool(storeType storecfg.Type, address string) { |
| 102 | + poolKey := fmt.Sprintf("%s:%s", storeType, address) |
| 103 | + |
| 104 | + poolsMutex.Lock() |
| 105 | + defer poolsMutex.Unlock() |
| 106 | + |
| 107 | + delete(pools, poolKey) |
| 108 | + logger.Infof("Removed %s connection pool from registry: address=%s", storeType, address) |
| 109 | +} |
| 110 | + |
| 111 | +// DefaultConnectionPoolConfig returns default connection pool configuration |
| 112 | +func DefaultConnectionPoolConfig() *ConnectionPoolConfig { |
| 113 | + return &ConnectionPoolConfig{ |
| 114 | + MaxIdleConns: 10, // Default: 10 idle connections |
| 115 | + MaxOpenConns: 100, // Default: 100 max open connections |
| 116 | + ConnMaxLifetime: time.Hour, // Default: 1 hour max lifetime |
| 117 | + ConnMaxIdleTime: 10 * time.Minute, // Default: 10 minutes max idle time |
| 118 | + } |
| 119 | +} |
| 120 | + |
| 121 | +// NewConnectionPool creates a new connection pool |
| 122 | +func NewConnectionPool(dialector gorm.Dialector, storeType storecfg.Type, address string, config *ConnectionPoolConfig) (*ConnectionPool, error) { |
| 123 | + db, err := gorm.Open(dialector, &gorm.Config{}) |
| 124 | + if err != nil { |
| 125 | + return nil, fmt.Errorf("failed to connect to %s: %w", storeType, err) |
| 126 | + } |
| 127 | + |
| 128 | + sqlDB, err := db.DB() |
| 129 | + if err != nil { |
| 130 | + return nil, fmt.Errorf("failed to get underlying sql.DB: %w", err) |
| 131 | + } |
| 132 | + |
| 133 | + // Configure connection pool |
| 134 | + sqlDB.SetMaxIdleConns(config.MaxIdleConns) |
| 135 | + sqlDB.SetMaxOpenConns(config.MaxOpenConns) |
| 136 | + sqlDB.SetConnMaxLifetime(config.ConnMaxLifetime) |
| 137 | + sqlDB.SetConnMaxIdleTime(config.ConnMaxIdleTime) |
| 138 | + |
| 139 | + return &ConnectionPool{ |
| 140 | + db: db, |
| 141 | + sqlDB: sqlDB, |
| 142 | + address: address, |
| 143 | + storeType: storeType, |
| 144 | + refCount: 1, // Initial reference count |
| 145 | + }, nil |
| 146 | +} |
| 147 | + |
| 148 | +// GetDB returns the gorm.DB instance |
| 149 | +func (p *ConnectionPool) GetDB() *gorm.DB { |
| 150 | + p.mu.RLock() |
| 151 | + defer p.mu.RUnlock() |
| 152 | + return p.db |
| 153 | +} |
| 154 | + |
| 155 | +// Address returns the connection address |
| 156 | +func (p *ConnectionPool) Address() string { |
| 157 | + p.mu.RLock() |
| 158 | + defer p.mu.RUnlock() |
| 159 | + return p.address |
| 160 | +} |
| 161 | + |
| 162 | +// RefCount returns the current reference count |
| 163 | +func (p *ConnectionPool) RefCount() int { |
| 164 | + p.mu.RLock() |
| 165 | + defer p.mu.RUnlock() |
| 166 | + return p.refCount |
| 167 | +} |
| 168 | + |
| 169 | +// IncrementRef increments the reference count |
| 170 | +func (p *ConnectionPool) IncrementRef() { |
| 171 | + p.mu.Lock() |
| 172 | + defer p.mu.Unlock() |
| 173 | + p.refCount++ |
| 174 | +} |
| 175 | + |
| 176 | +// Close closes the connection pool gracefully with reference counting |
| 177 | +// The pool is only actually closed when refCount reaches 0 |
| 178 | +func (p *ConnectionPool) Close() error { |
| 179 | + p.mu.Lock() |
| 180 | + defer p.mu.Unlock() |
| 181 | + |
| 182 | + if p.closed { |
| 183 | + return nil // Already closed |
| 184 | + } |
| 185 | + |
| 186 | + p.refCount-- |
| 187 | + logger.Infof("Decremented %s connection pool refCount: address=%s, refCount=%d", p.storeType, p.address, p.refCount) |
| 188 | + |
| 189 | + // Only close the pool when no stores are using it |
| 190 | + if p.refCount <= 0 { |
| 191 | + var closeErr error |
| 192 | + p.closeOnce.Do(func() { |
| 193 | + if p.sqlDB != nil { |
| 194 | + logger.Infof("Closing %s connection pool: address=%s", p.storeType, p.address) |
| 195 | + closeErr = p.sqlDB.Close() |
| 196 | + p.closed = true |
| 197 | + } |
| 198 | + RemovePool(p.storeType, p.address) |
| 199 | + }) |
| 200 | + return closeErr |
| 201 | + } |
| 202 | + |
| 203 | + return nil |
| 204 | +} |
| 205 | + |
| 206 | +// Ping checks if the database connection is alive |
| 207 | +func (p *ConnectionPool) Ping() error { |
| 208 | + p.mu.RLock() |
| 209 | + defer p.mu.RUnlock() |
| 210 | + |
| 211 | + if p.sqlDB != nil { |
| 212 | + return p.sqlDB.Ping() |
| 213 | + } |
| 214 | + return fmt.Errorf("connection pool not initialized") |
| 215 | +} |
| 216 | + |
| 217 | +// Stats returns database connection pool statistics |
| 218 | +func (p *ConnectionPool) Stats() sql.DBStats { |
| 219 | + p.mu.RLock() |
| 220 | + defer p.mu.RUnlock() |
| 221 | + |
| 222 | + if p.sqlDB != nil { |
| 223 | + return p.sqlDB.Stats() |
| 224 | + } |
| 225 | + return sql.DBStats{} |
| 226 | +} |
0 commit comments