cluster.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  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. keyspace: cfg.Keyspace,
  58. }
  59. impl.wgStart.Add(1)
  60. for i := 0; i < len(impl.cfg.Hosts); i++ {
  61. addr := strings.TrimSpace(impl.cfg.Hosts[i])
  62. if strings.Index(addr, ":") < 0 {
  63. addr = fmt.Sprintf("%s:%d", addr, impl.cfg.DefaultPort)
  64. }
  65. for j := 0; j < impl.cfg.NumConns; j++ {
  66. go impl.connect(addr)
  67. }
  68. }
  69. impl.wgStart.Wait()
  70. s := NewSession(impl)
  71. s.SetConsistency(cfg.Consistency)
  72. return s
  73. }
  74. type clusterImpl struct {
  75. cfg ClusterConfig
  76. hostPool *RoundRobin
  77. connPool map[string]*RoundRobin
  78. conns map[*Conn]struct{}
  79. keyspace string
  80. mu sync.Mutex
  81. started bool
  82. wgStart sync.WaitGroup
  83. quit bool
  84. quitWait chan bool
  85. quitOnce sync.Once
  86. }
  87. func (c *clusterImpl) connect(addr string) {
  88. cfg := ConnConfig{
  89. ProtoVersion: c.cfg.ProtoVersion,
  90. CQLVersion: c.cfg.CQLVersion,
  91. Timeout: c.cfg.Timeout,
  92. NumStreams: c.cfg.NumStreams,
  93. Compressor: c.cfg.Compressor,
  94. }
  95. delay := c.cfg.DelayMin
  96. for {
  97. conn, err := Connect(addr, cfg, c)
  98. if err != nil {
  99. log.Printf("failed to connect to %q: %v", addr, err)
  100. select {
  101. case <-time.After(delay):
  102. if delay *= 2; delay > c.cfg.DelayMax {
  103. delay = c.cfg.DelayMax
  104. }
  105. continue
  106. case <-c.quitWait:
  107. return
  108. }
  109. }
  110. c.addConn(conn, "")
  111. return
  112. }
  113. }
  114. func (c *clusterImpl) changeKeyspace(conn *Conn, keyspace string, connected bool) {
  115. if err := conn.UseKeyspace(keyspace); err != nil {
  116. conn.Close()
  117. if connected {
  118. c.removeConn(conn)
  119. }
  120. go c.connect(conn.Address())
  121. }
  122. if !connected {
  123. c.addConn(conn, keyspace)
  124. }
  125. }
  126. func (c *clusterImpl) addConn(conn *Conn, keyspace string) {
  127. c.mu.Lock()
  128. defer c.mu.Unlock()
  129. if c.quit {
  130. conn.Close()
  131. return
  132. }
  133. if keyspace != c.keyspace && c.keyspace != "" {
  134. // change the keyspace before adding the node to the pool
  135. go c.changeKeyspace(conn, c.keyspace, false)
  136. return
  137. }
  138. connPool := c.connPool[conn.Address()]
  139. if connPool == nil {
  140. connPool = NewRoundRobin()
  141. c.connPool[conn.Address()] = connPool
  142. c.hostPool.AddNode(connPool)
  143. if !c.started && c.hostPool.Size() >= c.cfg.StartupMin {
  144. c.started = true
  145. c.wgStart.Done()
  146. }
  147. }
  148. connPool.AddNode(conn)
  149. c.conns[conn] = struct{}{}
  150. }
  151. func (c *clusterImpl) removeConn(conn *Conn) {
  152. c.mu.Lock()
  153. defer c.mu.Unlock()
  154. conn.Close()
  155. connPool := c.connPool[conn.addr]
  156. if connPool == nil {
  157. return
  158. }
  159. connPool.RemoveNode(conn)
  160. if connPool.Size() == 0 {
  161. c.hostPool.RemoveNode(connPool)
  162. }
  163. delete(c.conns, conn)
  164. }
  165. func (c *clusterImpl) HandleError(conn *Conn, err error, closed bool) {
  166. if !closed {
  167. // ignore all non-fatal errors
  168. return
  169. }
  170. c.removeConn(conn)
  171. if !c.quit {
  172. go c.connect(conn.Address()) // reconnect
  173. }
  174. }
  175. func (c *clusterImpl) HandleKeyspace(conn *Conn, keyspace string) {
  176. c.mu.Lock()
  177. if c.keyspace == keyspace {
  178. c.mu.Unlock()
  179. return
  180. }
  181. c.keyspace = keyspace
  182. conns := make([]*Conn, 0, len(c.conns))
  183. for conn := range c.conns {
  184. conns = append(conns, conn)
  185. }
  186. c.mu.Unlock()
  187. // change the keyspace of all other connections too
  188. for i := 0; i < len(conns); i++ {
  189. if conns[i] == conn {
  190. continue
  191. }
  192. c.changeKeyspace(conns[i], keyspace, true)
  193. }
  194. }
  195. func (c *clusterImpl) Pick(qry *Query) *Conn {
  196. return c.hostPool.Pick(qry)
  197. }
  198. func (c *clusterImpl) Close() {
  199. c.quitOnce.Do(func() {
  200. c.mu.Lock()
  201. defer c.mu.Unlock()
  202. c.quit = true
  203. close(c.quitWait)
  204. for conn := range c.conns {
  205. conn.Close()
  206. }
  207. })
  208. }