vitess.io/vitess@v0.16.2/go/pools/refresh_pool.go (about) 1 /* 2 Copyright 2022 The Vitess Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package pools 18 19 import ( 20 "sync" 21 "time" 22 23 "vitess.io/vitess/go/vt/log" 24 ) 25 26 type ( 27 // RefreshCheck is a function used to determine if a resource pool should be 28 // refreshed (i.e. closed and reopened) 29 RefreshCheck func() (bool, error) 30 31 // poolRefresh refreshes the pool by calling the RefreshCheck function. 32 // If the RefreshCheck returns true, the pool is closed and reopened. 33 poolRefresh struct { 34 refreshCheck RefreshCheck 35 refreshInterval time.Duration 36 refreshTicker *time.Ticker 37 refreshStop chan struct{} 38 refreshWg sync.WaitGroup 39 40 pool refreshPool 41 } 42 ) 43 44 type refreshPool interface { 45 // reopen drains and reopens the connection pool 46 reopen() 47 48 // closeIdleResources scans the pool for idle resources and closes them. 49 closeIdleResources() 50 } 51 52 func newPoolRefresh(pool refreshPool, refreshCheck RefreshCheck, refreshInterval time.Duration) *poolRefresh { 53 if refreshCheck == nil || refreshInterval <= 0 { 54 return nil 55 } 56 return &poolRefresh{ 57 pool: pool, 58 refreshInterval: refreshInterval, 59 refreshCheck: refreshCheck, 60 } 61 } 62 63 func (pr *poolRefresh) startRefreshTicker() { 64 if pr == nil { 65 return 66 } 67 pr.refreshTicker = time.NewTicker(pr.refreshInterval) 68 pr.refreshStop = make(chan struct{}) 69 pr.refreshWg.Add(1) 70 go func() { 71 defer pr.refreshWg.Done() 72 for { 73 select { 74 case <-pr.refreshTicker.C: 75 val, err := pr.refreshCheck() 76 if err != nil { 77 log.Info(err) 78 } 79 if val { 80 go pr.pool.reopen() 81 return 82 } 83 case <-pr.refreshStop: 84 return 85 } 86 } 87 }() 88 } 89 90 func (pr *poolRefresh) stop() { 91 if pr == nil || pr.refreshTicker == nil { 92 return 93 } 94 pr.refreshTicker.Stop() 95 close(pr.refreshStop) 96 pr.refreshWg.Wait() 97 }