connectionpool.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  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. NumStreams: cfg.NumStreams,
  83. Compressor: cfg.Compressor,
  84. Authenticator: cfg.Authenticator,
  85. Keepalive: cfg.SocketKeepalive,
  86. tlsConfig: tlsConfig,
  87. },
  88. keyspace: cfg.Keyspace,
  89. hostPolicy: hostPolicy,
  90. connPolicy: connPolicy,
  91. hostConnPools: map[string]*hostConnPool{},
  92. }
  93. hosts := make([]HostInfo, len(cfg.Hosts))
  94. for i, hostAddr := range cfg.Hosts {
  95. hosts[i].Peer = hostAddr
  96. }
  97. pool.SetHosts(hosts)
  98. return pool, nil
  99. }
  100. func (p *policyConnPool) SetHosts(hosts []HostInfo) {
  101. p.mu.Lock()
  102. defer p.mu.Unlock()
  103. toRemove := make(map[string]struct{})
  104. for addr := range p.hostConnPools {
  105. toRemove[addr] = struct{}{}
  106. }
  107. // TODO connect to hosts in parallel, but wait for pools to be
  108. // created before returning
  109. for i := range hosts {
  110. pool, exists := p.hostConnPools[hosts[i].Peer]
  111. if !exists {
  112. // create a connection pool for the host
  113. pool = newHostConnPool(
  114. p.session,
  115. hosts[i].Peer,
  116. p.port,
  117. p.numConns,
  118. p.connCfg,
  119. p.keyspace,
  120. p.connPolicy(),
  121. )
  122. p.hostConnPools[hosts[i].Peer] = pool
  123. } else {
  124. // still have this host, so don't remove it
  125. delete(toRemove, hosts[i].Peer)
  126. }
  127. }
  128. for addr := range toRemove {
  129. pool := p.hostConnPools[addr]
  130. delete(p.hostConnPools, addr)
  131. pool.Close()
  132. }
  133. // update the policy
  134. p.hostPolicy.SetHosts(hosts)
  135. }
  136. func (p *policyConnPool) SetPartitioner(partitioner string) {
  137. p.hostPolicy.SetPartitioner(partitioner)
  138. }
  139. func (p *policyConnPool) Size() int {
  140. p.mu.RLock()
  141. count := 0
  142. for _, pool := range p.hostConnPools {
  143. count += pool.Size()
  144. }
  145. p.mu.RUnlock()
  146. return count
  147. }
  148. func (p *policyConnPool) Pick(qry *Query) (SelectedHost, *Conn) {
  149. nextHost := p.hostPolicy.Pick(qry)
  150. var (
  151. host SelectedHost
  152. conn *Conn
  153. )
  154. p.mu.RLock()
  155. defer p.mu.RUnlock()
  156. for conn == nil {
  157. host = nextHost()
  158. if host == nil {
  159. break
  160. } else if host.Info() == nil {
  161. panic(fmt.Sprintf("policy %T returned no host info: %+v", p.hostPolicy, host))
  162. }
  163. pool, ok := p.hostConnPools[host.Info().Peer]
  164. if !ok {
  165. continue
  166. }
  167. conn = pool.Pick(qry)
  168. }
  169. return host, conn
  170. }
  171. func (p *policyConnPool) Close() {
  172. p.mu.Lock()
  173. defer p.mu.Unlock()
  174. // remove the hosts from the policy
  175. p.hostPolicy.SetHosts([]HostInfo{})
  176. // close the pools
  177. for addr, pool := range p.hostConnPools {
  178. delete(p.hostConnPools, addr)
  179. pool.Close()
  180. }
  181. }
  182. // hostConnPool is a connection pool for a single host.
  183. // Connection selection is based on a provided ConnSelectionPolicy
  184. type hostConnPool struct {
  185. session *Session
  186. host string
  187. port int
  188. addr string
  189. size int
  190. connCfg *ConnConfig
  191. keyspace string
  192. policy ConnSelectionPolicy
  193. // protection for conns, closed, filling
  194. mu sync.RWMutex
  195. conns []*Conn
  196. closed bool
  197. filling bool
  198. }
  199. func newHostConnPool(session *Session, host string, port, size int, connCfg *ConnConfig,
  200. keyspace string, policy ConnSelectionPolicy) *hostConnPool {
  201. pool := &hostConnPool{
  202. session: session,
  203. host: host,
  204. port: port,
  205. addr: JoinHostPort(host, port),
  206. size: size,
  207. connCfg: connCfg,
  208. keyspace: keyspace,
  209. policy: policy,
  210. conns: make([]*Conn, 0, size),
  211. filling: false,
  212. closed: false,
  213. }
  214. // fill the pool with the initial connections before returning
  215. pool.fill()
  216. return pool
  217. }
  218. // Pick a connection from this connection pool for the given query.
  219. func (pool *hostConnPool) Pick(qry *Query) *Conn {
  220. pool.mu.RLock()
  221. if pool.closed {
  222. pool.mu.RUnlock()
  223. return nil
  224. }
  225. empty := len(pool.conns) == 0
  226. pool.mu.RUnlock()
  227. if empty {
  228. // try to fill the empty pool
  229. go pool.fill()
  230. return nil
  231. }
  232. return pool.policy.Pick(qry)
  233. }
  234. //Size returns the number of connections currently active in the pool
  235. func (pool *hostConnPool) Size() int {
  236. pool.mu.RLock()
  237. defer pool.mu.RUnlock()
  238. return len(pool.conns)
  239. }
  240. //Close the connection pool
  241. func (pool *hostConnPool) Close() {
  242. pool.mu.Lock()
  243. defer pool.mu.Unlock()
  244. if pool.closed {
  245. return
  246. }
  247. pool.closed = true
  248. // drain, but don't wait
  249. go pool.drain()
  250. }
  251. // Fill the connection pool
  252. func (pool *hostConnPool) fill() {
  253. pool.mu.RLock()
  254. // avoid filling a closed pool, or concurrent filling
  255. if pool.closed || pool.filling {
  256. pool.mu.RUnlock()
  257. return
  258. }
  259. // determine the filling work to be done
  260. startCount := len(pool.conns)
  261. fillCount := pool.size - startCount
  262. // avoid filling a full (or overfull) pool
  263. if fillCount <= 0 {
  264. pool.mu.RUnlock()
  265. return
  266. }
  267. // switch from read to write lock
  268. pool.mu.RUnlock()
  269. pool.mu.Lock()
  270. // double check everything since the lock was released
  271. startCount = len(pool.conns)
  272. fillCount = pool.size - startCount
  273. if pool.closed || pool.filling || fillCount <= 0 {
  274. // looks like another goroutine already beat this
  275. // goroutine to the filling
  276. pool.mu.Unlock()
  277. return
  278. }
  279. // ok fill the pool
  280. pool.filling = true
  281. // allow others to access the pool while filling
  282. pool.mu.Unlock()
  283. // only this goroutine should make calls to fill/empty the pool at this
  284. // point until after this routine or its subordinates calls
  285. // fillingStopped
  286. // fill only the first connection synchronously
  287. if startCount == 0 {
  288. err := pool.connect()
  289. pool.logConnectErr(err)
  290. if err != nil {
  291. // probably unreachable host
  292. go pool.fillingStopped()
  293. return
  294. }
  295. // filled one
  296. fillCount--
  297. // connect all connections to this host in sync
  298. for fillCount > 0 {
  299. err := pool.connect()
  300. pool.logConnectErr(err)
  301. // decrement, even on error
  302. fillCount--
  303. }
  304. go pool.fillingStopped()
  305. return
  306. }
  307. // fill the rest of the pool asynchronously
  308. go func() {
  309. for fillCount > 0 {
  310. err := pool.connect()
  311. pool.logConnectErr(err)
  312. // decrement, even on error
  313. fillCount--
  314. }
  315. // mark the end of filling
  316. pool.fillingStopped()
  317. }()
  318. }
  319. func (pool *hostConnPool) logConnectErr(err error) {
  320. if opErr, ok := err.(*net.OpError); ok && (opErr.Op == "dial" || opErr.Op == "read") {
  321. // connection refused
  322. // these are typical during a node outage so avoid log spam.
  323. } else if err != nil {
  324. // unexpected error
  325. log.Printf("error: failed to connect to %s due to error: %v", pool.addr, err)
  326. }
  327. }
  328. // transition back to a not-filling state.
  329. func (pool *hostConnPool) fillingStopped() {
  330. // wait for some time to avoid back-to-back filling
  331. // this provides some time between failed attempts
  332. // to fill the pool for the host to recover
  333. time.Sleep(time.Duration(rand.Int31n(100)+31) * time.Millisecond)
  334. pool.mu.Lock()
  335. pool.filling = false
  336. pool.mu.Unlock()
  337. }
  338. // create a new connection to the host and add it to the pool
  339. func (pool *hostConnPool) connect() error {
  340. // try to connect
  341. conn, err := Connect(pool.addr, pool.connCfg, pool, pool.session)
  342. if err != nil {
  343. return err
  344. }
  345. if pool.keyspace != "" {
  346. // set the keyspace
  347. if err := conn.UseKeyspace(pool.keyspace); err != nil {
  348. conn.Close()
  349. return err
  350. }
  351. }
  352. // add the Conn to the pool
  353. pool.mu.Lock()
  354. defer pool.mu.Unlock()
  355. if pool.closed {
  356. conn.Close()
  357. return nil
  358. }
  359. pool.conns = append(pool.conns, conn)
  360. pool.policy.SetConns(pool.conns)
  361. return nil
  362. }
  363. // handle any error from a Conn
  364. func (pool *hostConnPool) HandleError(conn *Conn, err error, closed bool) {
  365. if !closed {
  366. // still an open connection, so continue using it
  367. return
  368. }
  369. pool.mu.Lock()
  370. defer pool.mu.Unlock()
  371. if pool.closed {
  372. // pool closed
  373. return
  374. }
  375. // find the connection index
  376. for i, candidate := range pool.conns {
  377. if candidate == conn {
  378. // remove the connection, not preserving order
  379. pool.conns[i], pool.conns = pool.conns[len(pool.conns)-1], pool.conns[:len(pool.conns)-1]
  380. // update the policy
  381. pool.policy.SetConns(pool.conns)
  382. // lost a connection, so fill the pool
  383. go pool.fill()
  384. break
  385. }
  386. }
  387. }
  388. // removes and closes all connections from the pool
  389. func (pool *hostConnPool) drain() {
  390. pool.mu.Lock()
  391. defer pool.mu.Unlock()
  392. // empty the pool
  393. conns := pool.conns
  394. pool.conns = pool.conns[:0]
  395. // update the policy
  396. pool.policy.SetConns(pool.conns)
  397. // close the connections
  398. for _, conn := range conns {
  399. conn.Close()
  400. }
  401. }