connectionpool.go 8.8 KB

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