code prettyfing

This commit is contained in:
root 2024-06-22 21:29:19 +05:00
parent 4e0711fe8c
commit 538cd56a01
4 changed files with 75 additions and 84 deletions

10
main.go
View file

@ -1,18 +1,14 @@
package main
import (
//"os"
//"fmt"
//"log"
//exec "os/exec"
runner "runner/runner"
)
func main() {
err:=runner.Init()
if(err!=nil) {
err := runner.Init()
if(err != nil) {
panic(err)
}
limits := runner.Limits{Core: 3,Memory: 10000000, Time: 1000}
runner.IsolatedRun([]string{"/bin/echo","123"},limits)
runner.IsolatedRun([]string{"/bin/echo", "123"}, limits)
}

View file

@ -1,7 +1,6 @@
package runner
import (
//"errors"
"bytes"
"io"
"fmt"
@ -24,22 +23,22 @@ type Limits struct {
}
func extractNumbers(s string) (result []int) {
lastNumber,isNumber := false,false
var curNumber=0
for _,char :=range s {
isNumber=(char>='0' && char<='9')
lastNumber, isNumber := false,false
var curNumber = 0
for _, char := range s {
isNumber = (char >= '0' && char <= '9')
if(isNumber) {
curNumber*=10
curNumber+=int(char-'0')
curNumber *= 10
curNumber += int(char - '0')
}
if(!isNumber && lastNumber) {
result=append(result,curNumber)
curNumber=0
result = append(result, curNumber)
curNumber = 0
}
lastNumber=isNumber
lastNumber = isNumber
}
if(lastNumber) {
result=append(result,curNumber)
result = append(result, curNumber)
}
return
}
@ -54,39 +53,35 @@ func Init() error {
}
//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:])...)
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) {
if(len(coresIsolated) == 0) {
return fmt.Errorf("no free cores available")//TODO: trouble description
}
log.Println("running on cores:",coresIsolated)
log.Println("running on cores:", coresIsolated)
log.Println("Runner initialisation successful!")
return nil
}
func IsolatedRun(command []string,limits Limits) {
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)
//log.Printf("%d",limits.Core)
//exec.Command("starter/starter", string(limits.Core),string(limits.Memory),string(limits.Time),runId,command...);
args:=[]string{string(limits.Core),string(limits.Memory),string(limits.Time),runId}
args=append(args,command...)
cmd:=exec.Command("/root/runner/starter/starter",args...)
//cmd:=exec.Command("/usr/bin/echo","123")
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) }
//log.Println(stdBuffer.String())
os.RemoveAll("starter/"+runId)
os.RemoveAll("starter/" + runId)
cmd.Wait()
}

View file

@ -10,22 +10,22 @@ type ENTestPair struct {
}
var ENTests = []ENTestPair {
{"123",[]int{123}},
{"abc123abc",[]int{123}},
{"",[]int{}},
{"0",[]int{0}},
{"1a2a3a6",[]int{1,2,3,6}},
{"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 _, 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)
for i := 0; i < len(result); i++ {
if(result[i] != test.result[i]) {
t.Error("for", test.test, "expected", test.result, "got", result)
}
}
}

View file

@ -34,22 +34,22 @@ struct killparams{
};
#define READ_SIZE 100
char read_buf[READ_SIZE+1];
char read_buf[READ_SIZE + 1];
#include "ns_exec.c"
#include "cgroup_prepare.c"
//time limit realisation
static int killafter(void *arg) {
//die when parent dies
if (prctl(PR_SET_PDEATHSIG, SIGKILL)) die("cannot PR_SET_PDEATHSIG for child process: %m\n");
struct killparams* params = (struct killparams*) arg;
struct timespec tw={params->time/1000,((params->time)%1000)*1000000};
struct timespec tw = {params -> time / 1000, ((params->time) % 1000) * 1000000};
struct timespec tr;
nanosleep(&tw,&tr);
kill(params->pid,SIGKILL);
nanosleep(&tw, &tr);
kill(params->pid, SIGKILL);
}
//const size_t STACK_SIZE=1000000;
#define STACK_SIZE 1000000
static char nmstack[STACK_SIZE];
static char killstack[STACK_SIZE];
@ -59,30 +59,31 @@ static void parse_args(int argc, char **argv, struct params *params,struct limit
puts("usage:\n starter <core_id> <memory_amount> <time limit in ms> <shared folder> <command, arg1,arg2,...>");
exit(0);
}
argc--;argv++;
limits->core=atoi(argv[0]);
argc--;argv++;
limits->memory=atoi(argv[0]);
argc--;argv++;
limits->time=atoi(argv[0]);
argc--;argv++;
params->shared_folder=argv[0];
argc--;argv++;
argc--; argv++;
limits->core = atoi(argv[0]);
argc--; argv++;
limits->memory = atoi(argv[0]);
argc--; argv++;
limits->time = atoi(argv[0]);
argc--; argv++;
params->shared_folder = argv[0];
argc--; argv++;
params->argv = argv;
}
//setup user namespace
static void prepare_userns(int pid) {
char path[100];
char line[100];
int uid = 0;
int gid = 0;
int unprivileged_uid=66534;
int unprivileged_gid=65534;
int uid = 0;//root
int gid = 0;//root
int unprivileged_uid = 66534;//nobody
int unprivileged_gid = 65534;//nogroup
sprintf(path, "/proc/%d/uid_map", pid);
sprintf(line, "0 %d 1\n1 %d 1000\n", uid, unprivileged_uid);
sprintf(line, "0 %d 1\n1 %d 1000\n", uid, unprivileged_uid);//map root to uid 0,nobody to uid 1000
write_file(path, line);
sprintf(path, "/proc/%d/setgroups", pid);
@ -90,40 +91,39 @@ static void prepare_userns(int pid) {
write_file(path, line);
sprintf(path, "/proc/%d/gid_map", pid);
sprintf(line, "0 %d 1\n1 %d 1000\n", gid, unprivileged_gid);
sprintf(line, "0 %d 1\n1 %d 1000\n", gid, unprivileged_gid);//map root to gid 0,nogroup to gid 1000
write_file(path, line);
}
int main(int argc,char** argv) {
if(setuid(0)) die("need to be run as root");
if(setgid(0)) die("need to be run as root");
//getting binary folder
//get binary folder
char bin_path[PATH_MAX];
if (realpath (argv[0], bin_path) == 0) die("unable to resolve real path: %m");
for(int i = strlen(bin_path);i>0 && bin_path[i]!='/';i--) bin_path[i]=0;
if (realpath (argv[0], bin_path) == 0) die("unable to resolve real path: %m");//get absolute path to executable
for(int i = strlen(bin_path); i > 0 && bin_path[i] != '/';i--) bin_path[i]=0;//cut filename to get directory name
if(chdir(bin_path)) die("unable to chdir to binary path: %m");
//setting random seed
//set random seed
srand(time(NULL));
//setup parameters
struct params params;
memset(&params, 0, sizeof(struct params));
struct limits limits;
memset(&limits, 0, sizeof(struct limits));
parse_args(argc, argv, &params, &limits);
prepare_cgroup(&limits);
if (pipe(params.fd) < 0) die("can't open pipe: %m");
int clone_flags = SIGCHLD | CLONE_NEWUTS | CLONE_NEWUSER | CLONE_NEWNS | CLONE_NEWPID | CLONE_NEWNET | CLONE_NEWIPC | CLONE_NEWCGROUP/* | CLONE_NEWTIME*/;
int nsrun_pid=clone(nsrun,nmstack+STACK_SIZE,clone_flags,&params);
int pipe=params.fd[1];
//sleep(1);
if (pipe(params.fd) < 0) die("can't open pipe: %m");//a pipe to report readiness
int clone_flags = SIGCHLD | CLONE_NEWUTS | CLONE_NEWUSER | CLONE_NEWNS | CLONE_NEWPID | CLONE_NEWNET | CLONE_NEWIPC | CLONE_NEWCGROUP;
int nsrun_pid = clone(nsrun, nmstack + STACK_SIZE, clone_flags, &params);//make new namespace
int pipe = params.fd[1];
prepare_userns(nsrun_pid);
if (nsrun_pid<0) {die("faled to clone");}
if (nsrun_pid < 0) die("faled to clone");
add_to_cgroup(nsrun_pid);
//dup2(STDOUT_FILENO,params.out[0]);
if (write(pipe, "OK", 2) != 2) die("Failed to write to pipe: %m");//report readiness
struct killparams killparams;
killparams.time=limits.time;
killparams.pid=nsrun_pid;
clone(killafter,killstack+STACK_SIZE,SIGCHLD,&killparams);
killparams.time = limits.time;
killparams.pid = nsrun_pid;
clone(killafter, killstack + STACK_SIZE, SIGCHLD, &killparams);
if (waitpid(nsrun_pid, NULL, 0) == -1) die("Failed to wait pid %d: %m\n", nsrun_pid);
remove_cgroup();
return 0;