connectionpool.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  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. "math/rand"
  12. "net"
  13. "sync"
  14. "sync/atomic"
  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. if sslOpts.Config == nil {
  27. sslOpts.Config = &tls.Config{}
  28. }
  29. // ca cert is optional
  30. if sslOpts.CaPath != "" {
  31. if sslOpts.RootCAs == nil {
  32. sslOpts.RootCAs = x509.NewCertPool()
  33. }
  34. pem, err := ioutil.ReadFile(sslOpts.CaPath)
  35. if err != nil {
  36. return nil, fmt.Errorf("connectionpool: unable to open CA certs: %v", err)
  37. }
  38. if !sslOpts.RootCAs.AppendCertsFromPEM(pem) {
  39. return nil, errors.New("connectionpool: failed parsing or CA certs")
  40. }
  41. }
  42. if sslOpts.CertPath != "" || sslOpts.KeyPath != "" {
  43. mycert, err := tls.LoadX509KeyPair(sslOpts.CertPath, sslOpts.KeyPath)
  44. if err != nil {
  45. return nil, fmt.Errorf("connectionpool: unable to load X509 key pair: %v", err)
  46. }
  47. sslOpts.Certificates = append(sslOpts.Certificates, mycert)
  48. }
  49. sslOpts.InsecureSkipVerify = !sslOpts.EnableHostVerification
  50. // return clone to avoid race
  51. return sslOpts.Config.Clone(), nil
  52. }
  53. type policyConnPool struct {
  54. session *Session
  55. port int
  56. numConns int
  57. keyspace string
  58. mu sync.RWMutex
  59. hostConnPools map[string]*hostConnPool
  60. endpoints []string
  61. }
  62. func connConfig(cfg *ClusterConfig) (*ConnConfig, error) {
  63. var (
  64. err error
  65. tlsConfig *tls.Config
  66. )
  67. // TODO(zariel): move tls config setup into session init.
  68. if cfg.SslOpts != nil {
  69. tlsConfig, err = setupTLSConfig(cfg.SslOpts)
  70. if err != nil {
  71. return nil, err
  72. }
  73. }
  74. return &ConnConfig{
  75. ProtoVersion: cfg.ProtoVersion,
  76. CQLVersion: cfg.CQLVersion,
  77. Timeout: cfg.Timeout,
  78. ConnectTimeout: cfg.ConnectTimeout,
  79. Compressor: cfg.Compressor,
  80. Authenticator: cfg.Authenticator,
  81. Keepalive: cfg.SocketKeepalive,
  82. tlsConfig: tlsConfig,
  83. }, nil
  84. }
  85. func newPolicyConnPool(session *Session) *policyConnPool {
  86. // create the pool
  87. pool := &policyConnPool{
  88. session: session,
  89. port: session.cfg.Port,
  90. numConns: session.cfg.NumConns,
  91. keyspace: session.cfg.Keyspace,
  92. hostConnPools: map[string]*hostConnPool{},
  93. }
  94. pool.endpoints = make([]string, len(session.cfg.Hosts))
  95. copy(pool.endpoints, session.cfg.Hosts)
  96. return pool
  97. }
  98. func (p *policyConnPool) SetHosts(hosts []*HostInfo) {
  99. p.mu.Lock()
  100. defer p.mu.Unlock()
  101. toRemove := make(map[string]struct{})
  102. for addr := range p.hostConnPools {
  103. toRemove[addr] = struct{}{}
  104. }
  105. pools := make(chan *hostConnPool)
  106. createCount := 0
  107. for _, host := range hosts {
  108. if !host.IsUp() {
  109. // don't create a connection pool for a down host
  110. continue
  111. }
  112. ip := host.ConnectAddress().String()
  113. if _, exists := p.hostConnPools[ip]; exists {
  114. // still have this host, so don't remove it
  115. delete(toRemove, ip)
  116. continue
  117. }
  118. createCount++
  119. go func(host *HostInfo) {
  120. // create a connection pool for the host
  121. pools <- newHostConnPool(
  122. p.session,
  123. host,
  124. p.port,
  125. p.numConns,
  126. p.keyspace,
  127. )
  128. }(host)
  129. }
  130. // add created pools
  131. for createCount > 0 {
  132. pool := <-pools
  133. createCount--
  134. if pool.Size() > 0 {
  135. // add pool only if there a connections available
  136. p.hostConnPools[string(pool.host.ConnectAddress())] = pool
  137. }
  138. }
  139. for addr := range toRemove {
  140. pool := p.hostConnPools[addr]
  141. delete(p.hostConnPools, addr)
  142. go pool.Close()
  143. }
  144. }
  145. func (p *policyConnPool) Size() int {
  146. p.mu.RLock()
  147. count := 0
  148. for _, pool := range p.hostConnPools {
  149. count += pool.Size()
  150. }
  151. p.mu.RUnlock()
  152. return count
  153. }
  154. func (p *policyConnPool) getPool(host *HostInfo) (pool *hostConnPool, ok bool) {
  155. ip := host.ConnectAddress().String()
  156. p.mu.RLock()
  157. pool, ok = p.hostConnPools[ip]
  158. p.mu.RUnlock()
  159. return
  160. }
  161. func (p *policyConnPool) Close() {
  162. p.mu.Lock()
  163. defer p.mu.Unlock()
  164. // close the pools
  165. for addr, pool := range p.hostConnPools {
  166. delete(p.hostConnPools, addr)
  167. pool.Close()
  168. }
  169. }
  170. func (p *policyConnPool) addHost(host *HostInfo) {
  171. ip := host.ConnectAddress().String()
  172. p.mu.Lock()
  173. pool, ok := p.hostConnPools[ip]
  174. if !ok {
  175. pool = newHostConnPool(
  176. p.session,
  177. host,
  178. host.Port(), // TODO: if port == 0 use pool.port?
  179. p.numConns,
  180. p.keyspace,
  181. )
  182. p.hostConnPools[ip] = pool
  183. }
  184. p.mu.Unlock()
  185. pool.fill()
  186. }
  187. func (p *policyConnPool) removeHost(ip net.IP) {
  188. k := ip.String()
  189. p.mu.Lock()
  190. pool, ok := p.hostConnPools[k]
  191. if !ok {
  192. p.mu.Unlock()
  193. return
  194. }
  195. delete(p.hostConnPools, k)
  196. p.mu.Unlock()
  197. go pool.Close()
  198. }
  199. func (p *policyConnPool) hostUp(host *HostInfo) {
  200. // TODO(zariel): have a set of up hosts and down hosts, we can internally
  201. // detect down hosts, then try to reconnect to them.
  202. p.addHost(host)
  203. }
  204. func (p *policyConnPool) hostDown(ip net.IP) {
  205. // TODO(zariel): mark host as down so we can try to connect to it later, for
  206. // now just treat it has removed.
  207. p.removeHost(ip)
  208. }
  209. // hostConnPool is a connection pool for a single host.
  210. // Connection selection is based on a provided ConnSelectionPolicy
  211. type hostConnPool struct {
  212. session *Session
  213. host *HostInfo
  214. port int
  215. addr string
  216. size int
  217. keyspace string
  218. // protection for conns, closed, filling
  219. mu sync.RWMutex
  220. conns []*Conn
  221. closed bool
  222. filling bool
  223. pos uint32
  224. }
  225. func (h *hostConnPool) String() string {
  226. h.mu.RLock()
  227. defer h.mu.RUnlock()
  228. return fmt.Sprintf("[filling=%v closed=%v conns=%v size=%v host=%v]",
  229. h.filling, h.closed, len(h.conns), h.size, h.host)
  230. }
  231. func newHostConnPool(session *Session, host *HostInfo, port, size int,
  232. keyspace string) *hostConnPool {
  233. pool := &hostConnPool{
  234. session: session,
  235. host: host,
  236. port: port,
  237. addr: (&net.TCPAddr{IP: host.ConnectAddress(), Port: host.Port()}).String(),
  238. size: size,
  239. keyspace: keyspace,
  240. conns: make([]*Conn, 0, size),
  241. filling: false,
  242. closed: false,
  243. }
  244. // the pool is not filled or connected
  245. return pool
  246. }
  247. // Pick a connection from this connection pool for the given query.
  248. func (pool *hostConnPool) Pick() *Conn {
  249. pool.mu.RLock()
  250. defer pool.mu.RUnlock()
  251. if pool.closed {
  252. return nil
  253. }
  254. size := len(pool.conns)
  255. if size < pool.size {
  256. // try to fill the pool
  257. go pool.fill()
  258. if size == 0 {
  259. return nil
  260. }
  261. }
  262. pos := int(atomic.AddUint32(&pool.pos, 1) - 1)
  263. var (
  264. leastBusyConn *Conn
  265. streamsAvailable int
  266. )
  267. // find the conn which has the most available streams, this is racy
  268. for i := 0; i < size; i++ {
  269. conn := pool.conns[(pos+i)%size]
  270. if streams := conn.AvailableStreams(); streams > streamsAvailable {
  271. leastBusyConn = conn
  272. streamsAvailable = streams
  273. }
  274. }
  275. return leastBusyConn
  276. }
  277. //Size returns the number of connections currently active in the pool
  278. func (pool *hostConnPool) Size() int {
  279. pool.mu.RLock()
  280. defer pool.mu.RUnlock()
  281. return len(pool.conns)
  282. }
  283. //Close the connection pool
  284. func (pool *hostConnPool) Close() {
  285. pool.mu.Lock()
  286. if pool.closed {
  287. pool.mu.Unlock()
  288. return
  289. }
  290. pool.closed = true
  291. // ensure we dont try to reacquire the lock in handleError
  292. // TODO: improve this as the following can happen
  293. // 1) we have locked pool.mu write lock
  294. // 2) conn.Close calls conn.closeWithError(nil)
  295. // 3) conn.closeWithError calls conn.Close() which returns an error
  296. // 4) conn.closeWithError calls pool.HandleError with the error from conn.Close
  297. // 5) pool.HandleError tries to lock pool.mu
  298. // deadlock
  299. // empty the pool
  300. conns := pool.conns
  301. pool.conns = nil
  302. pool.mu.Unlock()
  303. // close the connections
  304. for _, conn := range conns {
  305. conn.Close()
  306. }
  307. }
  308. // Fill the connection pool
  309. func (pool *hostConnPool) fill() {
  310. pool.mu.RLock()
  311. // avoid filling a closed pool, or concurrent filling
  312. if pool.closed || pool.filling {
  313. pool.mu.RUnlock()
  314. return
  315. }
  316. // determine the filling work to be done
  317. startCount := len(pool.conns)
  318. fillCount := pool.size - startCount
  319. // avoid filling a full (or overfull) pool
  320. if fillCount <= 0 {
  321. pool.mu.RUnlock()
  322. return
  323. }
  324. // switch from read to write lock
  325. pool.mu.RUnlock()
  326. pool.mu.Lock()
  327. // double check everything since the lock was released
  328. startCount = len(pool.conns)
  329. fillCount = pool.size - startCount
  330. if pool.closed || pool.filling || fillCount <= 0 {
  331. // looks like another goroutine already beat this
  332. // goroutine to the filling
  333. pool.mu.Unlock()
  334. return
  335. }
  336. // ok fill the pool
  337. pool.filling = true
  338. // allow others to access the pool while filling
  339. pool.mu.Unlock()
  340. // only this goroutine should make calls to fill/empty the pool at this
  341. // point until after this routine or its subordinates calls
  342. // fillingStopped
  343. // fill only the first connection synchronously
  344. if startCount == 0 {
  345. err := pool.connect()
  346. pool.logConnectErr(err)
  347. if err != nil {
  348. // probably unreachable host
  349. pool.fillingStopped(true)
  350. // this is call with the connection pool mutex held, this call will
  351. // then recursively try to lock it again. FIXME
  352. if pool.session.cfg.ConvictionPolicy.AddFailure(err, pool.host) {
  353. go pool.session.handleNodeDown(pool.host.ConnectAddress(), pool.port)
  354. }
  355. return
  356. }
  357. // filled one
  358. fillCount--
  359. }
  360. // fill the rest of the pool asynchronously
  361. go func() {
  362. err := pool.connectMany(fillCount)
  363. // mark the end of filling
  364. pool.fillingStopped(err != nil)
  365. }()
  366. }
  367. func (pool *hostConnPool) logConnectErr(err error) {
  368. if opErr, ok := err.(*net.OpError); ok && (opErr.Op == "dial" || opErr.Op == "read") {
  369. // connection refused
  370. // these are typical during a node outage so avoid log spam.
  371. if gocqlDebug {
  372. Logger.Printf("unable to dial %q: %v\n", pool.host.ConnectAddress(), err)
  373. }
  374. } else if err != nil {
  375. // unexpected error
  376. Logger.Printf("error: failed to connect to %s due to error: %v", pool.addr, err)
  377. }
  378. }
  379. // transition back to a not-filling state.
  380. func (pool *hostConnPool) fillingStopped(hadError bool) {
  381. if hadError {
  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. }
  387. pool.mu.Lock()
  388. pool.filling = false
  389. pool.mu.Unlock()
  390. }
  391. // connectMany creates new connections concurrent.
  392. func (pool *hostConnPool) connectMany(count int) error {
  393. if count == 0 {
  394. return nil
  395. }
  396. var (
  397. wg sync.WaitGroup
  398. mu sync.Mutex
  399. connectErr error
  400. )
  401. wg.Add(count)
  402. for i := 0; i < count; i++ {
  403. go func() {
  404. defer wg.Done()
  405. err := pool.connect()
  406. pool.logConnectErr(err)
  407. if err != nil {
  408. mu.Lock()
  409. connectErr = err
  410. mu.Unlock()
  411. }
  412. }()
  413. }
  414. // wait for all connections are done
  415. wg.Wait()
  416. return connectErr
  417. }
  418. // create a new connection to the host and add it to the pool
  419. func (pool *hostConnPool) connect() (err error) {
  420. // TODO: provide a more robust connection retry mechanism, we should also
  421. // be able to detect hosts that come up by trying to connect to downed ones.
  422. // try to connect
  423. var conn *Conn
  424. reconnectionPolicy := pool.session.cfg.ReconnectionPolicy
  425. for i := 0; i < reconnectionPolicy.GetMaxRetries(); i++ {
  426. conn, err = pool.session.connect(pool.host, pool)
  427. if err == nil {
  428. break
  429. }
  430. if opErr, isOpErr := err.(*net.OpError); isOpErr {
  431. // if the error is not a temporary error (ex: network unreachable) don't
  432. // retry
  433. if !opErr.Temporary() {
  434. break
  435. }
  436. }
  437. if gocqlDebug {
  438. Logger.Printf("connection failed %q: %v, reconnecting with %T\n",
  439. pool.host.ConnectAddress(), err, reconnectionPolicy)
  440. }
  441. time.Sleep(reconnectionPolicy.GetInterval(i))
  442. }
  443. if err != nil {
  444. return err
  445. }
  446. if pool.keyspace != "" {
  447. // set the keyspace
  448. if err = conn.UseKeyspace(pool.keyspace); err != nil {
  449. conn.Close()
  450. return err
  451. }
  452. }
  453. // add the Conn to the pool
  454. pool.mu.Lock()
  455. defer pool.mu.Unlock()
  456. if pool.closed {
  457. conn.Close()
  458. return nil
  459. }
  460. pool.conns = append(pool.conns, conn)
  461. return nil
  462. }
  463. // handle any error from a Conn
  464. func (pool *hostConnPool) HandleError(conn *Conn, err error, closed bool) {
  465. if !closed {
  466. // still an open connection, so continue using it
  467. return
  468. }
  469. // TODO: track the number of errors per host and detect when a host is dead,
  470. // then also have something which can detect when a host comes back.
  471. pool.mu.Lock()
  472. defer pool.mu.Unlock()
  473. if pool.closed {
  474. // pool closed
  475. return
  476. }
  477. // find the connection index
  478. for i, candidate := range pool.conns {
  479. if candidate == conn {
  480. // remove the connection, not preserving order
  481. pool.conns[i], pool.conns = pool.conns[len(pool.conns)-1], pool.conns[:len(pool.conns)-1]
  482. // lost a connection, so fill the pool
  483. go pool.fill()
  484. break
  485. }
  486. }
  487. }