github.com/sym3tri/etcd@v0.2.1-0.20140422215517-a563d82f95d6/store/watcher.go (about) 1 /* 2 Copyright 2013 CoreOS Inc. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package store 18 19 type Watcher struct { 20 EventChan chan *Event 21 stream bool 22 recursive bool 23 sinceIndex uint64 24 hub *watcherHub 25 removed bool 26 remove func() 27 } 28 29 // notify function notifies the watcher. If the watcher interests in the given path, 30 // the function will return true. 31 func (w *Watcher) notify(e *Event, originalPath bool, deleted bool) bool { 32 // watcher is interested the path in three cases and under one condition 33 // the condition is that the event happens after the watcher's sinceIndex 34 35 // 1. the path at which the event happens is the path the watcher is watching at. 36 // For example if the watcher is watching at "/foo" and the event happens at "/foo", 37 // the watcher must be interested in that event. 38 39 // 2. the watcher is a recursive watcher, it interests in the event happens after 40 // its watching path. For example if watcher A watches at "/foo" and it is a recursive 41 // one, it will interest in the event happens at "/foo/bar". 42 43 // 3. when we delete a directory, we need to force notify all the watchers who watches 44 // at the file we need to delete. 45 // For example a watcher is watching at "/foo/bar". And we deletes "/foo". The watcher 46 // should get notified even if "/foo" is not the path it is watching. 47 if (w.recursive || originalPath || deleted) && e.Index() >= w.sinceIndex { 48 // We cannot block here if the EventChan capacity is full, otherwise 49 // etcd will hang. EventChan capacity is full when the rate of 50 // notifications are higher than our send rate. 51 // If this happens, we close the channel. 52 select { 53 case w.EventChan <- e: 54 default: 55 // We have missed a notification. Remove the watcher. 56 // Removing the watcher also closes the EventChan. 57 w.remove() 58 } 59 return true 60 } 61 return false 62 } 63 64 // Remove removes the watcher from watcherHub 65 // The actual remove function is guaranteed to only be executed once 66 func (w *Watcher) Remove() { 67 w.hub.mutex.Lock() 68 defer w.hub.mutex.Unlock() 69 70 close(w.EventChan) 71 w.remove() 72 }