connection.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. // Copyright 2012-present Oliver Eilhard. All rights reserved.
  2. // Use of this source code is governed by a MIT-license.
  3. // See http://olivere.mit-license.org/license.txt for details.
  4. package elastic
  5. import (
  6. "fmt"
  7. "sync"
  8. "time"
  9. )
  10. // conn represents a single connection to a node in a cluster.
  11. type conn struct {
  12. sync.RWMutex
  13. nodeID string // node ID
  14. url string
  15. failures int
  16. dead bool
  17. deadSince *time.Time
  18. }
  19. // newConn creates a new connection to the given URL.
  20. func newConn(nodeID, url string) *conn {
  21. c := &conn{
  22. nodeID: nodeID,
  23. url: url,
  24. }
  25. return c
  26. }
  27. // String returns a representation of the connection status.
  28. func (c *conn) String() string {
  29. c.RLock()
  30. defer c.RUnlock()
  31. return fmt.Sprintf("%s [dead=%v,failures=%d,deadSince=%v]", c.url, c.dead, c.failures, c.deadSince)
  32. }
  33. // NodeID returns the ID of the node of this connection.
  34. func (c *conn) NodeID() string {
  35. c.RLock()
  36. defer c.RUnlock()
  37. return c.nodeID
  38. }
  39. // URL returns the URL of this connection.
  40. func (c *conn) URL() string {
  41. c.RLock()
  42. defer c.RUnlock()
  43. return c.url
  44. }
  45. // IsDead returns true if this connection is marked as dead, i.e. a previous
  46. // request to the URL has been unsuccessful.
  47. func (c *conn) IsDead() bool {
  48. c.RLock()
  49. defer c.RUnlock()
  50. return c.dead
  51. }
  52. // MarkAsDead marks this connection as dead, increments the failures
  53. // counter and stores the current time in dead since.
  54. func (c *conn) MarkAsDead() {
  55. c.Lock()
  56. c.dead = true
  57. if c.deadSince == nil {
  58. utcNow := time.Now().UTC()
  59. c.deadSince = &utcNow
  60. }
  61. c.failures += 1
  62. c.Unlock()
  63. }
  64. // MarkAsAlive marks this connection as eligible to be returned from the
  65. // pool of connections by the selector.
  66. func (c *conn) MarkAsAlive() {
  67. c.Lock()
  68. c.dead = false
  69. c.Unlock()
  70. }
  71. // MarkAsHealthy marks this connection as healthy, i.e. a request has been
  72. // successfully performed with it.
  73. func (c *conn) MarkAsHealthy() {
  74. c.Lock()
  75. c.dead = false
  76. c.deadSince = nil
  77. c.failures = 0
  78. c.Unlock()
  79. }