1
0

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 := ""
  19. if runtime.GOOS == "windows" {
  20. oldExe = filepath.Join(exDir, ".nginx-ui.old."+strconv.FormatInt(time.Now().Unix(), 10))
  21. }
  22. // Setup update options
  23. opts := selfupdate.Options{
  24. OldSavePath: oldExe,
  25. }
  26. // Check permissions
  27. if err := opts.CheckPermissions(); err != nil {
  28. return err
  29. }
  30. // Copy current executable to test file
  31. srcFile, err := os.Open(u.ExPath)
  32. if err != nil {
  33. return errors.Wrap(err, "failed to open source executable")
  34. }
  35. defer srcFile.Close()
  36. // Create destination file
  37. destFile, err := os.Create(testBinaryPath)
  38. if err != nil {
  39. return errors.Wrap(err, "failed to create test executable")
  40. }
  41. defer destFile.Close()
  42. // Copy file content
  43. _, err = io.Copy(destFile, srcFile)
  44. if err != nil {
  45. return errors.Wrap(err, "failed to copy executable content")
  46. }
  47. // Set executable permissions
  48. if err = destFile.Chmod(0755); err != nil {
  49. return errors.Wrap(err, "failed to set executable permission")
  50. }
  51. // Reopen file for selfupdate
  52. srcFile.Close()
  53. srcFile, err = os.Open(testBinaryPath)
  54. if err != nil {
  55. return errors.Wrap(err, "failed to open test executable for update")
  56. }
  57. defer srcFile.Close()
  58. // Prepare and check binary
  59. if err = selfupdate.PrepareAndCheckBinary(srcFile, opts); err != nil {
  60. var pathErr *os.PathError
  61. if errors.As(err, &pathErr) {
  62. return pathErr.Err
  63. }
  64. return err
  65. }
  66. // Commit binary update
  67. if err = selfupdate.CommitBinary(opts); err != nil {
  68. if rerr := selfupdate.RollbackError(err); rerr != nil {
  69. return rerr
  70. }
  71. var pathErr *os.PathError
  72. if errors.As(err, &pathErr) {
  73. return pathErr.Err
  74. }
  75. return err
  76. }
  77. _ = os.Remove(testBinaryPath)
  78. // Wait for file to be written
  79. time.Sleep(1 * time.Second)
  80. // Gracefully restart
  81. risefront.Restart()
  82. return nil
  83. }