github.com/Axway/agent-sdk@v1.1.101/pkg/cmd/service/daemon/helper.go (about)

     1  package daemon
     2  
     3  import (
     4  	"bytes"
     5  	"os"
     6  	"os/exec"
     7  	"strconv"
     8  	"strings"
     9  )
    10  
    11  // Service constants
    12  const (
    13  	success = "\t\t\t\t\t[  \033[32mOK\033[0m  ]" // Show colored "OK"
    14  	failed  = "\t\t\t\t\t[\033[31mFAILED\033[0m]" // Show colored "FAILED"
    15  )
    16  
    17  // override for testing
    18  var execCmd = execCommand
    19  
    20  // execCommand - runs the command and returns the output
    21  func execCommand(name string, arg ...string) ([]byte, error) {
    22  	// #nosec
    23  	cmd := exec.Command(name, arg...)
    24  
    25  	// Set up byte buffers to read stdout
    26  	var outbytes bytes.Buffer
    27  	cmd.Stdout = &outbytes
    28  	err := cmd.Run()
    29  	if err != nil {
    30  		return nil, err
    31  	}
    32  
    33  	return outbytes.Bytes(), nil
    34  }
    35  
    36  // ExecPath tries to get executable path
    37  func ExecPath() (string, error) {
    38  	return os.Executable()
    39  }
    40  
    41  // Lookup path for executable file
    42  func executablePath(name string) (string, error) {
    43  	if path, err := exec.LookPath(name); err == nil {
    44  		if _, err := fs.Stat(path); err == nil {
    45  			return path, nil
    46  		}
    47  	}
    48  	return os.Executable()
    49  }
    50  
    51  // Check root rights to use system service
    52  func checkPrivileges() (bool, error) {
    53  
    54  	if output, err := execCmd("id", "-g"); err == nil {
    55  		if gid, parseErr := strconv.ParseUint(strings.TrimSpace(string(output)), 10, 32); parseErr == nil {
    56  			if gid == 0 {
    57  				return true, nil
    58  			}
    59  			return false, ErrRootPrivileges
    60  		}
    61  	}
    62  	return false, ErrUnsupportedSystem
    63  }