connectionpool.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  1. // Copyright (c) 2012 The gocql Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package gocql
  5. import (
  6. "crypto/tls"
  7. "crypto/x509"
  8. "errors"
  9. "fmt"
  10. "io/ioutil"
  11. "log"
  12. "math/rand"
  13. "net"
  14. "sync"
  15. "time"
  16. )
  17. // interface to implement to receive the host information
  18. type SetHosts interface {
  19. SetHosts(hosts []HostInfo)
  20. }
  21. // interface to implement to receive the partitioner value
  22. type SetPartitioner interface {
  23. SetPartitioner(partitioner string)
  24. }
  25. func setupTLSConfig(sslOpts *SslOptions) (*tls.Config, error) {
  26. // ca cert is optional
  27. if sslOpts.CaPath != "" {
  28. if sslOpts.RootCAs == nil {
  29. sslOpts.RootCAs = x509.NewCertPool()
  30. }
  31. pem, err := ioutil.ReadFile(sslOpts.CaPath)
  32. if err != nil {
  33. return nil, fmt.Errorf("connectionpool: unable to open CA certs: %v", err)
  34. }
  35. if !sslOpts.RootCAs.AppendCertsFromPEM(pem) {
  36. return nil, errors.New("connectionpool: failed parsing or CA certs")
  37. }
  38. }
  39. if sslOpts.CertPath != "" || sslOpts.KeyPath != "" {
  40. mycert, err := tls.LoadX509KeyPair(sslOpts.CertPath, sslOpts.KeyPath)
  41. if err != nil {
  42. return nil, fmt.Errorf("connectionpool: unable to load X509 key pair: %v", err)
  43. }
  44. sslOpts.Certificates = append(sslOpts.Certificates, mycert)
  45. }
  46. sslOpts.InsecureSkipVerify = !sslOpts.EnableHostVerification
  47. return &sslOpts.Config, nil
  48. }
  49. type policyConnPool struct {
  50. session *Session
  51. port int
  52. numConns int
  53. connCfg *ConnConfig
  54. keyspace string
  55. mu sync.RWMutex
  56. hostPolicy HostSelectionPolicy
  57. connPolicy func() ConnSelectionPolicy
  58. hostConnPools map[string]*hostConnPool
  59. }
  60. func newPolicyConnPool(session *Session, hostPolicy HostSelectionPolicy,
  61. connPolicy func() ConnSelectionPolicy) (*policyConnPool, error) {
  62. var (
  63. err error
  64. tlsConfig *tls.Config
  65. )
  66. cfg := session.cfg
  67. if cfg.SslOpts != nil {
  68. tlsConfig, err = setupTLSConfig(cfg.SslOpts)
  69. if err != nil {
  70. return nil, err
  71. }
  72. }
  73. // create the pool
  74. pool := &policyConnPool{
  75. session: session,
  76. port: cfg.Port,
  77. numConns: cfg.NumConns,
  78. connCfg: &ConnConfig{
  79. ProtoVersion: cfg.ProtoVersion,
  80. CQLVersion: cfg.CQLVersion,
  81. Timeout: cfg.Timeout,
  82. Compressor: cfg.Compressor,
  83. Authenticator: cfg.Authenticator,
  84. Keepalive: cfg.SocketKeepalive,
  85. tlsConfig: tlsConfig,
  86. },
  87. keyspace: cfg.Keyspace,
  88. hostPolicy: hostPolicy,
  89. connPolicy: connPolicy,
  90. hostConnPools: map[string]*hostConnPool{},
  91. }
  92. hosts := make([]HostInfo, len(cfg.Hosts))
  93. for i, hostAddr := range cfg.Hosts {
  94. hosts[i].Peer = hostAddr
  95. }
  96. pool.SetHosts(hosts)
  97. return pool, nil
  98. }
  99. func (p *policyConnPool) SetHosts(hosts []HostInfo) {
  100. p.mu.Lock()
  101. defer p.mu.Unlock()
  102. toRemove := make(map[string]struct{})
  103. for addr := range p.hostConnPools {
  104. toRemove[addr] = struct{}{}
  105. }
  106. // TODO connect to hosts in parallel, but wait for pools to be
  107. // created before returning
  108. for i := range hosts {
  109. pool, exists := p.hostConnPools[hosts[i].Peer]
  110. if !exists {
  111. // create a connection pool for the host
  112. pool = newHostConnPool(
  113. p.session,
  114. hosts[i].Peer,
  115. p.port,
  116. p.numConns,
  117. p.connCfg,
  118. p.keyspace,
  119. p.connPolicy(),
  120. )
  121. p.hostConnPools[hosts[i].Peer] = pool
  122. } else {
  123. // still have this host, so don't remove it
  124. delete(toRemove, hosts[i].Peer)
  125. }
  126. }
  127. for addr := range toRemove {
  128. pool := p.hostConnPools[addr]
  129. delete(p.hostConnPools, addr)
  130. pool.Close()
  131. }
  132. // update the policy
  133. p.hostPolicy.SetHosts(hosts)
  134. }
  135. func (p *policyConnPool) SetPartitioner(partitioner string) {
  136. p.hostPolicy.SetPartitioner(partitioner)
  137. }
  138. func (p *policyConnPool) Size() int {
  139. p.mu.RLock()
  140. count := 0
  141. for _, pool := range p.hostConnPools {
  142. count += pool.Size()
  143. }
  144. p.mu.RUnlock()
  145. return count
  146. }
  147. func (p *policyConnPool) Pick(qry *Query) (SelectedHost, *Conn) {
  148. nextHost := p.hostPolicy.Pick(qry)
  149. var (
  150. host SelectedHost
  151. conn *Conn
  152. )
  153. p.mu.RLock()
  154. defer p.mu.RUnlock()
  155. for conn == nil {
  156. host = nextHost()
  157. if host == nil {
  158. break
  159. } else if host.Info() == nil {
  160. panic(fmt.Sprintf("policy %T returned no host info: %+v", p.hostPolicy, host))
  161. }
  162. pool, ok := p.hostConnPools[host.Info().Peer]
  163. if !ok {
  164. continue
  165. }
  166. conn = pool.Pick(qry)
  167. }
  168. return host, conn
  169. }
  170. func (p *policyConnPool) Close() {
  171. p.mu.Lock()
  172. defer p.mu.Unlock()
  173. // remove the hosts from the policy
  174. p.hostPolicy.SetHosts([]HostInfo{})
  175. // close the pools
  176. for addr, pool := range p.hostConnPools {
  177. delete(p.hostConnPools, addr)
  178. pool.Close()
  179. }
  180. }
  181. // hostConnPool is a connection pool for a single host.
  182. // Connection selection is based on a provided ConnSelectionPolicy
  183. type hostConnPool struct {
  184. session *Session
  185. host string
  186. port int
  187. addr string
  188. size int
  189. connCfg *ConnConfig
  190. keyspace string
  191. policy ConnSelectionPolicy
  192. // protection for conns, closed, filling
  193. mu sync.RWMutex
  194. conns []*Conn
  195. closed bool
  196. filling bool
  197. }
  198. func newHostConnPool(session *Session, host string, port, size int, connCfg *ConnConfig,
  199. keyspace string, policy ConnSelectionPolicy) *hostConnPool {
  200. pool := &hostConnPool{
  201. session: session,
  202. host: host,
  203. port: port,
  204. addr: JoinHostPort(host, port),
  205. size: size,
  206. connCfg: connCfg,
  207. keyspace: keyspace,
  208. policy: policy,
  209. conns: make([]*Conn, 0, size),
  210. filling: false,
  211. closed: false,
  212. }
  213. // fill the pool with the initial connections before returning
  214. pool.fill()
  215. return pool
  216. }
  217. // Pick a connection from this connection pool for the given query.
  218. func (pool *hostConnPool) Pick(qry *Query) *Conn {
  219. pool.mu.RLock()
  220. if pool.closed {
  221. pool.mu.RUnlock()
  222. return nil
  223. }
  224. empty := len(pool.conns) == 0
  225. pool.mu.RUnlock()
  226. if empty {
  227. // try to fill the empty pool
  228. go pool.fill()
  229. return nil
  230. }
  231. return pool.policy.Pick(qry)
  232. }
  233. //Size returns the number of connections currently active in the pool
  234. func (pool *hostConnPool) Size() int {
  235. pool.mu.RLock()
  236. defer pool.mu.RUnlock()
  237. return len(pool.conns)
  238. }
  239. //Close the connection pool
  240. func (pool *hostConnPool) Close() {
  241. pool.mu.Lock()
  242. defer pool.mu.Unlock()
  243. if pool.closed {
  244. return
  245. }
  246. pool.closed = true
  247. // drain, but don't wait
  248. go pool.drain()
  249. }
  250. // Fill the connection pool
  251. func (pool *hostConnPool) fill() {
  252. pool.mu.RLock()
  253. // avoid filling a closed pool, or concurrent filling
  254. if pool.closed || pool.filling {
  255. pool.mu.RUnlock()
  256. return
  257. }
  258. // determine the filling work to be done
  259. startCount := len(pool.conns)
  260. fillCount := pool.size - startCount
  261. // avoid filling a full (or overfull) pool
  262. if fillCount <= 0 {
  263. pool.mu.RUnlock()
  264. return
  265. }
  266. // switch from read to write lock
  267. pool.mu.RUnlock()
  268. pool.mu.Lock()
  269. // double check everything since the lock was released
  270. startCount = len(pool.conns)
  271. fillCount = pool.size - startCount
  272. if pool.closed || pool.filling || fillCount <= 0 {
  273. // looks like another goroutine already beat this
  274. // goroutine to the filling
  275. pool.mu.Unlock()
  276. return
  277. }
  278. // ok fill the pool
  279. pool.filling = true
  280. // allow others to access the pool while filling
  281. pool.mu.Unlock()
  282. // only this goroutine should make calls to fill/empty the pool at this
  283. // point until after this routine or its subordinates calls
  284. // fillingStopped
  285. // fill only the first connection synchronously
  286. if startCount == 0 {
  287. err := pool.connect()
  288. pool.logConnectErr(err)
  289. if err != nil {
  290. // probably unreachable host
  291. go pool.fillingStopped()
  292. return
  293. }
  294. // filled one
  295. fillCount--
  296. // connect all connections to this host in sync
  297. for fillCount > 0 {
  298. err := pool.connect()
  299. pool.logConnectErr(err)
  300. // decrement, even on error
  301. fillCount--
  302. }
  303. go pool.fillingStopped()
  304. return
  305. }
  306. // fill the rest of the pool asynchronously
  307. go func() {
  308. for fillCount > 0 {
  309. err := pool.connect()
  310. pool.logConnectErr(err)
  311. // decrement, even on error
  312. fillCount--
  313. }
  314. // mark the end of filling
  315. pool.fillingStopped()
  316. }()
  317. }
  318. func (pool *hostConnPool) logConnectErr(err error) {
  319. if opErr, ok := err.(*net.OpError); ok && (opErr.Op == "dial" || opErr.Op == "read") {
  320. // connection refused
  321. // these are typical during a node outage so avoid log spam.
  322. } else if err != nil {
  323. // unexpected error
  324. log.Printf("error: failed to connect to %s due to error: %v", pool.addr, err)
  325. }
  326. }
  327. // transition back to a not-filling state.
  328. func (pool *hostConnPool) fillingStopped() {
  329. // wait for some time to avoid back-to-back filling
  330. // this provides some time between failed attempts
  331. // to fill the pool for the host to recover
  332. time.Sleep(time.Duration(rand.Int31n(100)+31) * time.Millisecond)
  333. pool.mu.Lock()
  334. pool.filling = false
  335. pool.mu.Unlock()
  336. }
  337. // create a new connection to the host and add it to the pool
  338. func (pool *hostConnPool) connect() error {
  339. // try to connect
  340. conn, err := Connect(pool.addr, pool.connCfg, pool, pool.session)
  341. if err != nil {
  342. return err
  343. }
  344. if pool.keyspace != "" {
  345. // set the keyspace
  346. if err := conn.UseKeyspace(pool.keyspace); err != nil {
  347. conn.Close()
  348. return err
  349. }
  350. }
  351. // add the Conn to the pool
  352. pool.mu.Lock()
  353. defer pool.mu.Unlock()
  354. if pool.closed {
  355. conn.Close()
  356. return nil
  357. }
  358. pool.conns = append(pool.conns, conn)
  359. pool.policy.SetConns(pool.conns)
  360. return nil
  361. }
  362. // handle any error from a Conn
  363. func (pool *hostConnPool) HandleError(conn *Conn, err error, closed bool) {
  364. if !closed {
  365. // still an open connection, so continue using it
  366. return
  367. }
  368. pool.mu.Lock()
  369. defer pool.mu.Unlock()
  370. if pool.closed {
  371. // pool closed
  372. return
  373. }
  374. // find the connection index
  375. for i, candidate := range pool.conns {
  376. if candidate == conn {
  377. // remove the connection, not preserving order
  378. pool.conns[i], pool.conns = pool.conns[len(pool.conns)-1], pool.conns[:len(pool.conns)-1]
  379. // update the policy
  380. pool.policy.SetConns(pool.conns)
  381. // lost a connection, so fill the pool
  382. go pool.fill()
  383. break
  384. }
  385. }
  386. }
  387. // removes and closes all connections from the pool
  388. func (pool *hostConnPool) drain() {
  389. pool.mu.Lock()
  390. defer pool.mu.Unlock()
  391. // empty the pool
  392. conns := pool.conns
  393. pool.conns = pool.conns[:0]
  394. // update the policy
  395. pool.policy.SetConns(pool.conns)
  396. // close the connections
  397. for _, conn := range conns {
  398. conn.Close()
  399. }
  400. }