Debian Codegraph @

api/v0/detector/zoo/detect.go

raw symbols SCIP
1 /**
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 */
18
19 package zoo
20
21 import (
22 "encoding/json"
23 "fmt"
24 "math"
25 "net/url"
26 "strconv"
27 "strings"
28 "sync"
29 "sync/atomic"
30 "time"
31
32 "github.com/gogo/protobuf/proto"
33 log "github.com/golang/glog"
34 "github.com/mesos/mesos-go/api/v0/detector"
35 mesos "github.com/mesos/mesos-go/api/v0/mesosproto"
36 )
37
38 const (
39 // prefix for nodes listed at the ZK URL path
40 nodePrefix = "info_"
41 nodeJSONPrefix = "json.info_"
42 defaultMinDetectorCyclePeriod = 1 * time.Second
43 )
44
45 type (
46 ZKInterface interface {
47 Stopped() <-chan struct{}
48 Stop()
49 Data(string) ([]byte, error)
50 WatchChildren(string) (string, <-chan []string, <-chan error)
51 }
52
53 infoCodec func(path, node string) (*mesos.MasterInfo, error)
54
55 // Detector uses ZooKeeper to detect new leading master.
56 MasterDetector struct {
57 // detection should not signal master change listeners more frequently than this
58 cancel func()
59 client ZKInterface
60 done chan struct{}
61 // latch: only install, at most, one ignoreChanged listener; see MasterDetector.Detect
62 ignoreInstalled int32
63 leaderNode string
64 minDetectorCyclePeriod time.Duration
65
66 // guard against concurrent invocations of bootstrapFunc
67 bootstrapLock sync.RWMutex
68 bootstrapFunc func(ZKInterface, <-chan struct{}) (ZKInterface, error) // for one-time zk client initiation
69 }
70 )
71
72 // reasonable default for a noop change listener
73 var ignoreChanged = detector.OnMasterChanged(func(*mesos.MasterInfo) {})
74
75 // MinCyclePeriod is a functional option that determines the highest frequency of master change notifications
76 func MinCyclePeriod(d time.Duration) detector.Option {
77 return func(di interface{}) detector.Option {
78 md := di.(*MasterDetector)
79 old := md.minDetectorCyclePeriod
80 md.minDetectorCyclePeriod = d
81 return MinCyclePeriod(old)
82 }
83 }
84
85 func Bootstrap(f func(ZKInterface, <-chan struct{}) (ZKInterface, error)) detector.Option {
86 return func(di interface{}) detector.Option {
87 md := di.(*MasterDetector)
88 old := md.bootstrapFunc
89 md.bootstrapFunc = f
90 return Bootstrap(old)
91 }
92 }
93
94 // Internal constructor function
95 func NewMasterDetector(zkurls string, options ...detector.Option) (*MasterDetector, error) {
96 zkHosts, zkPath, err := parseZk(zkurls)
97 if err != nil {
98 log.Fatalln("Failed to parse url", err)
99 return nil, err
100 }
101
102 detector := &MasterDetector{
103 minDetectorCyclePeriod: defaultMinDetectorCyclePeriod,
104 done: make(chan struct{}),
105 cancel: func() {},
106 }
107
108 detector.bootstrapFunc = func(client ZKInterface, _ <-chan struct{}) (ZKInterface, error) {
109 if client == nil {
110 return connect2(zkHosts, zkPath)
111 }
112 return client, nil
113 }
114
115 // apply options last so that they can override default behavior
116 for _, opt := range options {
117 opt(detector)
118 }
119
120 log.V(2).Infoln("Created new detector to watch", zkHosts, zkPath)
121 return detector, nil
122 }
123
124 func parseZk(zkurls string) ([]string, string, error) {
125 u, err := url.Parse(zkurls)
126 if err != nil {
127 log.V(1).Infof("failed to parse url: %v", err)
128 return nil, "", err
129 }
130 if u.Scheme != "zk" {
131 return nil, "", fmt.Errorf("invalid url scheme for zk url: '%v'", u.Scheme)
132 }
133 return strings.Split(u.Host, ","), u.Path, nil
134 }
135
136 // returns a chan that, when closed, indicates termination of the detector
137 func (md *MasterDetector) Done() <-chan struct{} {
138 return md.done
139 }
140
141 func (md *MasterDetector) Cancel() {
142 md.bootstrapLock.RLock()
143 defer md.bootstrapLock.RUnlock()
144 md.cancel()
145 }
146
147 func (md *MasterDetector) childrenChanged(path string, list []string, obs detector.MasterChanged) {
148 md.notifyMasterChanged(path, list, obs)
149 md.notifyAllMasters(path, list, obs)
150 }
151
152 func (md *MasterDetector) notifyMasterChanged(path string, list []string, obs detector.MasterChanged) {
153 // mesos v0.24 writes JSON only, v0.23 writes json and protobuf, v0.22 and prior only write protobuf
154 topNode, codec := md.selectTopNode(list)
155 if md.leaderNode == topNode {
156 log.V(2).Infof("ignoring children-changed event, leader has not changed: %v", path)
157 return
158 }
159
160 log.V(2).Infof("changing leader node from %q -> %q", md.leaderNode, topNode)
161 md.leaderNode = topNode
162
163 var masterInfo *mesos.MasterInfo
164 if md.leaderNode != "" {
165 var err error
166 if masterInfo, err = codec(path, topNode); err != nil {
167 log.Errorln(err.Error())
168 }
169 }
170 log.V(2).Infof("detected master info: %+v", masterInfo)
171 logPanic(func() { obs.OnMasterChanged(masterInfo) })
172 }
173
174 // logPanic safely executes the given func, recovering from and logging a panic if one occurs.
175 func logPanic(f func()) {
176 defer func() {
177 if r := recover(); r != nil {
178 log.Errorf("recovered from client panic: %v", r)
179 }
180 }()
181 f()
182 }
183
184 func (md *MasterDetector) pullMasterInfo(path, node string) (*mesos.MasterInfo, error) {
185 data, err := md.client.Data(fmt.Sprintf("%s/%s", path, node))
186 if err != nil {
187 return nil, fmt.Errorf("failed to retrieve leader data: %v", err)
188 }
189
190 masterInfo := &mesos.MasterInfo{}
191 err = proto.Unmarshal(data, masterInfo)
192 if err != nil {
193 return nil, fmt.Errorf("failed to unmarshal protobuf MasterInfo data from zookeeper: %v", err)
194 }
195 return masterInfo, nil
196 }
197
198 func (md *MasterDetector) pullMasterJsonInfo(path, node string) (*mesos.MasterInfo, error) {
199 data, err := md.client.Data(fmt.Sprintf("%s/%s", path, node))
200 if err != nil {
201 return nil, fmt.Errorf("failed to retrieve leader data: %v", err)
202 }
203
204 masterInfo := &mesos.MasterInfo{}
205 err = json.Unmarshal(data, masterInfo)
206 if err != nil {
207 return nil, fmt.Errorf("failed to unmarshal json MasterInfo data from zookeeper: %v", err)
208 }
209 return masterInfo, nil
210 }
211
212 func (md *MasterDetector) notifyAllMasters(path string, list []string, obs detector.MasterChanged) {
213 all, ok := obs.(detector.AllMasters)
214 if !ok {
215 // not interested in entire master list
216 return
217 }
218
219 // mesos v0.24 writes JSON only, v0.23 writes json and protobuf, v0.22 and prior only write protobuf
220 masters := map[string]*mesos.MasterInfo{}
221 tryStore := func(node string, codec infoCodec) {
222 info, err := codec(path, node)
223 if err != nil {
224 log.Errorln(err.Error())
225 } else {
226 masters[info.GetId()] = info
227 }
228 }
229 for _, node := range list {
230 // compare https://github.com/apache/mesos/blob/0.23.0/src/master/detector.cpp#L437
231 if strings.HasPrefix(node, nodePrefix) {
232 tryStore(node, md.pullMasterInfo)
233 } else if strings.HasPrefix(node, nodeJSONPrefix) {
234 tryStore(node, md.pullMasterJsonInfo)
235 } else {
236 continue
237 }
238 }
239 masterList := make([]*mesos.MasterInfo, 0, len(masters))
240 for _, v := range masters {
241 masterList = append(masterList, v)
242 }
243
244 log.V(2).Infof("notifying of master membership change: %+v", masterList)
245 logPanic(func() { all.UpdatedMasters(masterList) })
246 }
247
248 func (md *MasterDetector) callBootstrap() (e error) {
249 log.V(2).Infoln("invoking detector boostrap")
250 md.bootstrapLock.Lock()
251 defer md.bootstrapLock.Unlock()
252
253 clientConfigured := md.client != nil
254
255 md.client, e = md.bootstrapFunc(md.client, md.done)
256 if e == nil && !clientConfigured && md.client != nil {
257 // chain the lifetime of this detector to that of the newly created client impl
258 client := md.client
259 md.cancel = client.Stop
260 go func() {
261 defer close(md.done)
262 <-client.Stopped()
263 }()
264 }
265 return
266 }
267
268 // the first call to Detect will kickstart a connection to zookeeper. a nil change listener may
269 // be spec'd, result of which is a detector that will still listen for master changes and record
270 // leaderhip changes internally but no listener would be notified. Detect may be called more than
271 // once, and each time the spec'd listener will be added to the list of those receiving notifications.
272 func (md *MasterDetector) Detect(f detector.MasterChanged) (err error) {
273 // kickstart zk client connectivity
274 if err := md.callBootstrap(); err != nil {
275 log.V(3).Infoln("failed to execute bootstrap function", err.Error())
276 return err
277 }
278
279 if f == nil {
280 // only ever install, at most, one ignoreChanged listener. multiple instances of it
281 // just consume resources and generate misleading log messages.
282 if !atomic.CompareAndSwapInt32(&md.ignoreInstalled, 0, 1) {
283 log.V(3).Infoln("ignoreChanged listener already installed")
284 return
285 }
286 f = ignoreChanged
287 }
288
289 log.V(3).Infoln("spawning detect()")
290 go md.detect(f)
291 return nil
292 }
293
294 func (md *MasterDetector) detect(f detector.MasterChanged) {
295 log.V(3).Infoln("detecting children at", CurrentPath)
296 detectLoop:
297 for {
298 select {
299 case <-md.Done():
300 return
301 default:
302 }
303 log.V(3).Infoln("watching children at", CurrentPath)
304 path, childrenCh, errCh := md.client.WatchChildren(CurrentPath)
305 rewatch := false
306 for {
307 started := time.Now()
308 select {
309 case children := <-childrenCh:
310 md.childrenChanged(path, children, f)
311 case err, ok := <-errCh:
312 // check for a tie first (required for predictability (tests)); the downside of
313 // doing this is that a listener might get two callbacks back-to-back ("new leader",
314 // followed by "no leader").
315 select {
316 case children := <-childrenCh:
317 md.childrenChanged(path, children, f)
318 default:
319 }
320 if ok {
321 log.V(1).Infoln("child watch ended with error, master lost; error was:", err.Error())
322 } else {
323 // detector shutdown likely...
324 log.V(1).Infoln("child watch ended, master lost")
325 }
326 select {
327 case <-md.Done():
328 return
329 default:
330 if md.leaderNode != "" {
331 log.V(2).Infof("changing leader node from %q -> \"\"", md.leaderNode)
332 md.leaderNode = ""
333 f.OnMasterChanged(nil)
334 }
335 }
336 rewatch = true
337 }
338 // rate-limit master changes
339 if elapsed := time.Now().Sub(started); elapsed > 0 {
340 log.V(2).Infoln("resting before next detection cycle")
341 select {
342 case <-md.Done():
343 return
344 case <-time.After(md.minDetectorCyclePeriod - elapsed): // noop
345 }
346 }
347 if rewatch {
348 continue detectLoop
349 }
350 }
351 }
352 }
353
354 func (md *MasterDetector) selectTopNode(list []string) (topNode string, codec infoCodec) {
355 // mesos v0.24 writes JSON only, v0.23 writes json and protobuf, v0.22 and prior only write protobuf
356 topNode = selectTopNodePrefix(list, nodeJSONPrefix)
357 codec = md.pullMasterJsonInfo
358 if topNode == "" {
359 topNode = selectTopNodePrefix(list, nodePrefix)
360 codec = md.pullMasterInfo
361
362 if topNode != "" {
363 log.Warningf("Leading master is using a Protobuf binary format when registering "+
364 "with Zookeeper (%s): this will be deprecated as of Mesos 0.24 (see MESOS-2340).",
365 topNode)
366 }
367 }
368 return
369 }
370
371 func selectTopNodePrefix(list []string, pre string) (node string) {
372 var leaderSeq uint64 = math.MaxUint64
373
374 for _, v := range list {
375 if !strings.HasPrefix(v, pre) {
376 continue // only care about participants
377 }
378 seqStr := strings.TrimPrefix(v, pre)
379 seq, err := strconv.ParseUint(seqStr, 10, 64)
380 if err != nil {
381 log.Warningf("unexpected zk node format '%s': %v", seqStr, err)
382 continue
383 }
384 if seq < leaderSeq {
385 leaderSeq = seq
386 node = v
387 }
388 }
389
390 if node == "" {
391 log.V(3).Infoln("No top node found.")
392 } else {
393 log.V(3).Infof("Top node selected: '%s'", node)
394 }
395 return node
396 }