miaopanel
1package system
2
3import (
4 "context"
5 "errors"
6 "fmt"
7 "os"
8 "runtime"
9 "strconv"
10 "time"
11)
12
13// Reboot schedules a host reboot a few seconds after the API response has
14// been flushed. systemd-run creates an independent transient timer, so the
15// reboot survives the panel process being stopped during shutdown.
16func Reboot(ctx context.Context) (string, error) {
17 if runtime.GOOS != "linux" {
18 return "", ErrUnsupported
19 }
20 if os.Geteuid() != 0 {
21 return "", errors.New("只有 root 可以重启服务器")
22 }
23 runner := NewRunner()
24 runner.Timeout = 10 * time.Second
25 if Lookup("systemd-run") {
26 unit := "mp-reboot-" + strconv.FormatInt(time.Now().Unix(), 10)
27 if _, err := runner.Run(ctx, "systemd-run", "--collect", "--on-active=2s",
28 "--unit="+unit, "systemctl", "reboot"); err == nil {
29 return "systemd-run", nil
30 }
31 }
32 if Lookup("systemctl") {
33 if _, err := runner.Run(ctx, "systemctl", "reboot", "--no-block"); err == nil {
34 return "systemctl", nil
35 }
36 }
37 if Lookup("shutdown") {
38 if _, err := runner.Run(ctx, "shutdown", "-r", "+1"); err == nil {
39 return "shutdown", nil
40 }
41 }
42 return "", fmt.Errorf("没有可用的重启命令(systemd-run/systemctl/shutdown)")
43}