connectionpool.go 9.6 KB

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