-
Notifications
You must be signed in to change notification settings - Fork 4.5k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
examples/features/gracefulstop: add example to demonstrate server graceful stop #7865
Merged
Merged
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
6b8ce78
examples/features/gracefulstop: add example to demonstrate server gra…
purnesh42H 5ee5e3b
use ServerStreaming scenario to demonstrate graceful shutdown
purnesh42H d48bd1f
use ServerStreaming scenario to demonstrate graceful shutdown
purnesh42H 9e46942
remove need ctrl+c
purnesh42H d71a54b
Unary and Client Stream to demo graceful stop
purnesh42H a7d55e8
Unary and Client Stream to demo graceful stop
purnesh42H f4424d0
address structure comments
purnesh42H 2ddb80e
address structure comments
purnesh42H c8e4d3a
add features/gracefulstop to example_test.sh
purnesh42H 0b880da
add client and server expectation outputs
purnesh42H File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
# Graceful Stop | ||
|
||
This example demonstrates how to gracefully stop a gRPC server using | ||
`Server.GracefulStop()`. The graceful shutdown process involves two key steps: | ||
|
||
- Initiate `Server.GracefulStop()`. This function blocks until all currently | ||
running RPCs have completed. This ensures that in-flight requests are | ||
allowed to finish processing. | ||
|
||
- It's crucial to call `Server.Stop()` with a timeout before calling | ||
`GracefulStop()`. This acts as a safety net, ensuring that the server | ||
eventually shuts down even if some in-flight RPCs don't complete within a | ||
reasonable timeframe. This prevents indefinite blocking. | ||
|
||
## Try it | ||
|
||
``` | ||
go run server/main.go | ||
``` | ||
|
||
``` | ||
go run client/main.go | ||
``` | ||
|
||
## Explanation | ||
|
||
The server starts with a client streaming and unary request handler. When | ||
client streaming is started, client streaming handler signals the server to | ||
initiate graceful stop and waits for the stream to be closed or aborted. Until | ||
the`Server.GracefulStop()` is initiated, server will continue to accept unary | ||
requests. Once `Server.GracefulStop()` is initiated, server will not accept | ||
new unary requests. | ||
|
||
Client will start the client stream to the server and starts making unary | ||
requests until receiving an error. Error will indicate that the server graceful | ||
shutdown is initiated so client will stop making further unary requests and | ||
closes the client stream. | ||
|
||
Server and client will keep track of number of unary requests processed on | ||
their side. Once the client has successfully closed the stream, server returns | ||
the total number of unary requests processed as response. The number from | ||
stream response should be equal to the number of unary requests tracked by | ||
client. This indicates that server has processed all in-flight requests before | ||
shutting down. | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,80 @@ | ||
/* | ||
* | ||
* Copyright 2024 gRPC authors. | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
|
||
// Binary client demonstrates sending multiple requests to server and observe | ||
// graceful stop. | ||
dfawley marked this conversation as resolved.
Show resolved
Hide resolved
|
||
package main | ||
|
||
import ( | ||
"context" | ||
"flag" | ||
"fmt" | ||
"log" | ||
"time" | ||
|
||
"google.golang.org/grpc" | ||
"google.golang.org/grpc/credentials/insecure" | ||
pb "google.golang.org/grpc/examples/features/proto/echo" | ||
) | ||
|
||
var addr = flag.String("addr", "localhost:50052", "the address to connect to") | ||
|
||
func main() { | ||
flag.Parse() | ||
|
||
conn, err := grpc.NewClient(*addr, grpc.WithTransportCredentials(insecure.NewCredentials())) | ||
if err != nil { | ||
log.Fatalf("Failed to create new client: %v", err) | ||
} | ||
defer conn.Close() | ||
c := pb.NewEchoClient(conn) | ||
|
||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) | ||
defer cancel() | ||
|
||
// Start a client stream and keep calling the `c.UnaryEcho` until receiving | ||
// an error. Error will indicate that server graceful stop is initiated and | ||
// it won't accept any new requests. | ||
stream, err := c.ClientStreamingEcho(ctx) | ||
if err != nil { | ||
log.Fatalf("Error starting stream: %v", err) | ||
} | ||
|
||
// Keep track of successful unary requests which can be compared later to | ||
// the successful unary requests reported by the server. | ||
unaryRequests := 0 | ||
for { | ||
r, err := c.UnaryEcho(ctx, &pb.EchoRequest{Message: "Hello"}) | ||
if err != nil { | ||
log.Printf("Error calling `UnaryEcho`. Server graceful stop initiated: %v", err) | ||
break | ||
} | ||
unaryRequests++ | ||
time.Sleep(200 * time.Millisecond) | ||
log.Printf(r.Message) | ||
} | ||
log.Printf("Successful unary requests made by client: %d", unaryRequests) | ||
|
||
r, err := stream.CloseAndRecv() | ||
if err != nil { | ||
log.Fatalf("Error closing stream: %v", err) | ||
} | ||
if fmt.Sprintf("%d", unaryRequests) != r.Message { | ||
log.Fatalf("Got %s successful unary requests processed from server, want: %d", r.Message, unaryRequests) | ||
} | ||
log.Printf("Successful unary requests processed by server and made by client are same.") | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,105 @@ | ||
/* | ||
* | ||
* Copyright 2024 gRPC authors. | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
|
||
// Binary server demonstrates how to gracefully stop a gRPC server. | ||
package main | ||
|
||
import ( | ||
"context" | ||
"errors" | ||
"flag" | ||
"fmt" | ||
"io" | ||
"log" | ||
"net" | ||
"sync/atomic" | ||
"time" | ||
|
||
"google.golang.org/grpc" | ||
pb "google.golang.org/grpc/examples/features/proto/echo" | ||
) | ||
|
||
var ( | ||
port = flag.Int("port", 50052, "port number") | ||
) | ||
|
||
type server struct { | ||
pb.UnimplementedEchoServer | ||
|
||
unaryRequests atomic.Int32 // to track number of unary RPCs processed | ||
streamStart chan struct{} // to signal if server streaming started | ||
} | ||
|
||
// ClientStreamingEcho implements the EchoService.ClientStreamingEcho method. | ||
// It signals the server that streaming has started and waits for the stream to | ||
// be done or aborted. If `io.EOF` is received on stream that means client | ||
// has successfully closed the stream using `stream.CloseAndRecv()`, so it | ||
// returns an `EchoResponse` with the total number of unary RPCs processed | ||
// otherwise, it returns the error indicating stream is aborted. | ||
func (s *server) ClientStreamingEcho(stream pb.Echo_ClientStreamingEchoServer) error { | ||
// Signal streaming start to initiate graceful stop which should wait until | ||
// server streaming finishes. | ||
s.streamStart <- struct{}{} | ||
|
||
if err := stream.RecvMsg(&pb.EchoResponse{}); err != nil { | ||
if errors.Is(err, io.EOF) { | ||
stream.SendAndClose(&pb.EchoResponse{Message: fmt.Sprintf("%d", s.unaryRequests.Load())}) | ||
return nil | ||
} | ||
return err | ||
} | ||
|
||
return nil | ||
} | ||
|
||
// UnaryEcho implements the EchoService.UnaryEcho method. It increments | ||
// `s.unaryRequests` on every call and returns it as part of `EchoResponse`. | ||
func (s *server) UnaryEcho(_ context.Context, req *pb.EchoRequest) (*pb.EchoResponse, error) { | ||
s.unaryRequests.Add(1) | ||
return &pb.EchoResponse{Message: req.Message}, nil | ||
} | ||
|
||
func main() { | ||
flag.Parse() | ||
|
||
address := fmt.Sprintf(":%v", *port) | ||
lis, err := net.Listen("tcp", address) | ||
if err != nil { | ||
log.Fatalf("failed to listen: %v", err) | ||
} | ||
|
||
s := grpc.NewServer() | ||
ss := &server{streamStart: make(chan struct{})} | ||
pb.RegisterEchoServer(s, ss) | ||
|
||
go func() { | ||
<-ss.streamStart // wait until server streaming starts | ||
time.Sleep(1 * time.Second) | ||
log.Println("Initiating graceful shutdown...") | ||
timer := time.AfterFunc(10*time.Second, func() { | ||
log.Println("Server couldn't stop gracefully in time. Doing force stop.") | ||
s.Stop() | ||
}) | ||
defer timer.Stop() | ||
s.GracefulStop() // gracefully stop server after in-flight server streaming rpc finishes | ||
dfawley marked this conversation as resolved.
Show resolved
Hide resolved
|
||
log.Println("Server stopped gracefully.") | ||
}() | ||
|
||
if err := s.Serve(lis); err != nil { | ||
log.Fatalf("failed to serve: %v", err) | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This needs expectations for server and/or client output to confirm it is working correctly.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Added. PTAL