cluster.go 5.9 KB

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