connectionpool.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  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.Port)
  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. SetHosts(host []HostInfo)
  80. }
  81. //NewPoolFunc is the type used by ClusterConfig to create a pool of a specific type.
  82. type NewPoolFunc func(*ClusterConfig) ConnectionPool
  83. //SimplePool is the current implementation of the connection pool inside gocql. This
  84. //pool is meant to be a simple default used by gocql so users can get up and running
  85. //quickly.
  86. type SimplePool struct {
  87. cfg *ClusterConfig
  88. hostPool *RoundRobin
  89. connPool map[string]*RoundRobin
  90. conns map[*Conn]struct{}
  91. keyspace string
  92. hostMu sync.RWMutex
  93. // this is the set of current hosts which the pool will attempt to connect to
  94. hosts map[string]*HostInfo
  95. // protects hostpool, connPoll, conns, quit
  96. mu sync.Mutex
  97. cFillingPool chan int
  98. quit bool
  99. quitWait chan bool
  100. quitOnce sync.Once
  101. }
  102. //NewSimplePool is the function used by gocql to create the simple connection pool.
  103. //This is the default if no other pool type is specified.
  104. func NewSimplePool(cfg *ClusterConfig) ConnectionPool {
  105. pool := &SimplePool{
  106. cfg: cfg,
  107. hostPool: NewRoundRobin(),
  108. connPool: make(map[string]*RoundRobin),
  109. conns: make(map[*Conn]struct{}),
  110. quitWait: make(chan bool),
  111. cFillingPool: make(chan int, 1),
  112. keyspace: cfg.Keyspace,
  113. hosts: make(map[string]*HostInfo),
  114. }
  115. for _, host := range cfg.Hosts {
  116. // seed hosts have unknown topology
  117. // TODO: Handle populating this during SetHosts
  118. pool.hosts[host] = &HostInfo{Peer: host}
  119. }
  120. //Walk through connecting to hosts. As soon as one host connects
  121. //defer the remaining connections to cluster.fillPool()
  122. for i := 0; i < len(cfg.Hosts); i++ {
  123. addr := strings.TrimSpace(cfg.Hosts[i])
  124. if strings.Index(addr, ":") < 0 {
  125. addr = fmt.Sprintf("%s:%d", addr, cfg.Port)
  126. }
  127. if pool.connect(addr) == nil {
  128. pool.cFillingPool <- 1
  129. go pool.fillPool()
  130. break
  131. }
  132. }
  133. return pool
  134. }
  135. func (c *SimplePool) connect(addr string) error {
  136. cfg := ConnConfig{
  137. ProtoVersion: c.cfg.ProtoVersion,
  138. CQLVersion: c.cfg.CQLVersion,
  139. Timeout: c.cfg.Timeout,
  140. NumStreams: c.cfg.NumStreams,
  141. Compressor: c.cfg.Compressor,
  142. Authenticator: c.cfg.Authenticator,
  143. Keepalive: c.cfg.SocketKeepalive,
  144. SslOpts: c.cfg.SslOpts,
  145. }
  146. conn, err := Connect(addr, cfg, c)
  147. if err != nil {
  148. log.Printf("connect: failed to connect to %q: %v", addr, err)
  149. return err
  150. }
  151. return c.addConn(conn)
  152. }
  153. func (c *SimplePool) addConn(conn *Conn) error {
  154. c.mu.Lock()
  155. defer c.mu.Unlock()
  156. if c.quit {
  157. conn.Close()
  158. return nil
  159. }
  160. //Set the connection's keyspace if any before adding it to the pool
  161. if c.keyspace != "" {
  162. if err := conn.UseKeyspace(c.keyspace); err != nil {
  163. log.Printf("error setting connection keyspace. %v", err)
  164. conn.Close()
  165. return err
  166. }
  167. }
  168. connPool := c.connPool[conn.Address()]
  169. if connPool == nil {
  170. connPool = NewRoundRobin()
  171. c.connPool[conn.Address()] = connPool
  172. c.hostPool.AddNode(connPool)
  173. }
  174. connPool.AddNode(conn)
  175. c.conns[conn] = struct{}{}
  176. return nil
  177. }
  178. //fillPool manages the pool of connections making sure that each host has the correct
  179. //amount of connections defined. Also the method will test a host with one connection
  180. //instead of flooding the host with number of connections defined in the cluster config
  181. func (c *SimplePool) fillPool() {
  182. //Debounce large amounts of requests to fill pool
  183. select {
  184. case <-time.After(1 * time.Millisecond):
  185. return
  186. case <-c.cFillingPool:
  187. defer func() { c.cFillingPool <- 1 }()
  188. }
  189. c.mu.Lock()
  190. isClosed := c.quit
  191. c.mu.Unlock()
  192. //Exit if cluster(session) is closed
  193. if isClosed {
  194. return
  195. }
  196. c.hostMu.RLock()
  197. //Walk through list of defined hosts
  198. for host := range c.hosts {
  199. addr := strings.TrimSpace(host)
  200. if strings.Index(addr, ":") < 0 {
  201. addr = fmt.Sprintf("%s:%d", addr, c.cfg.Port)
  202. }
  203. numConns := 1
  204. //See if the host already has connections in the pool
  205. c.mu.Lock()
  206. conns, ok := c.connPool[addr]
  207. c.mu.Unlock()
  208. if ok {
  209. //if the host has enough connections just exit
  210. numConns = conns.Size()
  211. if numConns >= c.cfg.NumConns {
  212. continue
  213. }
  214. } else {
  215. //See if the host is reachable
  216. if err := c.connect(addr); err != nil {
  217. continue
  218. }
  219. }
  220. //This is reached if the host is responsive and needs more connections
  221. //Create connections for host synchronously to mitigate flooding the host.
  222. go func(a string, conns int) {
  223. for ; conns < c.cfg.NumConns; conns++ {
  224. c.connect(addr)
  225. }
  226. }(addr, numConns)
  227. }
  228. c.hostMu.RUnlock()
  229. }
  230. // Should only be called if c.mu is locked
  231. func (c *SimplePool) removeConnLocked(conn *Conn) {
  232. conn.Close()
  233. connPool := c.connPool[conn.addr]
  234. if connPool == nil {
  235. return
  236. }
  237. connPool.RemoveNode(conn)
  238. if connPool.Size() == 0 {
  239. c.hostPool.RemoveNode(connPool)
  240. delete(c.connPool, conn.addr)
  241. }
  242. delete(c.conns, conn)
  243. }
  244. func (c *SimplePool) removeConn(conn *Conn) {
  245. c.mu.Lock()
  246. defer c.mu.Unlock()
  247. c.removeConnLocked(conn)
  248. }
  249. //HandleError is called by a Connection object to report to the pool an error has occured.
  250. //Logic is then executed within the pool to clean up the erroroneous connection and try to
  251. //top off the pool.
  252. func (c *SimplePool) HandleError(conn *Conn, err error, closed bool) {
  253. if !closed {
  254. // ignore all non-fatal errors
  255. return
  256. }
  257. c.removeConn(conn)
  258. if !c.quit {
  259. go c.fillPool() // top off pool.
  260. }
  261. }
  262. //Pick selects a connection to be used by the query.
  263. func (c *SimplePool) Pick(qry *Query) *Conn {
  264. //Check if connections are available
  265. c.mu.Lock()
  266. conns := len(c.conns)
  267. c.mu.Unlock()
  268. if conns == 0 {
  269. //try to populate the pool before returning.
  270. c.fillPool()
  271. }
  272. return c.hostPool.Pick(qry)
  273. }
  274. //Size returns the number of connections currently active in the pool
  275. func (p *SimplePool) Size() int {
  276. p.mu.Lock()
  277. conns := len(p.conns)
  278. p.mu.Unlock()
  279. return conns
  280. }
  281. //Close kills the pool and all associated connections.
  282. func (c *SimplePool) Close() {
  283. c.quitOnce.Do(func() {
  284. c.mu.Lock()
  285. defer c.mu.Unlock()
  286. c.quit = true
  287. close(c.quitWait)
  288. for conn := range c.conns {
  289. c.removeConnLocked(conn)
  290. }
  291. })
  292. }
  293. func (c *SimplePool) SetHosts(hosts []HostInfo) {
  294. c.hostMu.Lock()
  295. toRemove := make(map[string]struct{})
  296. for k := range c.hosts {
  297. toRemove[k] = struct{}{}
  298. }
  299. for _, host := range hosts {
  300. host := host
  301. delete(toRemove, host.Peer)
  302. // we already have it
  303. if _, ok := c.hosts[host.Peer]; ok {
  304. // TODO: Check rack, dc, token range is consistent, trigger topology change
  305. // update stored host
  306. continue
  307. }
  308. c.hosts[host.Peer] = &host
  309. }
  310. // can we hold c.mu whilst iterating this loop?
  311. for addr := range toRemove {
  312. c.removeHostLocked(addr)
  313. }
  314. c.hostMu.Unlock()
  315. c.fillPool()
  316. }
  317. func (c *SimplePool) removeHostLocked(addr string) {
  318. if _, ok := c.hosts[addr]; !ok {
  319. return
  320. }
  321. delete(c.hosts, addr)
  322. c.mu.Lock()
  323. defer c.mu.Unlock()
  324. if _, ok := c.connPool[addr]; !ok {
  325. return
  326. }
  327. for conn := range c.conns {
  328. if conn.Address() == addr {
  329. c.removeConnLocked(conn)
  330. }
  331. }
  332. }