cluster.go 6.4 KB

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