cluster.go 4.2 KB

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