Debian Codegraph @

server/signal.go

raw
1 // Copyright 2012-2025 The NATS Authors
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 //go:build !windows && !wasm
15
16 package server
17
18 import (
19 "errors"
20 "fmt"
21 "os"
22 "os/exec"
23 "os/signal"
24 "strconv"
25 "strings"
26 "syscall"
27 )
28
29 var processName = "nats-server"
30
31 // SetProcessName allows to change the expected name of the process.
32 func SetProcessName(name string) {
33 processName = name
34 }
35
36 // Signal Handling
37 func (s *Server) handleSignals() {
38 if s.getOpts().NoSigs {
39 return
40 }
41 c := make(chan os.Signal, 1)
42
43 signal.Notify(c, syscall.SIGINT, syscall.SIGTERM, syscall.SIGUSR1, syscall.SIGUSR2, syscall.SIGHUP)
44
45 go func() {
46 for {
47 select {
48 case sig := <-c:
49 s.handleSignal(sig)
50 case <-s.quitCh:
51 return
52 }
53 }
54 }()
55 }
56
57 func (s *Server) handleSignal(sig os.Signal) {
58 s.Noticef("Trapped %q signal", sig)
59 switch sig {
60 case syscall.SIGINT:
61 s.Shutdown()
62 s.WaitForShutdown()
63 os.Exit(0)
64 case syscall.SIGTERM:
65 // Shutdown unless graceful shutdown already in progress.
66 s.mu.Lock()
67 ldm := s.ldm
68 s.mu.Unlock()
69
70 if !ldm {
71 s.Shutdown()
72 s.WaitForShutdown()
73 os.Exit(0)
74 }
75 case syscall.SIGUSR1:
76 // File log re-open for rotating file logs.
77 s.ReOpenLogFile()
78 case syscall.SIGUSR2:
79 go s.lameDuckMode()
80 case syscall.SIGHUP:
81 // Config reload.
82 if err := s.Reload(); err != nil {
83 s.Errorf("Failed to reload server configuration: %s", err)
84 }
85 }
86 }
87
88 // ProcessSignal sends the given signal command to the given process. If pidStr
89 // is empty, this will send the signal to the single running instance of
90 // nats-server. If multiple instances are running, pidStr can be a globular
91 // expression ending with '*'. This returns an error if the given process is
92 // not running or the command is invalid.
93 func ProcessSignal(command Command, pidExpr string) error {
94 var (
95 err error
96 errStr string
97 pids = make([]int, 1)
98 pidStr = strings.TrimSuffix(pidExpr, "*")
99 isGlob = strings.HasSuffix(pidExpr, "*")
100 )
101
102 // Validate input if given
103 if pidStr != "" {
104 if pids[0], err = strconv.Atoi(pidStr); err != nil {
105 return fmt.Errorf("invalid pid: %s", pidStr)
106 }
107 }
108 // Gather all PIDs unless the input is specific
109 if pidStr == "" || isGlob {
110 if pids, err = resolvePids(); err != nil {
111 return err
112 }
113 }
114 // Multiple instances are running and the input is not an expression
115 if len(pids) > 1 && !isGlob {
116 errStr = fmt.Sprintf("multiple %s processes running:", processName)
117 for _, p := range pids {
118 errStr += fmt.Sprintf("\n%d", p)
119 }
120 return errors.New(errStr)
121 }
122 // No instances are running
123 if len(pids) == 0 {
124 return fmt.Errorf("no %s processes running", processName)
125 }
126
127 var signum syscall.Signal
128 if signum, err = CommandToSignal(command); err != nil {
129 return err
130 }
131
132 for _, pid := range pids {
133 if _pidStr := strconv.Itoa(pid); _pidStr != pidStr && pidStr != "" {
134 if !isGlob || !strings.HasPrefix(_pidStr, pidStr) {
135 continue
136 }
137 }
138 if err = kill(pid, signum); err != nil {
139 errStr += fmt.Sprintf("\nsignal %q %d: %s", command, pid, err)
140 }
141 }
142 if errStr != "" {
143 return errors.New(errStr)
144 }
145 return nil
146 }
147
148 // Translates a command to a signal number
149 func CommandToSignal(command Command) (syscall.Signal, error) {
150 switch command {
151 case CommandStop:
152 return syscall.SIGKILL, nil
153 case CommandQuit:
154 return syscall.SIGINT, nil
155 case CommandReopen:
156 return syscall.SIGUSR1, nil
157 case CommandReload:
158 return syscall.SIGHUP, nil
159 case commandLDMode:
160 return syscall.SIGUSR2, nil
161 case commandTerm:
162 return syscall.SIGTERM, nil
163 default:
164 return 0, fmt.Errorf("unknown signal %q", command)
165 }
166 }
167
168 // resolvePids returns the pids for all running nats-server processes.
169 func resolvePids() ([]int, error) {
170 // If pgrep isn't available, this will just bail out and the user will be
171 // required to specify a pid.
172 output, err := pgrep()
173 if err != nil {
174 switch err.(type) {
175 case *exec.ExitError:
176 // ExitError indicates non-zero exit code, meaning no processes
177 // found.
178 break
179 default:
180 return nil, errors.New("unable to resolve pid, try providing one")
181 }
182 }
183 var (
184 myPid = os.Getpid()
185 pidStrs = strings.Split(string(output), "\n")
186 pids = make([]int, 0, len(pidStrs))
187 )
188 for _, pidStr := range pidStrs {
189 if pidStr == "" {
190 continue
191 }
192 pid, err := strconv.Atoi(pidStr)
193 if err != nil {
194 return nil, errors.New("unable to resolve pid, try providing one")
195 }
196 // Ignore the current process.
197 if pid == myPid {
198 continue
199 }
200 pids = append(pids, pid)
201 }
202 return pids, nil
203 }
204
205 var kill = func(pid int, signal syscall.Signal) error {
206 return syscall.Kill(pid, signal)
207 }
208
209 var pgrep = func() ([]byte, error) {
210 return exec.Command("pgrep", processName).Output()
211 }