cluster.go 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  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. "errors"
  7. "sync"
  8. "time"
  9. "github.com/golang/groupcache/lru"
  10. )
  11. const defaultMaxPreparedStmts = 1000
  12. //Package global reference to Prepared Statements LRU
  13. var stmtsLRU preparedLRU
  14. //preparedLRU is the prepared statement cache
  15. type preparedLRU struct {
  16. sync.Mutex
  17. lru *lru.Cache
  18. }
  19. //Max adjusts the maximum size of the cache and cleans up the oldest records if
  20. //the new max is lower than the previous value. Not concurrency safe.
  21. func (p *preparedLRU) Max(max int) {
  22. for p.lru.Len() > max {
  23. p.lru.RemoveOldest()
  24. }
  25. p.lru.MaxEntries = max
  26. }
  27. func initStmtsLRU(max int) {
  28. if stmtsLRU.lru != nil {
  29. stmtsLRU.Max(max)
  30. } else {
  31. stmtsLRU.lru = lru.New(max)
  32. }
  33. }
  34. // To enable periodic node discovery enable DiscoverHosts in ClusterConfig
  35. type DiscoveryConfig struct {
  36. // If not empty will filter all discoverred hosts to a single Data Centre (default: "")
  37. DcFilter string
  38. // If not empty will filter all discoverred hosts to a single Rack (default: "")
  39. RackFilter string
  40. // The interval to check for new hosts (default: 30s)
  41. Sleep time.Duration
  42. }
  43. // ClusterConfig is a struct to configure the default cluster implementation
  44. // of gocoql. It has a varity of attributes that can be used to modify the
  45. // behavior to fit the most common use cases. Applications that requre a
  46. // different setup must implement their own cluster.
  47. type ClusterConfig struct {
  48. Hosts []string // addresses for the initial connections
  49. CQLVersion string // CQL version (default: 3.0.0)
  50. ProtoVersion int // version of the native protocol (default: 2)
  51. Timeout time.Duration // connection timeout (default: 600ms)
  52. Port int // port (default: 9042)
  53. Keyspace string // initial keyspace (optional)
  54. NumConns int // number of connections per host (default: 2)
  55. NumStreams int // number of streams per connection (default: max per protocol, either 128 or 32768)
  56. Consistency Consistency // default consistency level (default: Quorum)
  57. Compressor Compressor // compression algorithm (default: nil)
  58. Authenticator Authenticator // authenticator (default: nil)
  59. RetryPolicy RetryPolicy // Default retry policy to use for queries (default: 0)
  60. SocketKeepalive time.Duration // The keepalive period to use, enabled if > 0 (default: 0)
  61. ConnPoolType NewPoolFunc // The function used to create the connection pool for the session (default: NewSimplePool)
  62. DiscoverHosts bool // If set, gocql will attempt to automatically discover other members of the Cassandra cluster (default: false)
  63. MaxPreparedStmts int // Sets the maximum cache size for prepared statements globally for gocql (default: 1000)
  64. PageSize int // Default page size to use for created sessions (default: 0)
  65. Discovery DiscoveryConfig
  66. SslOpts *SslOptions
  67. }
  68. // NewCluster generates a new config for the default cluster implementation.
  69. func NewCluster(hosts ...string) *ClusterConfig {
  70. cfg := &ClusterConfig{
  71. Hosts: hosts,
  72. CQLVersion: "3.0.0",
  73. ProtoVersion: 2,
  74. Timeout: 600 * time.Millisecond,
  75. Port: 9042,
  76. NumConns: 2,
  77. Consistency: Quorum,
  78. ConnPoolType: NewSimplePool,
  79. DiscoverHosts: false,
  80. MaxPreparedStmts: defaultMaxPreparedStmts,
  81. }
  82. return cfg
  83. }
  84. // CreateSession initializes the cluster based on this config and returns a
  85. // session object that can be used to interact with the database.
  86. func (cfg *ClusterConfig) CreateSession() (*Session, error) {
  87. //Check that hosts in the ClusterConfig is not empty
  88. if len(cfg.Hosts) < 1 {
  89. return nil, ErrNoHosts
  90. }
  91. maxStreams := 128
  92. if cfg.ProtoVersion > protoVersion2 {
  93. maxStreams = 32768
  94. }
  95. if cfg.NumStreams <= 0 || cfg.NumStreams > maxStreams {
  96. cfg.NumStreams = maxStreams
  97. }
  98. pool := cfg.ConnPoolType(cfg)
  99. //Adjust the size of the prepared statements cache to match the latest configuration
  100. stmtsLRU.Lock()
  101. initStmtsLRU(cfg.MaxPreparedStmts)
  102. stmtsLRU.Unlock()
  103. //See if there are any connections in the pool
  104. if pool.Size() > 0 {
  105. s := NewSession(pool, *cfg)
  106. s.SetConsistency(cfg.Consistency)
  107. s.SetPageSize(cfg.PageSize)
  108. if cfg.DiscoverHosts {
  109. hostSource := &ringDescriber{
  110. session: s,
  111. dcFilter: cfg.Discovery.DcFilter,
  112. rackFilter: cfg.Discovery.RackFilter,
  113. }
  114. go hostSource.run(cfg.Discovery.Sleep)
  115. }
  116. return s, nil
  117. }
  118. pool.Close()
  119. return nil, ErrNoConnectionsStarted
  120. }
  121. var (
  122. ErrNoHosts = errors.New("no hosts provided")
  123. ErrNoConnectionsStarted = errors.New("no connections were made when creating the session")
  124. ErrHostQueryFailed = errors.New("unable to populate Hosts")
  125. )