connectionpool.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. package gocql
  2. import (
  3. "log"
  4. "sync"
  5. "time"
  6. )
  7. /*ConnectionPool represents the interface gocql will use to work with a collection of connections.
  8. Purpose
  9. The connection pool in gocql opens and closes connections as well as selects an available connection
  10. for gocql to execute a query against. The pool is also respnsible for handling connection errors that
  11. are caught by the connection experiencing the error.
  12. A connection pool should make a copy of the variables used from the ClusterConfig provided to the pool
  13. upon creation. ClusterConfig is a pointer and can be modified after the creation of the pool. This can
  14. lead to issues with variables being modified outside the expectations of the ConnectionPool type.
  15. Example of Single Connection Pool:
  16. type SingleConnection struct {
  17. conn *Conn
  18. cfg *ClusterConfig
  19. }
  20. func NewSingleConnection(cfg *ClusterConfig) ConnectionPool {
  21. addr := JoinHostPort(cfg.Hosts[0], cfg.Port)
  22. connCfg := ConnConfig{
  23. ProtoVersion: cfg.ProtoVersion,
  24. CQLVersion: cfg.CQLVersion,
  25. Timeout: cfg.Timeout,
  26. NumStreams: cfg.NumStreams,
  27. Compressor: cfg.Compressor,
  28. Authenticator: cfg.Authenticator,
  29. Keepalive: cfg.SocketKeepalive,
  30. }
  31. pool := SingleConnection{cfg:cfg}
  32. pool.conn = Connect(addr,connCfg,pool)
  33. return &pool
  34. }
  35. func (s *SingleConnection) HandleError(conn *Conn, err error, closed bool) {
  36. if closed {
  37. connCfg := ConnConfig{
  38. ProtoVersion: cfg.ProtoVersion,
  39. CQLVersion: cfg.CQLVersion,
  40. Timeout: cfg.Timeout,
  41. NumStreams: cfg.NumStreams,
  42. Compressor: cfg.Compressor,
  43. Authenticator: cfg.Authenticator,
  44. Keepalive: cfg.SocketKeepalive,
  45. }
  46. s.conn = Connect(conn.Address(),connCfg,s)
  47. }
  48. }
  49. func (s *SingleConnection) Pick(qry *Query) *Conn {
  50. if s.conn.isClosed {
  51. return nil
  52. }
  53. return s.conn
  54. }
  55. func (s *SingleConnection) Size() int {
  56. return 1
  57. }
  58. func (s *SingleConnection) Close() {
  59. s.conn.Close()
  60. }
  61. This is a very simple example of a type that exposes the connection pool interface. To assign
  62. this type as the connection pool to use you would assign it to the ClusterConfig like so:
  63. cluster := NewCluster("127.0.0.1")
  64. cluster.ConnPoolType = NewSingleConnection
  65. ...
  66. session, err := cluster.CreateSession()
  67. To see a more complete example of a ConnectionPool implementation please see the SimplePool type.
  68. */
  69. type ConnectionPool interface {
  70. Pick(*Query) *Conn
  71. Size() int
  72. HandleError(*Conn, error, bool)
  73. Close()
  74. SetHosts(host []HostInfo)
  75. }
  76. //NewPoolFunc is the type used by ClusterConfig to create a pool of a specific type.
  77. type NewPoolFunc func(*ClusterConfig) ConnectionPool
  78. //SimplePool is the current implementation of the connection pool inside gocql. This
  79. //pool is meant to be a simple default used by gocql so users can get up and running
  80. //quickly.
  81. type SimplePool struct {
  82. cfg *ClusterConfig
  83. hostPool *RoundRobin
  84. connPool map[string]*RoundRobin
  85. conns map[*Conn]struct{}
  86. keyspace string
  87. hostMu sync.RWMutex
  88. // this is the set of current hosts which the pool will attempt to connect to
  89. hosts map[string]*HostInfo
  90. // protects hostpool, connPoll, conns, quit
  91. mu sync.Mutex
  92. cFillingPool chan int
  93. quit bool
  94. quitWait chan bool
  95. quitOnce sync.Once
  96. }
  97. //NewSimplePool is the function used by gocql to create the simple connection pool.
  98. //This is the default if no other pool type is specified.
  99. func NewSimplePool(cfg *ClusterConfig) ConnectionPool {
  100. pool := &SimplePool{
  101. cfg: cfg,
  102. hostPool: NewRoundRobin(),
  103. connPool: make(map[string]*RoundRobin),
  104. conns: make(map[*Conn]struct{}),
  105. quitWait: make(chan bool),
  106. cFillingPool: make(chan int, 1),
  107. keyspace: cfg.Keyspace,
  108. hosts: make(map[string]*HostInfo),
  109. }
  110. for _, host := range cfg.Hosts {
  111. // seed hosts have unknown topology
  112. // TODO: Handle populating this during SetHosts
  113. pool.hosts[host] = &HostInfo{Peer: host}
  114. }
  115. //Walk through connecting to hosts. As soon as one host connects
  116. //defer the remaining connections to cluster.fillPool()
  117. for i := 0; i < len(cfg.Hosts); i++ {
  118. addr := JoinHostPort(cfg.Hosts[i], cfg.Port)
  119. if pool.connect(addr) == nil {
  120. pool.cFillingPool <- 1
  121. go pool.fillPool()
  122. break
  123. }
  124. }
  125. return pool
  126. }
  127. func (c *SimplePool) connect(addr string) error {
  128. cfg := ConnConfig{
  129. ProtoVersion: c.cfg.ProtoVersion,
  130. CQLVersion: c.cfg.CQLVersion,
  131. Timeout: c.cfg.Timeout,
  132. NumStreams: c.cfg.NumStreams,
  133. Compressor: c.cfg.Compressor,
  134. Authenticator: c.cfg.Authenticator,
  135. Keepalive: c.cfg.SocketKeepalive,
  136. SslOpts: c.cfg.SslOpts,
  137. }
  138. conn, err := Connect(addr, cfg, c)
  139. if err != nil {
  140. log.Printf("connect: failed to connect to %q: %v", addr, err)
  141. return err
  142. }
  143. return c.addConn(conn)
  144. }
  145. func (c *SimplePool) addConn(conn *Conn) error {
  146. c.mu.Lock()
  147. defer c.mu.Unlock()
  148. if c.quit {
  149. conn.Close()
  150. return nil
  151. }
  152. //Set the connection's keyspace if any before adding it to the pool
  153. if c.keyspace != "" {
  154. if err := conn.UseKeyspace(c.keyspace); err != nil {
  155. log.Printf("error setting connection keyspace. %v", err)
  156. conn.Close()
  157. return err
  158. }
  159. }
  160. connPool := c.connPool[conn.Address()]
  161. if connPool == nil {
  162. connPool = NewRoundRobin()
  163. c.connPool[conn.Address()] = connPool
  164. c.hostPool.AddNode(connPool)
  165. }
  166. connPool.AddNode(conn)
  167. c.conns[conn] = struct{}{}
  168. return nil
  169. }
  170. //fillPool manages the pool of connections making sure that each host has the correct
  171. //amount of connections defined. Also the method will test a host with one connection
  172. //instead of flooding the host with number of connections defined in the cluster config
  173. func (c *SimplePool) fillPool() {
  174. //Debounce large amounts of requests to fill pool
  175. select {
  176. case <-time.After(1 * time.Millisecond):
  177. return
  178. case <-c.cFillingPool:
  179. defer func() { c.cFillingPool <- 1 }()
  180. }
  181. c.mu.Lock()
  182. isClosed := c.quit
  183. c.mu.Unlock()
  184. //Exit if cluster(session) is closed
  185. if isClosed {
  186. return
  187. }
  188. c.hostMu.RLock()
  189. //Walk through list of defined hosts
  190. for host := range c.hosts {
  191. addr := JoinHostPort(host, c.cfg.Port)
  192. numConns := 1
  193. //See if the host already has connections in the pool
  194. c.mu.Lock()
  195. conns, ok := c.connPool[addr]
  196. c.mu.Unlock()
  197. if ok {
  198. //if the host has enough connections just exit
  199. numConns = conns.Size()
  200. if numConns >= c.cfg.NumConns {
  201. continue
  202. }
  203. } else {
  204. //See if the host is reachable
  205. if err := c.connect(addr); err != nil {
  206. continue
  207. }
  208. }
  209. //This is reached if the host is responsive and needs more connections
  210. //Create connections for host synchronously to mitigate flooding the host.
  211. go func(a string, conns int) {
  212. for ; conns < c.cfg.NumConns; conns++ {
  213. c.connect(a)
  214. }
  215. }(addr, numConns)
  216. }
  217. c.hostMu.RUnlock()
  218. }
  219. // Should only be called if c.mu is locked
  220. func (c *SimplePool) removeConnLocked(conn *Conn) {
  221. conn.Close()
  222. connPool := c.connPool[conn.addr]
  223. if connPool == nil {
  224. return
  225. }
  226. connPool.RemoveNode(conn)
  227. if connPool.Size() == 0 {
  228. c.hostPool.RemoveNode(connPool)
  229. delete(c.connPool, conn.addr)
  230. }
  231. delete(c.conns, conn)
  232. }
  233. func (c *SimplePool) removeConn(conn *Conn) {
  234. c.mu.Lock()
  235. defer c.mu.Unlock()
  236. c.removeConnLocked(conn)
  237. }
  238. //HandleError is called by a Connection object to report to the pool an error has occured.
  239. //Logic is then executed within the pool to clean up the erroroneous connection and try to
  240. //top off the pool.
  241. func (c *SimplePool) HandleError(conn *Conn, err error, closed bool) {
  242. if !closed {
  243. // ignore all non-fatal errors
  244. return
  245. }
  246. c.removeConn(conn)
  247. if !c.quit {
  248. go c.fillPool() // top off pool.
  249. }
  250. }
  251. //Pick selects a connection to be used by the query.
  252. func (c *SimplePool) Pick(qry *Query) *Conn {
  253. //Check if connections are available
  254. c.mu.Lock()
  255. conns := len(c.conns)
  256. c.mu.Unlock()
  257. if conns == 0 {
  258. //try to populate the pool before returning.
  259. c.fillPool()
  260. }
  261. return c.hostPool.Pick(qry)
  262. }
  263. //Size returns the number of connections currently active in the pool
  264. func (p *SimplePool) Size() int {
  265. p.mu.Lock()
  266. conns := len(p.conns)
  267. p.mu.Unlock()
  268. return conns
  269. }
  270. //Close kills the pool and all associated connections.
  271. func (c *SimplePool) Close() {
  272. c.quitOnce.Do(func() {
  273. c.mu.Lock()
  274. defer c.mu.Unlock()
  275. c.quit = true
  276. close(c.quitWait)
  277. for conn := range c.conns {
  278. c.removeConnLocked(conn)
  279. }
  280. })
  281. }
  282. func (c *SimplePool) SetHosts(hosts []HostInfo) {
  283. c.hostMu.Lock()
  284. toRemove := make(map[string]struct{})
  285. for k := range c.hosts {
  286. toRemove[k] = struct{}{}
  287. }
  288. for _, host := range hosts {
  289. host := host
  290. delete(toRemove, host.Peer)
  291. // we already have it
  292. if _, ok := c.hosts[host.Peer]; ok {
  293. // TODO: Check rack, dc, token range is consistent, trigger topology change
  294. // update stored host
  295. continue
  296. }
  297. c.hosts[host.Peer] = &host
  298. }
  299. // can we hold c.mu whilst iterating this loop?
  300. for addr := range toRemove {
  301. c.removeHostLocked(addr)
  302. }
  303. c.hostMu.Unlock()
  304. c.fillPool()
  305. }
  306. func (c *SimplePool) removeHostLocked(addr string) {
  307. if _, ok := c.hosts[addr]; !ok {
  308. return
  309. }
  310. delete(c.hosts, addr)
  311. c.mu.Lock()
  312. defer c.mu.Unlock()
  313. if _, ok := c.connPool[addr]; !ok {
  314. return
  315. }
  316. for conn := range c.conns {
  317. if conn.Address() == addr {
  318. c.removeConnLocked(conn)
  319. }
  320. }
  321. }