cluster.go 6.0 KB

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