forked from vitessio/vitess
-
Notifications
You must be signed in to change notification settings - Fork 0
/
conn_cache.go
194 lines (166 loc) · 4.51 KB
/
conn_cache.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
// Copyright 2012, Google Inc. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package zk
import (
"bytes"
"fmt"
"math/rand"
"strings"
"sync"
"time"
log "github.com/golang/glog"
"github.com/youtube/vitess/go/stats"
"launchpad.net/gozk/zookeeper"
)
var (
cachedConnStates = stats.NewCounters("ZkCachedConn")
cachedConnStatesMutex sync.Mutex
)
func init() {
rand.Seed(time.Now().UnixNano())
}
/* When you need to talk to multiple zk cells, you need a simple
abstraction so you aren't caching clients all over the place.
ConnCache guarantees that you have at most one zookeeper connection per cell.
*/
const (
DISCONNECTED = 0
CONNECTING = 1
CONNECTED = 2
)
type cachedConn struct {
mutex sync.Mutex // used to notify if multiple goroutine simultaneously want a connection
zconn Conn
states *stats.States
}
type ConnCache struct {
mutex sync.Mutex
zconnCellMap map[string]*cachedConn // map cell name to connection
useZkocc bool
}
func (cc *ConnCache) setState(zcell string, conn *cachedConn, state int64) {
conn.states.SetState(state)
cachedConnStatesMutex.Lock()
defer cachedConnStatesMutex.Unlock()
cachedConnStates.Set(zcell, state)
}
func (cc *ConnCache) ConnForPath(zkPath string) (cn Conn, err error) {
zcell, err := ZkCellFromZkPath(zkPath)
if err != nil {
return nil, &zookeeper.Error{Op: "dial", Code: zookeeper.ZBADARGUMENTS}
}
cc.mutex.Lock()
if cc.zconnCellMap == nil {
cc.mutex.Unlock()
return nil, &zookeeper.Error{Op: "dial", Code: zookeeper.ZCLOSING}
}
conn, ok := cc.zconnCellMap[zcell]
if !ok {
conn = &cachedConn{}
conn.states = stats.NewStates("ZkCachedConn"+strings.Title(zcell), []string{"Disconnected", "Connecting", "Connected"}, time.Now(), DISCONNECTED)
cc.zconnCellMap[zcell] = conn
}
cc.mutex.Unlock()
// We only want one goroutine at a time trying to connect here, so keep the
// lock during the zk dial process.
conn.mutex.Lock()
defer conn.mutex.Unlock()
if conn.zconn != nil {
return conn.zconn, nil
}
zkAddr, err := ZkPathToZkAddr(zkPath, cc.useZkocc)
if err != nil {
return nil, &zookeeper.Error{Op: "dial", Code: zookeeper.ZBADARGUMENTS}
}
cc.setState(zcell, conn, CONNECTING)
if cc.useZkocc {
conn.zconn, err = DialZkocc(zkAddr, *baseTimeout)
} else {
conn.zconn, err = cc.newZookeeperConn(zkAddr, zcell)
}
if conn.zconn != nil {
cc.setState(zcell, conn, CONNECTED)
} else {
cc.setState(zcell, conn, DISCONNECTED)
}
return conn.zconn, err
}
func (cc *ConnCache) newZookeeperConn(zkAddr, zcell string) (Conn, error) {
conn, session, err := DialZkTimeout(zkAddr, *baseTimeout, *connectTimeout)
if err != nil {
return nil, err
}
go cc.handleSessionEvents(zcell, conn, session)
return conn, nil
}
func (cc *ConnCache) handleSessionEvents(cell string, conn Conn, session <-chan zookeeper.Event) {
closeRequired := false
for event := range session {
switch event.State {
case zookeeper.STATE_EXPIRED_SESSION, zookeeper.STATE_CONNECTING:
closeRequired = true
fallthrough
case zookeeper.STATE_CLOSED:
var cached *cachedConn
cc.mutex.Lock()
if cc.zconnCellMap != nil {
cached = cc.zconnCellMap[cell]
}
cc.mutex.Unlock()
// keek the entry in the map, but nil the Conn
// (that will trigger a re-dial next time
// we ask for a variable)
if cached != nil {
cached.mutex.Lock()
if closeRequired {
cached.zconn.Close()
}
cached.zconn = nil
cached.mutex.Unlock()
cc.setState(cell, cached, DISCONNECTED)
}
log.Infof("zk conn cache: session for cell %v ended: %v", cell, event)
return
default:
log.Infof("zk conn cache: session for cell %v event: %v", cell, event)
}
}
}
func (cc *ConnCache) Close() error {
cc.mutex.Lock()
defer cc.mutex.Unlock()
for _, conn := range cc.zconnCellMap {
conn.mutex.Lock()
if conn.zconn != nil {
conn.zconn.Close()
conn.zconn = nil
}
conn.mutex.Unlock()
}
cc.zconnCellMap = nil
return nil
}
// Implements expvar.Var()
func (cc *ConnCache) String() string {
cc.mutex.Lock()
defer cc.mutex.Unlock()
b := bytes.NewBuffer(make([]byte, 0, 4096))
fmt.Fprintf(b, "{")
firstCell := true
for cell, conn := range cc.zconnCellMap {
if firstCell {
firstCell = false
} else {
fmt.Fprintf(b, ", ")
}
fmt.Fprintf(b, "\"%v\": %v", cell, conn.states.String())
}
fmt.Fprintf(b, "}")
return b.String()
}
func NewConnCache(useZkocc bool) *ConnCache {
return &ConnCache{
zconnCellMap: make(map[string]*cachedConn),
useZkocc: useZkocc}
}