update.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package console
  2. import (
  3. _ "embed"
  4. "fmt"
  5. "mtp20access/global"
  6. "net/http"
  7. "os"
  8. "os/exec"
  9. "path/filepath"
  10. "regexp"
  11. "runtime"
  12. "strings"
  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. global.M2A_LOG.Info("111111111")
  21. if IsUpdateing {
  22. c.String(http.StatusOK, "正在升级中...")
  23. return
  24. }
  25. global.M2A_LOG.Info("22222222")
  26. if runtime.GOOS == "windows" {
  27. c.String(http.StatusOK, "windows不支持, 仅支持linux下执行")
  28. return
  29. }
  30. // logger.GetLogger().Debug("*********************auto update*******************************")
  31. IsUpdateing = true
  32. defer func() {
  33. IsUpdateing = false
  34. }()
  35. global.M2A_LOG.Info("33333333")
  36. filename := c.DefaultQuery("filename", "")
  37. if createsh() {
  38. global.M2A_LOG.Info("7777777777")
  39. c.String(http.StatusOK, "正在执行升级, 升级会保留原有的config.yaml,且重启服务。注意:请勿刷新本页面。")
  40. rx := regexp.MustCompile(`mtp20_access_*\.zip`) // mtp20_access_20221009092417.zip
  41. names := rx.FindStringSubmatch(filename)
  42. // 正则表达式检查文件名是否符合规范
  43. if len(names) > 0 && names[0] == filename {
  44. fmt.Println("filename:", filename)
  45. cmd := exec.Command("sh", "./update.sh", filename)
  46. fmt.Println("cmd param:", cmd.Args)
  47. cmd.Run()
  48. } else {
  49. _ = exec.Command("sh", "./update.sh").Run()
  50. }
  51. } else {
  52. global.M2A_LOG.Info("88888888888888888")
  53. c.String(http.StatusBadRequest, "创建脚本失败, 可能是权限不足")
  54. }
  55. }
  56. // 生成update.sh文件
  57. func createsh() bool {
  58. global.M2A_LOG.Info("4444444444")
  59. dir := ""
  60. if str, err := filepath.Abs(filepath.Dir(os.Args[0])); err == nil {
  61. dir = strings.Replace(str, "\\", "/", -1)
  62. } else {
  63. return false
  64. }
  65. global.M2A_LOG.Info("555555555555")
  66. // 创建文件
  67. if f, err := os.OpenFile(dir+"/update.sh", os.O_RDWR|os.O_TRUNC|os.O_CREATE, 0666); err == nil {
  68. f.Write([]byte(strShell))
  69. f.Close()
  70. } else {
  71. return false
  72. }
  73. global.M2A_LOG.Info("66666666666")
  74. return true
  75. }