// Monitor automatically reports panics which occur in the function it's called
// from. Must be deferred.
976530
func (client *Client) Monitor() {
	if err := recover(); err != nil {
		client.Notify(newError(err, 2))
		panic(err)
	}
}
239945
func (m *Monitor) Run(looper director.Looper) {
	looper.Loop(func() error {
		log.Debugf("Running checks")

		var wg sync.WaitGroup

		// Make immutable copy of m.Checks (checks are still mutable)
		m.RLock()
		checks := make(map[string]*Check, len(m.Checks))
		for k, v := range m.Checks {
			checks[k] = v
		}
		m.RUnlock()

		wg.Add(len(checks))
		for _, check := range checks {
			// Run all checks in parallel in goroutines
			resultChan := make(chan checkResult, 1)

			go func(check *Check, resultChan chan checkResult) {
				result, err := check.Command.Run(check.Args)
				resultChan <- checkResult{result, err}
			}(check, resultChan) // copy check pointer for the goroutine

			go func(check *Check, resultChan chan checkResult) {
				defer wg.Done()

				// We make the call but we time out if it gets too close to the
				// m.CheckInterval.
				select {
				case result := <-resultChan:
					check.UpdateStatus(result.status, result.err)
				case <-time.After(m.CheckInterval - 1*time.Millisecond):
					log.Errorf("Error, check %s timed out! (%v)", check.ID, check.Args)
					check.UpdateStatus(UNKNOWN, errors.New("Timed out!"))
				}
			}(check, resultChan) // copy check pointer for the goroutine
		}

		// Let's make sure we don't continue to spool up
		// huge quantities of goroutines. Wait on all of them
		// to complete before moving on. This could slow down
		// our check loop if something doesn't time out properly.
		wg.Wait()

		return nil
	})
}
6806
func condMonitor(freq time.Duration, cond *sync.Cond) (*Monitor, error) {
	m := &Monitor{
		tick:   time.NewTicker(freq),
		inited: true,
		cond:   cond,
	}
	m.state.Set(stateRunning)
	if err := m.monitorLoop(); err != nil {
		return nil, err
	}
	return m, nil
}
609424
func (s *State) SetMonitor(m monitor.Monitor) {
	s.mu.Lock()
	defer s.mu.Unlock()

	s.monitor = m
}
781432
func (h *httpStreamHandler) monitorStreamPair(p *httpStreamPair, timeout <-chan time.Time) {
	select {
	case <-timeout:
		err := fmt.Errorf("(conn=%v, request=%s) timed out waiting for streams", h.conn, p.requestID)
		utilruntime.HandleError(err)
		p.printError(err.Error())
	case <-p.complete:
		klog.V(5).Infof("(conn=%v, request=%s) successfully received error and data streams", h.conn, p.requestID)
	}
	h.removeStreamPair(p.requestID)
}
708964
func (p *Phosphor) monitorConfig() {
	configChange := p.configProvider.Notify()
	configTimer := time.NewTicker(configForceReloadTime)
	immediate := make(chan struct{}, 1)
	immediate <- struct{}{}

	for {
		select {
		case <-p.exitChan:
			configTimer.Stop()
			return
		case <-immediate:
		case <-configChange:
		case <-configTimer.C:
		}
		if err := p.reloadConfig(); err != nil {
			log.Warnf("[Phosphor] Failed to reload configuration: %v", err)
		}
	}
}
1201284
func (m *Monitor) GetX11Monitor() C.RROutput {
	ret := C.glfwGetX11Monitor(m.data)
	panicError()
	return ret
}
851368
func (client *DockerClient) monitorEvents(monitorId int64, uri string, callback EventCallback) {
	err := client.sendRequestCallback("GET", uri, nil, nil, func(resp *http.Response) error {
		decoder := json.NewDecoder(resp.Body)
		client.monitorLock.RLock()
		_, toContinue := client.monitors[monitorId]
		client.monitorLock.RUnlock()
		for toContinue {
			var event Event
			if err := decoder.Decode(&event); err != nil {
				return err
			}
			callback(event, nil)
			client.monitorLock.RLock()
			_, toContinue = client.monitors[monitorId]
			client.monitorLock.RUnlock()
		}
		return nil
	}, nil, true)
	if err != nil && err != io.EOF {
		callback(Event{}, err)
	}
}
761545
func RPCMonitor(m *monitor.Monitor) interface{} {
	return func(endpoint string) (*monitor.Node, error) {
		i, n := m.NodeByName(endpoint)
		if i == -1 {
			n = monitor.NewNode(endpoint)
			if err := m.Monitor(n); err != nil {
				return nil, err
			}
		}
		return n, nil
	}
}
767155
func (s *Server) StartExitMonitor() {
	watcher, err := fsnotify.NewWatcher()
	if err != nil {
		logrus.Fatalf("Failed to create new watch: %v", err)
	}
	defer watcher.Close()

	done := make(chan struct{})
	go func() {
		for {
			select {
			case event := <-watcher.Events:
				logrus.Debugf("event: %v", event)
				if event.Op&fsnotify.Create == fsnotify.Create {
					containerID := filepath.Base(event.Name)
					logrus.Debugf("container or sandbox exited: %v", containerID)
					c := s.GetContainer(containerID)
					if c != nil {
						logrus.Debugf("container exited and found: %v", containerID)
						err := s.Runtime().UpdateContainerStatus(c)
						if err != nil {
							logrus.Warnf("Failed to update container status %s: %v", containerID, err)
						} else {
							s.ContainerStateToDisk(c)
						}
					} else {
						sb := s.GetSandbox(containerID)
						if sb != nil {
							c := sb.InfraContainer()
							if c == nil {
								logrus.Warnf("no infra container set for sandbox: %v", containerID)
								continue
							}
							logrus.Debugf("sandbox exited and found: %v", containerID)
							err := s.Runtime().UpdateContainerStatus(c)
							if err != nil {
								logrus.Warnf("Failed to update sandbox infra container status %s: %v", c.ID(), err)
							} else {
								s.ContainerStateToDisk(c)
							}
						}
					}
				}
			case err := <-watcher.Errors:
				logrus.Debugf("watch error: %v", err)
				return
			case <-s.monitorsChan:
				logrus.Debug("closing exit monitor...")
				close(done)
				return
			}
		}
	}()
	if err := watcher.Add(s.config.ContainerExitsDir); err != nil {
		logrus.Errorf("watcher.Add(%q) failed: %s", s.config.ContainerExitsDir, err)
		close(done)
	}
	<-done
}
876508
func (m *Monitor) Watch(disco discovery.Discoverer, looper director.Looper) {
	m.DiscoveryFn = disco.Services // Store this so we can use it from Services()

	looper.Loop(func() error {
		services := disco.Services()

		// Add checks when new services are found
		for _, svc := range services {
			if m.Checks[svc.ID] == nil {
				check := m.CheckForService(&svc, disco)
				if check.Command == nil {
					log.Errorf(
						"Attempted to add %s (id: %s) but no check configured!",
						svc.Name, svc.ID,
					)
				} else {
					m.AddCheck(check)
				}
			}
		}

		m.Lock()
		defer m.Unlock()
	OUTER:
		// We remove checks when encountering a missing service. This
		// prevents us from storing up checks forever. This is the only
		// way we'll find out about a service going away.
		for _, check := range m.Checks {
			for _, svc := range services {
				// Continue if we have a matching service/check pair
				if svc.ID == check.ID {
					continue OUTER
				}
			}

			// Remove checks for services that are no longer running
			delete(m.Checks, check.ID)
		}

		return nil
	})
}
269375
func Monitor(ctx context.Context, cli client.SystemAPIClient, options types.EventsOptions, fun func(m eventtypes.Message)) chan error {
	handler := NewHandler(func(_ eventtypes.Message) string {
		// Let's return always the same thing to not filter at all
		return ""
	})
	handler.Handle("", fun)

	return MonitorWithHandler(ctx, cli, options, handler)
}
1045717
func New(interval time.Duration) *Monitor {
	m := Monitor{
		serial:   SerialDevices{},
		network:  NetworkDevices{},
		Interval: interval,
	}
	return &m
}
428530
func initMonitor(c context.Context, config config) (monitor.Monitor, error) {
	if config.Endpoint == "" {
		logging.Infof(c, "tsmon is disabled because no endpoint is configured")
		return nil, nil
	}
	if strings.ToLower(config.Endpoint) == "none" {
		logging.Infof(c, "tsmon is explicitly disabled")
		return nil, nil
	}

	endpointURL, err := url.Parse(config.Endpoint)
	if err != nil {
		return nil, err
	}

	switch endpointURL.Scheme {
	case "file":
		return monitor.NewDebugMonitor(endpointURL.Path), nil
	case "http", "https":
		client, err := newAuthenticator(c, config.Credentials, config.ActAs, monitor.ProdxmonScopes).Client()
		if err != nil {
			return nil, err
		}

		return monitor.NewHTTPMonitor(c, client, endpointURL)
	default:
		return nil, fmt.Errorf("unknown tsmon endpoint url: %s", config.Endpoint)
	}
}
849973
func (n *LevelLogger) Panic(v ...interface{}) {
	if !n.Enabled() {
		return
	}
	s := fmt.Sprint(v...)
	n.mu.RLock()
	n.logger.Output(callDepth, s)
	n.mu.RUnlock()
	panic(s)
}
98550
func MonitorExternal(clients ...Client) {
	hs := make(HealthState)

	type externalError struct {
		name string
		err  error
	}
	errs := make(chan externalError)
	done := make(chan bool)

	go func() {
		for extErr := range errs {
			hs[extErr.name] = extErr.err
		}
		close(done)
	}()

	var wg sync.WaitGroup
	wg.Add(len(clients))
	for _, client := range clients {
		go func(client Client) {
			if name, err := client.Healthcheck(); err != nil {
				log.ErrorC("unsuccessful healthcheck", err, log.Data{"external_service": name})
				errs <- externalError{name, err}
			}
			wg.Done()
		}(client)
	}

	wg.Wait()
	close(errs)
	<-done

	mutex.Lock()
	healthState = hs
	healthLastChecked = time.Now()
	if len(hs) == 0 {
		healthLastSuccess = healthLastChecked
	}
	mutex.Unlock()
}
380017
func (m *Monitor) Stop() {
	close(m.monitorQuit)

	for _, n := range m.Nodes {
		m.Unmonitor(n)
	}
}