How do I configure failure actions of a Windows service written in Go?

↘锁芯ラ 提交于 2019-12-05 16:36:18
iamacarpet

After some guidance from here, plus reading through the source code for the existing Go Windows Service interface, I came up with my own answer, which I'll try to document below.

For type reference when working with the Windows DLLs, the MSDN docs are here.

My code looks like this:

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)))
}

In my basic example, you need to pass a Service Handle, then it'll set the failure actions to a hard coded default of:

  1. Restart the first time after 1 second.
  2. Restart the second time after 10 seconds.
  3. Restart the third time and any subsequent times after 60 seconds.
  4. Reset the failure counter after 60 seconds.

I've just tested and it seems to work ok.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!