main.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. package main
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "net/http"
  6. _ "net/http/pprof"
  7. "ordonnance/conf"
  8. "ordonnance/logger"
  9. "ordonnance/route"
  10. "os"
  11. "os/exec"
  12. "time"
  13. "github.com/urfave/cli"
  14. )
  15. var pidPath string
  16. var pidName string
  17. func main() {
  18. app := cli.NewApp()
  19. pidName = "./ordonnance"
  20. pidPath = pidName + ".pid"
  21. app.Name = "ordonnance"
  22. app.Author = "ordonnance authors"
  23. app.Version = "0.0.1"
  24. app.Copyright = "ordonnance authors reserved"
  25. app.Usage = "ordonnance start|stop|restart|{-d}"
  26. app.Commands = []cli.Command{
  27. cli.Command{
  28. Name: "start",
  29. Flags: []cli.Flag{
  30. &cli.BoolFlag{Name: "d", Usage: "run background"},
  31. },
  32. Aliases: []string{"start"},
  33. Action: start,
  34. },
  35. cli.Command{
  36. Name: "stop",
  37. Aliases: []string{"stop"},
  38. Action: stop,
  39. },
  40. cli.Command{
  41. Name: "restart",
  42. Aliases: []string{"restart"},
  43. Action: restart,
  44. },
  45. }
  46. app.Run(os.Args)
  47. }
  48. func start(ctx *cli.Context) error {
  49. d := ctx.Bool("d")
  50. logger.Info("start_d ", d)
  51. if d {
  52. start := exec.Command(pidName, "start")
  53. start.Start()
  54. os.Exit(0)
  55. }
  56. doStart()
  57. return nil
  58. }
  59. // Start 启动
  60. func doStart() {
  61. pid := fmt.Sprintf("%d", os.Getpid())
  62. if err := ioutil.WriteFile(pidPath, []byte(pid), 0666); err != nil {
  63. logger.Warn("start pid error ", pid)
  64. panic(err)
  65. }
  66. go func() {
  67. http.ListenAndServe(":6060", nil)
  68. }()
  69. addr := conf.GetPort()
  70. route.RunService(addr)
  71. }
  72. // Stop 停止
  73. func stop(ctx *cli.Context) error {
  74. pid, _ := ioutil.ReadFile(pidPath)
  75. logger.Info("doStop ", ctx.String("stop"), string(pid))
  76. cmd := exec.Command("kill", "-9", string(pid))
  77. cmd.Start()
  78. if err := ioutil.WriteFile(pidPath, nil, 0666); err != nil {
  79. logger.Warnf("write pid error %v %v", string(pid), err.Error())
  80. }
  81. return nil
  82. }
  83. // Restart 重启
  84. func restart(ctx *cli.Context) error {
  85. logger.Info("doRestart ", ctx.String("restart"))
  86. pid, _ := ioutil.ReadFile(pidPath)
  87. logger.Info("restarting..." + string(pid))
  88. stop := exec.Command("kill", "-9", string(pid))
  89. stop.Start()
  90. time.Sleep(5 * time.Second)
  91. start := exec.Command(pidName, "start")
  92. start.Start()
  93. return nil
  94. }