update.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /**
  2. * @Author: zou.yingbin
  3. * @Create : 2021/10/20 15:20
  4. * @Modify : 2021/10/20 15:20
  5. * @Note : 生成用于内网升级的.sh脚本
  6. */
  7. package other
  8. import (
  9. _ "embed"
  10. "fmt"
  11. "github.com/gin-gonic/gin"
  12. "mtp2_if/logger"
  13. "net/http"
  14. "os"
  15. "os/exec"
  16. "path/filepath"
  17. "regexp"
  18. "runtime"
  19. "strings"
  20. )
  21. //go:embed upmtpgo.sh
  22. var strShell string
  23. var IsUpdateing = false
  24. // MakeUpdateScript 生成脚本
  25. func MakeUpdateScript(c *gin.Context) {
  26. if IsUpdateing {
  27. c.String(http.StatusOK, "正在升级中...")
  28. return
  29. }
  30. if runtime.GOOS == "windows" {
  31. c.String(http.StatusOK, "windows不支持, 仅支持linux下执行")
  32. return
  33. }
  34. logger.GetLogger().Debug("*********************auto update*******************************")
  35. IsUpdateing = true
  36. defer func() {
  37. IsUpdateing = false
  38. }()
  39. filename := c.DefaultQuery("filename", "")
  40. if createsh() {
  41. c.String(http.StatusOK, "正在执行升级, 升级会保留原有的config.xml和cfg.json,且重启服务。稍后请在日志页面查看版本信息, 请勿刷新本页面。")
  42. rx := regexp.MustCompile(`mtp2_queryservice_r[\d_]*\.zip`)
  43. names := rx.FindStringSubmatch(filename)
  44. // 正则表达式检查文件名是否符合规范
  45. if len(names) > 0 && names[0] == filename {
  46. fmt.Println("filename:", filename)
  47. cmd := exec.Command("sh", "./update.sh", filename)
  48. fmt.Println("cmd param:", cmd.Args)
  49. cmd.Run()
  50. } else {
  51. _ = exec.Command("sh", "./update.sh").Run()
  52. }
  53. } else {
  54. c.String(http.StatusBadRequest, "创建脚本失败, 可能是权限不足")
  55. }
  56. }
  57. // 生成update.sh文件
  58. func createsh() bool {
  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. // 先删除原脚本
  66. os.Remove(dir + "/update.sh")
  67. // 创建文件
  68. if f, err := os.OpenFile(dir+"/update.sh", os.O_RDWR|os.O_CREATE, 0666); err == nil {
  69. _, err = f.Write([]byte(strShell))
  70. f.Close()
  71. } else {
  72. return false
  73. }
  74. return true
  75. }