Files
crawlab/core/utils/process.go
Marvin Zhang 3276083994 refactor: replace apex/log with structured logger across multiple services
- Replaced all instances of apex/log with a structured logger interface in various services, including Api, Server, Config, and others, to enhance logging consistency and context.
- Updated logging calls to utilize the new logger methods, improving error tracking and service monitoring.
- Added logger initialization in services and controllers to ensure proper logging setup.
- Improved error handling and logging messages for better clarity during service operations.
- Removed unused apex/log imports and cleaned up related code for better maintainability.
2024-12-24 19:11:19 +08:00

102 lines
2.1 KiB
Go

package utils
import (
"errors"
"github.com/shirou/gopsutil/process"
"os/exec"
"runtime"
"strings"
)
func BuildCmd(cmdStr string) (cmd *exec.Cmd, err error) {
if cmdStr == "" {
return nil, errors.New("command string is empty")
}
args := strings.Split(cmdStr, " ")
return exec.Command(args[0], args[1:]...), nil
}
func ProcessIdExists(pid int) (exists bool) {
if runtime.GOOS == "windows" {
return processIdExistsWindows(pid)
} else {
return processIdExistsLinuxMac(pid)
}
}
func processIdExistsWindows(pid int) (exists bool) {
exists, err := process.PidExists(int32(pid))
if err != nil {
logger.Errorf("error checking if process exists: %v", err)
}
return exists
}
func processIdExistsLinuxMac(pid int) (exists bool) {
exists, err := process.PidExists(int32(pid))
if err != nil {
logger.Errorf("error checking if process exists: %v", err)
}
return exists
}
func GetProcesses() (processes []*process.Process, err error) {
processes, err = process.Processes()
if err != nil {
logger.Errorf("error getting processes: %v", err)
return nil, err
}
return processes, nil
}
type KillProcessOptions struct {
Force bool
}
func KillProcess(cmd *exec.Cmd, force bool) error {
// process
p, err := process.NewProcess(int32(cmd.Process.Pid))
if err != nil {
logger.Errorf("failed to get process: %v", err)
return err
}
// kill process
return killProcessRecursive(p, force)
}
func killProcessRecursive(p *process.Process, force bool) (err error) {
// children processes
cps, err := p.Children()
if err != nil {
if !errors.Is(err, process.ErrorNoChildren) {
logger.Errorf("failed to get children processes: %v", err)
} else if errors.Is(err, process.ErrorProcessNotRunning) {
return nil
}
return killProcess(p, force)
}
// iterate children processes
for _, cp := range cps {
if err := killProcessRecursive(cp, force); err != nil {
return err
}
}
return killProcess(p, force)
}
func killProcess(p *process.Process, force bool) (err error) {
if force {
err = p.Kill()
} else {
err = p.Terminate()
}
if err != nil {
logger.Errorf("failed to kill process (force: %v): %v", force, err)
return err
}
return nil
}