/
reboot_nix.go
72 lines (62 loc) · 1.49 KB
/
reboot_nix.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
// Copyright 2014 Canonical Ltd.
// Copyright 2014 Cloudbase Solutions SRL
// Licensed under the AGPLv3, see LICENCE file for details.
// +build !windows
package reboot
import (
"fmt"
"os"
"strings"
"github.com/juju/errors"
"github.com/juju/juju/apiserver/params"
)
func writeScript(args []string, after int) (string, error) {
tpl := `#!/bin/bash
sleep %d
%s`
script := fmt.Sprintf(tpl, after, strings.Join(args, " "))
f, err := tmpFile()
if err != nil {
return "", errors.Trace(err)
}
defer f.Close()
_, err = f.WriteString(script)
if err != nil {
return "", errors.Trace(err)
}
name := f.Name()
err = os.Chmod(name, 0755)
if err != nil {
return "", errors.Trace(err)
}
return name, nil
}
// scheduleAction will do a reboot or shutdown after given number of seconds
// this function executes the operating system's reboot binary with apropriate
// parameters to schedule the reboot
// If action is params.ShouldDoNothing, it will return immediately.
func scheduleAction(action params.RebootAction, after int) error {
if action == params.ShouldDoNothing {
return nil
}
args := []string{"shutdown"}
switch action {
case params.ShouldReboot:
args = append(args, "-r")
case params.ShouldShutdown:
args = append(args, "-h")
}
args = append(args, "now")
script, err := writeScript(args, after)
if err != nil {
return err
}
// Use the "at" command to schedule a reboot without blocking
scheduled := []string{
"at",
"-f",
script,
"now",
}
return runCommand(scheduled)
}