refactor(native): move platform-specific code to different files

This commit is contained in:
Siyuan Miao 2025-04-15 16:48:09 +02:00
parent daa7185883
commit db2ce258ae
3 changed files with 56 additions and 26 deletions

View File

@ -8,9 +8,7 @@ import (
"io"
"net"
"os"
"os/exec"
"sync"
"syscall"
"time"
"github.com/jetkvm/kvm/resource"
@ -262,30 +260,8 @@ func ExtractAndRunNativeBin() error {
return fmt.Errorf("failed to make binary executable: %w", err)
}
// Run the binary in the background
cmd := exec.Command(binaryPath)
nativeOutputLock := sync.Mutex{}
nativeStdout := &nativeOutput{
mu: &nativeOutputLock,
logger: nativeLogger.Info().Str("pipe", "stdout"),
}
nativeStderr := &nativeOutput{
mu: &nativeOutputLock,
logger: nativeLogger.Info().Str("pipe", "stderr"),
}
// Redirect stdout and stderr to the current process
cmd.Stdout = nativeStdout
cmd.Stderr = nativeStderr
// Set the process group ID so we can kill the process and its children when this process exits
cmd.SysProcAttr = &syscall.SysProcAttr{
Setpgid: true,
Pdeathsig: syscall.SIGKILL,
}
// Start the command
if err := cmd.Start(); err != nil {
cmd, err := startNativeBinary(binaryPath)
if err != nil {
return fmt.Errorf("failed to start binary: %w", err)
}

42
native_linux.go Normal file
View File

@ -0,0 +1,42 @@
//go:build linux
package kvm
import (
"fmt"
"os/exec"
"sync"
"syscall"
)
func startNativeBinary(binaryPath string) (*exec.Cmd, error) {
// Run the binary in the background
cmd := exec.Command(binaryPath)
nativeOutputLock := sync.Mutex{}
nativeStdout := &nativeOutput{
mu: &nativeOutputLock,
logger: nativeLogger.Info().Str("pipe", "stdout"),
}
nativeStderr := &nativeOutput{
mu: &nativeOutputLock,
logger: nativeLogger.Info().Str("pipe", "stderr"),
}
// Redirect stdout and stderr to the current process
cmd.Stdout = nativeStdout
cmd.Stderr = nativeStderr
// Set the process group ID so we can kill the process and its children when this process exits
cmd.SysProcAttr = &syscall.SysProcAttr{
Setpgid: true,
Pdeathsig: syscall.SIGKILL,
}
// Start the command
if err := cmd.Start(); err != nil {
return nil, fmt.Errorf("failed to start binary: %w", err)
}
return cmd, nil
}

12
native_notlinux.go Normal file
View File

@ -0,0 +1,12 @@
//go:build !linux
package kvm
import (
"fmt"
"os/exec"
)
func startNativeBinary(binaryPath string) (*exec.Cmd, error) {
return nil, fmt.Errorf("not supported")
}