Skip to content

Commit 402b954

Browse files
refactor: ignore exception in preexec_fn.
1 parent 5c2cf27 commit 402b954

File tree

1 file changed

+6
-5
lines changed

1 file changed

+6
-5
lines changed

apps/common/utils/tool_code.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -14,11 +14,11 @@
1414
import tempfile
1515
import time
1616
from contextlib import contextmanager
17+
from contextlib import suppress
1718
from textwrap import dedent
1819

1920
import uuid_utils.compat as uuid
2021
from django.utils.translation import gettext_lazy as _
21-
2222
from common.utils.logger import maxkb_logger
2323
from maxkb.const import BASE_DIR, CONFIG
2424
from maxkb.const import PROJECT_DIR
@@ -242,17 +242,18 @@ def _exec(self, execute_file):
242242
kwargs = {'cwd': BASE_DIR, 'env': {
243243
'LD_PRELOAD': f'{_sandbox_path}/lib/sandbox.so',
244244
}}
245+
def _set_resource_limit():
246+
if not _enable_sandbox or not sys.platform.startswith("linux"): return
247+
with suppress(Exception): resource.setrlimit(resource.RLIMIT_AS, (_process_limit_mem_mb * 1024 * 1024,) * 2)
248+
with suppress(Exception): os.sched_setaffinity(0, set(random.sample(list(os.sched_getaffinity(0)), _process_limit_cpu_cores)))
245249
try:
246250
subprocess_result = subprocess.run(
247251
[sys.executable, execute_file],
248252
timeout=_process_limit_timeout_seconds,
249253
text=True,
250254
capture_output=True,
251255
**kwargs,
252-
preexec_fn=(lambda: None if (not _enable_sandbox or not sys.platform.startswith("linux")) else (
253-
resource.setrlimit(resource.RLIMIT_AS, (_process_limit_mem_mb * 1024 * 1024,) * 2),
254-
os.sched_setaffinity(0, set(random.sample(list(os.sched_getaffinity(0)), _process_limit_cpu_cores)))
255-
))
256+
preexec_fn=_set_resource_limit
256257
)
257258
return subprocess_result
258259
except subprocess.TimeoutExpired:

0 commit comments

Comments
 (0)