github.com/erda-project/erda-infra@v1.0.9/providers/cassandra/session.go (about) 1 // Copyright (c) 2021 Terminus, Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package cassandra 16 17 import ( 18 "sync" 19 "time" 20 21 "github.com/erda-project/erda-infra/base/logs" 22 "github.com/gocql/gocql" 23 ) 24 25 // ReconnectionConfig . 26 type ReconnectionConfig struct { 27 Enable bool `file:"enable" default:"true"` 28 CheckInterval time.Duration `file:"check_interval" default:"10m"` 29 CheckTimeout time.Duration `file:"check_timeout" default:"60s"` 30 } 31 32 // Session manager of gocql.Session. 33 type Session struct { 34 session *gocql.Session 35 mu sync.RWMutex 36 log logs.Logger 37 done chan struct{} 38 } 39 40 // Session get gocql.Session. 41 func (s *Session) Session() *gocql.Session { 42 s.mu.RLock() 43 defer s.mu.RUnlock() 44 return s.session 45 } 46 47 // Close . 48 func (s *Session) Close() { 49 close(s.done) 50 } 51 52 func (s *Session) updateSession(gs *gocql.Session) { 53 s.mu.Lock() 54 defer s.mu.Unlock() 55 s.session = gs 56 } 57 58 func (s *Session) checkAndReconnect(p *provider, cfg *SessionConfig) { 59 log := s.log.Sub("reconnection") 60 log.Infof("start to check connection every %s, timeout %s", cfg.Reconnection.CheckInterval, cfg.Reconnection.CheckTimeout) 61 ticker := time.NewTicker(cfg.Reconnection.CheckInterval) 62 defer ticker.Stop() 63 64 for { 65 if s.Session().Closed() { 66 break 67 } 68 select { 69 case <-s.done: 70 s.log.Infof("done signal trigger") 71 return 72 case <-ticker.C: 73 err := s.Session().Query("SELECT cql_version FROM system.local").Exec() 74 if err != nil { 75 newSession, err := p.newSession(cfg.Keyspace.Name, cfg.Consistency) 76 if err != nil { 77 log.Errorf("new session failed: %s", err) 78 continue 79 } 80 s.updateSession(newSession) 81 } 82 } 83 } 84 }