// Monitor sned MONITOR command to redis server.
165878
func (r *Redis) Monitor() (*MonitorCommand, error) {
	c, err := r.pool.Get()
	if err != nil {
		return nil, err
	}
	if err := c.SendCommand("MONITOR"); err != nil {
		return nil, err
	}
	rp, err := c.RecvReply()
	if err != nil {
		return nil, err
	}
	if err := rp.OKValue(); err != nil {
		return nil, err
	}
	return &MonitorCommand{r, c}, nil
}
1134803
func (m *MonitorCommand) Receive() (string, error) {
	rp, err := m.conn.RecvReply()
	if err != nil {
		return "", err
	}
	return rp.StatusValue()
}
795617
func (api *ProxyLBAPI) Monitor(id int64, body *sacloud.ResourceMonitorRequest) (*sacloud.MonitorValues, error) {
	return api.baseAPI.applianceMonitorBy(id, "activity/proxylb", 0, body)
}
1345075
func (s *Server) ExecSync(ctx context.Context, req *pb.ExecSyncRequest) (resp *pb.ExecSyncResponse, err error) {
	const operation = "exec_sync"
	defer func() {
		recordOperation(operation, time.Now())
		recordError(operation, err)
	}()
	logrus.Debugf("ExecSyncRequest %+v", req)
	c, err := s.GetContainerFromShortID(req.ContainerId)
	if err != nil {
		return nil, err
	}

	if err = s.Runtime().UpdateContainerStatus(c); err != nil {
		return nil, err
	}

	cState := c.State()
	if !(cState.Status == oci.ContainerStateRunning || cState.Status == oci.ContainerStateCreated) {
		return nil, fmt.Errorf("container is not created or running")
	}

	cmd := req.Cmd
	if cmd == nil {
		return nil, fmt.Errorf("exec command cannot be empty")
	}

	execResp, err := s.Runtime().ExecSyncContainer(c, cmd, req.Timeout)
	if err != nil {
		return nil, err
	}
	resp = &pb.ExecSyncResponse{
		Stdout:   execResp.Stdout,
		Stderr:   execResp.Stderr,
		ExitCode: execResp.ExitCode,
	}

	logrus.Infof("Exec'd %s in %s", cmd, c.Description())
	logrus.Debugf("ExecSyncResponse: %+v", resp)
	return resp, nil
}
83621
func (s *notifySocket) run(pid1 int) {
	buf := make([]byte, 512)
	notifySocketHostAddr := net.UnixAddr{Name: s.host, Net: "unixgram"}
	client, err := net.DialUnix("unixgram", nil, &notifySocketHostAddr)
	if err != nil {
		logrus.Error(err)
		return
	}
	for {
		r, err := s.socket.Read(buf)
		if err != nil {
			break
		}
		var out bytes.Buffer
		for _, line := range bytes.Split(buf[0:r], []byte{'\n'}) {
			if bytes.HasPrefix(line, []byte("READY=")) {
				_, err = out.Write(line)
				if err != nil {
					return
				}

				_, err = out.Write([]byte{'\n'})
				if err != nil {
					return
				}

				_, err = client.Write(out.Bytes())
				if err != nil {
					return
				}

				// now we can inform systemd to use pid1 as the pid to monitor
				if pid1 > 0 {
					newPid := fmt.Sprintf("MAINPID=%d\n", pid1)
					client.Write([]byte(newPid))
				}
				return
			}
		}
	}
}
1331332
func MonitorWithHandler(ctx context.Context, cli client.SystemAPIClient, options types.EventsOptions, handler *Handler) chan error {
	eventChan := make(chan eventtypes.Message)
	errChan := make(chan error)
	started := make(chan struct{})

	go handler.Watch(eventChan)
	go monitorEvents(ctx, cli, options, started, eventChan, errChan)

	go func() {
		for {
			select {
			case <-ctx.Done():
				// close(eventChan)
				errChan <- nil
			}
		}
	}()

	<-started
	return errChan
}
1223571
func (c *CloudNodeLifecycleController) MonitorNodes() {
	instances, ok := c.cloud.Instances()
	if !ok {
		utilruntime.HandleError(fmt.Errorf("failed to get instances from cloud provider"))
		return
	}

	nodes, err := c.nodeLister.List(labels.Everything())
	if err != nil {
		klog.Errorf("error listing nodes from cache: %s", err)
		return
	}

	for _, node := range nodes {
		// Default NodeReady status to v1.ConditionUnknown
		status := v1.ConditionUnknown
		if _, c := nodeutil.GetNodeCondition(&node.Status, v1.NodeReady); c != nil {
			status = c.Status
		}

		if status == v1.ConditionTrue {
			// if taint exist remove taint
			err = controller.RemoveTaintOffNode(c.kubeClient, node.Name, node, ShutdownTaint)
			if err != nil {
				klog.Errorf("error patching node taints: %v", err)
			}
			continue
		}

		// we need to check this first to get taint working in similar in all cloudproviders
		// current problem is that shutdown nodes are not working in similar way ie. all cloudproviders
		// does not delete node from kubernetes cluster when instance it is shutdown see issue #46442
		shutdown, err := shutdownInCloudProvider(context.TODO(), c.cloud, node)
		if err != nil {
			klog.Errorf("error checking if node %s is shutdown: %v", node.Name, err)
		}

		if shutdown && err == nil {
			// if node is shutdown add shutdown taint
			err = controller.AddOrUpdateTaintOnNode(c.kubeClient, node.Name, ShutdownTaint)
			if err != nil {
				klog.Errorf("failed to apply shutdown taint to node %s, it may have been deleted.", node.Name)
			}
			// Continue checking the remaining nodes since the current one is shutdown.
			continue
		}

		// At this point the node has NotReady status, we need to check if the node has been removed
		// from the cloud provider. If node cannot be found in cloudprovider, then delete the node
		exists, err := ensureNodeExistsByProviderID(instances, node)
		if err != nil {
			klog.Errorf("error checking if node %s exists: %v", node.Name, err)
			continue
		}

		if exists {
			// Continue checking the remaining nodes since the current one is fine.
			continue
		}

		klog.V(2).Infof("deleting node since it is no longer present in cloud provider: %s", node.Name)

		ref := &v1.ObjectReference{
			Kind:      "Node",
			Name:      node.Name,
			UID:       types.UID(node.UID),
			Namespace: "",
		}

		c.recorder.Eventf(ref, v1.EventTypeNormal,
			fmt.Sprintf("Deleting node %v because it does not exist in the cloud provider", node.Name),
			"Node %s event: %s", node.Name, deleteNodeEvent)

		if err := c.kubeClient.CoreV1().Nodes().Delete(node.Name, nil); err != nil {
			klog.Errorf("unable to delete node %q: %v", node.Name, err)
		}
	}
}
624680
func (db *BytesConnectionRedis) Watch(resp func(keyval.BytesWatchResp), closeChan chan string, keys ...string) error {
	if db.closed {
		return fmt.Errorf("watch(%v) called on a closed connection", keys)
	}
	db.closeCh = closeChan

	return watch(db, resp, db.closeCh, nil, nil, keys...)
}
273854
func (w *checkWatcher) Watch(allocID, taskName, checkID string, check *structs.ServiceCheck, restarter TaskRestarter) {
	if !check.TriggersRestarts() {
		// Not watched, noop
		return
	}

	c := &checkRestart{
		allocID:        allocID,
		taskName:       taskName,
		checkID:        checkID,
		checkName:      check.Name,
		taskKey:        fmt.Sprintf("%s%s", allocID, taskName), // unique task ID
		task:           restarter,
		interval:       check.Interval,
		grace:          check.CheckRestart.Grace,
		graceUntil:     time.Now().Add(check.CheckRestart.Grace),
		timeLimit:      check.Interval * time.Duration(check.CheckRestart.Limit-1),
		ignoreWarnings: check.CheckRestart.IgnoreWarnings,
		logger:         w.logger.With("alloc_id", allocID, "task", taskName, "check", check.Name),
	}

	update := checkWatchUpdate{
		checkID:      checkID,
		checkRestart: c,
	}

	select {
	case w.checkUpdateCh <- update:
		// sent watch
	case <-w.done:
		// exited; nothing to do
	}
}
648292
func Start(ctx context.Context) (*Monitor, error) {
	m := NewMonitor()
	cfg := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(clientcmd.NewDefaultClientConfigLoadingRules(), &clientcmd.ConfigOverrides{})
	clusterConfig, err := cfg.ClientConfig()
	if err != nil {
		return nil, fmt.Errorf("could not load client configuration: %v", err)
	}
	client, err := kubernetes.NewForConfig(clusterConfig)
	if err != nil {
		return nil, err
	}
	configClient, err := configclientset.NewForConfig(clusterConfig)
	if err != nil {
		return nil, err
	}

	if err := startAPIMonitoring(ctx, m, clusterConfig); err != nil {
		return nil, err
	}
	startPodMonitoring(ctx, m, client)
	startNodeMonitoring(ctx, m, client)
	startEventMonitoring(ctx, m, client)
	startClusterOperatorMonitoring(ctx, m, configClient)

	m.StartSampling(ctx)
	return m, nil
}
1268957
func MonitorState(cancel <-chan struct{}, conn client.Connection, req StateRequest, check func(s *State, exists bool) bool) (*State, error) {
	logger := plog.WithFields(log.Fields{
		"hostid":     req.HostID,
		"serviceid":  req.ServiceID,
		"instanceid": req.InstanceID,
	})

	basepth := "/"
	if req.PoolID != "" {
		basepth = path.Join("/pools", req.PoolID)
	}

	// Monitor the state of the object
	done := make(chan struct{})
	defer func() { close(done) }()
	for {
		// Get the current host state and set the watch
		hspth := path.Join(basepth, "/hosts", req.HostID, "instances", req.StateID())
		hsok := true
		hsdat := &HostState{}
		hsev, err := conn.GetW(hspth, hsdat, done)
		if err == client.ErrNoNode {
			hsok = false
		} else if err != nil {
			logger.WithError(err).Debug("Could not watch host state")
			return nil, &StateError{
				Request:   req,
				Operation: "watch",
				Message:   "could not watch host state",
			}
		}

		// Get the current service state and set the watch
		sspth := path.Join(basepth, "/services", req.ServiceID, req.StateID())
		ssok := true
		ssdat := &ServiceState{}
		ssev, err := conn.GetW(sspth, ssdat, done)
		if err == client.ErrNoNode {
			ssok = false
		} else if err != nil {
			logger.WithError(err).Debug("Could not watch service state")
			return nil, &StateError{
				Request:   req,
				Operation: "watch",
				Message:   "could not watch service state",
			}
		}

		cspth := path.Join(sspth, "current")
		csok := true
		cstate := &CurrentStateContainer{}
		csev, err := conn.GetW(cspth, cstate, done)
		if err == client.ErrNoNode {
			csok = false
		} else if err != nil {
			logger.WithError(err).Debug("Could not watch service status")
			return nil, &StateError{
				Request:   req,
				Operation: "watch",
				Message:   "could not watch service status",
			}
		}

		// Ensure the nodes are compatible
		if hsok != ssok || ssok != csok {
			logger.WithFields(log.Fields{
				"hoststateexists":     hsok,
				"servicestateexists":  ssok,
				"servicestatusexists": csok,
			}).Debug("Incongruent state")
			return nil, &StateError{
				Request:   req,
				Operation: "watch",
				Message:   "incongruent state",
			}
		}
		exists := hsok && ssok && csok

		// Does the state statisfy the requirements?
		state := &State{
			HostState:             *hsdat,
			ServiceState:          *ssdat,
			CurrentStateContainer: *cstate,
			HostID:                req.HostID,
			ServiceID:             req.ServiceID,
			InstanceID:            req.InstanceID,
		}

		// Only return the state if the value is true.  Return an error if the
		// state has been deleted.
		if check(state, exists) {
			return state, nil
		} else if !exists {
			logger.Debug("State does not exist")
			return nil, &StateError{
				Request:   req,
				Operation: "watch",
				Message:   "state does not exist",
			}
		}

		// Wait for something to happen
		select {
		case <-hsev:
		case <-ssev:
		case <-csev:
		case <-cancel:
			logger.Debug("Aborted state monitor")
			return nil, nil
		}

		close(done)
		done = make(chan struct{})
	}
}
335043
func (s *Server) monitorLeadership() {
	var weAreLeaderCh chan struct{}
	var leaderLoop sync.WaitGroup
	for {
		select {
		case isLeader := <-s.leaderCh:
			switch {
			case isLeader:
				if weAreLeaderCh != nil {
					s.logger.Error("attempted to start the leader loop while running")
					continue
				}

				weAreLeaderCh = make(chan struct{})
				leaderLoop.Add(1)
				go func(ch chan struct{}) {
					defer leaderLoop.Done()
					s.leaderLoop(ch)
				}(weAreLeaderCh)
				s.logger.Info("cluster leadership acquired")

			default:
				if weAreLeaderCh == nil {
					s.logger.Error("attempted to stop the leader loop while not running")
					continue
				}

				s.logger.Debug("shutting down leader loop")
				close(weAreLeaderCh)
				leaderLoop.Wait()
				weAreLeaderCh = nil
				s.logger.Info("cluster leadership lost")
			}

		case <-s.shutdownCh:
			return
		}
	}
}
1097345
func (api *API) Watch() params.NotifyWatchResult {
	watch := api.backend.WatchForMigration()
	if _, ok := <-watch.Changes(); ok {
		return params.NotifyWatchResult{
			NotifyWatcherId: api.resources.Register(watch),
		}
	}
	return params.NotifyWatchResult{
		Error: common.ServerError(watcher.EnsureErr(watch)),
	}
}
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)
	}
}
1096973
func NewMonitor(ctx context.Context, nPages int, agentPipe io.Reader, server1_0, server1_2 net.Listener) (m *Monitor, err error) {
	m = &Monitor{
		ctx:              ctx,
		listeners:        make(map[listener.MonitorListener]struct{}),
		nPages:           nPages,
		perfReaderCancel: func() {}, // no-op to avoid doing null checks everywhere
	}

	// start new MonitorListener handler
	go m.connectionHandler1_0(ctx, server1_0)
	go m.connectionHandler1_2(ctx, server1_2)

	// start agent event pipe reader
	go m.agentPipeReader(ctx, agentPipe)

	return m, nil
}
820314
func (w *Window) Monitor() *Monitor {
	var monitor *glfw.Monitor
	mainthread.Call(func() {
		monitor = w.window.GetMonitor()
	})
	if monitor == nil {
		return nil
	}
	return &Monitor{
		monitor: monitor,
	}
}
1248881
func (m *Monitor) Monitor(n *Node) error {
	m.mtx.Lock()
	m.Nodes = append(m.Nodes, n)
	m.mtx.Unlock()

	blockCh := make(chan tmtypes.Header, 10)
	n.SendBlocksTo(blockCh)
	blockLatencyCh := make(chan float64, 10)
	n.SendBlockLatenciesTo(blockLatencyCh)
	disconnectCh := make(chan bool, 10)
	n.NotifyAboutDisconnects(disconnectCh)

	if err := n.Start(); err != nil {
		return err
	}

	m.Network.NewNode(n.Name)

	m.nodeQuit[n.Name] = make(chan struct{})
	go m.listen(n.Name, blockCh, blockLatencyCh, disconnectCh, m.nodeQuit[n.Name])

	return nil
}