// handleCheck processes and responds to the supplied check. It will only return
// unrecoverable errors; mere untruth of the assertion just indicates a bad
// request, and is communicated back to the check's originator.
169964
func (manager *Manager) handleCheck(check check) error {
	key := check.leaseKey
	store := manager.config.Store
	manager.config.Logger.Tracef("[%s] handling Check for lease %s on behalf of %s",
		manager.logContext, key.Lease, check.holderName)

	info, found := manager.lookupLease(key)
	if !found || info.Holder != check.holderName {
		// TODO(jam): 2019-02-05 Currently raftlease.Store.Refresh does nothing.
		//  We probably shouldn't have this refresh-and-try-again if it is going to be a no-op.
		//  Instead we should probably just report failure.
		if found {
			manager.config.Logger.Tracef("[%s] handling Check for lease %s on behalf of %s, found held by %s, refreshing",
				manager.logContext, key.Lease, check.holderName, info.Holder)
		} else {
			manager.config.Logger.Tracef("[%s] handling Check for lease %s on behalf of %s, not found, refreshing",
				manager.logContext, key.Lease, check.holderName)
		}
		if err := store.Refresh(); err != nil {
			return errors.Trace(err)
		}
		info, found = manager.lookupLease(key)
		if !found {
			// Someone thought they were the leader and held a Claim or they wouldn't
			// have tried to do a mutating operation. However, when they actually
			// got to this point, we detected that they were, actually, out of
			// date. Schedule a sync
			manager.ensureNextTimeout(time.Millisecond)
		}
	}

	var response error
	if !found || info.Holder != check.holderName {
		manager.config.Logger.Tracef("[%s] handling Check for lease %s on behalf of %s, not held",
			manager.logContext, key.Lease, check.holderName)
		response = lease.ErrNotHeld
	} else if check.trapdoorKey != nil {
		response = info.Trapdoor(check.attempt, check.trapdoorKey)
	}
	check.respond(errors.Trace(response))
	return nil
}
645372
func (h EventHandlerFunc) HandleEvent(ctx context.Context, e Event) error {
	return h(ctx, e)
}
766859
func checkResp(resp *http.Response, err error) (*http.Response, error) {
	// If the err is already there, there was an error higher up the chain, so
	// just return that.
	if err != nil {
		return resp, err
	}

	switch resp.StatusCode {
	case 200, 201, 202, 204, 205, 206:
		return resp, nil
	default:
		return resp, NewHTTPError(resp)
	}
}
1078476
func (s *ID) Check() error {
	_, err := ParseID(string(*s))
	return trace.Wrap(err)
}
219729
func (c *CheckHTTP) check() {
	method := c.Method
	if method == "" {
		method = "GET"
	}

	req, err := http.NewRequest(method, c.HTTP, nil)
	if err != nil {
		c.Logger.Printf("[WARN] agent: Check %q HTTP request failed: %s", c.CheckID, err)
		c.Notify.UpdateCheck(c.CheckID, api.HealthCritical, err.Error())
		return
	}

	req.Header = http.Header(c.Header)

	// this happens during testing but not in prod
	if req.Header == nil {
		req.Header = make(http.Header)
	}

	if host := req.Header.Get("Host"); host != "" {
		req.Host = host
	}

	if req.Header.Get("User-Agent") == "" {
		req.Header.Set("User-Agent", UserAgent)
	}
	if req.Header.Get("Accept") == "" {
		req.Header.Set("Accept", "text/plain, text/*, */*")
	}

	resp, err := c.httpClient.Do(req)
	if err != nil {
		c.Logger.Printf("[WARN] agent: Check %q HTTP request failed: %s", c.CheckID, err)
		c.Notify.UpdateCheck(c.CheckID, api.HealthCritical, err.Error())
		return
	}
	defer resp.Body.Close()

	// Read the response into a circular buffer to limit the size
	output, _ := circbuf.NewBuffer(BufSize)
	if _, err := io.Copy(output, resp.Body); err != nil {
		c.Logger.Printf("[WARN] agent: Check %q error while reading body: %s", c.CheckID, err)
	}

	// Format the response body
	result := fmt.Sprintf("HTTP %s %s: %s Output: %s", method, c.HTTP, resp.Status, output.String())

	if resp.StatusCode >= 200 && resp.StatusCode <= 299 {
		// PASSING (2xx)
		c.Logger.Printf("[DEBUG] agent: Check %q is passing", c.CheckID)
		c.Notify.UpdateCheck(c.CheckID, api.HealthPassing, result)

	} else if resp.StatusCode == 429 {
		// WARNING
		// 429 Too Many Requests (RFC 6585)
		// The user has sent too many requests in a given amount of time.
		c.Logger.Printf("[WARN] agent: Check %q is now warning", c.CheckID)
		c.Notify.UpdateCheck(c.CheckID, api.HealthWarning, result)

	} else {
		// CRITICAL
		c.Logger.Printf("[WARN] agent: Check %q is now critical", c.CheckID)
		c.Notify.UpdateCheck(c.CheckID, api.HealthCritical, result)
	}
}
1372483
func (v *LargeDeltas) GetCheckTrue() (o bool) {
	if v != nil && v.CheckTrue != nil {
		return *v.CheckTrue
	}

	return
}
941013
func (b *PluginBackend) HandleExistenceCheck(ctx context.Context, req *logical.Request) (bool, bool, error) {
	b.RLock()
	canary := b.canary

	// Lazy-load backend
	if !b.loaded {
		// Upgrade lock
		b.RUnlock()
		b.Lock()
		// Check once more after lock swap
		if !b.loaded {
			err := b.startBackend(ctx)
			if err != nil {
				b.Unlock()
				return false, false, err
			}
		}
		b.Unlock()
		b.RLock()
	}

	checkFound, exists, err := b.Backend.HandleExistenceCheck(ctx, req)
	b.RUnlock()
	if err != nil &&
		(err.Error() == rpc.ErrShutdown.Error() || err == bplugin.ErrPluginShutdown) {
		// Reload plugin if it's an rpc.ErrShutdown
		b.Lock()
		if b.canary == canary {
			err := b.reloadBackend(ctx)
			if err != nil {
				b.Unlock()
				return false, false, err
			}
			b.canary, err = uuid.GenerateUUID()
			if err != nil {
				b.Unlock()
				return false, false, err
			}
		}
		b.Unlock()

		// Try request once more
		b.RLock()
		defer b.RUnlock()
		return b.Backend.HandleExistenceCheck(ctx, req)
	}
	return checkFound, exists, err
}
184671
func (s *Store) EnsureCheck(idx uint64, hc *structs.HealthCheck) error {
	tx := s.db.Txn(true)
	defer tx.Abort()

	// Call the check registration
	if err := s.ensureCheckTxn(tx, idx, hc); err != nil {
		return err
	}

	tx.Commit()
	return nil
}
121062
func (h *handler) HandleEvent(ctx context.Context, event eh.Event) error {
	select {
	case h.ch <- event:
	default:
		return fmt.Errorf("missed event: %s", event)
	}
	return nil
}
327790
func (r *ready) check() bool {
	rwMutex := r.c.L.(*sync.RWMutex)
	rwMutex.RLock()
	defer rwMutex.RUnlock()
	return r.ok
}
209089
func RunChecks(checks []Checker, ww io.Writer, ignorePreflightErrors sets.String) error {
	var errsBuffer bytes.Buffer

	for _, c := range checks {
		name := c.Name()
		warnings, errs := c.Check()

		if setHasItemOrAll(ignorePreflightErrors, name) {
			// Decrease severity of errors to warnings for this check
			warnings = append(warnings, errs...)
			errs = []error{}
		}

		for _, w := range warnings {
			io.WriteString(ww, fmt.Sprintf("\t[WARNING %s]: %v\n", name, w))
		}
		for _, i := range errs {
			errsBuffer.WriteString(fmt.Sprintf("\t[ERROR %s]: %v\n", name, i.Error()))
		}
	}
	if errsBuffer.Len() > 0 {
		return &Error{Msg: errsBuffer.String()}
	}
	return nil
}
1365562
func (check StatusChecker) RunCheck() Status {
	statusChannel := make(chan Status, 1)
	go func() {
		status := check()
		if status.GoodToGo {
			status.Message = "OK"
		}
		statusChannel <- status
	}()
	select {
	case status := <-statusChannel:
		return status
	case <-time.After(time.Second * time.Duration(timeout)):
		return Status{GoodToGo: false, Message: timeoutMessage}
	}
}
922601
func CheckResponse(res *http.Response) error {
	if res.StatusCode >= 200 && res.StatusCode <= 299 {
		return nil
	}
	slurp, err := ioutil.ReadAll(res.Body)
	if err == nil {
		jerr := new(errorReply)
		err = json.Unmarshal(slurp, jerr)
		if err == nil && jerr.Error != nil {
			if jerr.Error.Code == 0 {
				jerr.Error.Code = res.StatusCode
			}
			jerr.Error.Body = string(slurp)
			return jerr.Error
		}
	}
	return &Error{
		Code:   res.StatusCode,
		Body:   string(slurp),
		Header: res.Header,
	}
}
742338
func (c *accountIDOptions) Check() error {
	_, err := strkey.Decode(strkey.VersionByteAccountID, c.AccountID)
	if err != nil {
		return ErrInvalidAccountID
	}
	return nil
}
1287307
func check(err error) {
	if err != nil {
		b := make([]byte, 2<<10)
		b = b[:runtime.Stack(b, false)]
		log.Printf("Unlikely error condition triggered: %v at %s", err, b)
		panic(err)
	}
}
12912
func (_m *Store) AddCheck(check types.CheckSpec) error {
	ret := _m.Called(check)

	var r0 error
	if rf, ok := ret.Get(0).(func(types.CheckSpec) error); ok {
		r0 = rf(check)
	} else {
		r0 = ret.Error(0)
	}

	return r0
}
1221014
func (e *Engine) performCheck() {
	log.Printf("Checking for updates to Torus")

	latest, err := e.getLatestVersion()
	if err != nil {
		log.Printf("Could not retrieve latest version of Tours: %s", err)
		return
	}

	e.targetVersion = latest
	if err := e.storeLastCheck(); err != nil {
		log.Printf("Cannot store the last check date: %s", err)
	}

	log.Printf("Successfully checked for updates; available version: %s", latest)
}