github.com/makyo/juju@v0.0.0-20160425123129-2608902037e9/cmd/jujud/reboot/reboot_nix.go (about)

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