func pingHost( dialer transport.Dialer, host string, timeout time.Duration, validator ConnCheck, ) (common.MapStr, reason.Reason) { start := time.Now() deadline := start.Add(timeout) conn, err := dialer.Dial("tcp", host) if err != nil { debugf("dial failed with: %v", err) return nil, reason.IOFailed(err) } defer conn.Close() if validator == nil { // no additional validation step => ping success return common.MapStr{}, nil } if err := conn.SetDeadline(deadline); err != nil { debugf("setting connection deadline failed with: %v", err) return nil, reason.IOFailed(err) } validateStart := time.Now() err = validator.Validate(conn) if err != nil && err != errRecvMismatch { debugf("check failed with: %v", err) return nil, reason.IOFailed(err) } end := time.Now() event := common.MapStr{ "validate_rtt": look.RTT(end.Sub(validateStart)), } if err != nil { event["error"] = reason.FailValidate(err) } return event, nil }
func execPing( client *http.Client, req *http.Request, body []byte, timeout time.Duration, validator func(*http.Response) error, ) (common.MapStr, reason.Reason) { ctx, cancel := context.WithTimeout(context.Background(), timeout) defer cancel() req = req.WithContext(ctx) if len(body) > 0 { req.Body = ioutil.NopCloser(bytes.NewBuffer(body)) req.ContentLength = int64(len(body)) } start := time.Now() resp, err := client.Do(req) end := time.Now() if err != nil { return nil, reason.IOFailed(err) } defer resp.Body.Close() if err := validator(resp); err != nil { return nil, reason.ValidateFailed(err) } rtt := end.Sub(start) event := common.MapStr{ "response": common.MapStr{ "status": resp.StatusCode, }, "rtt": look.RTT(rtt), } return event, nil }