update.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. package console
  2. import (
  3. _ "embed"
  4. "fmt"
  5. "net/http"
  6. "os"
  7. "os/exec"
  8. "path/filepath"
  9. "regexp"
  10. "runtime"
  11. "strings"
  12. "time"
  13. "github.com/gin-gonic/gin"
  14. )
  15. //go:embed upmtpgo.sh
  16. var strShell string
  17. var IsUpdateing = false
  18. // MakeUpdateScript 生成脚本
  19. func MakeUpdateScript(c *gin.Context) {
  20. if IsUpdateing {
  21. println("正在升级中...")
  22. c.String(http.StatusOK, "正在升级中...")
  23. return
  24. }
  25. if runtime.GOOS == "windows" {
  26. c.String(http.StatusOK, "windows不支持, 仅支持linux下执行")
  27. return
  28. }
  29. // logger.GetLogger().Debug("*********************auto update*******************************")
  30. IsUpdateing = true
  31. defer func() {
  32. IsUpdateing = false
  33. }()
  34. filename := c.DefaultQuery("filename", "")
  35. if createsh() {
  36. c.String(http.StatusOK, "正在执行升级, 升级会保留原有的config.yaml,且重启服务。注意:请勿刷新本页面。")
  37. go runch(filename)
  38. } else {
  39. c.String(http.StatusBadRequest, "创建脚本失败, 可能是权限不足")
  40. return
  41. }
  42. }
  43. func runch(filename string) {
  44. time.Sleep(3 * time.Second)
  45. rx := regexp.MustCompile(`mtp20_access_*\.zip`) // mtp20_access_20221009092417.zip
  46. names := rx.FindStringSubmatch(filename)
  47. // 正则表达式检查文件名是否符合规范
  48. if len(names) > 0 && names[0] == filename {
  49. fmt.Println("filename:", filename)
  50. cmd := exec.Command("sh", "./update.sh", filename)
  51. fmt.Println("cmd param:", cmd.Args)
  52. cmd.Run()
  53. out, err := cmd.CombinedOutput()
  54. if err != nil {
  55. fmt.Printf("update out:\n%s\n", string(out))
  56. }
  57. fmt.Printf("update out:\n%s\n", string(out))
  58. } else {
  59. cmd := exec.Command("sh", "./update.sh")
  60. cmd.Run()
  61. out, err := cmd.CombinedOutput()
  62. if err != nil {
  63. fmt.Printf("update out:\n%s\n", string(out))
  64. }
  65. }
  66. }
  67. // 生成update.sh文件
  68. func createsh() bool {
  69. dir := ""
  70. if str, err := filepath.Abs(filepath.Dir(os.Args[0])); err == nil {
  71. dir = strings.Replace(str, "\\", "/", -1)
  72. } else {
  73. return false
  74. }
  75. // 创建文件
  76. if f, err := os.OpenFile(dir+"/update.sh", os.O_RDWR|os.O_TRUNC|os.O_CREATE, 0666); err == nil {
  77. f.Write([]byte(strShell))
  78. f.Close()
  79. } else {
  80. return false
  81. }
  82. return true
  83. }