cluster.go 5.7 KB

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