Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Provide a way to control Windows service state #394

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions controls_nwin.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
//go:build !windows
// +build !windows

package service

// ControlsHandler is a stub of windows specific helper for common code.
type ControlsHandler struct {
}
88 changes: 45 additions & 43 deletions service.go
Original file line number Diff line number Diff line change
Expand Up @@ -167,42 +167,44 @@ func New(i Interface, c *Config) (Service, error) {
}

// KeyValue provides a list of system specific options.
// * OS X
// - LaunchdConfig string () - Use custom launchd config.
// - KeepAlive bool (true) - Prevent the system from stopping the service automatically.
// - RunAtLoad bool (false) - Run the service after its job has been loaded.
// - SessionCreate bool (false) - Create a full user session.
//
// * Solaris
// - Prefix string ("application") - Service FMRI prefix.
// * OS X
// - LaunchdConfig string () - Use custom launchd config.
// - KeepAlive bool (true) - Prevent the system from stopping the service automatically.
// - RunAtLoad bool (false) - Run the service after its job has been loaded.
// - SessionCreate bool (false) - Create a full user session.
// - Solaris
// - Prefix string ("application") - Service FMRI prefix.
//
// * POSIX
// - UserService bool (false) - Install as a current user service.
// - SystemdScript string () - Use custom systemd script.
// - UpstartScript string () - Use custom upstart script.
// - SysvScript string () - Use custom sysv script.
// - OpenRCScript string () - Use custom OpenRC script.
// - RunWait func() (wait for SIGNAL) - Do not install signal but wait for this function to return.
// - ReloadSignal string () [USR1, ...] - Signal to send on reload.
// - PIDFile string () [/run/prog.pid] - Location of the PID file.
// - LogOutput bool (false) - Redirect StdErr & StandardOutPath to files.
// - Restart string (always) - How shall service be restarted.
// - SuccessExitStatus string () - The list of exit status that shall be considered as successful,
// in addition to the default ones.
// - LogDirectory string(/var/log) - The path to the log files directory
// * POSIX
// - UserService bool (false) - Install as a current user service.
// - SystemdScript string () - Use custom systemd script.
// - UpstartScript string () - Use custom upstart script.
// - SysvScript string () - Use custom sysv script.
// - OpenRCScript string () - Use custom OpenRC script.
// - RunWait func() (wait for SIGNAL) - Do not install signal but wait for this function to return.
// - ReloadSignal string () [USR1, ...] - Signal to send on reload.
// - PIDFile string () [/run/prog.pid] - Location of the PID file.
// - LogOutput bool (false) - Redirect StdErr & StandardOutPath to files.
// - Restart string (always) - How shall service be restarted.
// - SuccessExitStatus string () - The list of exit status that shall be considered as successful,
// in addition to the default ones.
// - LogDirectory string(/var/log) - The path to the log files directory
//
// * Linux (systemd)
// - LimitNOFILE int (-1) - Maximum open files (ulimit -n)
// (https://serverfault.com/questions/628610/increasing-nproc-for-processes-launched-by-systemd-on-centos-7)
// * Windows
// - DelayedAutoStart bool (false) - After booting, start this service after some delay.
// - Password string () - Password to use when interfacing with the system service manager.
// - Interactive bool (false) - The service can interact with the desktop. (more information https://docs.microsoft.com/en-us/windows/win32/services/interactive-services)
// - DelayedAutoStart bool (false) - after booting start this service after some delay.
// - StartType string ("automatic") - Start service type. (automatic | manual | disabled)
// - OnFailure string ("restart" ) - Action to perform on service failure. (restart | reboot | noaction)
// - OnFailureDelayDuration string ( "1s" ) - Delay before restarting the service, time.Duration string.
// - OnFailureResetPeriod int ( 10 ) - Reset period for errors, seconds.
// * Linux (systemd)
// - LimitNOFILE int (-1) - Maximum open files (ulimit -n)
// (https://serverfault.com/questions/628610/increasing-nproc-for-processes-launched-by-systemd-on-centos-7)
//
// * Windows
// - DelayedAutoStart bool (false) - After booting, start this service after some delay.
// - Password string () - Password to use when interfacing with the system service manager.
// - Interactive bool (false) - The service can interact with the desktop. (more information https://docs.microsoft.com/en-us/windows/win32/services/interactive-services)
// - DelayedAutoStart bool (false) - After booting start this service after some delay.
// - StartType string ("automatic") - Start service type. (automatic | manual | disabled)
// - OnFailure string ("restart" ) - Action to perform on service failure. (restart | reboot | noaction)
// - OnFailureDelayDuration string ( "1s" ) - Delay before restarting the service, time.Duration string.
// - OnFailureResetPeriod int ( 10 ) - Reset period for errors, seconds.
// - ExtraControls ControlsHandler (nil, nil) - Handle controls other than Stop and Shutdown.
type KeyValue map[string]interface{}

// bool returns the value of the given name, assuming the value is a boolean.
Expand Down Expand Up @@ -325,16 +327,16 @@ type System interface {
// Interface represents the service interface for a program. Start runs before
// the hosting process is granted control and Stop runs when control is returned.
//
// 1. OS service manager executes user program.
// 2. User program sees it is executed from a service manager (IsInteractive is false).
// 3. User program calls Service.Run() which blocks.
// 4. Interface.Start() is called and quickly returns.
// 5. User program runs.
// 6. OS service manager signals the user program to stop.
// 7. Interface.Stop() is called and quickly returns.
// - For a successful exit, os.Exit should not be called in Interface.Stop().
// 8. Service.Run returns.
// 9. User program should quickly exit.
// 1. OS service manager executes user program.
// 2. User program sees it is executed from a service manager (IsInteractive is false).
// 3. User program calls Service.Run() which blocks.
// 4. Interface.Start() is called and quickly returns.
// 5. User program runs.
// 6. OS service manager signals the user program to stop.
// 7. Interface.Stop() is called and quickly returns.
// - For a successful exit, os.Exit should not be called in Interface.Stop().
// 8. Service.Run returns.
// 9. User program should quickly exit.
type Interface interface {
// Start provides a place to initiate the service. The service doesn't
// signal a completed start until after this function returns, so the
Expand Down
137 changes: 106 additions & 31 deletions service_windows.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,30 @@ type WindowsLogger struct {
errs chan<- error
}

// ControlsHandler provides a way to set allowed controls and handle them.
// Note that Stop and Shutdown will not be passed throw this handler, also there are no
// Start control. User must handle Star, Stop and Shutdown with base service Interface.
type ControlsHandler struct {
Changes <-chan svc.Accepted
Handler func(request svc.ChangeRequest) svc.Status
}

// winControls is a helper function to extract ControlsHandler from Config
func (kv KeyValue) winControls() ControlsHandler {
const extraControlsName = "ExtraControls"
if v, found := kv[extraControlsName]; found {
if castValue, is := v.(ControlsHandler); is {
return castValue
}
}
return ControlsHandler{
Changes: nil,
Handler: func(req svc.ChangeRequest) svc.Status {
return req.CurrentStatus
},
}
}

type windowsSystem struct{}

func (windowsSystem) String() string {
Expand Down Expand Up @@ -178,48 +202,99 @@ func (ws *windowsService) getError() error {
return ws.stopStartErr
}

func (ws *windowsService) Execute(args []string, r <-chan svc.ChangeRequest, changes chan<- svc.Status) (bool, uint32) {
const cmdsAccepted = svc.AcceptStop | svc.AcceptShutdown
changes <- svc.Status{State: svc.StartPending}
type changesWrapper struct {
change chan<- svc.Status
last *svc.Status
}

func (w *changesWrapper) set(st svc.Status) {
w.last = &st
w.change <- st
}

func (w *changesWrapper) get() *svc.Status {
return w.last
}

func wrapChanges(ch chan<- svc.Status) *changesWrapper {
return &changesWrapper{
change: ch,
}
}

func (ws *windowsService) Execute(args []string, r <-chan svc.ChangeRequest, changesCh chan<- svc.Status) (bool, uint32) {
controls := ws.Config.Option.winControls()

changes := wrapChanges(changesCh)
changes.set(svc.Status{State: svc.StartPending})

if err := ws.i.Start(ws); err != nil {
ws.setError(err)
return true, 1
}

changes <- svc.Status{State: svc.Running, Accepts: cmdsAccepted}
loop:
cmdsAccepted := svc.AcceptStop | svc.AcceptShutdown
// give service a chance to init with proper accepts
// if it has nothing to init (or had no time to decide) we use defaults
select {
case cmdsAccepted = <-controls.Changes:
default:
}

changes.set(svc.Status{State: svc.Running, Accepts: cmdsAccepted})
err := ws.run(r, changes, controls)
if err != nil {
ws.setError(err)
return true, 2
}

return false, 0
}

func (ws *windowsService) run(r <-chan svc.ChangeRequest, changes *changesWrapper, controls ControlsHandler) error {
for {
c := <-r
switch c.Cmd {
case svc.Interrogate:
changes <- c.CurrentStatus
case svc.Stop:
changes <- svc.Status{State: svc.StopPending}
if err := ws.i.Stop(ws); err != nil {
ws.setError(err)
return true, 2
}
break loop
case svc.Shutdown:
changes <- svc.Status{State: svc.StopPending}
var err error
if wsShutdown, ok := ws.i.(Shutdowner); ok {
err = wsShutdown.Shutdown(ws)
} else {
err = ws.i.Stop(ws)
select {
case c := <-r:
switch c.Cmd {
case svc.Interrogate:
changes.set(c.CurrentStatus)
case svc.Stop:
changes.set(svc.Status{State: svc.StopPending})
if err := ws.i.Stop(ws); err != nil {
return err
}
return nil
case svc.Shutdown:
changes.set(svc.Status{State: svc.StopPending})
var err error
if wsShutdown, ok := ws.i.(Shutdowner); ok {
err = wsShutdown.Shutdown(ws)
} else {
err = ws.i.Stop(ws)
}
if err != nil {
return err
}
return nil
default:
res := c.CurrentStatus
if controls.Handler != nil {
res = controls.Handler(c)
}
changes.set(res)
}
if err != nil {
ws.setError(err)
return true, 2

case accepts := <-controls.Changes:
st := changes.get()
if st == nil {
st = &svc.Status{
State: svc.Stopped,
}
}
break loop
default:
continue loop
st.Accepts = accepts
changes.set(*st)
}
}

return false, 0
}

func lowPrivMgr() (*mgr.Mgr, error) {
Expand Down