// startWatcher starts the fsnotify watcher on the passed paths
422206
func startWatcher(paths []string, ch chan int) {
	watcher, err := fsnotify.NewWatcher()
	if err != nil {
		beeLogger.Log.Fatalf("Could not start the watcher: %v", err)
	}
	defer watcher.Close()

	// Feed the paths to the watcher
	for _, path := range paths {
		if err := watcher.Add(path); err != nil {
			beeLogger.Log.Fatalf("Could not set a watch on path: %v", err)
		}
	}

	for {
		select {
		case evt := <-watcher.Events:
			build := true
			if filepath.Ext(evt.Name) != ".go" {
				continue
			}

			mt := utils.GetFileModTime(evt.Name)
			if t := eventsModTime[evt.Name]; mt == t {
				build = false
			}
			eventsModTime[evt.Name] = mt

			if build {
				go func() {
					if verbose {
						utils.Notify("Rebuilding application with the new changes", "bee")
					}

					// Wait 1s before re-build until there is no file change
					scheduleTime := time.Now().Add(1 * time.Second)
					time.Sleep(time.Until(scheduleTime))
					_, err := buildDebug()
					if err != nil {
						utils.Notify("Build Failed: "+err.Error(), "bee")
					} else {
						ch <- 0 // Notify listeners
					}
				}()
			}
		case err := <-watcher.Errors:
			if err != nil {
				ch <- -1
			}
		}
	}
}
934678
func (api *CloudSpecAPI) WatchCloudSpecChanges() (watcher.NotifyWatcher, error) {
	var results params.NotifyWatchResults
	args := params.Entities{Entities: []params.Entity{{api.modelTag.String()}}}
	err := api.facade.FacadeCall("WatchCloudSpecsChanges", args, &results)
	if err != nil {
		return nil, err
	}
	if n := len(results.Results); n != 1 {
		return nil, errors.Errorf("expected 1 result, got %d", n)
	}
	result := results.Results[0]
	if result.Error != nil {
		return nil, errors.Annotate(result.Error, "API request failed")
	}
	return apiwatcher.NewNotifyWatcher(api.facade.RawAPICaller(), result), nil
}
364651
func (b *EtcdBackend) NewWatcher(ctx context.Context, watch backend.Watch) (backend.Watcher, error) {
	select {
	case <-b.watchStarted.Done():
	case <-ctx.Done():
		return nil, trace.ConnectionProblem(ctx.Err(), "context is closing")
	}
	return b.buf.NewWatcher(ctx, watch)
}
768747
func (fsh *Handler) Watch(paths []string, onEvent func(event fsnotify.Event), onClose func()) error {
	var err error
	fsh.watcher, err = fsnotify.NewWatcher()
	if err != nil {
		return errors.Errorf("failed to init fileDB file system watcher: %v", err)
	}
	for _, path := range paths {
		fsh.watcher.Add(path)
	}

	go func() {
		for {
			select {
			case event, ok := <-fsh.watcher.Events:
				if !ok {
					onClose()
					return
				}
				onEvent(event)
			case err := <-fsh.watcher.Errors:
				if err != nil {
					fsh.log.Errorf("filesystem notification error %v", err)
				}
			}
		}
	}()

	return nil
}
519376
func NewWatcher() *Watcher {
	w := &Watcher{
		pins:         make(map[uintptr]Pin),
		fds:          fdHeap{},
		cmdChan:      make(chan watcherCmd, watcherCmdChanLen),
		Notification: make(chan WatcherNotification, notificationLen),
	}
	heap.Init(&w.fds)
	go w.watch()
	return w
}
549907
func NewWatcher(sockDir string, deprecatedSockDir string) *Watcher {
	return &Watcher{
		path:           sockDir,
		deprecatedPath: deprecatedSockDir,
		fs:             &utilfs.DefaultFs{},

		handlers:    make(map[string]PluginHandler),
		plugins:     make(map[string]pathInfo),
		pluginsPool: make(map[string]map[string]*sync.Mutex),
	}
}
1330119
func AddRecursiveWatch(watcher *fsnotify.Watcher, path string) error {
	file, err := os.Stat(path)
	if err != nil {
		if os.IsNotExist(err) {
			return nil
		}
		return fmt.Errorf("error introspecting path %s: %v", path, err)
	}
	if !file.IsDir() {
		return nil
	}

	folders, err := getSubFolders(path)
	for _, v := range folders {
		klog.V(5).Infof("adding watch on path %s", v)
		err = watcher.Add(v)
		if err != nil {
			// "no space left on device" issues are usually resolved via
			// $ sudo sysctl fs.inotify.max_user_watches=65536
			return fmt.Errorf("error adding watcher for path %s: %v", v, err)
		}
	}
	return nil
}
377256
func (gc *GenericChannelAspect) StartTimer(d time.Duration) {
	timer := time.Tick(d)
	go func() {
		for {
			<-timer
			gc.calculate()
		}
	}()
}
843072
func (w *Watcher) watch(path string) error {
	return w.addWatch(path, sys_AGNOSTIC_EVENTS)
}
409509
func (c *ConnectCALeaf) rootWatcher(ctx context.Context) {
	atomic.AddUint32(&c.testRootWatchStartCount, 1)
	defer atomic.AddUint32(&c.testRootWatchStopCount, 1)

	ch := make(chan cache.UpdateEvent, 1)
	err := c.Cache.Notify(ctx, ConnectCARootName, &structs.DCSpecificRequest{
		Datacenter: c.Datacenter,
	}, "roots", ch)

	notifyChange := func() {
		c.rootWatchMu.Lock()
		defer c.rootWatchMu.Unlock()

		for ch := range c.rootWatchSubscribers {
			select {
			case ch <- struct{}{}:
			default:
				// Don't block - chans are 1-buffered so act as an edge trigger and
				// reload CA state directly from cache so they never "miss" updates.
			}
		}
	}

	if err != nil {
		// Trigger all inflight watchers. We don't pass the error, but they will
		// reload from cache and observe the same error and return it to the caller,
		// or if it's transient, will continue and the next Fetch will get us back
		// into the right state. Seems better than busy loop-retrying here given
		// that almost any error we would see here would also be returned from the
		// cache get this will trigger.
		notifyChange()
		return
	}

	var oldRoots *structs.IndexedCARoots
	// Wait for updates to roots or all requests to stop
	for {
		select {
		case <-ctx.Done():
			return
		case e := <-ch:
			// Root response changed in some way. Note this might be the initial
			// fetch.
			if e.Err != nil {
				// See above rationale about the error propagation
				notifyChange()
				continue
			}

			roots, ok := e.Result.(*structs.IndexedCARoots)
			if !ok {
				// See above rationale about the error propagation
				notifyChange()
				continue
			}

			// Check that the active root is actually different from the last CA
			// config there are many reasons the config might have changed without
			// actually updating the CA root that is signing certs in the cluster.
			// The Fetch calls will also validate this since the first call here we
			// don't know if it changed or not, but there is no point waking up all
			// Fetch calls to check this if we know none of them will need to act on
			// this update.
			if oldRoots != nil && oldRoots.ActiveRootID == roots.ActiveRootID {
				continue
			}

			// Distribute the update to all inflight requests - they will decide
			// whether or not they need to act on it.
			notifyChange()
			oldRoots = roots
		}
	}
}
1191072
func (c *SampleController) StartWatch(namespace string, stopCh chan struct{}) error {

	resourceHandlers := cache.ResourceEventHandlerFuncs{
		AddFunc:    c.onAdd,
		UpdateFunc: c.onUpdate,
		DeleteFunc: c.onDelete,
	}
	restClient := c.sampleClientset.RESTClient()
	watcher := opkit.NewWatcher(sample.SampleResource, namespace, resourceHandlers, restClient)
	go watcher.Watch(&sample.Sample{}, stopCh)
	return nil
}
1281688
func (r *readdcw) watch(path string, event Event, recursive bool) error {
	if event&^(All|fileNotifyChangeAll) != 0 {
		return errors.New("notify: unknown event")
	}

	r.Lock()
	defer r.Unlock()

	if wd, ok := r.m[path]; ok {
		dbgprint("watch: already exists")
		wd.filter &^= stateUnwatch
		return nil
	}

	if err := r.lazyinit(); err != nil {
		return err
	}

	wd, err := newWatched(r.cph, uint32(event), recursive, path)
	if err != nil {
		return err
	}

	r.m[path] = wd
	dbgprint("watch: new watch added")

	return nil
}
16423
func (ns *NamedStopwatch) start(name string) {
	if ns == nil {
		return
	}
	if s, ok := ns.stopwatches[name]; ok {
		s.Start()
	}
}
382832
func (ec *externalControllers) WatchController(controllerUUID string) NotifyWatcher {
	return newEntityWatcher(ec.st, externalControllersC, controllerUUID)
}
135793
func (i *inotify) watch(path string, e Event) (err error) {
	if e&^(All|Event(unix.IN_ALL_EVENTS)) != 0 {
		return errors.New("notify: unknown event")
	}
	if err = i.lazyinit(); err != nil {
		return
	}
	iwd, err := unix.InotifyAddWatch(int(i.fd), path, encode(e))
	if err != nil {
		return
	}
	i.RLock()
	wd := i.m[int32(iwd)]
	i.RUnlock()
	if wd == nil {
		i.Lock()
		if i.m[int32(iwd)] == nil {
			i.m[int32(iwd)] = &watched{path: path, mask: uint32(e)}
		}
		i.Unlock()
	} else {
		i.Lock()
		wd.mask = uint32(e)
		i.Unlock()
	}
	return nil
}
460259
func (m *NodeManager) CloseWatcher(i int) {
	m.mu.Lock()
	defer m.mu.Unlock()

	delete(m.watchers, i)
}
796896
func (i *inotify) Watch(path string, e Event) error {
	return i.watch(path, e)
}