woj-sandbox/resource.c

46 lines
1.7 KiB
C
Raw Normal View History

2022-10-02 16:06:27 +08:00
#include "resource.h"
#include "err.h"
#include "utils/log.h"
#include <stdlib.h>
#include <sys/resource.h>
#define SET_LIMIT(resource, limit, name, unit) \
do { \
if (limit) { \
LOG_INFO("Setting " name " limit to %ld " unit, limit); \
if (setrlimit(resource, &(struct rlimit){limit, limit})) { \
LOG_ERR("Failed to set " name " limit"); \
exit(ERR_RLIMIT_SET); \
} \
} \
} while (0)
2023-12-28 00:58:15 +08:00
void setup_rlimit(char *config[CFG_IS_VALID + 1]) {
2022-10-02 16:06:27 +08:00
LOG_INFO("Setting resource limit");
2023-12-28 00:58:15 +08:00
char *mem_limit_str = config[CFG_MEMORY_LIMIT]; // in mb
char *nproc_limit_str = config[CFG_NPROC_LIMIT];
char *time_limit_str = config[CFG_TIME_LIMIT]; // in ms
2022-10-02 16:06:27 +08:00
long mem_limit = 0, nproc_limit = 0, time_limit = 0;
if (mem_limit_str) {
// convert to bytes and double the memory limit
2023-12-28 00:58:15 +08:00
mem_limit = strtol(mem_limit_str, NULL, 10) * 1024 * 1024;
2022-10-02 16:06:27 +08:00
}
if (nproc_limit_str) {
nproc_limit = strtol(nproc_limit_str, NULL, 10);
}
if (time_limit_str) {
long limit = strtol(time_limit_str, NULL, 10);
2022-10-09 00:06:07 +08:00
time_limit = limit ? (limit + 1000) / 1000 : 0;
2022-10-02 16:06:27 +08:00
}
SET_LIMIT(RLIMIT_AS, mem_limit, "memory", "bytes");
2024-01-01 17:32:32 +08:00
SET_LIMIT(RLIMIT_NPROC, nproc_limit, "nproc", "processes"); // per user, **not** subprocess
2022-10-09 00:06:07 +08:00
SET_LIMIT(RLIMIT_CPU, time_limit, "time", "seconds"); // except blocked time
2022-10-02 16:06:27 +08:00
}