cluster.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. // Copyright (c) 2012 The gocql Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package gocql
  5. import (
  6. "fmt"
  7. "log"
  8. "strings"
  9. "sync"
  10. "time"
  11. )
  12. // ClusterConfig is a struct to configure the default cluster implementation
  13. // of gocoql. It has a varity of attributes that can be used to modify the
  14. // behavior to fit the most common use cases. Applications that requre a
  15. // different setup must implement their own cluster.
  16. type ClusterConfig struct {
  17. Hosts []string // addresses for the initial connections
  18. CQLVersion string // CQL version (default: 3.0.0)
  19. ProtoVersion int // version of the native protocol (default: 2)
  20. Timeout time.Duration // connection timeout (default: 200ms)
  21. DefaultPort int // default port (default: 9042)
  22. Keyspace string // initial keyspace (optional)
  23. NumConns int // number of connections per host (default: 2)
  24. NumStreams int // number of streams per connection (default: 128)
  25. DelayMin time.Duration // minimum reconnection delay (default: 1s)
  26. DelayMax time.Duration // maximum reconnection delay (default: 10min)
  27. StartupMin int // wait for StartupMin hosts (default: len(Hosts)/2+1)
  28. Consistency Consistency // default consistency level (default: Quorum)
  29. Compressor Compressor // compression algorithm (default: nil)
  30. }
  31. // NewCluster generates a new config for the default cluster implementation.
  32. func NewCluster(hosts ...string) *ClusterConfig {
  33. cfg := &ClusterConfig{
  34. Hosts: hosts,
  35. CQLVersion: "3.0.0",
  36. ProtoVersion: 2,
  37. Timeout: 200 * time.Millisecond,
  38. DefaultPort: 9042,
  39. NumConns: 2,
  40. NumStreams: 128,
  41. DelayMin: 1 * time.Second,
  42. DelayMax: 10 * time.Minute,
  43. StartupMin: len(hosts)/2 + 1,
  44. Consistency: Quorum,
  45. }
  46. return cfg
  47. }
  48. // CreateSession initializes the cluster based on this config and returns a
  49. // session object that can be used to interact with the database.
  50. func (cfg *ClusterConfig) CreateSession() *Session {
  51. impl := &clusterImpl{
  52. cfg: *cfg,
  53. hostPool: NewRoundRobin(),
  54. connPool: make(map[string]*RoundRobin),
  55. conns: make(map[*Conn]struct{}),
  56. quitWait: make(chan bool),
  57. }
  58. impl.wgStart.Add(1)
  59. for i := 0; i < len(impl.cfg.Hosts); i++ {
  60. addr := strings.TrimSpace(impl.cfg.Hosts[i])
  61. if strings.IndexByte(addr, ':') < 0 {
  62. addr = fmt.Sprintf("%s:%d", addr, impl.cfg.DefaultPort)
  63. }
  64. for j := 0; j < impl.cfg.NumConns; j++ {
  65. go impl.connect(addr)
  66. }
  67. }
  68. impl.wgStart.Wait()
  69. return NewSession(impl)
  70. }
  71. type clusterImpl struct {
  72. cfg ClusterConfig
  73. hostPool *RoundRobin
  74. connPool map[string]*RoundRobin
  75. conns map[*Conn]struct{}
  76. keyspace string
  77. mu sync.Mutex
  78. started bool
  79. wgStart sync.WaitGroup
  80. quit bool
  81. quitWait chan bool
  82. quitOnce sync.Once
  83. }
  84. func (c *clusterImpl) connect(addr string) {
  85. cfg := ConnConfig{
  86. ProtoVersion: c.cfg.ProtoVersion,
  87. CQLVersion: c.cfg.CQLVersion,
  88. Timeout: c.cfg.Timeout,
  89. NumStreams: c.cfg.NumStreams,
  90. Compressor: c.cfg.Compressor,
  91. }
  92. delay := c.cfg.DelayMin
  93. for {
  94. conn, err := Connect(addr, cfg, c)
  95. if err != nil {
  96. log.Printf("failed to connect to %q: %v", addr, err)
  97. select {
  98. case <-time.After(delay):
  99. if delay *= 2; delay > c.cfg.DelayMax {
  100. delay = c.cfg.DelayMax
  101. }
  102. continue
  103. case <-c.quitWait:
  104. return
  105. }
  106. }
  107. c.addConn(conn, "")
  108. return
  109. }
  110. }
  111. func (c *clusterImpl) changeKeyspace(conn *Conn, keyspace string, connected bool) {
  112. if err := conn.UseKeyspace(keyspace); err != nil {
  113. conn.Close()
  114. if connected {
  115. c.removeConn(conn)
  116. }
  117. go c.connect(conn.Address())
  118. }
  119. if !connected {
  120. c.addConn(conn, keyspace)
  121. }
  122. }
  123. func (c *clusterImpl) addConn(conn *Conn, keyspace string) {
  124. c.mu.Lock()
  125. defer c.mu.Unlock()
  126. if c.quit {
  127. conn.Close()
  128. return
  129. }
  130. if keyspace != c.keyspace && c.keyspace != "" {
  131. // change the keyspace before adding the node to the pool
  132. go c.changeKeyspace(conn, c.keyspace, false)
  133. return
  134. }
  135. connPool := c.connPool[conn.Address()]
  136. if connPool == nil {
  137. connPool = NewRoundRobin()
  138. c.connPool[conn.Address()] = connPool
  139. c.hostPool.AddNode(connPool)
  140. if !c.started && c.hostPool.Size() >= c.cfg.StartupMin {
  141. c.started = true
  142. c.wgStart.Done()
  143. }
  144. }
  145. connPool.AddNode(conn)
  146. c.conns[conn] = struct{}{}
  147. }
  148. func (c *clusterImpl) removeConn(conn *Conn) {
  149. c.mu.Lock()
  150. defer c.mu.Unlock()
  151. conn.Close()
  152. connPool := c.connPool[conn.addr]
  153. if connPool == nil {
  154. return
  155. }
  156. connPool.RemoveNode(conn)
  157. if connPool.Size() == 0 {
  158. c.hostPool.RemoveNode(connPool)
  159. }
  160. delete(c.conns, conn)
  161. }
  162. func (c *clusterImpl) HandleError(conn *Conn, err error, closed bool) {
  163. if !closed {
  164. // ignore all non-fatal errors
  165. return
  166. }
  167. c.removeConn(conn)
  168. go c.connect(conn.Address()) // reconnect
  169. }
  170. func (c *clusterImpl) HandleKeyspace(conn *Conn, keyspace string) {
  171. c.mu.Lock()
  172. if c.keyspace == keyspace {
  173. c.mu.Unlock()
  174. return
  175. }
  176. c.keyspace = keyspace
  177. conns := make([]*Conn, 0, len(c.conns))
  178. for conn := range c.conns {
  179. conns = append(conns, conn)
  180. }
  181. c.mu.Unlock()
  182. // change the keyspace of all other connections too
  183. for i := 0; i < len(conns); i++ {
  184. if conns[i] == conn {
  185. continue
  186. }
  187. c.changeKeyspace(conns[i], keyspace, true)
  188. }
  189. }
  190. func (c *clusterImpl) Pick(qry *Query) *Conn {
  191. return c.hostPool.Pick(qry)
  192. }
  193. func (c *clusterImpl) Close() {
  194. c.quitOnce.Do(func() {
  195. c.mu.Lock()
  196. defer c.mu.Unlock()
  197. c.quit = true
  198. close(c.quitWait)
  199. for conn := range c.conns {
  200. conn.Close()
  201. }
  202. })
  203. }