Skip to content

Commit

Permalink
Close connection before exiting
Browse files Browse the repository at this point in the history
os.Exit() calls in main() are causing `defer` statements to be ignored.
This surfaced in several bug reports (such as Java gRPC servers) as health
RPCs causing stack traces or "broken pipe" errors.

Signed-off-by: Ahmet Alp Balkan <[email protected]>
  • Loading branch information
ahmetb committed Feb 5, 2020
1 parent 4574e80 commit 8840591
Showing 1 changed file with 13 additions and 4 deletions.
17 changes: 13 additions & 4 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,8 @@ const (
)

func init() {


log.SetFlags(0)
flag.StringVar(&flAddr, "addr", "", "(required) tcp host:port to connect")
flag.StringVar(&flService, "service", "", "service name to check (default: \"\")")
Expand Down Expand Up @@ -162,6 +164,9 @@ func buildCredentials(skipVerify bool, caCerts, clientCert, clientKey, serverNam
}

func main() {
retcode := 0
defer func() { os.Exit(retcode) }()

ctx, cancel := context.WithCancel(context.Background())

c := make(chan os.Signal, 1)
Expand All @@ -182,7 +187,8 @@ func main() {
creds, err := buildCredentials(flTLSNoVerify, flTLSCACert, flTLSClientCert, flTLSClientKey, flTLSServerName)
if err != nil {
log.Printf("failed to initialize tls credentials. error=%v", err)
os.Exit(StatusInvalidArguments)
retcode = StatusInvalidArguments
return
}
opts = append(opts, grpc.WithTransportCredentials(creds))
} else {
Expand All @@ -202,7 +208,8 @@ func main() {
} else {
log.Printf("error: failed to connect service at %q: %+v", flAddr, err)
}
os.Exit(StatusConnectionFailure)
retcode = StatusConnectionFailure
return
}
connDuration := time.Since(connStart)
defer conn.Close()
Expand All @@ -222,13 +229,15 @@ func main() {
} else {
log.Printf("error: health rpc failed: %+v", err)
}
os.Exit(StatusRPCFailure)
retcode = StatusRPCFailure
return
}
rpcDuration := time.Since(rpcStart)

if resp.GetStatus() != healthpb.HealthCheckResponse_SERVING {
log.Printf("service unhealthy (responded with %q)", resp.GetStatus().String())
os.Exit(StatusUnhealthy)
retcode = StatusUnhealthy
return
}
if flVerbose {
log.Printf("time elapsed: connect=%v rpc=%v", connDuration, rpcDuration)
Expand Down

0 comments on commit 8840591

Please sign in to comment.