<commit_before>"""Run a python process in a jail."""

# Instructions:
#   - AppArmor.md from xserver

import os, os.path
import resource
import shutil
import subprocess
import sys
import threading
import time

from .util import temp_directory

# TODO: limit too much stdout data?

# Configure the Python command

PYTHON_CMD = None

def configure(python_bin, user=None):
    """Configure the jailpy module."""
    global PYTHON_CMD
    PYTHON_CMD = []
    if user:
        PYTHON_CMD.extend(['sudo', '-u', 'sandbox'])
    PYTHON_CMD.extend([python_bin, '-E'])

def is_configured():
    return bool(PYTHON_CMD)

# By default, look where our current Python is, and maybe there's a
# python-sandbox alongside.  Only do this if running in a virtualenv.
if hasattr(sys, 'real_prefix'):
    if os.path.isdir(sys.prefix + "-sandbox"):
        configure(sys.prefix + "-sandbox/bin/python", "sandbox")


class JailResult(object):
    """A passive object for us to return from jailpy."""
    pass

def jailpy(code, files=None, argv=None, stdin=None):
    """
    Run Python code in a jailed subprocess.

    `code` is a string containing the Python code to run.

    `files` is a list of file paths.

    Return an object with:

        .stdout: stdout of the program, a string
        .stderr: stderr of the program, a string
        .status: return status of the process: an int, 0 for successful

    """
    if not PYTHON_CMD:
        raise Exception("jailpy needs to be configured")

    with temp_directory(delete_when_done=True) as tmpdir:

        # All the supporting files are copied into our directory.
        for filename in files or ():
            if os.path.isfile(filename):
                shutil.copy(filename, tmpdir)
            else:
                dest = os.path.join(tmpdir, os.path.basename(filename))
                shutil.copytree(filename, dest)

        # Create the main file.
        with open(os.path.join(tmpdir, "jailed_code.py"), "w") as jailed:
            jailed.write(code)

        cmd = PYTHON_CMD + ['jailed_code.py'] + (argv or [])

        subproc = subprocess.Popen(
            cmd, preexec_fn=set_process_limits, cwd=tmpdir,
            stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,<commit_msg>Add some logging to codejail<commit_after>"""Run a python process in a jail."""

# Instructions:
#   - AppArmor.md from xserver

import logging
import os, os.path
import resource
import shutil
import subprocess
import sys
import threading
import time

from .util import temp_directory

log = logging.getLogger(__name__)

# TODO: limit too much stdout data?

# Configure the Python command

PYTHON_CMD = None

def configure(python_bin, user=None):
    """Configure the jailpy module."""
    global PYTHON_CMD
    PYTHON_CMD = []
    if user:
        PYTHON_CMD.extend(['sudo', '-u', 'sandbox'])
    PYTHON_CMD.extend([python_bin, '-E'])

def is_configured():
    return bool(PYTHON_CMD)

# By default, look where our current Python is, and maybe there's a
# python-sandbox alongside.  Only do this if running in a virtualenv.
if hasattr(sys, 'real_prefix'):
    if os.path.isdir(sys.prefix + "-sandbox"):
        configure(sys.prefix + "-sandbox/bin/python", "sandbox")


class JailResult(object):
    """A passive object for us to return from jailpy."""
    pass

def jailpy(code, files=None, argv=None, stdin=None):
    """
    Run Python code in a jailed subprocess.

    `code` is a string containing the Python code to run.

    `files` is a list of file paths.

    Return an object with:

        .stdout: stdout of the program, a string
        .stderr: stderr of the program, a string
        .status: return status of the process: an int, 0 for successful

    """
    if not PYTHON_CMD:
        raise Exception("jailpy needs to be configured")

    with temp_directory(delete_when_done=True) as tmpdir:

        log.debug("Executing jailed code: %r", code)

        # All the supporting files are copied into our directory.
        for filename in files or ():
            if os.path.isfile(filename):
                shutil.copy(filename, tmpdir)
            else:
                dest = os.path.join(tmpdir, os.path.basename(filename))
                shutil.copytree(filename, dest)

        # Create the main file.
        with open(os.path.join(tmpdir, "jailed_code.py"), "w") as jailed:
            jailed.write(code)

        cmd = PYTHON_CMD + ['jailed_code.py'] + (argv or [])

        subproc = subprocess.Popen(
            cmd, preexec_fn=set_process_limits, cwd=tmpdir,
            stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
{'fraction_non_alphanumeric': 0.10278557546966098, 'fraction_numerical': 0.0004318721658389117, 'mean_word_length': 2.8312655086848637, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4848307', 'n_tokens_mistral': 1475, 'n_tokens_neox': 1421, 'n_words': 462}