Debian Codegraph @

cmd/serve_windows.go

raw
1 //go:build windows && !noserver
2
3 package cmd
4
5 import (
6 "fmt"
7 "sync"
8
9 "golang.org/x/sys/windows/svc"
10 "heckel.io/ntfy/v2/log"
11 "heckel.io/ntfy/v2/server"
12 )
13
14 const serviceName = "ntfy"
15
16 // sigHandlerConfigReload is a no-op on Windows since SIGHUP is not available.
17 // Windows users can restart the service to reload configuration.
18 func sigHandlerConfigReload(config string) {
19 log.Debug("Config hot-reload via SIGHUP is not supported on Windows")
20 }
21
22 // runAsWindowsService runs the ntfy server as a Windows service
23 func runAsWindowsService(conf *server.Config) error {
24 return svc.Run(serviceName, &windowsService{conf: conf})
25 }
26
27 // windowsService implements the svc.Handler interface
28 type windowsService struct {
29 conf *server.Config
30 server *server.Server
31 mu sync.Mutex
32 }
33
34 // Execute is the main entry point for the Windows service
35 func (s *windowsService) Execute(args []string, requests <-chan svc.ChangeRequest, status chan<- svc.Status) (bool, uint32) {
36 const cmdsAccepted = svc.AcceptStop | svc.AcceptShutdown
37 status <- svc.Status{State: svc.StartPending}
38
39 // Create and start the server
40 var err error
41 s.mu.Lock()
42 s.server, err = server.New(s.conf)
43 s.mu.Unlock()
44 if err != nil {
45 log.Error("Failed to create server: %s", err.Error())
46 return true, 1
47 }
48
49 // Start server in a goroutine
50 serverErrChan := make(chan error, 1)
51 go func() {
52 serverErrChan <- s.server.Run()
53 }()
54
55 status <- svc.Status{State: svc.Running, Accepts: cmdsAccepted}
56 log.Info("Windows service started")
57
58 for {
59 select {
60 case err := <-serverErrChan:
61 if err != nil {
62 log.Error("Server error: %s", err.Error())
63 return true, 1
64 }
65 return false, 0
66 case req := <-requests:
67 switch req.Cmd {
68 case svc.Interrogate:
69 status <- req.CurrentStatus
70 case svc.Stop, svc.Shutdown:
71 log.Info("Windows service stopping...")
72 status <- svc.Status{State: svc.StopPending}
73 s.mu.Lock()
74 if s.server != nil {
75 s.server.Stop()
76 }
77 s.mu.Unlock()
78 return false, 0
79 default:
80 log.Warn("Unexpected service control request: %d", req.Cmd)
81 }
82 }
83 }
84 }
85
86 // maybeRunAsService checks if the process is running as a Windows service,
87 // and if so, runs the server as a service. Returns true if it ran as a service.
88 func maybeRunAsService(conf *server.Config) (bool, error) {
89 isService, err := svc.IsWindowsService()
90 if err != nil {
91 return false, fmt.Errorf("failed to detect Windows service mode: %w", err)
92 } else if !isService {
93 return false, nil
94 }
95 log.Info("Running as Windows service")
96 if err := runAsWindowsService(conf); err != nil {
97 return true, fmt.Errorf("failed to run as Windows service: %w", err)
98 }
99 return true, nil
100 }