Develop a computational course infra: autograding, containerized environments, resource…
- User
Develop a computational course infra: autograding, containerized environments, resource quotas, and support tickets.
Assistant
Develop a computational course infra: autograding, containerized environments, resource quotas, and support tickets.
The user wants a computational course infrastructure. This involves:
This is a significant architectural request. I need to provide a high-level design, technology choices, and potentially some implementation skeletons or examples.
Key Components:
Frontend/Interface:
Backend/API:
Execution Engine (The Core):
Database:
Support System:
Drafting the Architecture:
python:3.9-slim, etc.Implementation Steps/Code Structure:
Directory Structure:
app/ (Backend code)worker/ (Grading logic)assignments/ (Example assignment configs)docker/ (Dockerfiles)Autograding Logic:
Resource Quotas:
docker run --memory="256m" --cpus="0.5" --pids-limit=50 ...Support Tickets:
POST /api/tickets.Ticket(user_id, subject, body, status).Refining the Tech Stack for the "MVP" (Minimum Viable Product):
Detailed Design - The "Grader" Worker: This is the hardest part.
--network=none).Structuring the Response: I will structure this as a comprehensive technical design document with code examples.
Self-Correction/Refinement during thought process:
setrlimit inside the container or strictly via Docker flags is important. Network isolation is non-negotiable.Code snippets to generate:
docker-py).Let's write the response. I'll aim for a modular, extensible design.
Focus Areas:
fork bombs, crypto miners, or access to host files.Let's assemble the pieces.
{
"image": "python:3.11-slim",
"setup": "pip install pytest",
"run_command": "python test_runner.py",
"timeout": 30,
"mem_limit": "256m"
}
container = client.containers.run(
image,
command,
volumes={'/sub': {'bind': '/home/user/sub', 'mode': 'rw'}},
mem_limit=quota,
cpu_period=100000, cpu_quota=50000, # 50%
network_disabled=True,
remove=True,
detach=True
)
The request asks to "Develop" it. I should provide a robust skeleton project structure.
Plan:
This looks solid. I will write the code with comments explaining the "why". The Docker part needs to be very specific about security.
Self-Correction on Code Complexity: Keep the frontend out of it to keep the response focused on the infrastructure. Use curl commands or simple API descriptions.
Support Tickets: Integrate into the DB schema.
Autograding output: Standard JSON format used by tools like Gradescope is good inspiration: { "score": 10, "tests": [...] }.
Let's go. This is a comprehensive architectural design and implementation skeleton for a Computational Course Infrastructure. This system is designed to securely handle code submissions, execute them in isolated environments, enforce resource limits, and manage student support.
We will use a Microservices-ish architecture utilizing Docker for isolation and Python (FastAPI) for the API logic.
course-infra/
├── api/ # Main FastAPI Application
│ ├── main.py # Routes for Submission & Tickets
│ ├── models.py # Database Schemas
│ └── requirements.txt
├── worker/ # Autograding Logic
│ ├── grader.py # Consumes queue & runs docker
│ └── gradescope_style/ # Example autograder logic
├── assignments/ # Configuration for specific assignments
│ └── hw1/ # Example Assignment
│ ├── config.json # Limits (CPU/Mem)
│ └── setup.sh # Dependencies
├── docker-compose.yml # Infrastructure orcheststration
└── Dockerfile.worker # The worker environment
To support flexible resource quotas, we define assignments via JSON.
assignments/hw1/config.json
{
"assignment_id": "hw1",
"image": "python:3.9-slim",
"max_memory_mb": 256,
"cpu_quota": 25000, // 25% of CPU (Docker uses 100,000 for 1 full CPU)
"timeout_seconds": 10,
"tests": [
{"name": "test_addition", "input": "5 5", "expected_output": "10"},
{"name": "test_failure", "input": "1 1", "expected_output": "2"}
]
}
This is the critical security component. It pulls a job, creates a temporary container, enforces quotas, and captures results.
worker/grader.py
import docker
import json
import os
import time
import redis
# Connect to Docker Daemon and Redis
client = docker.from_env()
redis_client = redis.Redis(host='redis', port=6379, db=0)
def grade_submission(job_data):
submission_id = job_data['submission_id']
student_code = job_data['code']
config = json.load(open(f"../assignments/{job_data['assignment_id']}/config.json"))
print(f"Grading {submission_id}...")
# 1. Create a temporary directory for the submission
temp_dir = f"/tmp/{submission_id}"
os.makedirs(temp_dir, exist_ok=True)
# Write student code to a file
with open(f"{temp_dir}/main.py", "w") as f:
f.write(student_code)
# 2. Define Resource Quotas (Security)
host_config = client.containers.create_host_config(
mem_limit=f"{config['max_memory_mb']}m",
cpu_quota=config['cpu_quota'],
network_disabled=True, # Disable internet access
read_only_rootfs=False, # Set True if you want immutable container FS
binds={temp_dir: {'bind': '/app/student', 'mode': 'rw'}}
)
results = []
# 3. Run against test cases
for test in config['tests']:
try:
# Run the container
container = client.containers.run(
config['image'],
command=f"python /app/student/main.py", # Simplified command
volumes={temp_dir: {'bind': '/app/student', 'mode': 'rw'}},
mem_limit=f"{config['max_memory_mb']}m",
cpu_quota=config['cpu_quota'],
network_disabled=True,
remove=True,
timeout=config['timeout_seconds'],
environment={"INPUT": test['input']}
)
output = container.decode('utf-8').strip()
passed = output == test['expected_output']
results.append({
"test": test['name'],
"passed": passed,
"output": output
})
except docker.errors.ContainerError as e:
results.append({"test": test['name'], "passed": False, "error": "Runtime Error", "logs": str(e)})
except docker.errors.APIError as e:
results.append({"test": test['name'], "passed": False, "error": "Docker API Error"})
except Exception as e:
results.append({"test": test['name'], "passed": False, "error": str(e)})
# 4. Cleanup and Save Result
# Ideally, write result to DB here.
print(f"Finished {submission_id}. Results: {results}")
return results
def listen():
print("Worker listening for jobs...")
while True:
# Blocking pop from Redis queue
_, job = redis_client.blpop('grading_queue')
job_data = json.loads(job)
grade_submission(job_data)
if __name__ == "__main__":
listen()
We use FastAPI to handle the submission of code and the management of support tickets.
api/main.py
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
import redis
import json
import uuid
from typing import List, Optional
# Mock Database
fake_db = {
"submissions": {},
"tickets": []
}
app = FastAPI(title="Course Infrastructure API")
r = redis.Redis(host='redis', port=6379, db=0)
# --- Models ---
class Submission(BaseModel):
student_id: str
assignment_id: str
code: str
class Ticket(BaseModel):
student_id: str
subject: str
message: str
class TicketUpdate(BaseModel):
status: str # "open", "resolved"
response: Optional[str] = None
# --- Routes ---
@app.post("/submit")
def submit_code(sub: Submission):
"""Receives code, pushes to queue, returns submission ID."""
sub_id = str(uuid.uuid4())
job = {
"submission_id": sub_id,
"assignment_id": sub.assignment_id,
"code": sub.code,
"student_id": sub.student_id
}
# Push to Redis Queue (Producer)
r.rpush('grading_queue', json.dumps(job))
fake_db["submissions"][sub_id] = {"status": "queued", "result": None}
return {"status": "queued", "submission_id": sub_id}
@app.get("/result/{sub_id}")
def get_result(sub_id: str):
"""Polls for grading result."""
# In real prod, query DB updated by worker
# Here we just mock it or check local memory for demo
return fake_db["submissions"].get(sub_id, {"error": "Not found"})
# --- Support Ticket System ---
@app.post("/tickets")
def create_ticket(ticket: Ticket):
"""Allows students to raise issues."""
ticket_id = str(uuid.uuid4())
ticket_entry = {
"ticket_id": ticket_id,
"student_id": ticket.student_id,
"subject": ticket.subject,
"message": ticket.message,
"status": "open",
"thread": []
}
fake_db["tickets"].append(ticket_entry)
return {"status": "created", "ticket_id": ticket_id}
@app.get("/tickets/{student_id}")
def get_student_tickets(student_id: str):
"""Retrieve all tickets for a student."""
return [t for t in fake_db["tickets"] if t["student_id"] == student_id]
@app.patch("/tickets/{ticket_id}")
def update_ticket(ticket_id: str, update: TicketUpdate):
"""Instructor responds or closes ticket."""
for t in fake_db["tickets"]:
if t["ticket_id"] == ticket_id:
t["status"] = update.status
if update.response:
t["thread"].append(update.response)
return t
raise HTTPException(status_code=404, detail="Ticket not found")
This spins up the API, the Redis queue, and the grading worker.
docker-compose.yml
version: '3.8'
services:
# The API Gateway
api:
build: ./api
ports:
- "8000:8000"
volumes:
- ./api:/app
depends_on:
- redis
# The Job Queue
redis:
image: redis:alpine
ports:
- "6379:6379"
# The Grading Worker
worker:
build:
context: .
dockerfile: Dockerfile.worker
volumes:
- /var/run/docker.sock:/var/run/docker.sock # CRITICAL: Allows worker to spawn siblings
- ./assignments:/app/assignments
- ./worker:/app
depends_on:
- redis
volumes:
db_data:
Dockerfile.worker
FROM python:3.9-slim
# Install Docker CLI inside the worker so it can control the host daemon
RUN apt-get update && apt-get install -y docker.io
COPY ./worker/requirements.txt /app/requirements.txt
RUN pip install -r /app/requirements.txt
COPY ./worker /app
WORKDIR /app
CMD ["python", "grader.py"]
The most critical aspect of computational infra is preventing students from breaking the server.
network_disabled=True in docker.containers.run prevents students from making HTTP requests (e.g., to phone home or cheat).userns-remap). This ensures that root inside the student container maps to an unprivileged user on the host machine.mem_limit="256m". If the code tries to allocate more, the OOM (Out of Memory) Killer in the Linux kernel kills the container process immediately.cpu_quota=25000. This defines a slice of CPU time. 100,000 = 1 full core. 25,000 = 25% of a core.While not implemented in the basic script above, in production you should add:
device_read_bps=1024*1024, # Limit read to 1MB/s
device_write_bps=1024*1024 # Limit write to 1MB/s
docker-compose up --build
curl -X 'POST' \
'http://localhost:8000/submit' \
-H 'Content-Type: application/json' \
-d '{
"student_id": "user_123",
"assignment_id": "hw1",
"code": "print(input())"
}'
fake_db with PostgreSQL or MongoDB.stdout/stderr to S3 buckets for students to debug their failed attempts.