cluster.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  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. Consistency Consistency // default consistency level (default: Quorum)
  27. Compressor Compressor // compression algorithm (default: nil)
  28. Authenticator Authenticator // authenticator (default: nil)
  29. RetryPolicy RetryPolicy // Default retry policy to use for queries (default: 0)
  30. SocketKeepalive time.Duration // The keepalive period to use, enabled if > 0 (default: 0)
  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: 600 * time.Millisecond,
  39. DefaultPort: 9042,
  40. NumConns: 2,
  41. NumStreams: 128,
  42. Consistency: Quorum,
  43. }
  44. return cfg
  45. }
  46. // CreateSession initializes the cluster based on this config and returns a
  47. // session object that can be used to interact with the database.
  48. func (cfg *ClusterConfig) CreateSession() (*Session, error) {
  49. //Check that hosts in the ClusterConfig is not empty
  50. if len(cfg.Hosts) < 1 {
  51. return nil, ErrNoHosts
  52. }
  53. impl := &clusterImpl{
  54. cfg: *cfg,
  55. hostPool: NewRoundRobin(),
  56. connPool: make(map[string]*RoundRobin),
  57. conns: make(map[*Conn]struct{}),
  58. quitWait: make(chan bool),
  59. cFillingPool: make(chan int, 1),
  60. keyspace: cfg.Keyspace,
  61. }
  62. //Walk through connecting to hosts. As soon as one host connects
  63. //defer the remaining connections to cluster.fillPool()
  64. for i := 0; i < len(impl.cfg.Hosts); i++ {
  65. addr := strings.TrimSpace(impl.cfg.Hosts[i])
  66. if strings.Index(addr, ":") < 0 {
  67. addr = fmt.Sprintf("%s:%d", addr, impl.cfg.DefaultPort)
  68. }
  69. err := impl.connect(addr)
  70. if err == nil {
  71. impl.cFillingPool <- 1
  72. go impl.fillPool()
  73. break
  74. }
  75. }
  76. //See if there are any connections in the pool
  77. impl.mu.Lock()
  78. conns := len(impl.conns)
  79. impl.mu.Unlock()
  80. if conns > 0 {
  81. s := NewSession(impl)
  82. s.SetConsistency(cfg.Consistency)
  83. return s, nil
  84. }
  85. impl.Close()
  86. return nil, ErrNoConnectionsStarted
  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. cFillingPool chan int
  96. quit bool
  97. quitWait chan bool
  98. quitOnce sync.Once
  99. }
  100. func (c *clusterImpl) connect(addr string) error {
  101. cfg := ConnConfig{
  102. ProtoVersion: c.cfg.ProtoVersion,
  103. CQLVersion: c.cfg.CQLVersion,
  104. Timeout: c.cfg.Timeout,
  105. NumStreams: c.cfg.NumStreams,
  106. Compressor: c.cfg.Compressor,
  107. Authenticator: c.cfg.Authenticator,
  108. Keepalive: c.cfg.SocketKeepalive,
  109. }
  110. for {
  111. conn, err := Connect(addr, cfg, c)
  112. if err != nil {
  113. log.Printf("failed to connect to %q: %v", addr, err)
  114. return err
  115. }
  116. return c.addConn(conn)
  117. }
  118. }
  119. func (c *clusterImpl) addConn(conn *Conn) error {
  120. c.mu.Lock()
  121. defer c.mu.Unlock()
  122. if c.quit {
  123. conn.Close()
  124. return nil
  125. }
  126. //Set the connection's keyspace if any before adding it to the pool
  127. if c.keyspace != "" {
  128. if err := conn.UseKeyspace(c.keyspace); err != nil {
  129. log.Printf("error setting connection keyspace. %v", err)
  130. conn.Close()
  131. return err
  132. }
  133. }
  134. connPool := c.connPool[conn.Address()]
  135. if connPool == nil {
  136. connPool = NewRoundRobin()
  137. c.connPool[conn.Address()] = connPool
  138. c.hostPool.AddNode(connPool)
  139. }
  140. connPool.AddNode(conn)
  141. c.conns[conn] = struct{}{}
  142. return nil
  143. }
  144. //fillPool manages the pool of connections making sure that each host has the correct
  145. //amount of connections defined. Also the method will test a host with one connection
  146. //instead of flooding the host with number of connections defined in the cluster config
  147. func (c *clusterImpl) fillPool() {
  148. //Debounce large amounts of requests to fill pool
  149. select {
  150. case <-time.After(1 * time.Millisecond):
  151. return
  152. case <-c.cFillingPool:
  153. defer func() { c.cFillingPool <- 1 }()
  154. }
  155. c.mu.Lock()
  156. isClosed := c.quit
  157. c.mu.Unlock()
  158. //Exit if cluster(session) is closed
  159. if isClosed {
  160. return
  161. }
  162. //Walk through list of defined hosts
  163. for i := 0; i < len(c.cfg.Hosts); i++ {
  164. addr := strings.TrimSpace(c.cfg.Hosts[i])
  165. if strings.Index(addr, ":") < 0 {
  166. addr = fmt.Sprintf("%s:%d", addr, c.cfg.DefaultPort)
  167. }
  168. var numConns int = 1
  169. //See if the host already has connections in the pool
  170. c.mu.Lock()
  171. conns, ok := c.connPool[addr]
  172. c.mu.Unlock()
  173. if ok {
  174. //if the host has enough connections just exit
  175. numConns = conns.Size()
  176. if numConns >= c.cfg.NumConns {
  177. continue
  178. }
  179. } else {
  180. //See if the host is reachable
  181. if err := c.connect(addr); err != nil {
  182. continue
  183. }
  184. }
  185. //This is reached if the host is responsive and needs more connections
  186. //Create connections for host synchronously to mitigate flooding the host.
  187. go func(a string, conns int) {
  188. for ; conns < c.cfg.NumConns; conns++ {
  189. c.connect(addr)
  190. }
  191. }(addr, numConns)
  192. }
  193. }
  194. // Should only be called if c.mu is locked
  195. func (c *clusterImpl) removeConnLocked(conn *Conn) {
  196. conn.Close()
  197. connPool := c.connPool[conn.addr]
  198. if connPool == nil {
  199. return
  200. }
  201. connPool.RemoveNode(conn)
  202. if connPool.Size() == 0 {
  203. c.hostPool.RemoveNode(connPool)
  204. delete(c.connPool, conn.addr)
  205. }
  206. delete(c.conns, conn)
  207. }
  208. func (c *clusterImpl) removeConn(conn *Conn) {
  209. c.mu.Lock()
  210. defer c.mu.Unlock()
  211. c.removeConnLocked(conn)
  212. }
  213. func (c *clusterImpl) HandleError(conn *Conn, err error, closed bool) {
  214. if !closed {
  215. // ignore all non-fatal errors
  216. return
  217. }
  218. c.removeConn(conn)
  219. if !c.quit {
  220. go c.fillPool() // top off pool.
  221. }
  222. }
  223. func (c *clusterImpl) Pick(qry *Query) *Conn {
  224. //Check if connections are available
  225. c.mu.Lock()
  226. conns := len(c.conns)
  227. c.mu.Unlock()
  228. if conns == 0 {
  229. //try to populate the pool before returning.
  230. c.fillPool()
  231. }
  232. return c.hostPool.Pick(qry)
  233. }
  234. func (c *clusterImpl) Close() {
  235. c.quitOnce.Do(func() {
  236. c.mu.Lock()
  237. defer c.mu.Unlock()
  238. c.quit = true
  239. close(c.quitWait)
  240. for conn := range c.conns {
  241. c.removeConnLocked(conn)
  242. }
  243. })
  244. }
  245. var (
  246. ErrNoHosts = errors.New("no hosts provided")
  247. ErrNoConnectionsStarted = errors.New("no connections were made when creating the session")
  248. )