connectionpool.go 13 KB

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