ms-runner/runner/runner.go
2024-06-22 21:29:19 +05:00

88 lines
2.4 KiB
Go

package runner
import (
"bytes"
"io"
"fmt"
"log"
"os"
"strings"
exec "os/exec"
cgroups "github.com/containerd/cgroups"
rand "math/rand"
"time"
)
const runIdLength = 20
var coresIsolated []int
type Limits struct {
Core int
Memory int
Time int
}
func extractNumbers(s string) (result []int) {
lastNumber, isNumber := false,false
var curNumber = 0
for _, char := range s {
isNumber = (char >= '0' && char <= '9')
if(isNumber) {
curNumber *= 10
curNumber += int(char - '0')
}
if(!isNumber && lastNumber) {
result = append(result, curNumber)
curNumber = 0
}
lastNumber = isNumber
}
if(lastNumber) {
result = append(result, curNumber)
}
return
}
func Init() error {
rand.Seed(time.Now().UnixNano())
//croup initialisation:
if cgroups.Mode() == cgroups.Unified {
log.Println("cgroups v2 usage approved")
} else {
return fmt.Errorf("cgroups v2 are not enabled")//TODO: trouble description
}
//isolated cores initialisation:
cmdlineBytes := make([]byte, 400)
cmdlineFile, _ := os.Open("/proc/cmdline");
countCmdlineBytes, _ := cmdlineFile.Read(cmdlineBytes);
cmdline := string(cmdlineBytes[:countCmdlineBytes])
kernelParams := strings.Split(cmdline," ")
for _, param := range kernelParams{
if(len(param) >= 9 && param[:9] == "isolcpus=") {
coresIsolated = append(coresIsolated, extractNumbers(param[9:])...)
}
}
if(len(coresIsolated) == 0) {
return fmt.Errorf("no free cores available")//TODO: trouble description
}
log.Println("running on cores:", coresIsolated)
log.Println("Runner initialisation successful!")
return nil
}
func IsolatedRun(command []string, limits Limits) {
var runId string
for i := 0; i < runIdLength; i++ {runId += string('a' + byte(rand.Int31n(26)))}
os.Mkdir("starter/" + runId, 0777)
args := []string{string(limits.Core), string(limits.Memory), string(limits.Time), runId}
args = append(args, command...)
cmd := exec.Command("starter/starter", args...)
var stdBuffer bytes.Buffer
mw := io.MultiWriter(os.Stdout, &stdBuffer)
cmd.Stdout = mw
err := cmd.Run();
if err != nil { log.Fatal(err) }
os.RemoveAll("starter/" + runId)
cmd.Wait()
}