test_commit_restart.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. package upgrader
  2. import (
  3. "io"
  4. "os"
  5. "path/filepath"
  6. "runtime"
  7. "strconv"
  8. "time"
  9. "code.pfad.fr/risefront"
  10. "github.com/minio/selfupdate"
  11. "github.com/pkg/errors"
  12. )
  13. func (u *Upgrader) TestCommitAndRestart() error {
  14. // Get the directory of the current executable
  15. exDir := filepath.Dir(u.ExPath)
  16. testBinaryPath := filepath.Join(exDir, "nginx-ui.test")
  17. // Create temporary old file path
  18. oldExe := filepath.Join(exDir, ".nginx-ui.old."+strconv.FormatInt(time.Now().Unix(), 10))
  19. // Setup update options
  20. opts := selfupdate.Options{
  21. OldSavePath: oldExe,
  22. }
  23. // Check permissions
  24. if err := opts.CheckPermissions(); err != nil {
  25. return err
  26. }
  27. // Copy current executable to test file
  28. srcFile, err := os.Open(u.ExPath)
  29. if err != nil {
  30. return errors.Wrap(err, "failed to open source executable")
  31. }
  32. defer srcFile.Close()
  33. // Create destination file
  34. destFile, err := os.Create(testBinaryPath)
  35. if err != nil {
  36. return errors.Wrap(err, "failed to create test executable")
  37. }
  38. defer destFile.Close()
  39. // Copy file content
  40. _, err = io.Copy(destFile, srcFile)
  41. if err != nil {
  42. return errors.Wrap(err, "failed to copy executable content")
  43. }
  44. // Set executable permissions
  45. if err = destFile.Chmod(0755); err != nil {
  46. return errors.Wrap(err, "failed to set executable permission")
  47. }
  48. // Reopen file for selfupdate
  49. srcFile.Close()
  50. srcFile, err = os.Open(testBinaryPath)
  51. if err != nil {
  52. return errors.Wrap(err, "failed to open test executable for update")
  53. }
  54. defer srcFile.Close()
  55. // Prepare and check binary
  56. if err = selfupdate.PrepareAndCheckBinary(srcFile, opts); err != nil {
  57. var pathErr *os.PathError
  58. if errors.As(err, &pathErr) {
  59. return pathErr.Err
  60. }
  61. return err
  62. }
  63. // Commit binary update
  64. if err = selfupdate.CommitBinary(opts); err != nil {
  65. if rerr := selfupdate.RollbackError(err); rerr != nil {
  66. return rerr
  67. }
  68. var pathErr *os.PathError
  69. if errors.As(err, &pathErr) {
  70. return pathErr.Err
  71. }
  72. return err
  73. }
  74. if runtime.GOOS != "windows" {
  75. _ = os.Remove(oldExe)
  76. _ = os.Remove(testBinaryPath)
  77. }
  78. // Wait for file to be written
  79. time.Sleep(1 * time.Second)
  80. // Gracefully restart
  81. risefront.Restart()
  82. return nil
  83. }