From ea3c009305bd4256d88892f952c59318aee81da5 Mon Sep 17 00:00:00 2001 From: Jesse Duffield Date: Sat, 18 Jun 2022 13:21:29 +1000 Subject: [PATCH] extract process kill logic --- go.mod | 1 + go.sum | 2 + pkg/commands/os.go | 11 ++ pkg/commands/os_default_platform.go | 23 --- pkg/commands/os_windows.go | 129 ----------------- vendor/github.com/jesseduffield/kill/LICENSE | 21 +++ .../github.com/jesseduffield/kill/README.md | 3 + .../kill/kill_default_platform.go | 33 +++++ .../jesseduffield/kill/kill_windows.go | 136 ++++++++++++++++++ vendor/modules.txt | 3 + 10 files changed, 210 insertions(+), 152 deletions(-) create mode 100644 vendor/github.com/jesseduffield/kill/LICENSE create mode 100644 vendor/github.com/jesseduffield/kill/README.md create mode 100644 vendor/github.com/jesseduffield/kill/kill_default_platform.go create mode 100644 vendor/github.com/jesseduffield/kill/kill_windows.go diff --git a/go.mod b/go.mod index b0abab8b..c7925e43 100644 --- a/go.mod +++ b/go.mod @@ -15,6 +15,7 @@ require ( github.com/integrii/flaggy v1.4.0 github.com/jesseduffield/asciigraph v0.0.0-20190605104717-6d88e39309ee github.com/jesseduffield/gocui v0.3.1-0.20220417002912-bce22fd599f6 + github.com/jesseduffield/kill v0.0.0-20220618033138-bfbe04675d10 github.com/jesseduffield/yaml v0.0.0-20190702115811-b900b7e08b56 github.com/mcuadros/go-lookup v0.0.0-20171110082742-5650f26be767 github.com/mgutz/str v1.2.0 diff --git a/go.sum b/go.sum index 9830fcb4..b72e4b19 100644 --- a/go.sum +++ b/go.sum @@ -52,6 +52,8 @@ github.com/jesseduffield/asciigraph v0.0.0-20190605104717-6d88e39309ee h1:7Zi/OQ github.com/jesseduffield/asciigraph v0.0.0-20190605104717-6d88e39309ee/go.mod h1:Z9UKHveKXXgyo8ME7R8yxh/BUTFOK+FgfWKlhy8oOAg= github.com/jesseduffield/gocui v0.3.1-0.20220417002912-bce22fd599f6 h1:Fmay0Lz21taUpXiIbFkjjIIcn0E5GKwp5UFRuXaOiGQ= github.com/jesseduffield/gocui v0.3.1-0.20220417002912-bce22fd599f6/go.mod h1:znJuCDnF2Ph40YZSlBwdX/4GEofnIoWLGdT4mK5zRAU= +github.com/jesseduffield/kill v0.0.0-20220618033138-bfbe04675d10 h1:jmpr7KpX2+2GRiE91zTgfq49QvgiqB0nbmlwZ8UnOx0= +github.com/jesseduffield/kill v0.0.0-20220618033138-bfbe04675d10/go.mod h1:aA97kHeNA+sj2Hbki0pvLslmE4CbDyhBeSSTUUnOuVo= github.com/jesseduffield/yaml v0.0.0-20190702115811-b900b7e08b56 h1:33wSxJWU/f2TAozHYtJ8zqBxEnEVYM+22moLoiAkxvg= github.com/jesseduffield/yaml v0.0.0-20190702115811-b900b7e08b56/go.mod h1:FZJBwOhE+RXz8EVZfY+xnbCw2cVOwxlK3/aIi581z/s= github.com/kisielk/errcheck v1.2.0/go.mod h1:/BMXB+zMLi60iA8Vv6Ksmxu/1UDYcXs4uQLJ+jE2L00= diff --git a/pkg/commands/os.go b/pkg/commands/os.go index e313e276..e449a6ee 100644 --- a/pkg/commands/os.go +++ b/pkg/commands/os.go @@ -12,6 +12,7 @@ import ( "github.com/go-errors/errors" + "github.com/jesseduffield/kill" "github.com/jesseduffield/lazydocker/pkg/config" "github.com/jesseduffield/lazydocker/pkg/utils" "github.com/mgutz/str" @@ -328,3 +329,13 @@ func (c *OSCommand) PipeCommands(commandStrings ...string) error { } return nil } + +// Kill kills a process. If the process has Setpgid == true, then we have anticipated that it might spawn its own child processes, so we've given it a process group ID (PGID) equal to its process id (PID) and given its child processes will inherit the PGID, we can kill that group, rather than killing the process itself. +func (c *OSCommand) Kill(cmd *exec.Cmd) error { + return kill.Kill(cmd) +} + +// PrepareForChildren sets Setpgid to true on the cmd, so that when we run it as a subprocess, we can kill its group rather than the process itself. This is because some commands, like `docker-compose logs` spawn multiple children processes, and killing the parent process isn't sufficient for killing those child processes. We set the group id here, and then in subprocess.go we check if the group id is set and if so, we kill the whole group rather than just the one process. +func (c *OSCommand) PrepareForChildren(cmd *exec.Cmd) { + kill.PrepareForChildren(cmd) +} diff --git a/pkg/commands/os_default_platform.go b/pkg/commands/os_default_platform.go index 7d289796..bbc3935a 100644 --- a/pkg/commands/os_default_platform.go +++ b/pkg/commands/os_default_platform.go @@ -4,9 +4,7 @@ package commands import ( - "os/exec" "runtime" - "syscall" ) func getPlatform() *Platform { @@ -20,24 +18,3 @@ func getPlatform() *Platform { fallbackEscapedQuote: "\"", } } - -// Kill kills a process. If the process has Setpgid == true, then we have anticipated that it might spawn its own child processes, so we've given it a process group ID (PGID) equal to its process id (PID) and given its child processes will inherit the PGID, we can kill that group, rather than killing the process itself. -func (c *OSCommand) Kill(cmd *exec.Cmd) error { - if cmd.Process == nil { - // somebody got to it before we were able to, poor bastard - return nil - } - if cmd.SysProcAttr != nil && cmd.SysProcAttr.Setpgid { - // minus sign means we're talking about a PGID as opposed to a PID - return syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL) - } - - return cmd.Process.Kill() -} - -// PrepareForChildren sets Setpgid to true on the cmd, so that when we run it as a sideproject, we can kill its group rather than the process itself. This is because some commands, like `docker-compose logs` spawn multiple children processes, and killing the parent process isn't sufficient for killing those child processes. We set the group id here, and then in subprocess.go we check if the group id is set and if so, we kill the whole group rather than just the one process. -func (c *OSCommand) PrepareForChildren(cmd *exec.Cmd) { - cmd.SysProcAttr = &syscall.SysProcAttr{ - Setpgid: true, - } -} diff --git a/pkg/commands/os_windows.go b/pkg/commands/os_windows.go index 374f8b7d..8fa9ce1c 100644 --- a/pkg/commands/os_windows.go +++ b/pkg/commands/os_windows.go @@ -1,12 +1,5 @@ package commands -import ( - "os" - "os/exec" - "syscall" - "unsafe" -) - func getPlatform() *Platform { return &Platform{ os: "windows", @@ -16,125 +9,3 @@ func getPlatform() *Platform { fallbackEscapedQuote: "\\'", } } - -// Kill kills a process. If the process has Setpgid == true, then we have anticipated that it might spawn its own child processes, so we've given it a process group ID (PGID) equal to its process id (PID) and given its child processes will inherit the PGID, we can kill that group, rather than killing the process itself. -func (c *OSCommand) Kill(cmd *exec.Cmd) error { - if cmd.Process == nil { - // somebody got to it before we were able to, poor bastard - return nil - } - - pids := Getppids(uint32(cmd.Process.Pid)) - for _, pid := range pids { - pro, err := os.FindProcess(int(pid)) - if err != nil { - continue - } - - pro.Kill() - } - - return nil -} - -// PrepareForChildren sets Setpgid to true on the cmd, so that when we run it as a sideproject, we can kill its group rather than the process itself. This is because some commands, like `docker-compose logs` spawn multiple children processes, and killing the parent process isn't sufficient for killing those child processes. We set the group id here, and then in subprocess.go we check if the group id is set and if so, we kill the whole group rather than just the one process. -func (c *OSCommand) PrepareForChildren(cmd *exec.Cmd) {} - -const ( - MAX_PATH = 260 - TH32CS_SNAPPROCESS = 0x00000002 -) - -type ProcessInfo struct { - Name string - Pid uint32 - PPid uint32 -} - -type PROCESSENTRY32 struct { - DwSize uint32 - CntUsage uint32 - Th32ProcessID uint32 - Th32DefaultHeapID uintptr - Th32ModuleID uint32 - CntThreads uint32 - Th32ParentProcessID uint32 - PcPriClassBase int32 - DwFlags uint32 - SzExeFile [MAX_PATH]uint16 -} - -type HANDLE uintptr - -var ( - modkernel32 = syscall.NewLazyDLL("kernel32.dll") - procCreateToolhelp32Snapshot = modkernel32.NewProc("CreateToolhelp32Snapshot") - procProcess32First = modkernel32.NewProc("Process32FirstW") - procProcess32Next = modkernel32.NewProc("Process32NextW") - procCloseHandle = modkernel32.NewProc("CloseHandle") -) - -func Getppids(pid uint32) []uint32 { - infos, err := GetProcs() - if err != nil { - return []uint32{pid} - } - var pids []uint32 = make([]uint32, 0, len(infos)) - var index int = 0 - pids = append(pids, pid) - - var length int = len(pids) - for index < length { - for _, info := range infos { - if info.PPid == pids[index] { - pids = append(pids, info.Pid) - } - } - index += 1 - length = len(pids) - } - return pids -} - -func GetProcs() (procs []ProcessInfo, err error) { - snap := createToolhelp32Snapshot(TH32CS_SNAPPROCESS, uint32(0)) - if snap == 0 { - err = syscall.GetLastError() - return - } - defer closeHandle(snap) - var pe32 PROCESSENTRY32 - pe32.DwSize = uint32(unsafe.Sizeof(pe32)) - if process32First(snap, &pe32) == false { - err = syscall.GetLastError() - return - } - procs = append(procs, ProcessInfo{syscall.UTF16ToString(pe32.SzExeFile[:260]), pe32.Th32ProcessID, pe32.Th32ParentProcessID}) - for process32Next(snap, &pe32) { - procs = append(procs, ProcessInfo{syscall.UTF16ToString(pe32.SzExeFile[:260]), pe32.Th32ProcessID, pe32.Th32ParentProcessID}) - } - return -} - -func createToolhelp32Snapshot(flags, processId uint32) HANDLE { - ret, _, _ := procCreateToolhelp32Snapshot.Call(uintptr(flags), uintptr(processId)) - if ret <= 0 { - return HANDLE(0) - } - return HANDLE(ret) -} - -func process32First(snapshot HANDLE, pe *PROCESSENTRY32) bool { - ret, _, _ := procProcess32First.Call(uintptr(snapshot), uintptr(unsafe.Pointer(pe))) - return ret != 0 -} - -func process32Next(snapshot HANDLE, pe *PROCESSENTRY32) bool { - ret, _, _ := procProcess32Next.Call(uintptr(snapshot), uintptr(unsafe.Pointer(pe))) - return ret != 0 -} - -func closeHandle(object HANDLE) bool { - ret, _, _ := procCloseHandle.Call(uintptr(object)) - return ret != 0 -} diff --git a/vendor/github.com/jesseduffield/kill/LICENSE b/vendor/github.com/jesseduffield/kill/LICENSE new file mode 100644 index 00000000..2a7175dc --- /dev/null +++ b/vendor/github.com/jesseduffield/kill/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022 Jesse Duffield + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vendor/github.com/jesseduffield/kill/README.md b/vendor/github.com/jesseduffield/kill/README.md new file mode 100644 index 00000000..75ca05db --- /dev/null +++ b/vendor/github.com/jesseduffield/kill/README.md @@ -0,0 +1,3 @@ +# Kill + +Go package for killing processes across different platforms. Handles killing children of processes as well as the process itself. diff --git a/vendor/github.com/jesseduffield/kill/kill_default_platform.go b/vendor/github.com/jesseduffield/kill/kill_default_platform.go new file mode 100644 index 00000000..6fb5a313 --- /dev/null +++ b/vendor/github.com/jesseduffield/kill/kill_default_platform.go @@ -0,0 +1,33 @@ +//go:build !windows +// +build !windows + +package kill + +import ( + "os/exec" + "syscall" +) + +// Kill kills a process. If the process has Setpgid == true, then we have anticipated that it might spawn its own child processes, so we've given it a process group ID (PGID) equal to its process id (PID) and given its child processes will inherit the PGID, we can kill that group, rather than killing the process itself. +func Kill(cmd *exec.Cmd) error { + if cmd.Process == nil { + // You can't kill a person with no body + return nil + } + + if cmd.SysProcAttr != nil && cmd.SysProcAttr.Setpgid { + // minus sign means we're talking about a PGID as opposed to a PID + return syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL) + } + + return cmd.Process.Kill() +} + +// PrepareForChildren ensures that child processes of this parent process will share the same group id +// as the parent, meaning when the call Kill on the parent process, we'll kill +// the whole group, parent and children both. Gruesome when you think about it. +func PrepareForChildren(cmd *exec.Cmd) { + cmd.SysProcAttr = &syscall.SysProcAttr{ + Setpgid: true, + } +} diff --git a/vendor/github.com/jesseduffield/kill/kill_windows.go b/vendor/github.com/jesseduffield/kill/kill_windows.go new file mode 100644 index 00000000..1ac08a12 --- /dev/null +++ b/vendor/github.com/jesseduffield/kill/kill_windows.go @@ -0,0 +1,136 @@ +// adapted from https://blog.csdn.net/fyxichen/article/details/51857864 + +package kill + +import ( + "os" + "os/exec" + "syscall" + "unsafe" +) + +// Kill kills a process, along with any child processes it may have spawned. +func Kill(cmd *exec.Cmd) error { + if cmd.Process == nil { + // You can't kill a person with no body + return nil + } + + pids := Getppids(uint32(cmd.Process.Pid)) + for _, pid := range pids { + pro, err := os.FindProcess(int(pid)) + if err != nil { + continue + } + + pro.Kill() + } + + return nil +} + +// PrepareForChildren ensures that child processes of this parent process will share the same group id +// as the parent, meaning when the call Kill on the parent process, we'll kill +// the whole group, parent and children both. Gruesome when you think about it. +func PrepareForChildren(cmd *exec.Cmd) { + // do nothing because on windows our Kill function handles children by default. +} + +const ( + MAX_PATH = 260 + TH32CS_SNAPPROCESS = 0x00000002 +) + +type ProcessInfo struct { + Name string + Pid uint32 + PPid uint32 +} + +type PROCESSENTRY32 struct { + DwSize uint32 + CntUsage uint32 + Th32ProcessID uint32 + Th32DefaultHeapID uintptr + Th32ModuleID uint32 + CntThreads uint32 + Th32ParentProcessID uint32 + PcPriClassBase int32 + DwFlags uint32 + SzExeFile [MAX_PATH]uint16 +} + +type HANDLE uintptr + +var ( + modkernel32 = syscall.NewLazyDLL("kernel32.dll") + procCreateToolhelp32Snapshot = modkernel32.NewProc("CreateToolhelp32Snapshot") + procProcess32First = modkernel32.NewProc("Process32FirstW") + procProcess32Next = modkernel32.NewProc("Process32NextW") + procCloseHandle = modkernel32.NewProc("CloseHandle") +) + +func Getppids(pid uint32) []uint32 { + infos, err := GetProcs() + if err != nil { + return []uint32{pid} + } + var pids []uint32 = make([]uint32, 0, len(infos)) + var index int = 0 + pids = append(pids, pid) + + var length int = len(pids) + for index < length { + for _, info := range infos { + if info.PPid == pids[index] { + pids = append(pids, info.Pid) + } + } + index += 1 + length = len(pids) + } + return pids +} + +func GetProcs() (procs []ProcessInfo, err error) { + snap := createToolhelp32Snapshot(TH32CS_SNAPPROCESS, uint32(0)) + if snap == 0 { + err = syscall.GetLastError() + return + } + defer closeHandle(snap) + var pe32 PROCESSENTRY32 + pe32.DwSize = uint32(unsafe.Sizeof(pe32)) + if process32First(snap, &pe32) == false { + err = syscall.GetLastError() + return + } + procs = append(procs, ProcessInfo{syscall.UTF16ToString(pe32.SzExeFile[:260]), pe32.Th32ProcessID, pe32.Th32ParentProcessID}) + for process32Next(snap, &pe32) { + procs = append(procs, ProcessInfo{syscall.UTF16ToString(pe32.SzExeFile[:260]), pe32.Th32ProcessID, pe32.Th32ParentProcessID}) + } + return +} + +func createToolhelp32Snapshot(flags, processId uint32) HANDLE { + ret, _, _ := procCreateToolhelp32Snapshot.Call(uintptr(flags), uintptr(processId)) + if ret <= 0 { + return HANDLE(0) + } + return HANDLE(ret) +} + +func process32First(snapshot HANDLE, pe *PROCESSENTRY32) bool { + ret, _, _ := procProcess32First.Call(uintptr(snapshot), uintptr(unsafe.Pointer(pe))) + return ret != 0 +} + +func process32Next(snapshot HANDLE, pe *PROCESSENTRY32) bool { + ret, _, _ := procProcess32Next.Call(uintptr(snapshot), uintptr(unsafe.Pointer(pe))) + return ret != 0 +} + +func closeHandle(object HANDLE) bool { + ret, _, _ := procCloseHandle.Call(uintptr(object)) + return ret != 0 +} diff --git a/vendor/modules.txt b/vendor/modules.txt index d9ccdfc8..3c9757d8 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -118,6 +118,9 @@ github.com/jesseduffield/asciigraph # github.com/jesseduffield/gocui v0.3.1-0.20220417002912-bce22fd599f6 ## explicit; go 1.12 github.com/jesseduffield/gocui +# github.com/jesseduffield/kill v0.0.0-20220618033138-bfbe04675d10 +## explicit; go 1.18 +github.com/jesseduffield/kill # github.com/jesseduffield/yaml v0.0.0-20190702115811-b900b7e08b56 ## explicit github.com/jesseduffield/yaml