cluster.go 5.5 KB

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