2023-03-12 01:06:06 +00:00
|
|
|
// This package allows us to initiate Time Sensitive components (Like registering the windows service) as early as possible in the startup process
|
2022-08-23 13:57:16 +00:00
|
|
|
package initiate
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
2023-04-22 10:17:51 +00:00
|
|
|
"os"
|
2022-08-23 13:57:16 +00:00
|
|
|
|
|
|
|
"golang.org/x/sys/windows/svc"
|
2023-04-22 10:17:51 +00:00
|
|
|
"golang.org/x/sys/windows/svc/eventlog"
|
2022-08-23 13:57:16 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
|
|
|
serviceName = "windows_exporter"
|
|
|
|
)
|
|
|
|
|
|
|
|
type windowsExporterService struct {
|
|
|
|
stopCh chan<- bool
|
|
|
|
}
|
|
|
|
|
2023-04-22 10:17:51 +00:00
|
|
|
var logger *eventlog.Log
|
|
|
|
|
2022-08-23 13:57:16 +00:00
|
|
|
func (s *windowsExporterService) Execute(args []string, r <-chan svc.ChangeRequest, changes chan<- svc.Status) (ssec bool, errno uint32) {
|
|
|
|
const cmdsAccepted = svc.AcceptStop | svc.AcceptShutdown
|
|
|
|
changes <- svc.Status{State: svc.StartPending}
|
|
|
|
changes <- svc.Status{State: svc.Running, Accepts: cmdsAccepted}
|
|
|
|
loop:
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case c := <-r:
|
|
|
|
switch c.Cmd {
|
|
|
|
case svc.Interrogate:
|
|
|
|
changes <- c.CurrentStatus
|
|
|
|
case svc.Stop, svc.Shutdown:
|
2023-04-22 10:17:51 +00:00
|
|
|
_ = logger.Info(100, "Service Stop Received")
|
2022-08-23 13:57:16 +00:00
|
|
|
s.stopCh <- true
|
|
|
|
break loop
|
|
|
|
default:
|
2023-04-22 10:17:51 +00:00
|
|
|
_ = logger.Error(102, fmt.Sprintf("unexpected control request #%d", c))
|
2022-08-23 13:57:16 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
changes <- svc.Status{State: svc.StopPending}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2022-08-23 15:47:31 +00:00
|
|
|
var StopCh = make(chan bool)
|
2022-08-23 13:57:16 +00:00
|
|
|
|
|
|
|
func init() {
|
|
|
|
isService, err := svc.IsWindowsService()
|
|
|
|
if err != nil {
|
2023-04-22 10:17:51 +00:00
|
|
|
logger, err := eventlog.Open("windows_exporter")
|
|
|
|
if err != nil {
|
|
|
|
os.Exit(2)
|
|
|
|
}
|
|
|
|
_ = logger.Error(102, fmt.Sprintf("Failed to detect service: %v", err))
|
|
|
|
os.Exit(1)
|
2022-08-23 13:57:16 +00:00
|
|
|
}
|
2023-04-22 10:17:51 +00:00
|
|
|
|
2022-08-23 13:57:16 +00:00
|
|
|
if isService {
|
2023-04-22 10:17:51 +00:00
|
|
|
logger, err := eventlog.Open("windows_exporter")
|
|
|
|
if err != nil {
|
|
|
|
os.Exit(2)
|
|
|
|
}
|
|
|
|
_ = logger.Info(100, "Attempting to start exporter service")
|
2022-08-23 13:57:16 +00:00
|
|
|
go func() {
|
|
|
|
err = svc.Run(serviceName, &windowsExporterService{stopCh: StopCh})
|
|
|
|
if err != nil {
|
2023-04-22 10:17:51 +00:00
|
|
|
_ = logger.Error(102, fmt.Sprintf("Failed to start service: %v", err))
|
2022-08-23 13:57:16 +00:00
|
|
|
}
|
|
|
|
}()
|
|
|
|
}
|
|
|
|
}
|