cluster.go 5.5 KB

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