github.com/sohaha/zlsgo@v1.7.13-0.20240501141223-10dd1a906f76/zutil/daemon/utils.go (about)

     1  package daemon
     2  
     3  import (
     4  	"bytes"
     5  	"context"
     6  	"errors"
     7  	"os"
     8  	"path/filepath"
     9  	"strings"
    10  
    11  	"github.com/sohaha/zlsgo/zshell"
    12  	"github.com/sohaha/zlsgo/ztype"
    13  )
    14  
    15  func (c *Config) execPath() (path string) {
    16  	if len(c.Executable) != 0 {
    17  		path, _ = filepath.Abs(c.Executable)
    18  		return path
    19  	}
    20  	path, _ = os.Executable()
    21  	return
    22  }
    23  
    24  func runGrep(grep, command string, args ...string) (res string, err error) {
    25  	var grepout bytes.Buffer
    26  	var out bytes.Buffer
    27  	var outErr bytes.Buffer
    28  	commands := []string{command}
    29  	commands = append(commands, args...)
    30  	err = runcmd(commands, bytes.NewReader([]byte("")), &out, &outErr)
    31  	if err != nil {
    32  		return
    33  	}
    34  	commands = []string{"grep", grep}
    35  	err = runcmd(commands, bytes.NewReader(out.Bytes()), &grepout, &outErr)
    36  	if err != nil {
    37  		return
    38  	}
    39  	res = grepout.String()
    40  	return
    41  }
    42  
    43  func isSudo() error {
    44  	_, id, _, err := zshell.Run("id -u")
    45  	if err != nil {
    46  		return err
    47  	}
    48  	id = strings.Replace(id, "\n", "", -1)
    49  	if id != "0" {
    50  		return ErrNotAnRootUser
    51  	}
    52  	return nil
    53  }
    54  
    55  func IsPermissionError(err error) bool {
    56  	return err == ErrNotAnAdministrator || err == ErrNotAnRootUser
    57  }
    58  
    59  func run(command string, args ...string) error {
    60  	var out bytes.Buffer
    61  	var outErr bytes.Buffer
    62  	commands := []string{command}
    63  	commands = append(commands, args...)
    64  	return runcmd(commands, bytes.NewReader([]byte("")), &out, &outErr)
    65  }
    66  
    67  func runcmd(commands []string, in *bytes.Reader, out, outErr *bytes.Buffer) error {
    68  	code, _, _, err := zshell.ExecCommand(context.Background(), commands, in, out, outErr)
    69  	if err != nil {
    70  		return err
    71  	}
    72  	if code != 0 {
    73  		errMsg := outErr.String()
    74  		if errMsg == "" {
    75  			errMsg = out.String()
    76  		}
    77  		err = errors.New(errMsg)
    78  	}
    79  	return err
    80  }
    81  
    82  func isServiceRestart(c *Config) bool {
    83  	load := optionRunAtLoadDefault
    84  	if l, ok := c.Options[optionRunAtLoad]; ok {
    85  		load = ztype.ToBool(l)
    86  	}
    87  	return load
    88  }