/*
handleHealth only fails if the user's health check function tells us.
*/
335942
func (s *HTTPScaffold) handleHealth(resp http.ResponseWriter, req *http.Request) {
	if req.Method != "GET" {
		resp.WriteHeader(http.StatusMethodNotAllowed)
		return
	}

	status, healthErr := s.callHealthCheck()

	if status == Failed {
		writeUnavailable(resp, req, status, healthErr)
	} else {
		resp.WriteHeader(http.StatusOK)
	}
}
1079619
func (s *ContainerDefinition) SetHealthCheck(v *HealthCheck) *ContainerDefinition {
	s.HealthCheck = v
	return s
}
395953
func (c *Client) GetHealthCheck(i *GetHealthCheckInput) (*HealthCheck, error) {
	if i.Service == "" {
		return nil, ErrMissingService
	}

	if i.Version == 0 {
		return nil, ErrMissingVersion
	}

	if i.Name == "" {
		return nil, ErrMissingName
	}

	path := fmt.Sprintf("/service/%s/version/%d/healthcheck/%s", i.Service, i.Version, i.Name)
	resp, err := c.Get(path, nil)
	if err != nil {
		return nil, err
	}

	var h *HealthCheck
	if err := decodeJSON(&h, resp.Body); err != nil {
		return nil, err
	}
	return h, nil
}
641740
func (s *UpdateHealthCheckOutput) SetHealthCheck(v *HealthCheck) *UpdateHealthCheckOutput {
	s.HealthCheck = v
	return s
}
510224
func (v *Vserver) AddHealthcheck(h *Healthcheck) error {
	key := h.Key()
	if _, ok := v.Healthchecks[key]; ok {
		return fmt.Errorf("Vserver %q already contains Healthcheck %q", v.Name, key)
	}
	v.Healthchecks[key] = h
	return nil
}
5607
func (s *GetHealthCheckOutput) SetHealthCheck(v *HealthCheck) *GetHealthCheckOutput {
	s.HealthCheck = v
	return s
}
566823
func handleRootHealthz(checks ...HealthzChecker) http.HandlerFunc {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		failed := false
		excluded := getExcludedChecks(r)
		var verboseOut bytes.Buffer
		for _, check := range checks {
			// no-op the check if we've specified we want to exclude the check
			if excluded.Has(check.Name()) {
				excluded.Delete(check.Name())
				fmt.Fprintf(&verboseOut, "[+]%v excluded: ok\n", check.Name())
				continue
			}
			if err := check.Check(r); err != nil {
				// don't include the error since this endpoint is public.  If someone wants more detail
				// they should have explicit permission to the detailed checks.
				klog.V(4).Infof("healthz check %v failed: %v", check.Name(), err)
				fmt.Fprintf(&verboseOut, "[-]%v failed: reason withheld\n", check.Name())
				failed = true
			} else {
				fmt.Fprintf(&verboseOut, "[+]%v ok\n", check.Name())
			}
		}
		if excluded.Len() > 0 {
			fmt.Fprintf(&verboseOut, "warn: some health checks cannot be excluded: no matches for %v\n", formatQuoted(excluded.List()...))
			klog.Warningf("cannot exclude some health checks, no health checks are installed matching %v",
				formatQuoted(excluded.List()...))
		}
		// always be verbose on failure
		if failed {
			klog.V(2).Infof("%vhealthz check failed", verboseOut.String())
			http.Error(w, fmt.Sprintf("%vhealthz check failed", verboseOut.String()), http.StatusInternalServerError)
			return
		}

		w.Header().Set("Content-Type", "text/plain; charset=utf-8")
		w.Header().Set("X-Content-Type-Options", "nosniff")
		if _, found := r.URL.Query()["verbose"]; !found {
			fmt.Fprint(w, "ok")
			return
		}

		verboseOut.WriteTo(w)
		fmt.Fprint(w, "healthz check passed\n")
	})
}
458838
func (s *TargetGroup) SetHealthCheckPort(v string) *TargetGroup {
	s.HealthCheckPort = &v
	return s
}
614137
func (couchInstance *CouchInstance) HealthCheck(ctx context.Context) error {
	connectURL, err := url.Parse(couchInstance.conf.URL)
	if err != nil {
		logger.Errorf("URL parse error: %s", err)
		return errors.Wrapf(err, "error parsing CouchDB URL: %s", couchInstance.conf.URL)
	}
	_, _, err = couchInstance.handleRequest(ctx, http.MethodHead, "", "HealthCheck", connectURL, nil, "", "", 0, true, nil)
	if err != nil {
		return fmt.Errorf("failed to connect to couch db [%s]", err)
	}
	return nil
}
652813
func (n *Node) healthCheck() {
	logDebug("[Node]", "(%v) starting healthcheck routine", n)

	healthCheckTicker := time.NewTicker(n.healthCheckInterval)
	defer healthCheckTicker.Stop()

	for {
		if !n.ensureHealthCheckCanContinue() {
			return
		}
		select {
		case <-n.stopChan:
			logDebug("[Node]", "(%v) healthcheck quitting", n)
			return
		case t := <-healthCheckTicker.C:
			if !n.ensureHealthCheckCanContinue() {
				return
			}
			logDebug("[Node]", "(%v) running healthcheck at %v", n, t)
			conn, cerr := n.cm.createConnection()
			if cerr != nil {
				conn.close()
				logError("[Node]", "(%v) failed healthcheck in createConnection, err: %v", n, cerr)
			} else {
				if !n.ensureHealthCheckCanContinue() {
					conn.close()
					return
				}
				hcmd := n.getHealthCheckCommand()
				logDebug("[Node]", "(%v) healthcheck executing %v", n, hcmd.Name())
				if hcerr := conn.execute(hcmd); hcerr != nil || !hcmd.Success() {
					conn.close()
					logError("[Node]", "(%v) failed healthcheck, err: %v", n, hcerr)
				} else {
					conn.close()
					logDebug("[Node]", "(%v) healthcheck success, err: %v, success: %v", n, hcerr, hcmd.Success())
					if n.ensureHealthCheckCanContinue() {
						n.setState(nodeRunning)
					}
					return
				}
			}
		}
	}
}
1129405
func ServeHealthCheck(mux *http.ServeMux, f func() error) {
	mux.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
		if err := f(); err != nil {
			w.WriteHeader(http.StatusServiceUnavailable)
			log.Errorln(w, err)
		} else {
			fmt.Fprintln(w, "ok")
		}
	})
}
977061
func (elasticsearch *HealthCheckClient) Healthcheck() (string, error) {

	logData := log.Data{"url": elasticsearch.path}

	URL, err := url.Parse(elasticsearch.path)
	if err != nil {
		log.ErrorC("failed to create url for elasticsearch healthcheck", err, logData)
		return elasticsearch.serviceName, err
	}

	path := URL.String()
	logData["url"] = path

	req, err := http.NewRequest("GET", path, nil)
	if err != nil {
		log.ErrorC("failed to create request for healthcheck call to elasticsearch", err, logData)
		return elasticsearch.serviceName, err
	}

	if elasticsearch.signRequests {
		awsauth.Sign(req)
	}

	resp, err := elasticsearch.cli.Do(req)
	if err != nil {
		log.ErrorC("failed to call elasticsearch", err, logData)
		return elasticsearch.serviceName, err
	}
	defer resp.Body.Close()

	logData["http_code"] = resp.StatusCode
	if resp.StatusCode < http.StatusOK || resp.StatusCode >= 300 {
		log.Error(ErrorUnexpectedStatusCode, logData)
		return elasticsearch.serviceName, ErrorUnexpectedStatusCode
	}

	jsonBody, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.ErrorC("failed to read response body from call to elastic", err, logData)
		return elasticsearch.serviceName, ErrorUnexpectedStatusCode
	}

	var clusterHealth ClusterHealth
	err = json.Unmarshal(jsonBody, &clusterHealth)
	if err != nil {
		log.Error(ErrorParsingBody, logData)
		return elasticsearch.serviceName, ErrorParsingBody
	}

	logData["cluster_health"] = clusterHealth.Status
	if clusterHealth.Status == unhealthy {
		log.Error(ErrorUnhealthyClusterStatus, logData)
		return elasticsearch.serviceName, ErrorUnhealthyClusterStatus
	}

	return elasticsearch.serviceName, nil
}
1303964
func (c *Check) CheckHealth(ctx context.Context) Response {
	response := Response{
		Name:   "Health",
		Status: StatusPass,
		Checks: make(Responses, len(c.healthChecks)),
	}
	for i, ch := range c.healthChecks {
		resp := ch.Check(ctx)
		if resp.Status != StatusPass {
			response.Status = resp.Status
		}
		response.Checks[i] = resp
	}
	sort.Sort(response.Checks)
	return response
}
682879
func (c *Client) healthchecker() {
	c.mu.RLock()
	timeout := c.healthcheckTimeout
	interval := c.healthcheckInterval
	c.mu.RUnlock()

	ticker := time.NewTicker(interval)
	defer ticker.Stop()

	for {
		select {
		case <-c.healthcheckStop:
			// we are asked to stop, so we signal back that we're stopping now
			c.healthcheckStop <- true
			return
		case <-ticker.C:
			c.healthcheck(context.Background(), timeout, false)
		}
	}
}
639558
func (t *toolbox) AddHealthCheckFunc(desc string, fn HealthCheckFunc) {
	t.healthCheckJobs = append(t.healthCheckJobs, &healthCheck{
		desc:  desc,
		check: fn,
	})
}
1180464
func (c *healthCheck) Check() (warnings, errors []error) {
	if err := c.f(c.client); err != nil {
		return nil, []error{err}
	}
	return nil, nil
}
269083
func (h *healthcheckManager) healthState(n *healthcheck.Notification) error {
	log.V(1).Infof("Received healthcheck notification: %v", n)

	h.lock.RLock()
	enabled := h.enabled
	h.lock.RUnlock()

	if !enabled {
		log.Warningf("Healthcheck manager is disabled; ignoring healthcheck notification %v", n)
		return nil
	}

	h.engine.syncServer.notify(&SyncNote{Type: SNTHealthcheck, Healthcheck: n})

	return h.queueHealthState(n)
}