connectionpool.go 12 KB

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