Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add: API for testing the online judge #6

Merged
merged 2 commits into from
May 22, 2024
Merged

add: API for testing the online judge #6

merged 2 commits into from
May 22, 2024

Conversation

Mahboob-A
Copy link
Owner

  • API CodeSubmitRobustAPI to test the online judge.

  • the client needs to pass the data following:

{
"lang":"cpp", 
"code":"cpp code", 
"input":"input for the code as list", 
"testcases":"testcases for the correct answers as list"
}

Copy link

sweep-ai bot commented May 22, 2024

Sweep: PR Review

Authors of pull request: @Mahboob-A

src/core_apps/judge_engine/views.py

Introduced two new API classes for handling code submissions using Docker containers, with detailed error handling and file operations.

Sweep Found These Issues

  • The CodeSubmitSimpleImplementation class does not handle the cleanup of the created files in the host system, which could lead to disk space issues over time.
  • file_path = f"user-files/{random.randint(10, 100000)}"
    curr_path = os.getcwd()
    print("curr path: ", os.getcwd())
    new_file_path = os.path.join(curr_path, file_path)

    View Diff

  • The CodeSubmitSimpleImplementation class does not handle the cleanup of the created files in the host system, which could lead to disk space issues over time.
  • file_path = f"user-files/{random.randint(10, 100000)}"
    curr_path = os.getcwd()
    print("curr path: ", os.getcwd())
    new_file_path = os.path.join(curr_path, file_path)

    View Diff

  • Sweep has identified a redundant function: The new function is redundant because its functionality is already covered by the _run_container method in CodeContainerHandler and the post method in CodeSubmitRobustAPI.
  • def post(self, request):
    start = time.time()
    lang = request.data.get("lang")
    code = request.data.get("code")
    input_data = request.data.get("input")
    print("Code: ", code)
    client = from_env()
    file_path = f"user-files/{random.randint(10, 100000)}"
    curr_path = os.getcwd()
    print("curr path: ", os.getcwd())
    new_file_path = os.path.join(curr_path, file_path)
    try:
    # Create and start a container
    container = client.containers.run(
    "simple_cpp", # Image name
    volumes={
    f"{new_file_path}/": {
    "bind": "/user-files",
    "mode": "rw",
    }
    },
    command=[
    "sh",
    "-c",
    f'echo "{code}" > /user-files/code.cpp && echo "{input_data}" > /user-files/input.txt && g++ /user-files/code.cpp -o /user-files/code && /user-files/code < /user-files/input.txt > /user-files/output.txt',
    ],
    detach=True,
    )
    # Wait for the container to finish
    result = container.wait()
    print("result: ", result)
    # Get the logs (output)
    output = container.logs().decode("utf-8")
    with open(f"{new_file_path}/output.txt", "r") as f:
    data = f.read()
    print("data: ", data)
    # Remove the container
    container.remove()
    end = time.time()
    print("total time taken: ", end - start)
    # Return output to the user
    return JsonResponse({"output": output})
    except docker.errors.ContainerError as e:
    print(f"Error: {e}")
    return JsonResponse({"error": str(e)}, status=500)
    except Exception as e:
    print(f"Unexpected error: {e}")
    return JsonResponse({"error": "An unexpected error occurred"}, status=500)
    # return JsonResponse({"error": "Method not allowed"}, status=405)

    View Diff

  • Sweep has identified a redundant function: The new function is redundant because its functionality is already covered by the post method in CodeSubmitSimpleImplementation and the code_exec_engine function.
  • def post(self, request):
    """Submit code to execute in secure docker container."""
    lang = request.data.get("lang")
    code = request.data.get("code")
    input_file = request.data.get("input")
    testcases = request.data.get("testcases")
    # print('lang: ', lang)
    # print("code: ", code)
    # print("input file ", input_file)
    # print("testcases: ", testcases)
    # print('request.data: ', request.data)
    # print('\ntype of requst.data: ', type(request.data))
    # print('\ntype of code: ', type(code))
    # print('\ntype of input: ', type(input_file))
    submission_id = uuid.uuid4()
    data = code_exec_engine(user_codes=request.data, submission_id=submission_id)
    return JsonResponse({"submission_id": submission_id, "data": data}, status=200)

    View Diff


src/online_judge/urls.py

Added a new URL pattern for "submit/" and removed extensive comments from the URL configuration file.


@Mahboob-A
Copy link
Owner Author

Mahboob-A commented May 22, 2024

Run your local server.
cd to where your manage.py file is located and run:

python manage.py runserver 

POST request to the API 127.0.0.1:8000/submit/robust-execute/ as the following:

Screenshot from 2024-05-22 11-58-26

You will receive the response as following:

image

@Mahboob-A
Copy link
Owner Author

The logs are generated as below:

Screenshot from 2024-05-22 12-28-42

@Mahboob-A Mahboob-A merged commit 4035feb into main May 22, 2024
@Mahboob-A
Copy link
Owner Author

Sweep: PR Review

Authors of pull request: @Mahboob-A

src/core_apps/judge_engine/views.py
Introduced two new API classes for handling code submissions using Docker containers, with detailed error handling and file operations.

Sweep Found These Issues

  • The CodeSubmitSimpleImplementation class does not handle the cleanup of the created files in the host system, which could lead to disk space issues over time.
    file_path = f"user-files/{random.randint(10, 100000)}"
    curr_path = os.getcwd()
    print("curr path: ", os.getcwd())
    new_file_path = os.path.join(curr_path, file_path)

View Diff

  • The CodeSubmitSimpleImplementation class does not handle the cleanup of the created files in the host system, which could lead to disk space issues over time.
    file_path = f"user-files/{random.randint(10, 100000)}"
    curr_path = os.getcwd()
    print("curr path: ", os.getcwd())
    new_file_path = os.path.join(curr_path, file_path)

View Diff

  • Sweep has identified a redundant function: The new function is redundant because its functionality is already covered by the _run_container method in CodeContainerHandler and the post method in CodeSubmitRobustAPI.
    def post(self, request):
    start = time.time()
    lang = request.data.get("lang")
    code = request.data.get("code")
    input_data = request.data.get("input")
    print("Code: ", code)
    client = from_env()
    file_path = f"user-files/{random.randint(10, 100000)}"
    curr_path = os.getcwd()
    print("curr path: ", os.getcwd())
    new_file_path = os.path.join(curr_path, file_path)
    try:
    # Create and start a container
    container = client.containers.run(
    "simple_cpp", # Image name
    volumes={
    f"{new_file_path}/": {
    "bind": "/user-files",
    "mode": "rw",
    }
    },
    command=[
    "sh",
    "-c",
    f'echo "{code}" > /user-files/code.cpp && echo "{input_data}" > /user-files/input.txt && g++ /user-files/code.cpp -o /user-files/code && /user-files/code < /user-files/input.txt > /user-files/output.txt',
    ],
    detach=True,
    )
    # Wait for the container to finish
    result = container.wait()
    print("result: ", result)
    # Get the logs (output)
    output = container.logs().decode("utf-8")
    with open(f"{new_file_path}/output.txt", "r") as f:
    data = f.read()
    print("data: ", data)
    # Remove the container
    container.remove()
    end = time.time()
    print("total time taken: ", end - start)
    # Return output to the user
    return JsonResponse({"output": output})
    except docker.errors.ContainerError as e:
    print(f"Error: {e}")
    return JsonResponse({"error": str(e)}, status=500)
    except Exception as e:
    print(f"Unexpected error: {e}")
    return JsonResponse({"error": "An unexpected error occurred"}, status=500)
    # return JsonResponse({"error": "Method not allowed"}, status=405)

View Diff

  • Sweep has identified a redundant function: The new function is redundant because its functionality is already covered by the post method in CodeSubmitSimpleImplementation and the code_exec_engine function.
    def post(self, request):
    """Submit code to execute in secure docker container."""
    lang = request.data.get("lang")
    code = request.data.get("code")
    input_file = request.data.get("input")
    testcases = request.data.get("testcases")
    # print('lang: ', lang)
    # print("code: ", code)
    # print("input file ", input_file)
    # print("testcases: ", testcases)
    # print('request.data: ', request.data)
    # print('\ntype of requst.data: ', type(request.data))
    # print('\ntype of code: ', type(code))
    # print('\ntype of input: ', type(input_file))
    submission_id = uuid.uuid4()
    data = code_exec_engine(user_codes=request.data, submission_id=submission_id)
    return JsonResponse({"submission_id": submission_id, "data": data}, status=200)

View Diff

src/online_judge/urls.py
Added a new URL pattern for "submit/" and removed extensive comments from the URL configuration file.

The files can not be deleted in case of using the simple API approach. hence please use the Robust API.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant