I'm writing a Windows Service in Go using the golang.org/x/sys/windows/svc
package.
So far, it's all working great and so easy to get started with, I love it.
I've written in some auto update functionality and I'm wanting the service to restart itself when it has completed an update.
I've tried spawning a process that will restart the service using the SCM
, but it logs an error message which seems to be to do with trying to control the service while running as Local System.
The service process could not connect to the service controller.
A better/easier way seems to be to os.Exit(1)
and have the service Failure Actions
set to Restart on Failure
, which works brilliantly!
The only trouble is, there doesn't seem to be the functionality to configure those options programatically using Go.
I've done some digging and it looks like they are configured by passing a struct to ChangeServiceConfig2
in advapi32.dll
- How to create service which restarts on crash
In golang/sys/blob/master/windows/svc/mgr/config.go - func updateDescription(handle windows.Handle, desc string) error
The code already calls windows.ChangeServiceConfig2
which is a link to the DLL call.
And the Microsoft docs for the SERVICE_FAILURE_ACTIONS
struct are here.
I'm having trouble figuring out how to build and pass that struct using Go - does anyone have any insights?
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:
In my basic example, you need to pass a Service Handle, then it'll set the failure actions to a hard coded default of:
I've just tested and it seems to work ok.