connectionpool.go 13 KB

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