Skip to content

Commit

Permalink
feat: graceful shutdown sbi server
Browse files Browse the repository at this point in the history
  • Loading branch information
yccodr committed Apr 25, 2024
1 parent 6f939e0 commit e9e39ad
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 26 deletions.
15 changes: 14 additions & 1 deletion cmd/main.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
package main

import (
"context"
"os"
"os/signal"
"path/filepath"
"runtime/debug"
"syscall"

"github.com/urfave/cli"

Expand Down Expand Up @@ -62,7 +65,17 @@ func action(cliCtx *cli.Context) error {
}
NSSF = nssf

nssf.Start(tlsKeyLogPath)
ctx, cancel := context.WithCancel(context.Background())
sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, os.Interrupt, syscall.SIGTERM)

go func() {
<-sigCh // Wait for interrupt signal to gracefully shutdown
cancel() // Notify each goroutine and wait them stopped
}()

nssf.Start(ctx)
nssf.Wait()

return nil
}
Expand Down
1 change: 0 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ require (
github.com/free5gc/openapi v1.0.8
github.com/free5gc/util v1.0.6
github.com/gin-gonic/gin v1.9.1
github.com/go-playground/assert/v2 v2.2.0
github.com/google/uuid v1.3.0
github.com/pkg/errors v0.9.1
github.com/sirupsen/logrus v1.8.1
Expand Down
40 changes: 16 additions & 24 deletions pkg/service/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,12 @@
package service

import (
"context"
"fmt"
"io"
"os"
"os/signal"
"runtime/debug"
"sync"
"syscall"

"github.com/sirupsen/logrus"

Expand Down Expand Up @@ -128,24 +127,7 @@ func (a *NssfApp) deregisterFromNrf() {
}
}

func (a *NssfApp) addSigTermHandler() {
signalChannel := make(chan os.Signal, 1)
signal.Notify(signalChannel, os.Interrupt, syscall.SIGTERM)
go func() {
defer func() {
if p := recover(); p != nil {
// Print stack for panic to log. Fatalf() will let program exit.
logger.InitLog.Fatalf("panic: %v\n%s", p, string(debug.Stack()))
}
}()

<-signalChannel
a.Terminate()
os.Exit(0)
}()
}

func (a *NssfApp) Start(tlsKeyLogPath string) {
func (a *NssfApp) Start(ctx context.Context) {
logger.InitLog.Infoln("Server started")

err := a.registerToNrf()
Expand All @@ -162,12 +144,22 @@ func (a *NssfApp) Start(tlsKeyLogPath string) {
}()

a.sbiServer.Run(&a.wg)
a.addSigTermHandler()
go a.listenShutdown(ctx)
}

func (nssf *NssfApp) Terminate() {
func (a *NssfApp) listenShutdown(ctx context.Context) {
<-ctx.Done()
a.Terminate()
}

func (a *NssfApp) Terminate() {
logger.InitLog.Infof("Terminating NSSF...")
nssf.deregisterFromNrf()
nssf.sbiServer.Shutdown()
a.deregisterFromNrf()
a.sbiServer.Shutdown()
a.Wait()
}

func (a *NssfApp) Wait() {
a.wg.Wait()
logger.InitLog.Infof("NSSF terminated")
}

0 comments on commit e9e39ad

Please sign in to comment.