connectionpool.go 12 KB

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