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