// NewWatcher adds a new watcher to the events buffer
503337
func (c *CircularBuffer) NewWatcher(ctx context.Context, watch Watch) (Watcher, error) {
	c.Lock()
	defer c.Unlock()

	select {
	case <-c.ctx.Done():
		return nil, trace.BadParameter("buffer is closed")
	default:
	}

	if watch.QueueSize == 0 {
		watch.QueueSize = len(c.events)
	}

	if len(watch.Prefixes) == 0 {
		// if watcher has no prefixes, assume it will match anything
		// starting from the separator (what includes all keys in backend invariant, see Keys function)
		watch.Prefixes = append(watch.Prefixes, []byte{Separator})
	} else {
		// if watcher's prefixes are redundant, keep only shorter prefixes
		// to avoid double fan out
		watch.Prefixes = removeRedundantPrefixes(watch.Prefixes)
	}

	closeCtx, cancel := context.WithCancel(ctx)
	w := &BufferWatcher{
		Watch:    watch,
		eventsC:  make(chan Event, watch.QueueSize),
		ctx:      closeCtx,
		cancel:   cancel,
		capacity: watch.QueueSize,
	}
	c.Debugf("Add %v.", w)
	select {
	case w.eventsC <- Event{Type: OpInit}:
	case <-c.ctx.Done():
		return nil, trace.BadParameter("buffer is closed")
	default:
		c.Warningf("Closing %v, buffer overflow.", w)
		w.Close()
		return nil, trace.BadParameter("buffer overflow")
	}
	c.watchers.add(w)
	return w, nil
}
35158
func NewWatcher() (*Watcher, error) {
	// Create inotify fd
	fd, errno := unix.InotifyInit1(unix.IN_CLOEXEC)
	if fd == -1 {
		return nil, errno
	}
	// Create epoll
	poller, err := newFdPoller(fd)
	if err != nil {
		unix.Close(fd)
		return nil, err
	}
	w := &Watcher{
		fd:       fd,
		poller:   poller,
		watches:  make(map[string]*watch),
		paths:    make(map[int]string),
		Events:   make(chan Event),
		Errors:   make(chan error),
		done:     make(chan struct{}),
		doneResp: make(chan struct{}),
	}

	go w.readEvents()
	return w, nil
}
902067
func NewWatcher() (*Watcher, error) {
	port, e := syscall.CreateIoCompletionPort(syscall.InvalidHandle, 0, 0, 0)
	if e != nil {
		return nil, os.NewSyscallError("CreateIoCompletionPort", e)
	}
	w := &Watcher{
		port:    port,
		watches: make(watchMap),
		input:   make(chan *input, 1),
		Events:  make(chan Event, 50),
		Errors:  make(chan error),
		quit:    make(chan chan<- error, 1),
	}
	go w.readEvents()
	return w, nil
}
895163
func newWaitWorker(config Config, targetVersion int) (worker.Worker, error) {
	watcher, err := config.Facade.WatchModelEnvironVersion(config.ModelTag)
	if err != nil {
		return nil, errors.Trace(err)
	}
	ww := waitWorker{
		watcher:       watcher,
		facade:        config.Facade,
		modelTag:      config.ModelTag,
		gate:          config.GateUnlocker,
		targetVersion: targetVersion,
	}
	if err := catacomb.Invoke(catacomb.Plan{
		Site: &ww.catacomb,
		Init: []worker.Worker{watcher},
		Work: ww.loop,
	}); err != nil {
		return nil, errors.Trace(err)
	}
	return &ww, nil
}
1093158
func (c *consulClient) ListAndWatch(name, prefix string, chanSize int) *Watcher {
	w := newWatcher(name, prefix, chanSize)

	log.WithField(fieldWatcher, w).Debug("Starting watcher...")

	go c.Watch(w)

	return w
}
597348
func (_ENS *ENSFilterer) WatchNewOwner(opts *bind.WatchOpts, sink chan<- *ENSNewOwner, node [][32]byte, label [][32]byte) (event.Subscription, error) {

	var nodeRule []interface{}
	for _, nodeItem := range node {
		nodeRule = append(nodeRule, nodeItem)
	}
	var labelRule []interface{}
	for _, labelItem := range label {
		labelRule = append(labelRule, labelItem)
	}

	logs, sub, err := _ENS.contract.WatchLogs(opts, "NewOwner", nodeRule, labelRule)
	if err != nil {
		return nil, err
	}
	return event.NewSubscription(func(quit <-chan struct{}) error {
		defer sub.Unsubscribe()
		for {
			select {
			case log := <-logs:
				// New log arrived, parse the event and forward to the user
				event := new(ENSNewOwner)
				if err := _ENS.contract.UnpackLog(event, "NewOwner", log); err != nil {
					return err
				}
				event.Raw = log

				select {
				case sink <- event:
				case err := <-sub.Err():
					return err
				case <-quit:
					return nil
				}
			case err := <-sub.Err():
				return err
			case <-quit:
				return nil
			}
		}
	}), nil
}
178202
func (db *BytesConnectionRedis) NewWatcher(prefix string) keyval.BytesWatcher {
	return db.NewBrokerWatcher(prefix)
}
139403
func NewWatcher() (*Watcher, error) {
	port, e := syscall.CreateIoCompletionPort(syscall.InvalidHandle, 0, 0, 0)
	if e != nil {
		return nil, os.NewSyscallError("CreateIoCompletionPort", e)
	}
	w := &Watcher{
		port:          port,
		watches:       make(watchMap),
		fsnFlags:      make(map[string]uint32),
		input:         make(chan *input, 1),
		Event:         make(chan *FileEvent, 50),
		internalEvent: make(chan *FileEvent),
		Error:         make(chan error),
		quit:          make(chan chan<- error, 1),
	}
	go w.readEvents()
	go w.purgeEvents()
	return w, nil
}
507256
func newWatcher(c chan<- EventInfo) watcher {
	r := &readdcw{
		m:   make(map[string]*watched),
		cph: syscall.InvalidHandle,
		c:   c,
	}
	runtime.SetFinalizer(r, func(r *readdcw) {
		if r.cph != syscall.InvalidHandle {
			syscall.CloseHandle(r.cph)
		}
	})
	return r
}
985948
func NewWatcher(paths *model.RevelContainer, eagerRefresh bool) *Watcher {
	return &Watcher{
		forceRefresh:   true,
		lastError:      -1,
		paths:          paths,
		refreshTimerMS: time.Duration(paths.Config.IntDefault("watch.rebuild.delay", 10)),
		eagerRefresh: eagerRefresh ||
			paths.DevMode &&
				paths.Config.BoolDefault("watch", true) &&
				paths.Config.StringDefault("watch.mode", "normal") == "eager",
		timerMutex:          &sync.Mutex{},
		refreshChannel:      make(chan *utils.Error, 10),
		refreshChannelCount: 0,
	}
}
400070
func New() *Watcher {
	// Set up the WaitGroup for w.Wait().
	var wg sync.WaitGroup
	wg.Add(1)

	return &Watcher{
		Event:   make(chan Event),
		Error:   make(chan error),
		Closed:  make(chan struct{}),
		close:   make(chan struct{}),
		mu:      new(sync.Mutex),
		wg:      &wg,
		files:   make(map[string]os.FileInfo),
		ignored: make(map[string]struct{}),
		names:   make(map[string]bool),
	}
}
90683
func (a *AuthWithRoles) NewWatcher(ctx context.Context, watch services.Watch) (services.Watcher, error) {
	if len(watch.Kinds) == 0 {
		return nil, trace.AccessDenied("can't setup global watch")
	}
	for _, kind := range watch.Kinds {
		switch kind.Kind {
		case services.KindNamespace:
			if err := a.action(defaults.Namespace, services.KindNamespace, services.VerbRead); err != nil {
				return nil, trace.Wrap(err)
			}
		case services.KindUser:
			if err := a.action(defaults.Namespace, services.KindUser, services.VerbRead); err != nil {
				return nil, trace.Wrap(err)
			}
		case services.KindRole:
			if err := a.action(defaults.Namespace, services.KindRole, services.VerbRead); err != nil {
				return nil, trace.Wrap(err)
			}
		case services.KindNode:
			if err := a.action(defaults.Namespace, services.KindNode, services.VerbRead); err != nil {
				return nil, trace.Wrap(err)
			}
		case services.KindProxy:
			if err := a.action(defaults.Namespace, services.KindProxy, services.VerbRead); err != nil {
				return nil, trace.Wrap(err)
			}
		case services.KindAuthServer:
			if err := a.action(defaults.Namespace, services.KindAuthServer, services.VerbRead); err != nil {
				return nil, trace.Wrap(err)
			}
		case services.KindTunnelConnection:
			if err := a.action(defaults.Namespace, services.KindTunnelConnection, services.VerbRead); err != nil {
				return nil, trace.Wrap(err)
			}
		case services.KindReverseTunnel:
			if err := a.action(defaults.Namespace, services.KindReverseTunnel, services.VerbRead); err != nil {
				return nil, trace.Wrap(err)
			}
		case services.KindClusterConfig:
			if err := a.action(defaults.Namespace, services.KindClusterConfig, services.VerbRead); err != nil {
				return nil, trace.Wrap(err)
			}
		case services.KindClusterName:
			if err := a.action(defaults.Namespace, services.KindClusterName, services.VerbRead); err != nil {
				return nil, trace.Wrap(err)
			}
		case services.KindToken:
			if err := a.action(defaults.Namespace, services.KindToken, services.VerbRead); err != nil {
				return nil, trace.Wrap(err)
			}
		case services.KindStaticTokens:
			if err := a.action(defaults.Namespace, services.KindStaticTokens, services.VerbRead); err != nil {
				return nil, trace.Wrap(err)
			}
		case services.KindCertAuthority:
			if kind.LoadSecrets {
				if err := a.action(defaults.Namespace, services.KindCertAuthority, services.VerbRead); err != nil {
					return nil, trace.Wrap(err)
				}
			} else {
				if err := a.action(defaults.Namespace, services.KindCertAuthority, services.VerbReadNoSecrets); err != nil {
					return nil, trace.Wrap(err)
				}
			}

		default:
			return nil, trace.AccessDenied("not authorized to watch %v events", kind.Kind)
		}
	}
	switch {
	case a.hasBuiltinRole(string(teleport.RoleProxy)):
		watch.QueueSize = defaults.ProxyQueueSize
	case a.hasBuiltinRole(string(teleport.RoleNode)):
		watch.QueueSize = defaults.NodeQueueSize
	}
	return a.authServer.NewWatcher(ctx, watch)
}
1066929
func (s *Wrapper) NewWatcher(ctx context.Context, watch Watch) (Watcher, error) {
	if err := s.GetReadError(); err != nil {
		return nil, trace.Wrap(err)
	}
	return s.backend.NewWatcher(ctx, watch)
}
1312652
func (s *Sanitizer) NewWatcher(ctx context.Context, watch Watch) (Watcher, error) {
	for _, prefix := range watch.Prefixes {
		if !isKeySafe(prefix) {
			return nil, trace.BadParameter(errorMessage)
		}
	}
	return s.backend.NewWatcher(ctx, watch)
}
161664
func NewWatcher(retry Retry, backoff backoff.Backoff) Watcher {
	return newWatcherWithClock(retry, backoff, glock.NewRealClock())
}
508788
func NewWorker(api Facade, env environs.Environ, credentialAPI common.CredentialAPI) (worker.Worker, error) {
	envNetworking, _ := environs.SupportsNetworking(env)
	w, err := watcher.NewNotifyWorker(watcher.NotifyConfig{
		Handler: &Undertaker{
			API:         api,
			Releaser:    envNetworking,
			CallContext: common.NewCloudCallContext(credentialAPI, nil),
		},
	})
	if err != nil {
		return nil, errors.Trace(err)
	}
	return w, nil
}
604152
func NewWatcher(net, addr, passwd string, names ...string) (w *Watcher, err error) {
	conn, err := DialAuthenticated(net, addr, passwd)
	if err != nil {
		return
	}
	w = &Watcher{
		conn:  conn,
		Event: make(chan string),
		Error: make(chan error),
		done:  make(chan bool),
		// Buffer channels to avoid race conditions with noIdle
		names: make(chan []string, 1),
		exit:  make(chan bool, 1),
	}
	go w.watch(names...)
	return
}