Skip to content

Commit

Permalink
Detect when a fargo error indicates not found
Browse files Browse the repository at this point in the history
The fargo library already provides the HTTPResponseStatusCode function
to extract an HTTP status code from a returned error, but here we want
to be able to inject similar errors for tests, so look for both a real
fargo error indicating that a heartbeat attempt failed to find its
target instance and a synthetic error returned by a fake connection
during a test.
  • Loading branch information
Steven E. Harris committed Jun 7, 2017
1 parent 4ede06e commit a843a9e
Showing 1 changed file with 26 additions and 10 deletions.
36 changes: 26 additions & 10 deletions sd/eureka/registrar.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,10 @@ type fargoUnsuccessfulHTTPResponse struct {
messagePrefix string
}

func (u *fargoUnsuccessfulHTTPResponse) Error() string {
return fmt.Sprintf("err=%s code=%d", u.messagePrefix, u.statusCode)
}

// Registrar maintains service instance liveness information in Eureka.
type Registrar struct {
conn fargoConnection
Expand Down Expand Up @@ -110,18 +114,30 @@ func (r *Registrar) loop() {
}
}

func httpResponseStatusCode(err error) (code int, present bool) {
if code, ok := fargo.HTTPResponseStatusCode(err); ok {
return code, true
}
// Allow injection of errors for testing.
if u, ok := err.(*fargoUnsuccessfulHTTPResponse); ok {
return u.statusCode, true
}
return 0, false
}

func isNotFound(err error) bool {
code, ok := httpResponseStatusCode(err)
return ok && code == http.StatusNotFound
}

func (r *Registrar) heartbeat() error {
err := r.conn.HeartBeatInstance(r.instance)
if err != nil {
if u, ok := err.(*fargoUnsuccessfulHTTPResponse); ok && u.statusCode == http.StatusNotFound {
// Instance expired (e.g. network partition). Re-register.
r.logger.Log("during", "heartbeat", err.Error())
return r.conn.ReregisterInstance(r.instance)
}
if err == nil {
return nil
}
if isNotFound(err) {
// Instance expired (e.g. network partition). Re-register.
return r.conn.ReregisterInstance(r.instance)
}
return err
}

func (u *fargoUnsuccessfulHTTPResponse) Error() string {
return fmt.Sprintf("err=%s code=%d", u.messagePrefix, u.statusCode)
}

0 comments on commit a843a9e

Please sign in to comment.