interrupt_unix.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. // Copyright 2015 The etcd Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. // +build !windows,!plan9
  15. package osutil
  16. import (
  17. "os"
  18. "os/signal"
  19. "sync"
  20. "syscall"
  21. "go.uber.org/zap"
  22. )
  23. // InterruptHandler is a function that is called on receiving a
  24. // SIGTERM or SIGINT signal.
  25. type InterruptHandler func()
  26. var (
  27. interruptRegisterMu, interruptExitMu sync.Mutex
  28. // interruptHandlers holds all registered InterruptHandlers in order
  29. // they will be executed.
  30. interruptHandlers = []InterruptHandler{}
  31. )
  32. // RegisterInterruptHandler registers a new InterruptHandler. Handlers registered
  33. // after interrupt handing was initiated will not be executed.
  34. func RegisterInterruptHandler(h InterruptHandler) {
  35. interruptRegisterMu.Lock()
  36. defer interruptRegisterMu.Unlock()
  37. interruptHandlers = append(interruptHandlers, h)
  38. }
  39. // HandleInterrupts calls the handler functions on receiving a SIGINT or SIGTERM.
  40. func HandleInterrupts(lg *zap.Logger) {
  41. notifier := make(chan os.Signal, 1)
  42. signal.Notify(notifier, syscall.SIGINT, syscall.SIGTERM)
  43. go func() {
  44. sig := <-notifier
  45. interruptRegisterMu.Lock()
  46. ihs := make([]InterruptHandler, len(interruptHandlers))
  47. copy(ihs, interruptHandlers)
  48. interruptRegisterMu.Unlock()
  49. interruptExitMu.Lock()
  50. if lg != nil {
  51. lg.Info("received signal; shutting down", zap.String("signal", sig.String()))
  52. } else {
  53. plog.Noticef("received %v signal, shutting down...", sig)
  54. }
  55. for _, h := range ihs {
  56. h()
  57. }
  58. signal.Stop(notifier)
  59. pid := syscall.Getpid()
  60. // exit directly if it is the "init" process, since the kernel will not help to kill pid 1.
  61. if pid == 1 {
  62. os.Exit(0)
  63. }
  64. setDflSignal(sig.(syscall.Signal))
  65. syscall.Kill(pid, sig.(syscall.Signal))
  66. }()
  67. }
  68. // Exit relays to os.Exit if no interrupt handlers are running, blocks otherwise.
  69. func Exit(code int) {
  70. interruptExitMu.Lock()
  71. os.Exit(code)
  72. }