-
package main
import (
"context"
"fmt"
"log"
"os"
"os/signal"
"syscall"
"time"
"go.uber.org/fx"
)
func main() {
server := fx.New(
fx.Invoke(func(lc fx.Lifecycle) {
fmt.Println("first invoke...")
lc.Append(fx.Hook{
OnStart: func(ctx context.Context) error {
fmt.Println("#1 start")
return nil
},
OnStop: func(ctx context.Context) error {
fmt.Println("#1 stop")
return nil
},
})
}),
fx.Invoke(func(lc fx.Lifecycle) {
fmt.Println("last invoke...")
lc.Append(fx.Hook{
OnStart: func(ctx context.Context) error {
fmt.Println("#2 start")
return nil
},
OnStop: func(ctx context.Context) error {
fmt.Println("#2 stop")
return nil
},
})
}),
)
go func() {
server.Run()
}()
kill := make(chan os.Signal, 1)
signal.Notify(kill, syscall.SIGINT, syscall.SIGTERM, syscall.SIGKILL, syscall.SIGQUIT)
<-kill
fmt.Println("killed")
ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
if err := server.Stop(ctx); err != nil {
log.Printf("error stopping gracefully")
}
} When I give the stop signal, the log
And I am expected to be
Is there anything I'm doing wrong? |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 3 replies
-
Thanks for the report and detailed repro steps. Which Go/Fx version are you on? I just tried to repro the issue using the code you posted but I'm seeing the expected output:
|
Beta Was this translation helpful? Give feedback.
-
full log
|
Beta Was this translation helpful? Give feedback.
-
Debugging it further, it looks like your code is triggering a race. while we fix this, you can avoid this problem by not invoking Stop manually by catching the SIGINT signal. i.e. Instead of: go func() {
server.Run()
}()
kill := make(chan os.Signal, 1)
signal.Notify(kill, syscall.SIGINT, syscall.SIGTERM, syscall.SIGKILL, syscall.SIGQUIT)
<-kill
fmt.Println("killed")
ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
if err := server.Stop(ctx); err != nil {
log.Printf("error stopping gracefully")
} Just the following code will already do what you were trying to hand-write. server.Run() |
Beta Was this translation helpful? Give feedback.
-
This was fixed with #931 |
Beta Was this translation helpful? Give feedback.
This was fixed with #931