2017-01-23 17:40:11 -05:00
|
|
|
// Copyright 2015 Daniel Theophanes.
|
|
|
|
// Use of this source code is governed by a zlib-style
|
|
|
|
// license that can be found in the LICENSE file.package service
|
|
|
|
|
|
|
|
//+build windows
|
|
|
|
|
|
|
|
package minwinsvc
|
|
|
|
|
|
|
|
import (
|
|
|
|
"os"
|
2017-01-23 17:44:23 -05:00
|
|
|
"strconv"
|
2017-01-23 17:40:11 -05:00
|
|
|
"sync"
|
|
|
|
|
|
|
|
"golang.org/x/sys/windows/svc"
|
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
2017-01-23 17:44:23 -05:00
|
|
|
onExit func()
|
|
|
|
guard sync.Mutex
|
|
|
|
skip, _ = strconv.ParseBool(os.Getenv("SKIP_MINWINSVC"))
|
2017-03-08 20:27:43 -05:00
|
|
|
isSSH = os.Getenv("SSH_ORIGINAL_COMMAND") != ""
|
2017-01-23 17:40:11 -05:00
|
|
|
)
|
|
|
|
|
|
|
|
func init() {
|
2017-03-08 20:27:43 -05:00
|
|
|
if skip || isSSH {
|
2017-01-23 17:44:23 -05:00
|
|
|
return
|
|
|
|
}
|
2017-01-23 17:40:11 -05:00
|
|
|
interactive, err := svc.IsAnInteractiveSession()
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
if interactive {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
go func() {
|
|
|
|
_ = svc.Run("", runner{})
|
|
|
|
|
|
|
|
guard.Lock()
|
|
|
|
f := onExit
|
|
|
|
guard.Unlock()
|
|
|
|
|
|
|
|
// Don't hold this lock in user code.
|
|
|
|
if f != nil {
|
|
|
|
f()
|
|
|
|
}
|
|
|
|
// Make sure we exit.
|
|
|
|
os.Exit(0)
|
|
|
|
}()
|
|
|
|
}
|
|
|
|
|
|
|
|
func setOnExit(f func()) {
|
|
|
|
guard.Lock()
|
|
|
|
onExit = f
|
|
|
|
guard.Unlock()
|
|
|
|
}
|
|
|
|
|
|
|
|
type runner struct{}
|
|
|
|
|
|
|
|
func (runner) 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}
|
|
|
|
|
|
|
|
changes <- svc.Status{State: svc.Running, Accepts: cmdsAccepted}
|
|
|
|
for {
|
|
|
|
c := <-r
|
|
|
|
switch c.Cmd {
|
|
|
|
case svc.Interrogate:
|
|
|
|
changes <- c.CurrentStatus
|
|
|
|
case svc.Stop, svc.Shutdown:
|
|
|
|
changes <- svc.Status{State: svc.StopPending}
|
|
|
|
return false, 0
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return false, 0
|
|
|
|
}
|