// StartHealth starts the health checking for all registered routes. Only routes
// with 'Endpoint' defined will get checked. 'pulse' is the delay (in seconds)
// between health checks (default 60?)
14971
func StartHealth(pulse int) {
	if pulse == 0 {
		pulse = 60
	}
	// i'sa guyanese ya kno
	for true {

		routesMutex.RLock()
		for i := range routes {
			if routes[i].Endpoint != "" {
				go checkPulse(&routes[i]) // todo: what if this gets deleted after being sent off
				// go checkPulse(routes[i].Endpoint, routes[i].ExpectedCode, routes[i].ExpectedBody,
				// 	routes[i].ExpectedHeader, routes[i].Timeout, routes[i].Attempts)
			}
			// todo: think through pulse
			// time.Sleep(routes[i].Pulse)
		}
		routesMutex.RUnlock()

		time.Sleep(time.Duration(pulse) * time.Second)
	}
}
1250791
func (c *Client) startupHealthcheck(parentCtx context.Context, timeout time.Duration) error {
	c.mu.Lock()
	urls := c.urls
	basicAuth := c.basicAuth
	basicAuthUsername := c.basicAuthUsername
	basicAuthPassword := c.basicAuthPassword
	c.mu.Unlock()

	// If we don't get a connection after "timeout", we bail.
	var lastErr error
	start := time.Now()
	done := false
	for !done {
		for _, url := range urls {
			req, err := http.NewRequest("HEAD", url, nil)
			if err != nil {
				return err
			}
			if basicAuth {
				req.SetBasicAuth(basicAuthUsername, basicAuthPassword)
			}
			ctx, cancel := context.WithTimeout(parentCtx, timeout)
			defer cancel()
			req = req.WithContext(ctx)
			res, err := c.c.Do(req)
			if err == nil && res != nil && res.StatusCode >= 200 && res.StatusCode < 300 {
				return nil
			} else if err != nil {
				lastErr = err
			}
		}
		select {
		case <-parentCtx.Done():
			lastErr = parentCtx.Err()
			done = true
			break
		case <-time.After(1 * time.Second):
			if time.Since(start) > timeout {
				done = true
				break
			}
		}
	}
	if lastErr != nil {
		if IsContextErr(lastErr) {
			return lastErr
		}
		return errors.Wrapf(ErrNoClient, "health check timeout: %v", lastErr)
	}
	return errors.Wrap(ErrNoClient, "health check timeout")
}
1270324
func IsValidHealthString(s string) bool {
	return s == types.Starting ||
		s == types.Healthy ||
		s == types.Unhealthy ||
		s == types.NoHealthcheck
}
13673
func (c *cluster) healthCheckNode(node *member) {
	// step: wait for the node to become active ... we are assuming a /ping is enough here
	ticker := time.NewTicker(c.healthCheckInterval)
	defer ticker.Stop()
	for range ticker.C {
		req, err := c.client.buildMarathonRequest("GET", node.endpoint, "ping", nil)
		if err == nil {
			res, err := c.client.Do(req)
			if err == nil && res.StatusCode == 200 {
				// step: mark the node as active again
				c.Lock()
				node.status = memberStatusUp
				c.Unlock()
				break
			}
		}
	}
}
1247213
func (r *Application) HasHealthChecks() bool {
	return r.HealthChecks != nil && len(*r.HealthChecks) > 0
}
189661
func (s *CreateLoadBalancerInput) SetHealthCheckPath(v string) *CreateLoadBalancerInput {
	s.HealthCheckPath = &v
	return s
}
18101
func (hs *HealthzServer) Run() {
	serveMux := http.NewServeMux()
	serveMux.Handle("/healthz", healthzHandler{hs: hs})
	server := hs.httpFactory.New(hs.addr, serveMux)

	go wait.Until(func() {
		klog.V(3).Infof("Starting goroutine for healthz on %s", hs.addr)

		listener, err := hs.listener.Listen(hs.addr)
		if err != nil {
			msg := fmt.Sprintf("Failed to start node healthz on %s: %v", hs.addr, err)
			if hs.recorder != nil {
				hs.recorder.Eventf(hs.nodeRef, api.EventTypeWarning, "FailedToStartNodeHealthcheck", msg)
			}
			klog.Error(msg)
			return
		}

		if err := server.Serve(listener); err != nil {
			klog.Errorf("Healthz closed with error: %v", err)
			return
		}
		klog.Error("Unexpected healthz closed.")
	}, nodeHealthzRetryInterval, wait.NeverStop)
}
690188
func startHealthCheckService() func() {
	if *flagHealthCheck == "" {
		return nil
	}
	address, err := parseAddress(*flagHealthCheck)
	if err != nil {
		logrus.WithError(err).Error("Failed to start health check service")
		return nil
	}
	thealthcheck.Configure(address)

	logrus.WithField("address", address).Info("Starting health check service")
	go thealthcheck.Start()

	// Add a static "ping" endpoint
	thealthcheck.AddEndpoint("/_PING_", func() (code int, body string) {
		return thealthcheck.StatusOK, "PONG"
	})
	return thealthcheck.Stop
}
722070
func (agent *ActionAgent) Healthy() (time.Duration, error) {
	agent.mutex.Lock()
	defer agent.mutex.Unlock()

	healthy := agent._healthy
	if healthy == nil {
		timeSinceLastCheck := time.Since(agent._healthyTime)
		if timeSinceLastCheck > *healthCheckInterval*3 {
			healthy = fmt.Errorf("last health check is too old: %s > %s", timeSinceLastCheck, *healthCheckInterval*3)
		}
	}

	return agent._replicationDelay, healthy
}
794267
func (d *Daemon) stopHealthchecks(c *container.Container) {
	h := c.State.Health
	if h != nil {
		h.CloseMonitorChannel()
	}
}
811490
func (sbc *SandboxConn) StreamHealth(ctx context.Context, callback func(*querypb.StreamHealthResponse) error) error {
	return fmt.Errorf("not implemented in test")
}
1286604
func (shardSwap *shardSchemaSwap) startHealthWatchers(ctx context.Context) error {
	shardSwap.allTablets = make(map[string]*discovery.TabletStats)

	shardSwap.tabletHealthCheck = discovery.NewHealthCheck(*vtctl.HealthcheckRetryDelay, *vtctl.HealthCheckTimeout)
	shardSwap.tabletHealthCheck.SetListener(shardSwap, true /* sendDownEvents */)

	topoServer := shardSwap.parent.topoServer
	cellList, err := topoServer.GetKnownCells(shardSwap.parent.ctx)
	if err != nil {
		return err
	}
	for _, cell := range cellList {
		watcher := discovery.NewShardReplicationWatcher(
			ctx,
			topoServer,
			shardSwap.tabletHealthCheck,
			cell,
			shardSwap.parent.keyspace,
			shardSwap.shardName,
			*vtctl.HealthCheckTimeout,
			discovery.DefaultTopoReadConcurrency)
		shardSwap.tabletWatchers = append(shardSwap.tabletWatchers, watcher)
	}
	for _, watcher := range shardSwap.tabletWatchers {
		if err := watcher.WaitForInitialTopology(); err != nil {
			return err
		}
	}
	shardSwap.tabletHealthCheck.WaitForInitialStatsUpdates()

	// Wait for all health connections to be either established or get broken.
waitHealthChecks:
	for {
		tabletList := shardSwap.getTabletList()
		for _, tabletStats := range tabletList {
			if tabletStats.Stats == nil && tabletStats.LastError == nil {
				select {
				case <-shardSwap.parent.ctx.Done():
					return shardSwap.parent.ctx.Err()
				case <-time.After(100 * time.Millisecond):
				}
				continue waitHealthChecks
			}
		}
		break waitHealthChecks
	}
	return nil
}
175839
func (c *Check) CheckHealth(ctx context.Context) Response {
	response := Response{
		Name:   "Health",
		Status: StatusPass,
		Checks: make(Responses, len(c.healthChecks)),
	}
	override := c.manualOverride.Load().(bool)
	if override {
		if c.manualHealthState.Load().(bool) {
			response.Status = StatusPass
		} else {
			response.Status = StatusFail
		}
		overrideResponse := Response{
			Name:    "manual-override",
			Message: "health manually overridden",
		}
		response.Checks = append(response.Checks, overrideResponse)
	}
	for i, ch := range c.healthChecks {
		resp := ch.Check(ctx)
		if resp.Status != StatusPass && !override {
			response.Status = resp.Status
		}
		response.Checks[i] = resp
	}
	sort.Sort(response.Checks)
	return response
}
233545
func NewDefaultHealthCheck() *HealthCheck {
	portIndex := 0
	path := ""
	maxConsecutiveFailures := 3

	return &HealthCheck{
		Protocol:               "HTTP",
		Path:                   &path,
		PortIndex:              &portIndex,
		MaxConsecutiveFailures: &maxConsecutiveFailures,
		GracePeriodSeconds:     30,
		IntervalSeconds:        10,
		TimeoutSeconds:         5,
	}
}
1216113
func RegisterDebugHealthHandler(ts *topo.Server) {
	http.HandleFunc("/debug/health", func(w http.ResponseWriter, r *http.Request) {
		if err := acl.CheckAccessHTTP(r, acl.MONITORING); err != nil {
			acl.SendError(w, err)
			return
		}
		w.Header().Set("Content-Type", "text/plain")
		if err := isHealthy(ts); err != nil {
			w.Write([]byte("not ok"))
			return
		}
		w.Write([]byte("ok"))
	})
}
428649
func (h *healthcheckManager) queueHealthState(n *healthcheck.Notification) error {
	h.lock.RLock()
	cfg := h.cfgs[n.Id]
	check := h.checks[n.Id]
	h.lock.RUnlock()

	if cfg == nil || check == nil {
		log.Warningf("Unknown healthcheck ID %v", n.Id)
		return nil
	}

	note := &checkNotification{
		key:         check.key,
		description: cfg.Checker.String(),
		status:      n.Status,
	}
	check.vserver.queueCheckNotification(note)

	return nil
}
375916
func (s *SlaveHealthChecker) Start() <-chan time.Time {
	go func() {
		t := time.NewTicker(s.checkDuration)
		defer t.Stop()
		for {
			select {
			case <-t.C:
				select {
				case <-s.stop:
					return
				default:
					// continue
				}
				if paused, slavepid := func() (x bool, y upid.UPID) {
					s.RLock()
					defer s.RUnlock()
					x = s.paused
					if s.slaveUPID != nil {
						y = *s.slaveUPID
					}
					return
				}(); !paused {
					s.doCheck(slavepid)
				}
			case <-s.stop:
				return
			}
		}
	}()
	return s.ch
}