gitee.com/quant1x/gox@v1.21.2/daemon/helper.go (about)

     1  // Copyright 2020 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by
     3  // license that can be found in the LICENSE file.
     4  
     5  //go:build go1.8
     6  // +build go1.8
     7  
     8  package daemon
     9  
    10  import (
    11  	"errors"
    12  	"os"
    13  	"os/exec"
    14  	"strconv"
    15  	"strings"
    16  )
    17  
    18  // Service constants
    19  const (
    20  	success = "\t\t\t\t\t[  \033[32mOK\033[0m  ]" // Show colored "OK"
    21  	failed  = "\t\t\t\t\t[\033[31mFAILED\033[0m]" // Show colored "FAILED"
    22  )
    23  
    24  var (
    25  	// ErrUnsupportedSystem appears if try to use service on system which is not supported by this release
    26  	ErrUnsupportedSystem = errors.New("Unsupported system")
    27  
    28  	// ErrRootPrivileges appears if run installation or deleting the service without root privileges
    29  	ErrRootPrivileges = errors.New("You must have root user privileges. Possibly using 'sudo' command should help")
    30  
    31  	// ErrAlreadyInstalled appears if service already installed on the system
    32  	ErrAlreadyInstalled = errors.New("Service has already been installed")
    33  
    34  	// ErrNotInstalled appears if try to delete service which was not been installed
    35  	ErrNotInstalled = errors.New("Service is not installed")
    36  
    37  	// ErrAlreadyRunning appears if try to start already running service
    38  	ErrAlreadyRunning = errors.New("Service is already running")
    39  
    40  	// ErrAlreadyStopped appears if try to stop already stopped service
    41  	ErrAlreadyStopped = errors.New("Service has already been stopped")
    42  )
    43  
    44  // ExecPath tries to get executable path
    45  func ExecPath() (string, error) {
    46  	return os.Executable()
    47  }
    48  
    49  // Lookup path for executable file
    50  func executablePath(name string) (string, error) {
    51  	if path, err := exec.LookPath(name); err == nil {
    52  		if _, err := os.Stat(path); err == nil {
    53  			return path, nil
    54  		}
    55  	}
    56  	return os.Executable()
    57  }
    58  
    59  // Check root rights to use system service
    60  func checkPrivileges() (bool, error) {
    61  
    62  	if output, err := exec.Command("id", "-g").Output(); err == nil {
    63  		if gid, parseErr := strconv.ParseUint(strings.TrimSpace(string(output)), 10, 32); parseErr == nil {
    64  			if gid == 0 {
    65  				return true, nil
    66  			}
    67  			return false, ErrRootPrivileges
    68  		}
    69  	}
    70  	return false, ErrUnsupportedSystem
    71  }