github.com/cloud-green/juju@v0.0.0-20151002100041-a00291338d3d/cmd/plugins/local/main.go (about)

     1  // Copyright 2014 Canonical Ltd.
     2  // Licensed under the AGPLv3, see LICENCE file for details.
     3  
     4  package local
     5  
     6  import (
     7  	"os"
     8  	"os/exec"
     9  
    10  	"github.com/juju/cmd"
    11  	"github.com/juju/loggo"
    12  
    13  	jujucmd "github.com/juju/juju/cmd"
    14  )
    15  
    16  var logger = loggo.GetLogger("juju.plugins.local")
    17  
    18  const localDoc = `
    19  
    20  Juju local is used to provide extra commands that assist with the local
    21  provider. 
    22  
    23  See Also:
    24      juju help local-provider
    25  `
    26  
    27  func jujuLocalPlugin() cmd.Command {
    28  	plugin := jujucmd.NewSuperCommand(cmd.SuperCommandParams{
    29  		Name:        "juju local",
    30  		UsagePrefix: "juju",
    31  		Doc:         localDoc,
    32  		Purpose:     "local provider specific commands",
    33  	})
    34  
    35  	return plugin
    36  }
    37  
    38  // Main registers subcommands for the juju-local executable.
    39  func Main(args []string) {
    40  	ctx, err := cmd.DefaultContext()
    41  	if err != nil {
    42  		logger.Debugf("error: %v\n", err)
    43  		os.Exit(2)
    44  	}
    45  	plugin := jujuLocalPlugin()
    46  	os.Exit(cmd.Main(plugin, ctx, args[1:]))
    47  }
    48  
    49  var checkIfRoot = func() bool {
    50  	return os.Getuid() == 0
    51  }
    52  
    53  // runAsRoot ensures that the executable is running as root.
    54  // If checkIfRoot returns true, the call function is called,
    55  // otherwise executable is executed using sudo and the extra args
    56  // passed through.
    57  func runAsRoot(executable string, args []string, context *cmd.Context, call func(*cmd.Context) error) error {
    58  	if checkIfRoot() {
    59  		logger.Debugf("running as root")
    60  		return call(context)
    61  	}
    62  
    63  	logger.Debugf("running as user")
    64  
    65  	fullpath, err := exec.LookPath(executable)
    66  	if err != nil {
    67  		return err
    68  	}
    69  
    70  	sudoArgs := []string{"--preserve-env", fullpath}
    71  	sudoArgs = append(sudoArgs, args...)
    72  
    73  	command := exec.Command("sudo", sudoArgs...)
    74  	// Now hook up stdin, stdout, stderr
    75  	command.Stdin = context.Stdin
    76  	command.Stdout = context.Stdout
    77  	command.Stderr = context.Stderr
    78  	// And run it!
    79  	return command.Run()
    80  }