connectionpool.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  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. 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.DefaultPort)
  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) newConn(addr string) (*Conn, 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. }
  145. conn, err := Connect(addr, cfg, c)
  146. if err != nil {
  147. log.Printf("newConn: failed to connect to %q: %v", addr, err)
  148. return nil, err
  149. }
  150. return conn, nil
  151. }
  152. func (c *SimplePool) connect(addr string) error {
  153. if conn, err := c.newConn(addr); err != nil {
  154. log.Printf("connect: failed to connect to %q: %v", addr, err)
  155. return err
  156. } else {
  157. return c.addConn(conn)
  158. }
  159. }
  160. func (c *SimplePool) addConn(conn *Conn) error {
  161. c.mu.Lock()
  162. defer c.mu.Unlock()
  163. if c.quit {
  164. conn.Close()
  165. return nil
  166. }
  167. //Set the connection's keyspace if any before adding it to the pool
  168. if c.keyspace != "" {
  169. if err := conn.UseKeyspace(c.keyspace); err != nil {
  170. log.Printf("error setting connection keyspace. %v", err)
  171. conn.Close()
  172. return err
  173. }
  174. }
  175. connPool := c.connPool[conn.Address()]
  176. if connPool == nil {
  177. connPool = NewRoundRobin()
  178. c.connPool[conn.Address()] = connPool
  179. c.hostPool.AddNode(connPool)
  180. }
  181. connPool.AddNode(conn)
  182. c.conns[conn] = struct{}{}
  183. return nil
  184. }
  185. //fillPool manages the pool of connections making sure that each host has the correct
  186. //amount of connections defined. Also the method will test a host with one connection
  187. //instead of flooding the host with number of connections defined in the cluster config
  188. func (c *SimplePool) fillPool() {
  189. //Debounce large amounts of requests to fill pool
  190. select {
  191. case <-time.After(1 * time.Millisecond):
  192. return
  193. case <-c.cFillingPool:
  194. defer func() { c.cFillingPool <- 1 }()
  195. }
  196. c.mu.Lock()
  197. isClosed := c.quit
  198. c.mu.Unlock()
  199. //Exit if cluster(session) is closed
  200. if isClosed {
  201. return
  202. }
  203. c.hostMu.RLock()
  204. //Walk through list of defined hosts
  205. for host := range c.hosts {
  206. addr := strings.TrimSpace(host)
  207. if strings.Index(addr, ":") < 0 {
  208. addr = fmt.Sprintf("%s:%d", addr, c.cfg.DefaultPort)
  209. }
  210. numConns := 1
  211. //See if the host already has connections in the pool
  212. c.mu.Lock()
  213. conns, ok := c.connPool[addr]
  214. c.mu.Unlock()
  215. if ok {
  216. //if the host has enough connections just exit
  217. numConns = conns.Size()
  218. if numConns >= c.cfg.NumConns {
  219. continue
  220. }
  221. } else {
  222. //See if the host is reachable
  223. if err := c.connect(addr); err != nil {
  224. continue
  225. }
  226. }
  227. //This is reached if the host is responsive and needs more connections
  228. //Create connections for host synchronously to mitigate flooding the host.
  229. go func(a string, conns int) {
  230. for ; conns < c.cfg.NumConns; conns++ {
  231. c.connect(addr)
  232. }
  233. }(addr, numConns)
  234. }
  235. c.hostMu.RUnlock()
  236. }
  237. // Should only be called if c.mu is locked
  238. func (c *SimplePool) removeConnLocked(conn *Conn) {
  239. conn.Close()
  240. connPool := c.connPool[conn.addr]
  241. if connPool == nil {
  242. return
  243. }
  244. connPool.RemoveNode(conn)
  245. if connPool.Size() == 0 {
  246. c.hostPool.RemoveNode(connPool)
  247. delete(c.connPool, conn.addr)
  248. }
  249. delete(c.conns, conn)
  250. }
  251. func (c *SimplePool) removeConn(conn *Conn) {
  252. c.mu.Lock()
  253. defer c.mu.Unlock()
  254. c.removeConnLocked(conn)
  255. }
  256. //HandleError is called by a Connection object to report to the pool an error has occured.
  257. //Logic is then executed within the pool to clean up the erroroneous connection and try to
  258. //top off the pool.
  259. func (c *SimplePool) HandleError(conn *Conn, err error, closed bool) {
  260. if !closed {
  261. // ignore all non-fatal errors
  262. return
  263. }
  264. c.removeConn(conn)
  265. if !c.quit {
  266. go c.fillPool() // top off pool.
  267. }
  268. }
  269. //Pick selects a connection to be used by the query.
  270. func (c *SimplePool) Pick(qry *Query) *Conn {
  271. //Check if connections are available
  272. c.mu.Lock()
  273. conns := len(c.conns)
  274. c.mu.Unlock()
  275. if conns == 0 {
  276. //try to populate the pool before returning.
  277. c.fillPool()
  278. }
  279. return c.hostPool.Pick(qry)
  280. }
  281. //Size returns the number of connections currently active in the pool
  282. func (p *SimplePool) Size() int {
  283. p.mu.Lock()
  284. conns := len(p.conns)
  285. p.mu.Unlock()
  286. return conns
  287. }
  288. //Close kills the pool and all associated connections.
  289. func (c *SimplePool) Close() {
  290. c.quitOnce.Do(func() {
  291. c.mu.Lock()
  292. defer c.mu.Unlock()
  293. c.quit = true
  294. close(c.quitWait)
  295. for conn := range c.conns {
  296. c.removeConnLocked(conn)
  297. }
  298. })
  299. }
  300. func (c *SimplePool) SetHosts(hosts []HostInfo) {
  301. c.hostMu.Lock()
  302. toRemove := make(map[string]struct{})
  303. for k := range c.hosts {
  304. toRemove[k] = struct{}{}
  305. }
  306. for _, host := range hosts {
  307. host := host
  308. delete(toRemove, host.Peer)
  309. // we already have it
  310. if _, ok := c.hosts[host.Peer]; ok {
  311. // TODO: Check rack, dc, token range is consistent, trigger topology change
  312. // update stored host
  313. continue
  314. }
  315. c.hosts[host.Peer] = &host
  316. }
  317. // can we hold c.mu whilst iterating this loop?
  318. for addr := range toRemove {
  319. c.removeHostLocked(addr)
  320. }
  321. c.hostMu.Unlock()
  322. }
  323. func (c *SimplePool) removeHostLocked(addr string) {
  324. if _, ok := c.hosts[addr]; !ok {
  325. return
  326. }
  327. delete(c.hosts, addr)
  328. c.mu.Lock()
  329. defer c.mu.Unlock()
  330. if _, ok := c.connPool[addr]; !ok {
  331. return
  332. }
  333. for conn := range c.conns {
  334. if conn.Address() == addr {
  335. c.removeConnLocked(conn)
  336. }
  337. }
  338. }