Browse Source

Merge pull request #581 from tranngoclam/graceful-shutdown

Gracefully shutdown in HTTP and gRPC apps
dcarns 3 years ago
parent
commit
1387dbee4c
3 changed files with 9 additions and 11 deletions
  1. 1 0
      .gitignore
  2. 3 4
      controllers/controller.go
  3. 5 7
      main.go

+ 1 - 0
.gitignore

@@ -16,3 +16,4 @@ netclient/netclient.exe
 config/dnsconfig/
 data/
 .vscode/
+.idea/

+ 3 - 4
controllers/controller.go

@@ -52,20 +52,19 @@ func HandleRESTRequests(wg *sync.WaitGroup) {
 		}
 	}()
 	logger.Log(0, "REST Server successfully started on port ", port, " (REST)")
-	c := make(chan os.Signal)
 
 	// Relay os.Interrupt to our channel (os.Interrupt = CTRL+C)
 	// Ignore other incoming signals
-	signal.Notify(c, os.Interrupt)
+	ctx, stop := signal.NotifyContext(context.TODO(), os.Interrupt)
+	defer stop()
 
 	// Block main routine until a signal is received
 	// As long as user doesn't press CTRL+C a message is not passed and our main routine keeps running
-	<-c
+	<-ctx.Done()
 
 	// After receiving CTRL+C Properly stop the server
 	logger.Log(0, "Stopping the REST server...")
 	srv.Shutdown(context.TODO())
 	logger.Log(0, "REST Server closed.")
 	logger.DumpFile(fmt.Sprintf("data/netmaker.log.%s", time.Now().Format(logger.TimeFormatDay)))
-
 }

+ 5 - 7
main.go

@@ -1,6 +1,7 @@
 package main
 
 import (
+	"context"
 	"fmt"
 	"net"
 	"os"
@@ -157,21 +158,18 @@ func runGRPC(wg *sync.WaitGroup) {
 	}()
 	logger.Log(0, "Agent Server successfully started on port ", grpcport, "(gRPC)")
 
-	// Right way to stop the server using a SHUTDOWN HOOK
-	// Create a channel to receive OS signals
-	c := make(chan os.Signal, 1)
-
 	// Relay os.Interrupt to our channel (os.Interrupt = CTRL+C)
 	// Ignore other incoming signals
-	signal.Notify(c, os.Interrupt)
+	ctx, stop := signal.NotifyContext(context.TODO(), os.Interrupt)
+	defer stop()
 
 	// Block main routine until a signal is received
 	// As long as user doesn't press CTRL+C a message is not passed and our main routine keeps running
-	<-c
+	<-ctx.Done()
 
 	// After receiving CTRL+C Properly stop the server
 	logger.Log(0, "Stopping the Agent server...")
-	s.Stop()
+	s.GracefulStop()
 	listener.Close()
 	logger.Log(0, "Agent server closed..")
 	logger.Log(0, "Closed DB connection.")