Skip to content

Commit 5420bed

Browse files
axwkarmi
authored andcommitted
estransport: refactor Next/Resurrect
Refactor Next and Resurrect to share most of the code. This fixes a bug whereby metrics would not have been updated. (cherry picked from commit 360c693)
1 parent cf9f4d0 commit 5420bed

File tree

1 file changed

+20
-26
lines changed

1 file changed

+20
-26
lines changed

estransport/connection.go

Lines changed: 20 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -99,33 +99,22 @@ func (cp *singleConnectionPool) Remove(c *Connection) error {
9999
// Next returns a connection from pool, or an error.
100100
//
101101
func (cp *roundRobinConnectionPool) Next() (*Connection, error) {
102-
var c *Connection
103-
104102
cp.Lock()
105103
defer cp.Unlock()
106104

107105
// Return next live connection
108106
if len(cp.live) > 0 {
109107
cp.curr = (cp.curr + 1) % len(cp.live)
110108
return cp.live[cp.curr], nil
111-
112109
} else if len(cp.dead) > 0 {
113-
// Try to resurrect a dead connection if no live connections are available
114-
if cp.debugLogger != nil {
115-
cp.debugLogger.Log("Resurrecting connection ")
116-
}
117-
c, cp.dead = cp.dead[len(cp.dead)-1], cp.dead[:len(cp.dead)-1] // Pop item
110+
// No live connections are available, resurrect one
111+
// of the dead connections with the fewest failures.
112+
c := cp.dead[len(cp.dead)-1]
113+
cp.dead = cp.dead[:len(cp.dead)-1]
118114
c.Lock()
119-
if cp.debugLogger != nil {
120-
cp.debugLogger.Log(c.URL.String() + "\n")
121-
}
122-
c.markAsLive()
123-
cp.live = append(cp.live, c)
124-
c.Unlock()
125-
126-
return c, nil
115+
defer c.Unlock()
116+
return c, cp.resurrectLocked(c, false)
127117
}
128-
129118
return nil, errors.New("no connection available")
130119
}
131120

@@ -209,24 +198,29 @@ func (cp *roundRobinConnectionPool) Resurrect(c *Connection) error {
209198
}
210199
return nil
211200
}
201+
return cp.resurrectLocked(c, true)
202+
}
212203

204+
func (cp *roundRobinConnectionPool) resurrectLocked(c *Connection, removeDead bool) error {
213205
if cp.debugLogger != nil {
214206
cp.debugLogger.Logf("Resurrecting %s\n", c.URL)
215207
}
216208

217209
c.markAsLive()
218210

219211
cp.live = append(cp.live, c)
220-
index := -1
221-
for i, conn := range cp.dead {
222-
if conn == c {
223-
index = i
212+
if removeDead {
213+
index := -1
214+
for i, conn := range cp.dead {
215+
if conn == c {
216+
index = i
217+
}
218+
}
219+
if index >= 0 {
220+
// Remove item; https://github.com/golang/go/wiki/SliceTricks
221+
copy(cp.dead[index:], cp.dead[index+1:])
222+
cp.dead = cp.dead[:len(cp.dead)-1]
224223
}
225-
}
226-
if index >= 0 {
227-
// Remove item; https://github.com/golang/go/wiki/SliceTricks
228-
copy(cp.dead[index:], cp.dead[index+1:])
229-
cp.dead = cp.dead[:len(cp.dead)-1]
230224
}
231225

232226
if cp.enableMetrics {

0 commit comments

Comments
 (0)