cluster.go 6.9 KB

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