cluster.go 6.0 KB

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