Skip to content

Commit

Permalink
reactor: Adjust the timing of shutdown execution to allow onShutdownH…
Browse files Browse the repository at this point in the history
…ook to complete
  • Loading branch information
li-jin-gou committed Sep 19, 2022
1 parent 97bb37e commit cfcda3c
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 12 deletions.
2 changes: 1 addition & 1 deletion pkg/app/server/hertz_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@ func TestHertz_Spin(t *testing.T) {
t.Fatal(err)
}
t.Logf("[%v]end SIGHUP\n", time.Now())

time.Sleep(3 * time.Second)
<-ch
assert.Nil(t, err)
assert.NotNil(t, resp)
Expand Down
26 changes: 15 additions & 11 deletions pkg/route/engine.go
Original file line number Diff line number Diff line change
Expand Up @@ -251,12 +251,14 @@ func (engine *Engine) NewContext() *app.RequestContext {

// Shutdown starts the server's graceful exit by next steps:
//
// 1. Trigger OnShutdown hooks concurrently, but don't wait them
// 2. Close the net listener, which means new connection won't be accepted
// 3. Wait all connections get closed:
// 1. Add executeOnShutdownHooks function to defer chain
// 2. Execute Deregister function to cancel service register
// 3. Close the net listener, which means new connection won't be accepted
// 4. Wait all connections get closed:
// One connection gets closed after reaching out the shorter time of processing
// one request (in hand or next incoming), idleTimeout or ExitWaitTime
// 4. Exit
// 5. Trigger OnShutdown hooks synchronously and wait them
// 6. Exit
func (engine *Engine) Shutdown(ctx context.Context) (err error) {
if atomic.LoadUint32(&engine.status) != statusRunning {
return errStatusNotRunning
Expand All @@ -265,12 +267,7 @@ func (engine *Engine) Shutdown(ctx context.Context) (err error) {
return
}

// trigger hooks if any
for i := range engine.OnShutdown {
go func(index int) {
engine.OnShutdown[index](ctx)
}(i)
}
defer engine.executeOnShutdownHooks(ctx)

if opt := engine.options; opt != nil && opt.Registry != nil {
if err = opt.Registry.Deregister(opt.RegistryInfo); err != nil {
Expand All @@ -280,12 +277,19 @@ func (engine *Engine) Shutdown(ctx context.Context) (err error) {
}

// call transport shutdown
if err := engine.transport.Shutdown(ctx); err != ctx.Err() {
if err = engine.transport.Shutdown(ctx); err != ctx.Err() {
return err
}

return
}

func (engine *Engine) executeOnShutdownHooks(ctx context.Context) {
for i := range engine.OnShutdown {
engine.OnShutdown[i](ctx)
}
}

func (engine *Engine) Run() (err error) {
if err = engine.Init(); err != nil {
return err
Expand Down

0 comments on commit cfcda3c

Please sign in to comment.