iitian_adda_iitk

Untitled

Aug 21st, 2025
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.44 KB | None | 0 0
  1. import os
  2. import shutil
  3. import subprocess
  4. import tempfile
  5. import logging
  6. import sys
  7.  
  8. # Setup logging
  9. logging.basicConfig(
  10. filename='judge_runner.log',
  11. filemode='a',
  12. format='%(asctime)s %(levelname)s %(message)s',
  13. level=logging.DEBUG
  14. )
  15.  
  16. IMAGE_NAME = "judge-image"
  17. IMAGE_TAG = "latest"
  18. IMAGE = f"{IMAGE_NAME}:{IMAGE_TAG}"
  19.  
  20. TEST_FOLDER = "test"
  21. TEST_FILE = 'main.py'
  22.  
  23. DEFAULT_COMILE_TIME_LIMIT = 100000000000
  24.  
  25. def create_folder_and_file(folder_name=TEST_FOLDER, file_name=TEST_FILE, content='print("\\t=== This is the default one\\n\\t=== Please change the code")'):
  26. try:
  27. os.makedirs(folder_name, exist_ok=True)
  28. with open(f'{folder_name}/{file_name}', 'w') as f:
  29. f.write(content)
  30. print(f"Created folder '{folder_name}' and file '{file_name}'.")
  31. logging.info(f"Created folder '{folder_name}' and file '{file_name}'.")
  32. except Exception as e:
  33. logging.error(f"Error creating folder/file: {e}")
  34. print(f"Error creating folder/file: {e}")
  35.  
  36. def delete_folder(folder_name=TEST_FOLDER):
  37. try:
  38. if os.path.exists(folder_name):
  39. shutil.rmtree(folder_name)
  40. logging.info(f"Deleted folder '{folder_name}'.")
  41. else:
  42. logging.info(f"Folder '{folder_name}' does not exist; nothing to delete.")
  43. except Exception as e:
  44. logging.error(f"Error deleting folder '{folder_name}': {e}")
  45.  
  46. def create_image(image=IMAGE):
  47. try:
  48. result = subprocess.run(
  49. ["docker", "images", "-q", image],
  50. capture_output=True, text=True
  51. )
  52. if not result.stdout.strip():
  53. logging.info(f"Image '{image}' not found. Building...")
  54. build_proc = subprocess.run(
  55. ["docker", "build", "-t", image, "."],
  56. check=True,
  57. stdout=subprocess.PIPE,
  58. stderr=subprocess.PIPE
  59. )
  60. logging.info(f"Docker build stdout: {build_proc.stdout.decode(errors='replace')}")
  61. logging.info(f"Docker build stderr: {build_proc.stderr.decode(errors='replace')}")
  62. else:
  63. logging.info(f"Image '{image}' already exists.")
  64. except subprocess.CalledProcessError as e:
  65. logging.error(f"Docker build failed: {e.stderr.decode(errors='replace') if e.stderr else str(e)}")
  66. except Exception as e:
  67. logging.error(f"Error in create_image: {e}")
  68.  
  69. def run_code_in_container(
  70. image=IMAGE,
  71. file_path=f'{TEST_FOLDER}/{TEST_FILE}',
  72. language='python',
  73. stdin='',
  74. time_limit=1,
  75. memory_limit=1024
  76. ):
  77. result = {
  78. 'success': False,
  79. 'stdout': '',
  80. 'stderr': '',
  81. 'error': None,
  82. 'safe': True
  83. }
  84.  
  85. language = language.lower()
  86. stdin = stdin.strip()
  87. compile_cmd = []
  88. run_cmd = []
  89.  
  90.  
  91. # Add project root to sys.path to allow importing from other directories
  92. sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
  93.  
  94. from judge.safe import check_code_safety
  95.  
  96. code = open(f'{file_path}', 'r').read()
  97.  
  98. safety = check_code_safety(file_path, language)
  99. logging.info(f"Code safety check result: {safety}")
  100.  
  101. if not safety['success']:
  102. result['error'] = 'Code safety check failed: ' + safety['reason']
  103. result['safe'] = False
  104. return result
  105.  
  106.  
  107. # Set up the correct command for each language
  108. if language == 'python':
  109. run_cmd = f'echo "{stdin}" | python3 {os.path.basename(file_path)}'
  110. elif language == 'c':
  111. compile_cmd = ['gcc', os.path.basename(file_path), '-o', 'main']
  112. run_cmd = ['echo', f'"{stdin}"', '|', './main']
  113. elif language == 'c++':
  114. compile_cmd = ['g++', os.path.basename(file_path), '-o', 'main']
  115. run_cmd = ['echo', f'"{stdin}"', '|', './main']
  116. else:
  117. result['error'] = 'Unsupported language'
  118. return result
  119.  
  120. with tempfile.TemporaryDirectory() as temp_dir:
  121. shutil.copy(file_path, os.path.join(temp_dir, os.path.basename(file_path)))
  122. container_folder = "/sandbox/temp"
  123. docker_base = f'docker run --rm -i --memory={memory_limit}m -v {temp_dir}:{container_folder} -w {container_folder} {image} '
  124.  
  125. # Compile if necessary
  126. if compile_cmd:
  127. compile_command = docker_base + compile_cmd
  128. try:
  129. subprocess.run(
  130. compile_command,
  131. stdout=subprocess.PIPE,
  132. stderr=subprocess.PIPE,
  133. # input=stdin.encode() if stdin else None,
  134. timeout=DEFAULT_COMILE_TIME_LIMIT,
  135. check=True
  136. )
  137. except subprocess.CalledProcessError as e:
  138. result['error'] = 'Compile error: ' + str(e)
  139. result['stdout'] = e.stdout.decode(errors="replace") if e.stdout else ''
  140. result['stderr'] = e.stderr.decode(errors="replace") if e.stderr else ''
  141. return result
  142. except subprocess.TimeoutExpired:
  143. result['error'] = 'Compile Time Limit Exceeded'
  144. return result
  145. except Exception as e:
  146. result['error'] = 'Compile exception: ' + str(e)
  147. return result
  148.  
  149. # Run the code
  150. run_command = docker_base + run_cmd
  151. print(run_command)
  152. try:
  153. run_proc = subprocess.run(
  154. run_command,
  155. stdout=subprocess.PIPE,
  156. stderr=subprocess.PIPE,
  157. # input=stdin.encode() if stdin else None,
  158. timeout=time_limit,
  159. check=True
  160. )
  161. result['success'] = True
  162. result['stdout'] = run_proc.stdout.decode(errors="replace")
  163. result['stderr'] = run_proc.stderr.decode(errors="replace")
  164. except subprocess.CalledProcessError as e:
  165. result['error'] = 'Run error: ' + str(e)
  166. result['stdout'] = e.stdout.decode(errors="replace") if e.stdout else ''
  167. result['stderr'] = e.stderr.decode(errors="replace") if e.stderr else ''
  168. except subprocess.TimeoutExpired:
  169. result['error'] = 'Time Limit Exceeded'
  170. except Exception as e:
  171. result['error'] = 'Run exception: ' + str(e)
  172.  
  173. return result
  174.  
  175. if __name__ == "__main__":
  176. create_folder_and_file()
  177. create_image()
  178. print(run_code_in_container())
  179. delete_folder()
Advertisement
Add Comment
Please, Sign In to add comment