cluster.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  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) changeKeyspace(conn *Conn, keyspace string, connected bool) {
  133. if err := conn.UseKeyspace(keyspace); err != nil {
  134. conn.Close()
  135. if connected {
  136. c.removeConn(conn)
  137. }
  138. go c.connect(conn.Address())
  139. }
  140. if !connected {
  141. c.addConn(conn, keyspace)
  142. }
  143. }
  144. func (c *clusterImpl) addConn(conn *Conn, keyspace string) {
  145. c.mu.Lock()
  146. defer c.mu.Unlock()
  147. if c.quit {
  148. conn.Close()
  149. return
  150. }
  151. if keyspace != c.keyspace && c.keyspace != "" {
  152. // change the keyspace before adding the node to the pool
  153. go c.changeKeyspace(conn, c.keyspace, false)
  154. return
  155. }
  156. connPool := c.connPool[conn.Address()]
  157. if connPool == nil {
  158. connPool = NewRoundRobin()
  159. c.connPool[conn.Address()] = connPool
  160. c.hostPool.AddNode(connPool)
  161. if !c.started && c.hostPool.Size() >= c.cfg.StartupMin {
  162. c.started = true
  163. c.cStart <- 1
  164. }
  165. }
  166. connPool.AddNode(conn)
  167. c.conns[conn] = struct{}{}
  168. }
  169. func (c *clusterImpl) removeConn(conn *Conn) {
  170. c.mu.Lock()
  171. defer c.mu.Unlock()
  172. conn.Close()
  173. connPool := c.connPool[conn.addr]
  174. if connPool == nil {
  175. return
  176. }
  177. connPool.RemoveNode(conn)
  178. if connPool.Size() == 0 {
  179. c.hostPool.RemoveNode(connPool)
  180. delete(c.connPool, conn.addr)
  181. }
  182. delete(c.conns, conn)
  183. }
  184. func (c *clusterImpl) HandleError(conn *Conn, err error, closed bool) {
  185. if !closed {
  186. // ignore all non-fatal errors
  187. return
  188. }
  189. c.removeConn(conn)
  190. if !c.quit {
  191. go c.connect(conn.Address()) // reconnect
  192. }
  193. }
  194. func (c *clusterImpl) HandleKeyspace(conn *Conn, keyspace string) {
  195. c.mu.Lock()
  196. if c.keyspace == keyspace {
  197. c.mu.Unlock()
  198. return
  199. }
  200. c.keyspace = keyspace
  201. conns := make([]*Conn, 0, len(c.conns))
  202. for conn := range c.conns {
  203. conns = append(conns, conn)
  204. }
  205. c.mu.Unlock()
  206. // change the keyspace of all other connections too
  207. for i := 0; i < len(conns); i++ {
  208. if conns[i] == conn {
  209. continue
  210. }
  211. c.changeKeyspace(conns[i], keyspace, true)
  212. }
  213. }
  214. func (c *clusterImpl) Pick(qry *Query) *Conn {
  215. return c.hostPool.Pick(qry)
  216. }
  217. func (c *clusterImpl) Close() {
  218. c.quitOnce.Do(func() {
  219. c.mu.Lock()
  220. defer c.mu.Unlock()
  221. c.quit = true
  222. close(c.quitWait)
  223. for conn := range c.conns {
  224. conn.Close()
  225. }
  226. })
  227. }
  228. var (
  229. ErrNoHosts = errors.New("no hosts provided")
  230. ErrNoConnections = errors.New("no connections were made in startup time frame")
  231. )