update.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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. "github.com/gin-gonic/gin"
  10. "mtp2_if/logger"
  11. "net/http"
  12. "os"
  13. "os/exec"
  14. "path/filepath"
  15. "runtime"
  16. "strings"
  17. )
  18. var IsUpdateing = false
  19. // MakeUpdateScript 生成脚本
  20. func MakeUpdateScript(c *gin.Context) {
  21. if IsUpdateing {
  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. if createsh() {
  35. c.String(http.StatusOK, "正在执行update.sh, 升级会保留原有的config.xml和cfg.json,且重启服务。稍后请在日志页面查看版本信息, 请勿刷新本页面。")
  36. _ = exec.Command("sh", "./update.sh").Run()
  37. } else {
  38. c.String(http.StatusBadRequest, "创建脚本失败, 可能是权限不足")
  39. }
  40. }
  41. // 生成update.sh文件
  42. func createsh() bool {
  43. dir := ""
  44. if str, err := filepath.Abs(filepath.Dir(os.Args[0])); err == nil {
  45. dir = strings.Replace(str, "\\", "/", -1)
  46. } else {
  47. return false
  48. }
  49. sh :=
  50. "# author : zyb\n" +
  51. "# note : 在程序运行目录执行此脚本, 升级go服务到最新构建的版本。升级完成自动重启go服务\n" +
  52. "# --------------------------------------------------------------------\n" +
  53. "\n" +
  54. "mkdir -p upmtpgo\n" +
  55. "cd upmtpgo\n" +
  56. "rm -f console\n" +
  57. "wget -c http://192.168.30.153:8080/view/mtp2.0_release/job/mtp2.0_QueryService_linux/label=192.168.31.56/lastBuild/console\n" +
  58. "filename=`grep -o -w -m1 mtp2.*zip console`\n" +
  59. "wget -c http://192.168.30.153/share/build/mtp2.0_release/$filename\n" +
  60. "rm -rf queryservice\n" +
  61. "unzip $filename -d queryservice\n" +
  62. "cp ../config/config.xml ./queryservice/config/config.xml\n" +
  63. "cp ../config/cfg.json ./queryservice/config/cfg.json\n" +
  64. "cp -rf ./queryservice/* ../\n" +
  65. "cd ..\n" +
  66. "rm -rf upmtpgo\n" +
  67. "pkill QueryService\n" +
  68. "nohup `pwd`/QueryService &"
  69. // 创建文件
  70. if f, err := os.OpenFile(dir+"/update.sh", os.O_RDWR|os.O_CREATE, 0666); err == nil {
  71. _, err = f.Write([]byte(sh))
  72. f.Close()
  73. } else {
  74. return false
  75. }
  76. return true
  77. }