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