| 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 |
| 15 |
|
| 16 |
package server |
| 17 |
|
| 18 |
import ( |
| 19 |
"errors" |
| 20 |
"fmt" |
| 21 |
"os" |
| 22 |
"os/exec" |
| 23 |
"path/filepath" |
| 24 |
"strings" |
| 25 |
"syscall" |
| 26 |
"testing" |
| 27 |
"time" |
| 28 |
|
| 29 |
"github.com/nats-io/nats-server/v2/logger" |
| 30 |
"github.com/nats-io/nats.go" |
| 31 |
) |
| 32 |
|
| 33 |
func TestSignalToReOpenLogFile(t *testing.T) { |
| 34 |
logFile := filepath.Join(t.TempDir(), "test.log") |
| 35 |
opts := &Options{ |
| 36 |
Host: "127.0.0.1", |
| 37 |
Port: -1, |
| 38 |
NoSigs: false, |
| 39 |
LogFile: logFile, |
| 40 |
} |
| 41 |
s := RunServer(opts) |
| 42 |
defer s.SetLogger(nil, false, false) |
| 43 |
defer s.Shutdown() |
| 44 |
|
| 45 |
// Set the file log |
| 46 |
fileLog := logger.NewFileLogger(s.opts.LogFile, s.opts.Logtime, s.opts.Debug, s.opts.Trace, true, logger.LogUTC(s.opts.LogtimeUTC)) |
| 47 |
s.SetLogger(fileLog, false, false) |
| 48 |
|
| 49 |
// Add a trace |
| 50 |
expectedStr := "This is a Notice" |
| 51 |
s.Noticef(expectedStr) |
| 52 |
buf, err := os.ReadFile(logFile) |
| 53 |
if err != nil { |
| 54 |
t.Fatalf("Error reading file: %v", err) |
| 55 |
} |
| 56 |
if !strings.Contains(string(buf), expectedStr) { |
| 57 |
t.Fatalf("Expected log to contain %q, got %q", expectedStr, string(buf)) |
| 58 |
} |
| 59 |
// Rename the file |
| 60 |
if err := os.Rename(logFile, logFile+".bak"); err != nil { |
| 61 |
t.Fatalf("Unable to rename file: %v", err) |
| 62 |
} |
| 63 |
// This should cause file to be reopened. |
| 64 |
syscall.Kill(syscall.Getpid(), syscall.SIGUSR1) |
| 65 |
// Wait a bit for action to be performed |
| 66 |
time.Sleep(500 * time.Millisecond) |
| 67 |
buf, err = os.ReadFile(logFile) |
| 68 |
if err != nil { |
| 69 |
t.Fatalf("Error reading file: %v", err) |
| 70 |
} |
| 71 |
expectedStr = "File log re-opened" |
| 72 |
if !strings.Contains(string(buf), expectedStr) { |
| 73 |
t.Fatalf("Expected log to contain %q, got %q", expectedStr, string(buf)) |
| 74 |
} |
| 75 |
} |
| 76 |
|
| 77 |
func TestSignalToReloadConfig(t *testing.T) { |
| 78 |
tmpl := ` |
| 79 |
listen: 127.0.0.1:-1 |
| 80 |
accounts: { |
| 81 |
A: { users: [ { user: %s, password: foo } ] } |
| 82 |
} |
| 83 |
` |
| 84 |
conf := createConfFile(t, []byte(fmt.Sprintf(tmpl, "foo"))) |
| 85 |
opts, err := ProcessConfigFile(conf) |
| 86 |
if err != nil { |
| 87 |
t.Fatalf("Error processing config file: %v", err) |
| 88 |
} |
| 89 |
opts.NoLog = true |
| 90 |
s := RunServer(opts) |
| 91 |
defer s.Shutdown() |
| 92 |
|
| 93 |
// Check that the reload time does not change when there are no changes. |
| 94 |
loaded := s.ConfigTime() |
| 95 |
time.Sleep(250 * time.Millisecond) |
| 96 |
syscall.Kill(syscall.Getpid(), syscall.SIGHUP) |
| 97 |
time.Sleep(250 * time.Millisecond) |
| 98 |
if reloaded := s.ConfigTime(); reloaded.Equal(loaded) { |
| 99 |
t.Fatalf("ConfigTime is incorrect.\nexpected reload time to change: %s\ngot: %s", loaded, reloaded) |
| 100 |
} |
| 101 |
|
| 102 |
// Repeat test to make sure that server services signals more than once... |
| 103 |
for i := 0; i < 2; i++ { |
| 104 |
loaded := s.ConfigTime() |
| 105 |
user := fmt.Sprintf("foo:%d", i) |
| 106 |
if err := os.WriteFile(conf, []byte(fmt.Sprintf(tmpl, user)), 0666); err != nil { |
| 107 |
t.Fatalf("Error creating config file: %v", err) |
| 108 |
} |
| 109 |
// Wait a bit to ensure ConfigTime changes. |
| 110 |
time.Sleep(5 * time.Millisecond) |
| 111 |
|
| 112 |
// This should cause config to be reloaded. |
| 113 |
syscall.Kill(syscall.Getpid(), syscall.SIGHUP) |
| 114 |
// Wait a bit for action to be performed |
| 115 |
time.Sleep(500 * time.Millisecond) |
| 116 |
|
| 117 |
if reloaded := s.ConfigTime(); !reloaded.After(loaded) { |
| 118 |
t.Fatalf("ConfigTime is incorrect.\nexpected greater than: %s\ngot: %s", loaded, reloaded) |
| 119 |
} |
| 120 |
} |
| 121 |
} |
| 122 |
|
| 123 |
func TestProcessSignalNoProcesses(t *testing.T) { |
| 124 |
pgrepBefore := pgrep |
| 125 |
pgrep = func() ([]byte, error) { |
| 126 |
return nil, &exec.ExitError{} |
| 127 |
} |
| 128 |
defer func() { |
| 129 |
pgrep = pgrepBefore |
| 130 |
}() |
| 131 |
|
| 132 |
err := ProcessSignal(CommandStop, "") |
| 133 |
if err == nil { |
| 134 |
t.Fatal("Expected error") |
| 135 |
} |
| 136 |
expectedStr := "no nats-server processes running" |
| 137 |
if err.Error() != expectedStr { |
| 138 |
t.Fatalf("Error is incorrect.\nexpected: %s\ngot: %s", expectedStr, err.Error()) |
| 139 |
} |
| 140 |
} |
| 141 |
|
| 142 |
func TestProcessSignalMultipleProcesses(t *testing.T) { |
| 143 |
pid := os.Getpid() |
| 144 |
pgrepBefore := pgrep |
| 145 |
pgrep = func() ([]byte, error) { |
| 146 |
return []byte(fmt.Sprintf("123\n456\n%d\n", pid)), nil |
| 147 |
} |
| 148 |
defer func() { |
| 149 |
pgrep = pgrepBefore |
| 150 |
}() |
| 151 |
|
| 152 |
err := ProcessSignal(CommandStop, "") |
| 153 |
if err == nil { |
| 154 |
t.Fatal("Expected error") |
| 155 |
} |
| 156 |
expectedStr := "multiple nats-server processes running:\n123\n456" |
| 157 |
if err.Error() != expectedStr { |
| 158 |
t.Fatalf("Error is incorrect.\nexpected: %s\ngot: %s", expectedStr, err.Error()) |
| 159 |
} |
| 160 |
} |
| 161 |
|
| 162 |
func TestProcessSignalMultipleProcessesGlob(t *testing.T) { |
| 163 |
pid := os.Getpid() |
| 164 |
pgrepBefore := pgrep |
| 165 |
pgrep = func() ([]byte, error) { |
| 166 |
return []byte(fmt.Sprintf("123\n456\n%d\n", pid)), nil |
| 167 |
} |
| 168 |
defer func() { |
| 169 |
pgrep = pgrepBefore |
| 170 |
}() |
| 171 |
|
| 172 |
err := ProcessSignal(CommandStop, "*") |
| 173 |
if err == nil { |
| 174 |
t.Fatal("Expected error") |
| 175 |
} |
| 176 |
lines := strings.Split(err.Error(), "\n") |
| 177 |
require_Len(t, len(lines), 3) |
| 178 |
require_Equal(t, lines[0], "") // Empty line comes first |
| 179 |
require_True(t, strings.HasPrefix(lines[1], "signal \"stop\" 123:")) |
| 180 |
require_True(t, strings.HasPrefix(lines[2], "signal \"stop\" 456:")) |
| 181 |
} |
| 182 |
|
| 183 |
func TestProcessSignalMultipleProcessesGlobPartial(t *testing.T) { |
| 184 |
pid := os.Getpid() |
| 185 |
pgrepBefore := pgrep |
| 186 |
pgrep = func() ([]byte, error) { |
| 187 |
return []byte(fmt.Sprintf("123\n124\n456\n%d\n", pid)), nil |
| 188 |
} |
| 189 |
defer func() { |
| 190 |
pgrep = pgrepBefore |
| 191 |
}() |
| 192 |
|
| 193 |
err := ProcessSignal(CommandStop, "12*") |
| 194 |
if err == nil { |
| 195 |
t.Fatal("Expected error") |
| 196 |
} |
| 197 |
lines := strings.Split(err.Error(), "\n") |
| 198 |
require_Len(t, len(lines), 3) |
| 199 |
require_Equal(t, lines[0], "") // Empty line comes first |
| 200 |
require_True(t, strings.HasPrefix(lines[1], "signal \"stop\" 123:")) |
| 201 |
require_True(t, strings.HasPrefix(lines[2], "signal \"stop\" 124:")) |
| 202 |
} |
| 203 |
|
| 204 |
func TestProcessSignalPgrepError(t *testing.T) { |
| 205 |
pgrepBefore := pgrep |
| 206 |
pgrep = func() ([]byte, error) { |
| 207 |
return nil, errors.New("error") |
| 208 |
} |
| 209 |
defer func() { |
| 210 |
pgrep = pgrepBefore |
| 211 |
}() |
| 212 |
|
| 213 |
err := ProcessSignal(CommandStop, "") |
| 214 |
if err == nil { |
| 215 |
t.Fatal("Expected error") |
| 216 |
} |
| 217 |
expectedStr := "unable to resolve pid, try providing one" |
| 218 |
if err.Error() != expectedStr { |
| 219 |
t.Fatalf("Error is incorrect.\nexpected: %s\ngot: %s", expectedStr, err.Error()) |
| 220 |
} |
| 221 |
} |
| 222 |
|
| 223 |
func TestProcessSignalPgrepMangled(t *testing.T) { |
| 224 |
pgrepBefore := pgrep |
| 225 |
pgrep = func() ([]byte, error) { |
| 226 |
return []byte("12x"), nil |
| 227 |
} |
| 228 |
defer func() { |
| 229 |
pgrep = pgrepBefore |
| 230 |
}() |
| 231 |
|
| 232 |
err := ProcessSignal(CommandStop, "") |
| 233 |
if err == nil { |
| 234 |
t.Fatal("Expected error") |
| 235 |
} |
| 236 |
expectedStr := "unable to resolve pid, try providing one" |
| 237 |
if err.Error() != expectedStr { |
| 238 |
t.Fatalf("Error is incorrect.\nexpected: %s\ngot: %s", expectedStr, err.Error()) |
| 239 |
} |
| 240 |
} |
| 241 |
|
| 242 |
func TestProcessSignalResolveSingleProcess(t *testing.T) { |
| 243 |
pid := os.Getpid() |
| 244 |
pgrepBefore := pgrep |
| 245 |
pgrep = func() ([]byte, error) { |
| 246 |
return []byte(fmt.Sprintf("123\n%d\n", pid)), nil |
| 247 |
} |
| 248 |
defer func() { |
| 249 |
pgrep = pgrepBefore |
| 250 |
}() |
| 251 |
killBefore := kill |
| 252 |
called := false |
| 253 |
kill = func(pid int, signal syscall.Signal) error { |
| 254 |
called = true |
| 255 |
if pid != 123 { |
| 256 |
t.Fatalf("pid is incorrect.\nexpected: 123\ngot: %d", pid) |
| 257 |
} |
| 258 |
if signal != syscall.SIGKILL { |
| 259 |
t.Fatalf("signal is incorrect.\nexpected: killed\ngot: %v", signal) |
| 260 |
} |
| 261 |
return nil |
| 262 |
} |
| 263 |
defer func() { |
| 264 |
kill = killBefore |
| 265 |
}() |
| 266 |
|
| 267 |
if err := ProcessSignal(CommandStop, ""); err != nil { |
| 268 |
t.Fatalf("ProcessSignal failed: %v", err) |
| 269 |
} |
| 270 |
|
| 271 |
if !called { |
| 272 |
t.Fatal("Expected kill to be called") |
| 273 |
} |
| 274 |
} |
| 275 |
|
| 276 |
func TestProcessSignalInvalidCommand(t *testing.T) { |
| 277 |
err := ProcessSignal(Command("invalid"), "123") |
| 278 |
if err == nil { |
| 279 |
t.Fatal("Expected error") |
| 280 |
} |
| 281 |
expectedStr := "unknown signal \"invalid\"" |
| 282 |
if err.Error() != expectedStr { |
| 283 |
t.Fatalf("Error is incorrect.\nexpected: %s\ngot: %s", expectedStr, err.Error()) |
| 284 |
} |
| 285 |
} |
| 286 |
|
| 287 |
func TestProcessSignalInvalidPid(t *testing.T) { |
| 288 |
err := ProcessSignal(CommandStop, "abc") |
| 289 |
if err == nil { |
| 290 |
t.Fatal("Expected error") |
| 291 |
} |
| 292 |
expectedStr := "invalid pid: abc" |
| 293 |
if err.Error() != expectedStr { |
| 294 |
t.Fatalf("Error is incorrect.\nexpected: %s\ngot: %s", expectedStr, err.Error()) |
| 295 |
} |
| 296 |
} |
| 297 |
|
| 298 |
func TestProcessSignalQuitProcess(t *testing.T) { |
| 299 |
killBefore := kill |
| 300 |
called := false |
| 301 |
kill = func(pid int, signal syscall.Signal) error { |
| 302 |
called = true |
| 303 |
if pid != 123 { |
| 304 |
t.Fatalf("pid is incorrect.\nexpected: 123\ngot: %d", pid) |
| 305 |
} |
| 306 |
if signal != syscall.SIGINT { |
| 307 |
t.Fatalf("signal is incorrect.\nexpected: interrupt\ngot: %v", signal) |
| 308 |
} |
| 309 |
return nil |
| 310 |
} |
| 311 |
defer func() { |
| 312 |
kill = killBefore |
| 313 |
}() |
| 314 |
|
| 315 |
if err := ProcessSignal(CommandQuit, "123"); err != nil { |
| 316 |
t.Fatalf("ProcessSignal failed: %v", err) |
| 317 |
} |
| 318 |
|
| 319 |
if !called { |
| 320 |
t.Fatal("Expected kill to be called") |
| 321 |
} |
| 322 |
} |
| 323 |
|
| 324 |
func TestProcessSignalTermProcess(t *testing.T) { |
| 325 |
killBefore := kill |
| 326 |
called := false |
| 327 |
kill = func(pid int, signal syscall.Signal) error { |
| 328 |
called = true |
| 329 |
if pid != 123 { |
| 330 |
t.Fatalf("pid is incorrect.\nexpected: 123\ngot: %d", pid) |
| 331 |
} |
| 332 |
if signal != syscall.SIGTERM { |
| 333 |
t.Fatalf("signal is incorrect.\nexpected: interrupt\ngot: %v", signal) |
| 334 |
} |
| 335 |
return nil |
| 336 |
} |
| 337 |
defer func() { |
| 338 |
kill = killBefore |
| 339 |
}() |
| 340 |
|
| 341 |
if err := ProcessSignal(commandTerm, "123"); err != nil { |
| 342 |
t.Fatalf("ProcessSignal failed: %v", err) |
| 343 |
} |
| 344 |
|
| 345 |
if !called { |
| 346 |
t.Fatal("Expected kill to be called") |
| 347 |
} |
| 348 |
} |
| 349 |
|
| 350 |
func TestProcessSignalReopenProcess(t *testing.T) { |
| 351 |
killBefore := kill |
| 352 |
called := false |
| 353 |
kill = func(pid int, signal syscall.Signal) error { |
| 354 |
called = true |
| 355 |
if pid != 123 { |
| 356 |
t.Fatalf("pid is incorrect.\nexpected: 123\ngot: %d", pid) |
| 357 |
} |
| 358 |
if signal != syscall.SIGUSR1 { |
| 359 |
t.Fatalf("signal is incorrect.\nexpected: user defined signal 1\ngot: %v", signal) |
| 360 |
} |
| 361 |
return nil |
| 362 |
} |
| 363 |
defer func() { |
| 364 |
kill = killBefore |
| 365 |
}() |
| 366 |
|
| 367 |
if err := ProcessSignal(CommandReopen, "123"); err != nil { |
| 368 |
t.Fatalf("ProcessSignal failed: %v", err) |
| 369 |
} |
| 370 |
|
| 371 |
if !called { |
| 372 |
t.Fatal("Expected kill to be called") |
| 373 |
} |
| 374 |
} |
| 375 |
|
| 376 |
func TestProcessSignalReloadProcess(t *testing.T) { |
| 377 |
killBefore := kill |
| 378 |
called := false |
| 379 |
kill = func(pid int, signal syscall.Signal) error { |
| 380 |
called = true |
| 381 |
if pid != 123 { |
| 382 |
t.Fatalf("pid is incorrect.\nexpected: 123\ngot: %d", pid) |
| 383 |
} |
| 384 |
if signal != syscall.SIGHUP { |
| 385 |
t.Fatalf("signal is incorrect.\nexpected: hangup\ngot: %v", signal) |
| 386 |
} |
| 387 |
return nil |
| 388 |
} |
| 389 |
defer func() { |
| 390 |
kill = killBefore |
| 391 |
}() |
| 392 |
|
| 393 |
if err := ProcessSignal(CommandReload, "123"); err != nil { |
| 394 |
t.Fatalf("ProcessSignal failed: %v", err) |
| 395 |
} |
| 396 |
|
| 397 |
if !called { |
| 398 |
t.Fatal("Expected kill to be called") |
| 399 |
} |
| 400 |
} |
| 401 |
|
| 402 |
func TestProcessSignalLameDuckMode(t *testing.T) { |
| 403 |
killBefore := kill |
| 404 |
called := false |
| 405 |
kill = func(pid int, signal syscall.Signal) error { |
| 406 |
called = true |
| 407 |
if pid != 123 { |
| 408 |
t.Fatalf("pid is incorrect.\nexpected: 123\ngot: %d", pid) |
| 409 |
} |
| 410 |
if signal != syscall.SIGUSR2 { |
| 411 |
t.Fatalf("signal is incorrect.\nexpected: sigusr2\ngot: %v", signal) |
| 412 |
} |
| 413 |
return nil |
| 414 |
} |
| 415 |
defer func() { |
| 416 |
kill = killBefore |
| 417 |
}() |
| 418 |
|
| 419 |
if err := ProcessSignal(commandLDMode, "123"); err != nil { |
| 420 |
t.Fatalf("ProcessSignal failed: %v", err) |
| 421 |
} |
| 422 |
|
| 423 |
if !called { |
| 424 |
t.Fatal("Expected kill to be called") |
| 425 |
} |
| 426 |
} |
| 427 |
|
| 428 |
func TestProcessSignalTermDuringLameDuckMode(t *testing.T) { |
| 429 |
opts := &Options{ |
| 430 |
Host: "127.0.0.1", |
| 431 |
Port: -1, |
| 432 |
NoSigs: true, |
| 433 |
NoLog: true, |
| 434 |
LameDuckDuration: 2 * time.Second, |
| 435 |
LameDuckGracePeriod: 1 * time.Second, |
| 436 |
} |
| 437 |
s := RunServer(opts) |
| 438 |
defer s.Shutdown() |
| 439 |
|
| 440 |
// Create single NATS Connection which will cause the server |
| 441 |
// to delay the shutdown. |
| 442 |
doneCh := make(chan struct{}) |
| 443 |
nc, err := nats.Connect(fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port), |
| 444 |
nats.DisconnectHandler(func(*nats.Conn) { |
| 445 |
close(doneCh) |
| 446 |
}), |
| 447 |
) |
| 448 |
if err != nil { |
| 449 |
t.Fatalf("Error on connect: %v", err) |
| 450 |
} |
| 451 |
defer nc.Close() |
| 452 |
|
| 453 |
// Trigger lame duck based shutdown. |
| 454 |
go s.lameDuckMode() |
| 455 |
|
| 456 |
// Wait for client to be disconnected. |
| 457 |
select { |
| 458 |
case <-doneCh: |
| 459 |
break |
| 460 |
case <-time.After(3 * time.Second): |
| 461 |
t.Fatalf("Timed out waiting for client to disconnect") |
| 462 |
} |
| 463 |
|
| 464 |
// Termination signal should not cause server to shutdown |
| 465 |
// while in lame duck mode already. |
| 466 |
s.handleSignal(syscall.SIGTERM) |
| 467 |
|
| 468 |
// Wait for server shutdown due to lame duck shutdown. |
| 469 |
timeoutCh := make(chan error) |
| 470 |
timer := time.AfterFunc(3*time.Second, func() { |
| 471 |
timeoutCh <- errors.New("Timed out waiting for server shutdown") |
| 472 |
}) |
| 473 |
for range time.NewTicker(1 * time.Millisecond).C { |
| 474 |
select { |
| 475 |
case err := <-timeoutCh: |
| 476 |
t.Fatal(err) |
| 477 |
default: |
| 478 |
} |
| 479 |
|
| 480 |
if !s.isRunning() { |
| 481 |
timer.Stop() |
| 482 |
break |
| 483 |
} |
| 484 |
} |
| 485 |
} |
| 486 |
|
| 487 |
func TestSignalInterruptHasSuccessfulExit(t *testing.T) { |
| 488 |
if os.Getenv("IN_TEST") == "1" { |
| 489 |
s := RunServer(&Options{}) |
| 490 |
defer s.Shutdown() |
| 491 |
require_NoError(t, syscall.Kill(syscall.Getpid(), syscall.SIGINT)) |
| 492 |
s.WaitForShutdown() |
| 493 |
return |
| 494 |
} |
| 495 |
// To check for successful/0 exit code, need execute as separate process. |
| 496 |
cmd := exec.Command(os.Args[0], "-test.run=TestSignalInterruptHasSuccessfulExit") |
| 497 |
cmd.Env = append(os.Environ(), "IN_TEST=1") |
| 498 |
err := cmd.Run() |
| 499 |
require_NoError(t, err) |
| 500 |
} |
| 501 |
|
| 502 |
func TestSignalTermHasSuccessfulExit(t *testing.T) { |
| 503 |
if os.Getenv("IN_TEST") == "1" { |
| 504 |
s := RunServer(&Options{}) |
| 505 |
defer s.Shutdown() |
| 506 |
require_NoError(t, syscall.Kill(syscall.Getpid(), syscall.SIGTERM)) |
| 507 |
s.WaitForShutdown() |
| 508 |
return |
| 509 |
} |
| 510 |
// To check for successful/0 exit code, need execute as separate process. |
| 511 |
cmd := exec.Command(os.Args[0], "-test.run=TestSignalTermHasSuccessfulExit") |
| 512 |
cmd.Env = append(os.Environ(), "IN_TEST=1") |
| 513 |
err := cmd.Run() |
| 514 |
require_NoError(t, err) |
| 515 |
} |