go-zero icon indicating copy to clipboard operation
go-zero copied to clipboard

shutdownListeners not called on some special scenarios

Open MisakiArt opened this issue 1 year ago • 4 comments

image

这段代码看意思是会执行AddShutdownListener()和AddWrapUpListener()注册的方法,但我这边测试时经常出现shutdownListeners.notifyListeners()不执行的情况, 经排查发现wrapUpListeners.notifyListeners()中执行了shutdown方法,取消了主程的阻塞,导致shutdownListeners.notifyListeners()没来得及执行 image

因为mian函数最后一行是server.Start(),到这里本以为问题就结束了 当我尝试注册更多的WrapUpListener时,发现无论如何主程都会等待所有的WrapUpListener执行结束再终止,而不是在执行完shutdown后立刻停止,这让我很困惑,代码如下: 按理说这个test不应该被打印

package main

import (
	"fmt"
	"github.com/zeromicro/go-zero/core/proc"
	"github.com/zeromicro/go-zero/rest"
	"syscall"
	"time"
)

func main() {
	var c rest.RestConf
	c.Host = "0.0.0.0"
	c.Port = 8082
	c.Log.Mode = "console"
	server := rest.MustNewServer(c, rest.WithCors("*"))
	defer server.Stop()

	fmt.Printf("Starting server at %s:%d...\n", c.Host, c.Port)
	proc.AddWrapUpListener(func() {
		time.Sleep(3 * time.Second)
		fmt.Println("test", time.Now().UnixNano())
	})
	time.AfterFunc(2*time.Second, func() {
		fmt.Println(syscall.Kill(syscall.Getpid(), syscall.SIGTERM))
	})
	server.Start()
}

输出如下: image

MisakiArt avatar Jul 25 '22 09:07 MisakiArt

从源码来看,gozero是尽量保证wrapUpListeners会执行完成(如果5.5s还不能执行完还是会被kill的),执行完wrapUpListeners,不管shutdownListeners有没有执行完,main goroutine都会退出。

taobig avatar Jul 26 '22 08:07 taobig

Bot detected the issue body's language is not English, translate it automatically. 👯👭🏻🧑‍🤝‍🧑👫🧑🏿‍🤝‍🧑🏻👩🏾‍🤝‍👨🏿👬🏿


From the source code point of view, gozero tries to ensure that wrapUpListeners will be executed (if it cannot be executed in 5.5s, it will still be killed). After wrapUpListeners are executed, the main goroutine will exit regardless of whether shutdownListeners are executed or not.

Issues-translate-bot avatar Jul 26 '22 08:07 Issues-translate-bot

能否提供一下main goroutine监听wrapUpListeners执行完的代码段,按现象看应该是有这个逻辑,但是尝试寻找了很久并没有找到

MisakiArt avatar Jul 26 '22 08:07 MisakiArt

Bot detected the issue body's language is not English, translate it automatically. 👯👭🏻🧑‍🤝‍🧑👫🧑🏿‍🤝‍🧑🏻👩🏾‍🤝‍👨🏿👬🏿


Can you provide the code segment where the main goroutine listens to the wrapUpListeners execution? According to the phenomenon, there should be this logic, but I have been trying to find it for a long time and have not found it.

Issues-translate-bot avatar Jul 26 '22 08:07 Issues-translate-bot

This issue is stale because it has been open for 30 days with no activity.

github-actions[bot] avatar Jul 28 '23 01:07 github-actions[bot]

This issue was closed because it has been inactive for 14 days since being marked as stale.

github-actions[bot] avatar Mar 20 '24 01:03 github-actions[bot]