test_commit_restart.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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. }
  77. // Wait for file to be written
  78. time.Sleep(1 * time.Second)
  79. // Gracefully restart
  80. risefront.Restart()
  81. return nil
  82. }