connectionpool.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  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. keyspace string
  54. mu sync.RWMutex
  55. hostPolicy HostSelectionPolicy
  56. connPolicy func() ConnSelectionPolicy
  57. hostConnPools map[string]*hostConnPool
  58. endpoints []string
  59. }
  60. func connConfig(session *Session) (*ConnConfig, error) {
  61. cfg := session.cfg
  62. var (
  63. err error
  64. tlsConfig *tls.Config
  65. )
  66. // TODO(zariel): move tls config setup into session init.
  67. if cfg.SslOpts != nil {
  68. tlsConfig, err = setupTLSConfig(cfg.SslOpts)
  69. if err != nil {
  70. return nil, err
  71. }
  72. }
  73. return &ConnConfig{
  74. ProtoVersion: cfg.ProtoVersion,
  75. CQLVersion: cfg.CQLVersion,
  76. Timeout: cfg.Timeout,
  77. Compressor: cfg.Compressor,
  78. Authenticator: cfg.Authenticator,
  79. Keepalive: cfg.SocketKeepalive,
  80. tlsConfig: tlsConfig,
  81. }, nil
  82. }
  83. func newPolicyConnPool(session *Session, hostPolicy HostSelectionPolicy,
  84. connPolicy func() ConnSelectionPolicy) *policyConnPool {
  85. // create the pool
  86. pool := &policyConnPool{
  87. session: session,
  88. port: session.cfg.Port,
  89. numConns: session.cfg.NumConns,
  90. keyspace: session.cfg.Keyspace,
  91. hostPolicy: hostPolicy,
  92. connPolicy: connPolicy,
  93. hostConnPools: map[string]*hostConnPool{},
  94. }
  95. pool.endpoints = make([]string, len(session.cfg.Hosts))
  96. copy(pool.endpoints, session.cfg.Hosts)
  97. return pool
  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 _, host := range hosts {
  109. pool, exists := p.hostConnPools[host.Peer()]
  110. if !exists && host.IsUp() {
  111. // create a connection pool for the host
  112. pool = newHostConnPool(
  113. p.session,
  114. host,
  115. p.port,
  116. p.numConns,
  117. p.keyspace,
  118. p.connPolicy(),
  119. )
  120. p.hostConnPools[host.Peer()] = pool
  121. } else {
  122. // still have this host, so don't remove it
  123. delete(toRemove, host.Peer())
  124. }
  125. }
  126. for addr := range toRemove {
  127. pool := p.hostConnPools[addr]
  128. delete(p.hostConnPools, addr)
  129. pool.Close()
  130. }
  131. // update the policy
  132. p.hostPolicy.SetHosts(hosts)
  133. }
  134. func (p *policyConnPool) SetPartitioner(partitioner string) {
  135. p.hostPolicy.SetPartitioner(partitioner)
  136. }
  137. func (p *policyConnPool) Size() int {
  138. p.mu.RLock()
  139. count := 0
  140. for _, pool := range p.hostConnPools {
  141. count += pool.Size()
  142. }
  143. p.mu.RUnlock()
  144. return count
  145. }
  146. func (p *policyConnPool) Pick(qry *Query) (SelectedHost, *Conn) {
  147. nextHost := p.hostPolicy.Pick(qry)
  148. var (
  149. host SelectedHost
  150. conn *Conn
  151. )
  152. p.mu.RLock()
  153. defer p.mu.RUnlock()
  154. for conn == nil {
  155. host = nextHost()
  156. if host == nil {
  157. break
  158. } else if host.Info() == nil {
  159. panic(fmt.Sprintf("policy %T returned no host info: %+v", p.hostPolicy, host))
  160. }
  161. pool, ok := p.hostConnPools[host.Info().Peer()]
  162. if !ok {
  163. continue
  164. }
  165. conn = pool.Pick(qry)
  166. }
  167. return host, conn
  168. }
  169. func (p *policyConnPool) Close() {
  170. p.mu.Lock()
  171. defer p.mu.Unlock()
  172. // remove the hosts from the policy
  173. p.hostPolicy.SetHosts(nil)
  174. // close the pools
  175. for addr, pool := range p.hostConnPools {
  176. delete(p.hostConnPools, addr)
  177. pool.Close()
  178. }
  179. }
  180. func (p *policyConnPool) addHost(host *HostInfo) {
  181. p.mu.Lock()
  182. defer p.mu.Unlock()
  183. pool, ok := p.hostConnPools[host.Peer()]
  184. if ok {
  185. go pool.fill()
  186. return
  187. }
  188. pool = newHostConnPool(
  189. p.session,
  190. host,
  191. host.Port(),
  192. p.numConns,
  193. p.keyspace,
  194. p.connPolicy(),
  195. )
  196. p.hostConnPools[host.Peer()] = pool
  197. // update policy
  198. // TODO: policy should not have conns, it should have hosts and return a host
  199. // iter which the pool will use to serve conns
  200. p.hostPolicy.AddHost(host)
  201. p.mu.Unlock()
  202. }
  203. func (p *policyConnPool) removeHost(addr string) {
  204. p.hostPolicy.RemoveHost(addr)
  205. p.mu.Lock()
  206. pool, ok := p.hostConnPools[addr]
  207. if !ok {
  208. p.mu.Unlock()
  209. return
  210. }
  211. delete(p.hostConnPools, addr)
  212. p.mu.Unlock()
  213. pool.Close()
  214. }
  215. func (p *policyConnPool) hostUp(host *HostInfo) {
  216. // TODO(zariel): have a set of up hosts and down hosts, we can internally
  217. // detect down hosts, then try to reconnect to them.
  218. p.addHost(host)
  219. }
  220. func (p *policyConnPool) hostDown(addr string) {
  221. // TODO(zariel): mark host as down so we can try to connect to it later, for
  222. // now just treat it has removed.
  223. p.removeHost(addr)
  224. }
  225. // hostConnPool is a connection pool for a single host.
  226. // Connection selection is based on a provided ConnSelectionPolicy
  227. type hostConnPool struct {
  228. session *Session
  229. host *HostInfo
  230. port int
  231. addr string
  232. size int
  233. keyspace string
  234. policy ConnSelectionPolicy
  235. // protection for conns, closed, filling
  236. mu sync.RWMutex
  237. conns []*Conn
  238. closed bool
  239. filling bool
  240. }
  241. func (h *hostConnPool) String() string {
  242. h.mu.RLock()
  243. defer h.mu.RUnlock()
  244. return fmt.Sprintf("[filling=%v closed=%v conns=%v size=%v host=%v]",
  245. h.filling, h.closed, len(h.conns), h.size, h.host)
  246. }
  247. func newHostConnPool(session *Session, host *HostInfo, port, size int,
  248. keyspace string, policy ConnSelectionPolicy) *hostConnPool {
  249. pool := &hostConnPool{
  250. session: session,
  251. host: host,
  252. port: port,
  253. addr: JoinHostPort(host.Peer(), port),
  254. size: size,
  255. keyspace: keyspace,
  256. policy: policy,
  257. conns: make([]*Conn, 0, size),
  258. filling: false,
  259. closed: false,
  260. }
  261. // fill the pool with the initial connections before returning
  262. pool.fill()
  263. return pool
  264. }
  265. // Pick a connection from this connection pool for the given query.
  266. func (pool *hostConnPool) Pick(qry *Query) *Conn {
  267. pool.mu.RLock()
  268. if pool.closed {
  269. pool.mu.RUnlock()
  270. return nil
  271. }
  272. size := len(pool.conns)
  273. pool.mu.RUnlock()
  274. if size < pool.size {
  275. // try to fill the pool
  276. go pool.fill()
  277. if size == 0 {
  278. return nil
  279. }
  280. }
  281. return pool.policy.Pick(qry)
  282. }
  283. //Size returns the number of connections currently active in the pool
  284. func (pool *hostConnPool) Size() int {
  285. pool.mu.RLock()
  286. defer pool.mu.RUnlock()
  287. return len(pool.conns)
  288. }
  289. //Close the connection pool
  290. func (pool *hostConnPool) Close() {
  291. pool.mu.Lock()
  292. defer pool.mu.Unlock()
  293. if pool.closed {
  294. return
  295. }
  296. pool.closed = true
  297. // drain, but don't wait
  298. go pool.drain()
  299. }
  300. // Fill the connection pool
  301. func (pool *hostConnPool) fill() {
  302. pool.mu.RLock()
  303. // avoid filling a closed pool, or concurrent filling
  304. if pool.closed || pool.filling {
  305. pool.mu.RUnlock()
  306. return
  307. }
  308. // determine the filling work to be done
  309. startCount := len(pool.conns)
  310. fillCount := pool.size - startCount
  311. // avoid filling a full (or overfull) pool
  312. if fillCount <= 0 {
  313. pool.mu.RUnlock()
  314. return
  315. }
  316. // switch from read to write lock
  317. pool.mu.RUnlock()
  318. pool.mu.Lock()
  319. // double check everything since the lock was released
  320. startCount = len(pool.conns)
  321. fillCount = pool.size - startCount
  322. if pool.closed || pool.filling || fillCount <= 0 {
  323. // looks like another goroutine already beat this
  324. // goroutine to the filling
  325. pool.mu.Unlock()
  326. return
  327. }
  328. // ok fill the pool
  329. pool.filling = true
  330. // allow others to access the pool while filling
  331. pool.mu.Unlock()
  332. // only this goroutine should make calls to fill/empty the pool at this
  333. // point until after this routine or its subordinates calls
  334. // fillingStopped
  335. // fill only the first connection synchronously
  336. if startCount == 0 {
  337. err := pool.connect()
  338. pool.logConnectErr(err)
  339. if err != nil {
  340. // probably unreachable host
  341. pool.fillingStopped()
  342. // this is calle with the connetion pool mutex held, this call will
  343. // then recursivly try to lock it again. FIXME
  344. go pool.session.handleNodeDown(net.ParseIP(pool.host.Peer()), pool.port)
  345. return
  346. }
  347. // filled one
  348. fillCount--
  349. // connect all connections to this host in sync
  350. for fillCount > 0 {
  351. err := pool.connect()
  352. pool.logConnectErr(err)
  353. // decrement, even on error
  354. fillCount--
  355. }
  356. pool.fillingStopped()
  357. return
  358. }
  359. // fill the rest of the pool asynchronously
  360. go func() {
  361. for fillCount > 0 {
  362. err := pool.connect()
  363. pool.logConnectErr(err)
  364. // decrement, even on error
  365. fillCount--
  366. }
  367. // mark the end of filling
  368. pool.fillingStopped()
  369. }()
  370. }
  371. func (pool *hostConnPool) logConnectErr(err error) {
  372. if opErr, ok := err.(*net.OpError); ok && (opErr.Op == "dial" || opErr.Op == "read") {
  373. // connection refused
  374. // these are typical during a node outage so avoid log spam.
  375. } else if err != nil {
  376. // unexpected error
  377. log.Printf("error: failed to connect to %s due to error: %v", pool.addr, err)
  378. }
  379. }
  380. // transition back to a not-filling state.
  381. func (pool *hostConnPool) fillingStopped() {
  382. // wait for some time to avoid back-to-back filling
  383. // this provides some time between failed attempts
  384. // to fill the pool for the host to recover
  385. time.Sleep(time.Duration(rand.Int31n(100)+31) * time.Millisecond)
  386. pool.mu.Lock()
  387. pool.filling = false
  388. pool.mu.Unlock()
  389. }
  390. // create a new connection to the host and add it to the pool
  391. func (pool *hostConnPool) connect() error {
  392. // try to connect
  393. conn, err := pool.session.connect(pool.addr, pool)
  394. if err != nil {
  395. return err
  396. }
  397. if pool.keyspace != "" {
  398. // set the keyspace
  399. if err := conn.UseKeyspace(pool.keyspace); err != nil {
  400. conn.Close()
  401. return err
  402. }
  403. }
  404. // add the Conn to the pool
  405. pool.mu.Lock()
  406. defer pool.mu.Unlock()
  407. if pool.closed {
  408. conn.Close()
  409. return nil
  410. }
  411. pool.conns = append(pool.conns, conn)
  412. conns := make([]*Conn, len(pool.conns))
  413. copy(conns, pool.conns)
  414. pool.policy.SetConns(conns)
  415. return nil
  416. }
  417. // handle any error from a Conn
  418. func (pool *hostConnPool) HandleError(conn *Conn, err error, closed bool) {
  419. if !closed {
  420. // still an open connection, so continue using it
  421. return
  422. }
  423. // TODO: track the number of errors per host and detect when a host is dead,
  424. // then also have something which can detect when a host comes back.
  425. pool.mu.Lock()
  426. defer pool.mu.Unlock()
  427. if pool.closed {
  428. // pool closed
  429. return
  430. }
  431. // find the connection index
  432. for i, candidate := range pool.conns {
  433. if candidate == conn {
  434. // remove the connection, not preserving order
  435. pool.conns[i], pool.conns = pool.conns[len(pool.conns)-1], pool.conns[:len(pool.conns)-1]
  436. // update the policy
  437. conns := make([]*Conn, len(pool.conns))
  438. copy(conns, pool.conns)
  439. pool.policy.SetConns(conns)
  440. // lost a connection, so fill the pool
  441. go pool.fill()
  442. break
  443. }
  444. }
  445. }
  446. // removes and closes all connections from the pool
  447. func (pool *hostConnPool) drain() {
  448. pool.mu.Lock()
  449. defer pool.mu.Unlock()
  450. // empty the pool
  451. conns := pool.conns
  452. pool.conns = pool.conns[:0:0]
  453. // update the policy
  454. pool.policy.SetConns(nil)
  455. // close the connections
  456. for _, conn := range conns {
  457. conn.Close()
  458. }
  459. }