91 lines
2.3 KiB
Go
91 lines
2.3 KiB
Go
//go:build windows
|
|
|
|
package plugin
|
|
|
|
import (
|
|
"fmt"
|
|
"os/exec"
|
|
"sync"
|
|
"syscall"
|
|
"unsafe"
|
|
|
|
"golang.org/x/sys/windows"
|
|
)
|
|
|
|
const (
|
|
createNoWindow = 0x08000000
|
|
createBreakawayFromJob = 0x01000000
|
|
createNewProcessGroup = 0x00000200
|
|
)
|
|
|
|
func configureSidecarCmd(cmd *exec.Cmd) {
|
|
cmd.SysProcAttr = &syscall.SysProcAttr{
|
|
HideWindow: true,
|
|
CreationFlags: createNoWindow | createNewProcessGroup,
|
|
}
|
|
}
|
|
|
|
func configureDetachedVMProcess(cmd *exec.Cmd) {
|
|
cmd.SysProcAttr = &syscall.SysProcAttr{
|
|
HideWindow: true,
|
|
CreationFlags: createNoWindow | createNewProcessGroup | createBreakawayFromJob,
|
|
}
|
|
}
|
|
|
|
type sidecarJob struct {
|
|
handle windows.Handle
|
|
closeOnce sync.Once
|
|
}
|
|
|
|
// newSidecarJob creates a Windows Job Object with KILL_ON_JOB_CLOSE so that
|
|
// closing the job (or host exit/crash) reclaims the entire Sidecar process tree
|
|
// with zero orphan processes (§8). Optional memLimitBytes caps process memory (L2).
|
|
func newSidecarJob(memLimitBytes uintptr) (*sidecarJob, error) {
|
|
h, err := windows.CreateJobObject(nil, nil)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("CreateJobObject: %w", err)
|
|
}
|
|
info := windows.JOBOBJECT_EXTENDED_LIMIT_INFORMATION{}
|
|
info.BasicLimitInformation.LimitFlags = windows.JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
|
|
if memLimitBytes > 0 {
|
|
info.BasicLimitInformation.LimitFlags |= windows.JOB_OBJECT_LIMIT_PROCESS_MEMORY
|
|
info.ProcessMemoryLimit = memLimitBytes
|
|
}
|
|
if _, err := windows.SetInformationJobObject(
|
|
h,
|
|
windows.JobObjectExtendedLimitInformation,
|
|
uintptr(unsafe.Pointer(&info)),
|
|
uint32(unsafe.Sizeof(info)),
|
|
); err != nil {
|
|
_ = windows.CloseHandle(h)
|
|
return nil, fmt.Errorf("SetInformationJobObject: %w", err)
|
|
}
|
|
return &sidecarJob{handle: h}, nil
|
|
}
|
|
|
|
func (j *sidecarJob) Assign(pid int) error {
|
|
if j == nil || j.handle == 0 || pid <= 0 {
|
|
return nil
|
|
}
|
|
proc, err := windows.OpenProcess(windows.PROCESS_SET_QUOTA|windows.PROCESS_TERMINATE, false, uint32(pid))
|
|
if err != nil {
|
|
return fmt.Errorf("OpenProcess(%d): %w", pid, err)
|
|
}
|
|
defer windows.CloseHandle(proc)
|
|
return windows.AssignProcessToJobObject(j.handle, proc)
|
|
}
|
|
|
|
func (j *sidecarJob) Close() {
|
|
if j == nil {
|
|
return
|
|
}
|
|
j.closeOnce.Do(func() {
|
|
if j.handle == 0 {
|
|
return
|
|
}
|
|
_ = windows.TerminateJobObject(j.handle, 1)
|
|
_ = windows.CloseHandle(j.handle)
|
|
j.handle = 0
|
|
})
|
|
}
|