cluster.go 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  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. MaxRoutingKeyInfo int // Sets the maximum cache size for query info about statements for each session (default: 1000)
  65. PageSize int // Default page size to use for created sessions (default: 0)
  66. Discovery DiscoveryConfig
  67. SslOpts *SslOptions
  68. }
  69. // NewCluster generates a new config for the default cluster implementation.
  70. func NewCluster(hosts ...string) *ClusterConfig {
  71. cfg := &ClusterConfig{
  72. Hosts: hosts,
  73. CQLVersion: "3.0.0",
  74. ProtoVersion: 2,
  75. Timeout: 600 * time.Millisecond,
  76. Port: 9042,
  77. NumConns: 2,
  78. Consistency: Quorum,
  79. ConnPoolType: NewSimplePool,
  80. DiscoverHosts: false,
  81. MaxPreparedStmts: defaultMaxPreparedStmts,
  82. MaxRoutingKeyInfo: 1000,
  83. }
  84. return cfg
  85. }
  86. // CreateSession initializes the cluster based on this config and returns a
  87. // session object that can be used to interact with the database.
  88. func (cfg *ClusterConfig) CreateSession() (*Session, error) {
  89. //Check that hosts in the ClusterConfig is not empty
  90. if len(cfg.Hosts) < 1 {
  91. return nil, ErrNoHosts
  92. }
  93. maxStreams := 128
  94. if cfg.ProtoVersion > protoVersion2 {
  95. maxStreams = 32768
  96. }
  97. if cfg.NumStreams <= 0 || cfg.NumStreams > maxStreams {
  98. cfg.NumStreams = maxStreams
  99. }
  100. pool := cfg.ConnPoolType(cfg)
  101. //Adjust the size of the prepared statements cache to match the latest configuration
  102. stmtsLRU.Lock()
  103. initStmtsLRU(cfg.MaxPreparedStmts)
  104. stmtsLRU.Unlock()
  105. //See if there are any connections in the pool
  106. if pool.Size() > 0 {
  107. s := NewSession(pool, *cfg)
  108. s.SetConsistency(cfg.Consistency)
  109. s.SetPageSize(cfg.PageSize)
  110. if cfg.DiscoverHosts {
  111. hostSource := &ringDescriber{
  112. session: s,
  113. dcFilter: cfg.Discovery.DcFilter,
  114. rackFilter: cfg.Discovery.RackFilter,
  115. }
  116. go hostSource.run(cfg.Discovery.Sleep)
  117. }
  118. return s, nil
  119. }
  120. pool.Close()
  121. return nil, ErrNoConnectionsStarted
  122. }
  123. var (
  124. ErrNoHosts = errors.New("no hosts provided")
  125. ErrNoConnectionsStarted = errors.New("no connections were made when creating the session")
  126. ErrHostQueryFailed = errors.New("unable to populate Hosts")
  127. )