sys.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. package core
  2. import (
  3. "errors"
  4. "fmt"
  5. "os"
  6. "os/exec"
  7. "regexp"
  8. "runtime"
  9. "strings"
  10. "time"
  11. "github.com/astaxie/beego/logs"
  12. )
  13. var BeforeStop = []func(){}
  14. var pidf = "/var/run/" + pname + ".pid"
  15. func Daemon() {
  16. for _, bs := range BeforeStop {
  17. bs()
  18. }
  19. args := os.Args[1:]
  20. execArgs := make([]string, 0)
  21. l := len(args)
  22. for i := 0; i < l; i++ {
  23. if strings.Index(args[i], "-d") == 0 {
  24. continue
  25. }
  26. execArgs = append(execArgs, args[i])
  27. }
  28. proc := exec.Command(os.Args[0], execArgs...)
  29. err := proc.Start()
  30. if err != nil {
  31. panic(err)
  32. }
  33. logs.Info(sillyGirl.Get("name", "傻妞") + "以静默形式运行")
  34. os.WriteFile(pidf, []byte(fmt.Sprintf("%d", proc.Process.Pid)), 0o644)
  35. os.Exit(0)
  36. }
  37. func GitPull(filename string) (bool, error) {
  38. if runtime.GOOS == "darwin" {
  39. return false, errors.New("骂你一句沙雕。")
  40. }
  41. rtn, err := exec.Command("sh", "-c", "cd "+ExecPath+filename+" && git stash && git pull").Output()
  42. if err != nil {
  43. return false, errors.New("拉取代失败:" + err.Error() + "。")
  44. }
  45. t := string(rtn)
  46. if !strings.Contains(t, "changed") {
  47. if strings.Contains(t, "Already") || strings.Contains(t, "已经是最新") {
  48. return false, nil
  49. } else {
  50. return false, errors.New("拉取代失败:" + t + "。")
  51. }
  52. }
  53. return true, nil
  54. }
  55. func CompileCode() error {
  56. cmd := exec.Command("sh", "-c", "cd "+ExecPath+" && go build -o "+pname)
  57. _, err := cmd.Output()
  58. if err != nil {
  59. return errors.New("编译失败:" + err.Error() + "。")
  60. }
  61. sillyGirl.Set("compiled_at", time.Now().Format("2006-01-02 15:04:05"))
  62. return nil
  63. }
  64. func killp() {
  65. // data, _ := os.ReadFile(pidf)
  66. // pid := Int(string(data))
  67. // if pid > 0 {
  68. // syscall.Kill(-pid, syscall.SIGKILL)
  69. // }
  70. pids, err := ppid()
  71. if err == nil {
  72. if len(pids) == 0 {
  73. return
  74. } else {
  75. exec.Command("sh", "-c", "kill -9 "+strings.Join(pids, " ")).Output()
  76. }
  77. } else {
  78. return
  79. }
  80. }
  81. func ppid() ([]string, error) {
  82. pid := fmt.Sprint(os.Getpid())
  83. pids := []string{}
  84. rtn, err := exec.Command("sh", "-c", "pidof "+pname).Output()
  85. if err != nil {
  86. return pids, err
  87. }
  88. re := regexp.MustCompile(`[\d]+`)
  89. for _, v := range re.FindAll(rtn, -1) {
  90. if string(v) != pid {
  91. pids = append(pids, string(v))
  92. }
  93. }
  94. return pids, nil
  95. }