github.com/wallyworld/juju@v0.0.0-20161013125918-6cf1bc9d917a/cmd/jujud/reboot/reboot_nix.go (about)

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