weaver icon indicating copy to clipboard operation
weaver copied to clipboard

Component `Deinit` method

Open fkorotkov opened this issue 2 years ago • 5 comments

Right now I'm playing around with Service Weaver and Dapr. I'm trying to create Pub/Sub subscribers in Init but I will also need to unregister a subscriber once the component is scaled down.

fkorotkov avatar Apr 20 '23 13:04 fkorotkov

Hi @fkorotkov! Thanks for your suggestion and for sharing your use case. I think the idea of a Deinit method sounds interesting. The team can chat about it more. One challenge I think we'd have to figure out is the fact that machines can fail abruptly. In these cases, it's impossible to run the Deinit function.

mwhittaker avatar Apr 20 '23 16:04 mwhittaker

I think if a machine crashes no one can do anything. But in regular scaling scenario such "graceful shutdown" can help with smoother operation IMO.

fkorotkov avatar Apr 20 '23 18:04 fkorotkov

I think ServiceWeaver needs a app.Shutdown(ctx) error or app.Cleanup(ctx) error method on the app and on each service component so that it can grafully shutdown each service.

And if a machine crashes it crashes and ServiceWeaver cannot do anything about it, but I think that ServiceWeaver should try to comply with k8s gracefull shutdown.

func main() {
	if err := weaver.Run(context.Background(), run); err != nil {
		log.Fatal(err)
	}
}

// the code below should be handled by ServiceWeaver.
func run(ctx context.Context, app *App) error {
	shutdown := make(chan os.Signal, 1)
	signal.Notify(shutdown, syscall.SIGINT, syscall.SIGTERM)

	sig := <-shutdown:
	
	return app.Shutdown(ctx)
}

k8s gracfull shutdown

  • SIGTERM signal is sent to the pod

  • At this point, Kubernetes waits for a specified time called the termination grace period.

  • https://cloud.google.com/blog/products/containers-kubernetes/kubernetes-best-practices-terminating-with-grace

unders avatar Sep 16 '23 15:09 unders

I have encountered the same requirement today. So I searched and found this April issue.

I think it's very necessary to provide a mechanism like "Deinit()" or "app.Shutdown()" to notify app to do same closing work and to end the goroutines. I hope this can be a base feature for Service Weaver.

bagualing avatar Nov 01 '23 03:11 bagualing

One the cleanest ways I've seen is how fx does it. See https://uber-go.github.io/fx/lifecycle.html

The lifecycle hook can be injected into any component in order to register startup / shutdown operations. A Shutdowner can also be injected into components which want to force the local instance to shut down.

vgough avatar Dec 07 '23 22:12 vgough

Added a Shutdown method. Please install the latest weaver version and follow the instructions described here https://serviceweaver.dev/docs.html#components-interfaces

rgrandl avatar May 30 '24 18:05 rgrandl

Wow! Thank you!

fkorotkov avatar May 30 '24 18:05 fkorotkov

Thank you! @rgrandl

bagualing avatar Jun 08 '24 05:06 bagualing