[英]How do I configure failure actions of a Windows service written in Go?
我正在使用golang.org/x/sys/windows/svc
包在Go中編寫Windows服務。
到目前為止,這一切都很好,很容易上手,我喜歡它。
我已經寫了一些自動更新功能,我希望服務在完成更新后重新啟動。
我已經嘗試生成一個將使用SCM
重新啟動服務的進程,但它會記錄一條錯誤消息,這似乎與嘗試在作為本地系統運行時控制服務有關。
The service process could not connect to the service controller.
一個更好/更簡單的方法似乎是os.Exit(1)
並將服務Failure Actions
設置為Restart on Failure
,它運行得非常好!
唯一的麻煩是,似乎沒有使用Go以編程方式配置這些選項的功能。
我已經做了一些挖掘,看起來它們是通過將結構傳遞給advapi32.dll
ChangeServiceConfig2
來advapi32.dll
- 如何創建在崩潰時重新啟動的服務
在golang / sys / blob / master / windows / svc / mgr / config.go中 - func updateDescription(handle windows.Handle, desc string) error
代碼已經調用了windows.ChangeServiceConfig2
,它是DLL調用的鏈接。
而SERVICE_FAILURE_ACTIONS
結構的Microsoft文檔就在這里 。
我無法弄清楚如何使用Go構建和傳遞該結構 - 有沒有人有任何見解?
經過這里的一些指導,加上閱讀現有Go Windows Service界面的源代碼,我想出了自己的答案,我將在下面記錄。
對於使用Windows DLL時的類型參考,MSDN文檔在此處 。
我的代碼看起來像這樣:
import (
"unsafe"
"golang.org/x/sys/windows"
)
const (
SC_ACTION_NONE = 0
SC_ACTION_RESTART = 1
SC_ACTION_REBOOT = 2
SC_ACTION_RUN_COMMAND = 3
SERVICE_CONFIG_FAILURE_ACTIONS = 2
)
type SERVICE_FAILURE_ACTIONS struct {
ResetPeriod uint32
RebootMsg *uint16
Command *uint16
ActionsCount uint32
Actions uintptr
}
type SC_ACTION struct {
Type uint32
Delay uint32
}
func setServiceFailureActions(handle windows.Handle) error {
t := []SC_ACTION{
{ Type: SC_ACTION_RESTART, Delay: uint32(1000) },
{ Type: SC_ACTION_RESTART, Delay: uint32(10000) },
{ Type: SC_ACTION_RESTART, Delay: uint32(60000) },
}
m := SERVICE_FAILURE_ACTIONS{ ResetPeriod: uint32(60), ActionsCount: uint32(3), Actions: uintptr(unsafe.Pointer(&t[0])) }
return windows.ChangeServiceConfig2(handle, SERVICE_CONFIG_FAILURE_ACTIONS, (*byte)(unsafe.Pointer(&m)))
}
在我的基本示例中,您需要傳遞一個服務句柄,然后它將故障操作設置為硬編碼默認值:
我剛剛測試過它似乎工作正常。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.