本站源代码
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

86 rindas
2.2KB

  1. // +build !windows
  2. // Copyright 2019 The Gitea Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. // This code is heavily inspired by the archived gofacebook/gracenet/net.go handler
  6. package graceful
  7. import (
  8. "fmt"
  9. "os"
  10. "os/exec"
  11. "strings"
  12. "sync"
  13. "syscall"
  14. )
  15. var killParent sync.Once
  16. // KillParent sends the kill signal to the parent process if we are a child
  17. func KillParent() {
  18. killParent.Do(func() {
  19. if IsChild {
  20. ppid := syscall.Getppid()
  21. if ppid > 1 {
  22. _ = syscall.Kill(ppid, syscall.SIGTERM)
  23. }
  24. }
  25. })
  26. }
  27. // RestartProcess starts a new process passing it the active listeners. It
  28. // doesn't fork, but starts a new process using the same environment and
  29. // arguments as when it was originally started. This allows for a newly
  30. // deployed binary to be started. It returns the pid of the newly started
  31. // process when successful.
  32. func RestartProcess() (int, error) {
  33. listeners := getActiveListeners()
  34. // Extract the fds from the listeners.
  35. files := make([]*os.File, len(listeners))
  36. for i, l := range listeners {
  37. var err error
  38. // Now, all our listeners actually have File() functions so instead of
  39. // individually casting we just use a hacky interface
  40. files[i], err = l.(filer).File()
  41. if err != nil {
  42. return 0, err
  43. }
  44. // Remember to close these at the end.
  45. defer files[i].Close()
  46. }
  47. // Use the original binary location. This works with symlinks such that if
  48. // the file it points to has been changed we will use the updated symlink.
  49. argv0, err := exec.LookPath(os.Args[0])
  50. if err != nil {
  51. return 0, err
  52. }
  53. // Pass on the environment and replace the old count key with the new one.
  54. var env []string
  55. for _, v := range os.Environ() {
  56. if !strings.HasPrefix(v, listenFDs+"=") {
  57. env = append(env, v)
  58. }
  59. }
  60. env = append(env, fmt.Sprintf("%s=%d", listenFDs, len(listeners)))
  61. allFiles := append([]*os.File{os.Stdin, os.Stdout, os.Stderr}, files...)
  62. process, err := os.StartProcess(argv0, os.Args, &os.ProcAttr{
  63. Dir: originalWD,
  64. Env: env,
  65. Files: allFiles,
  66. })
  67. if err != nil {
  68. return 0, err
  69. }
  70. return process.Pid, nil
  71. }
  72. type filer interface {
  73. File() (*os.File, error)
  74. }
上海开阖软件有限公司 沪ICP备12045867号-1