initial commit

This commit is contained in:
root 2024-06-20 21:41:25 +05:00
commit 24ff954904
9 changed files with 419 additions and 0 deletions

89
runner/runner.go Normal file
View file

@ -0,0 +1,89 @@
package runner
import (
"errors"
"fmt"
"log"
"os"
"strings"
exec "os/exec"
cgroups "github.com/containerd/cgroups"
//cgroup2 "github.com/containerd/cgroups/v3/cgroup2"
//specs "github.com/opencontainers/runtime-spec/specs-go"
rand "math/rand"
"time"
"os/user"
)
const runner_username string = "gaterunner"
const runIdLength = 20
var coresIsolated []int
type Limits {
core int
memory 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)
//user setup:
_,err:=user.Lookup(runner_username)
if err!=nil{
if errors.As(err, new(user.UnknownUserError)) {
exec.Command("useradd", runner_username).Run();
} else {
return fmt.Errorf("user error:",err)
}
}
log.Println("Runner initialisation successful!")
return nil
}
func IsolatedRun(command []string,core int) {
var runId string
for i:=0;i<runIdLength;i++{
runId+=string('a'+byte(rand.Int31n(26)))
}
}

32
runner/runner_test.go Normal file
View file

@ -0,0 +1,32 @@
package runner
import (
"testing"
)
type ENTestPair struct {
test string
result []int
}
var ENTests = []ENTestPair {
{"123",[]int{123}},
{"abc123abc",[]int{123}},
{"",[]int{}},
{"0",[]int{0}},
{"1a2a3a6",[]int{1,2,3,6}},
}
func TestExtractNumbers(t *testing.T) {
for _,test:=range(ENTests) {
result:=extractNumbers(test.test)
if(len(result)!=len(test.result)) {
t.Error("for",test.test,"expected",test.result,"got",result)
}
for i:=0;i<len(result);i++ {
if(result[i]!=test.result[i]) {
t.Error("for",test.test,"expected",test.result,"got",result)
}
}
}
}