cluster.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  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. "log"
  8. "strings"
  9. "sync"
  10. "time"
  11. "errors"
  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 cfg.Hosts == nil {
  54. return nil,ErrNoHosts
  55. } else 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. }
  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. }
  170. delete(c.conns, conn)
  171. }
  172. func (c *clusterImpl) HandleError(conn *Conn, err error, closed bool) {
  173. if !closed {
  174. // ignore all non-fatal errors
  175. return
  176. }
  177. c.removeConn(conn)
  178. if !c.quit {
  179. go c.connect(conn.Address()) // reconnect
  180. }
  181. }
  182. func (c *clusterImpl) HandleKeyspace(conn *Conn, keyspace string) {
  183. c.mu.Lock()
  184. if c.keyspace == keyspace {
  185. c.mu.Unlock()
  186. return
  187. }
  188. c.keyspace = keyspace
  189. conns := make([]*Conn, 0, len(c.conns))
  190. for conn := range c.conns {
  191. conns = append(conns, conn)
  192. }
  193. c.mu.Unlock()
  194. // change the keyspace of all other connections too
  195. for i := 0; i < len(conns); i++ {
  196. if conns[i] == conn {
  197. continue
  198. }
  199. c.changeKeyspace(conns[i], keyspace, true)
  200. }
  201. }
  202. func (c *clusterImpl) Pick(qry *Query) *Conn {
  203. return c.hostPool.Pick(qry)
  204. }
  205. func (c *clusterImpl) Close() {
  206. c.quitOnce.Do(func() {
  207. c.mu.Lock()
  208. defer c.mu.Unlock()
  209. c.quit = true
  210. close(c.quitWait)
  211. for conn := range c.conns {
  212. conn.Close()
  213. }
  214. })
  215. }
  216. var (
  217. ErrNoHosts = errors.New("no hosts provided")
  218. )