cluster.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  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. impl.Close()
  86. return nil, ErrNoConnections
  87. }
  88. }
  89. type clusterImpl struct {
  90. cfg ClusterConfig
  91. hostPool *RoundRobin
  92. connPool map[string]*RoundRobin
  93. conns map[*Conn]struct{}
  94. keyspace string
  95. mu sync.Mutex
  96. started bool
  97. cStart chan int
  98. quit bool
  99. quitWait chan bool
  100. quitOnce sync.Once
  101. }
  102. func (c *clusterImpl) connect(addr string) {
  103. cfg := ConnConfig{
  104. ProtoVersion: c.cfg.ProtoVersion,
  105. CQLVersion: c.cfg.CQLVersion,
  106. Timeout: c.cfg.Timeout,
  107. NumStreams: c.cfg.NumStreams,
  108. Compressor: c.cfg.Compressor,
  109. Authenticator: c.cfg.Authenticator,
  110. }
  111. delay := c.cfg.DelayMin
  112. for {
  113. conn, err := Connect(addr, cfg, c)
  114. if err != nil {
  115. log.Printf("failed to connect to %q: %v", addr, err)
  116. select {
  117. case <-time.After(delay):
  118. if delay *= 2; delay > c.cfg.DelayMax {
  119. delay = c.cfg.DelayMax
  120. }
  121. continue
  122. case <-c.quitWait:
  123. return
  124. }
  125. }
  126. c.addConn(conn, "")
  127. return
  128. }
  129. }
  130. func (c *clusterImpl) changeKeyspace(conn *Conn, keyspace string, connected bool) {
  131. if err := conn.UseKeyspace(keyspace); err != nil {
  132. conn.Close()
  133. if connected {
  134. c.removeConn(conn)
  135. }
  136. go c.connect(conn.Address())
  137. }
  138. if !connected {
  139. c.addConn(conn, keyspace)
  140. }
  141. }
  142. func (c *clusterImpl) addConn(conn *Conn, keyspace string) {
  143. c.mu.Lock()
  144. defer c.mu.Unlock()
  145. if c.quit {
  146. conn.Close()
  147. return
  148. }
  149. if keyspace != c.keyspace && c.keyspace != "" {
  150. // change the keyspace before adding the node to the pool
  151. go c.changeKeyspace(conn, c.keyspace, false)
  152. return
  153. }
  154. connPool := c.connPool[conn.Address()]
  155. if connPool == nil {
  156. connPool = NewRoundRobin()
  157. c.connPool[conn.Address()] = connPool
  158. c.hostPool.AddNode(connPool)
  159. if !c.started && c.hostPool.Size() >= c.cfg.StartupMin {
  160. c.started = true
  161. c.cStart <- 1
  162. }
  163. }
  164. connPool.AddNode(conn)
  165. c.conns[conn] = struct{}{}
  166. }
  167. func (c *clusterImpl) removeConn(conn *Conn) {
  168. c.mu.Lock()
  169. defer c.mu.Unlock()
  170. conn.Close()
  171. connPool := c.connPool[conn.addr]
  172. if connPool == nil {
  173. return
  174. }
  175. connPool.RemoveNode(conn)
  176. if connPool.Size() == 0 {
  177. c.hostPool.RemoveNode(connPool)
  178. delete(c.connPool, conn.addr)
  179. }
  180. delete(c.conns, conn)
  181. }
  182. func (c *clusterImpl) HandleError(conn *Conn, err error, closed bool) {
  183. if !closed {
  184. // ignore all non-fatal errors
  185. return
  186. }
  187. c.removeConn(conn)
  188. if !c.quit {
  189. go c.connect(conn.Address()) // reconnect
  190. }
  191. }
  192. func (c *clusterImpl) HandleKeyspace(conn *Conn, keyspace string) {
  193. c.mu.Lock()
  194. if c.keyspace == keyspace {
  195. c.mu.Unlock()
  196. return
  197. }
  198. c.keyspace = keyspace
  199. conns := make([]*Conn, 0, len(c.conns))
  200. for conn := range c.conns {
  201. conns = append(conns, conn)
  202. }
  203. c.mu.Unlock()
  204. // change the keyspace of all other connections too
  205. for i := 0; i < len(conns); i++ {
  206. if conns[i] == conn {
  207. continue
  208. }
  209. c.changeKeyspace(conns[i], keyspace, true)
  210. }
  211. }
  212. func (c *clusterImpl) Pick(qry *Query) *Conn {
  213. return c.hostPool.Pick(qry)
  214. }
  215. func (c *clusterImpl) Close() {
  216. c.quitOnce.Do(func() {
  217. c.mu.Lock()
  218. defer c.mu.Unlock()
  219. c.quit = true
  220. close(c.quitWait)
  221. for conn := range c.conns {
  222. conn.Close()
  223. }
  224. })
  225. }
  226. var (
  227. ErrNoHosts = errors.New("no hosts provided")
  228. ErrNoConnections = errors.New("no connections were made in startup time frame")
  229. )