Long Long Int。 2025-10-20 15:06 采纳率: 0%
浏览 4

domjudge压力测试返回500

我使用docker compose搭建了8.3.1版本的domjudge评测系统,准备举行比赛,在此之前,我使用domjudge系统的api准备模拟用户并行提交进行压力测试,presstest.py是我的压测脚本,使用API登录成功了,但使用api提交代码是返回500错误,请问是为什么

#!/usr/bin/env python3
"""
DOMjudge 压力测试脚本
用于模拟多个用户同时提交代码
"""

import requests
import threading
import time
import random
import json
from requests.auth import HTTPBasicAuth
import sys
import io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')

class DOMjudgeStressTester:
    def __init__(self, base_url, username_prefix, password, num_users=200):
        self.base_url = base_url.rstrip('/')
        self.username_prefix = username_prefix
        self.password = password
        self.num_users = num_users
        self.results = []
        self.lock = threading.Lock()
        
    def submit_solution(self, user_id, problem_id, language_id, source_code):
        """提交解决方案"""
        username = f"{self.username_prefix}{user_id+8:03d}"
        
        # DOMjudge API 端点
        submit_url = f"{self.base_url}/api/v4/contests/3/submissions"
        
        # 准备提交数据
        payload = {
            "problem_id": problem_id,
            "language_id": language_id,
            "code": source_code
        }
        
        headers = {
            "Content-Type": "application/json",
            "Accept": "application/json"
        }
        
        auth = HTTPBasicAuth(username, self.password)
        
        start_time = time.time()
        try:
            response = requests.post(
                submit_url,
                json=payload,
                headers=headers,
                auth=auth,
                timeout=30
            )
            end_time = time.time()
            response_time = end_time - start_time
            
            if response.status_code == 200:
                result = {
                    "user_id": user_id,
                    "username": username,
                    "status": "success",
                    "response_time": response_time,
                    "submission_id": response.json().get("id", "unknown")
                }
                print(f"✓ 用户 {username} 提交成功 (响应时间: {response_time:.2f}s)")
            else:
                result = {
                    "user_id": user_id,
                    "username": username,
                    "status": f"failed - HTTP {response.status_code}",
                    "response_time": response_time,
                    "error": response.text
                }
                print(f"✗ 用户 {username} 提交失败: {response.status_code}")
                print(f"错误信息: {response.text}")
                
        except requests.exceptions.RequestException as e:
            end_time = time.time()
            response_time = end_time - start_time
            result = {
                "user_id": user_id,
                "username": username,
                "status": f"error - {str(e)}",
                "response_time": response_time
            }
            print(f"✗ 用户 {username} 请求异常: {str(e)}")
        
        with self.lock:
            self.results.append(result)
        
        return result
    
    def worker(self, user_id, problem_id, language_id, source_code):
        """工作线程函数"""
        time.sleep(random.uniform(0, 2))  # 随机延迟,模拟真实用户行为
        return self.submit_solution(user_id, problem_id, language_id, source_code)
    
    def run_stress_test(self, problem_id, language_id, source_code_file):
        """运行压力测试"""
        print(f"开始压力测试: {self.num_users} 个用户同时提交")
        print("=" * 50)
        
        # 读取源代码文件
        try:
            with open(source_code_file, 'r') as f:
                source_code = f.read()
        except FileNotFoundError:
            print(f"错误: 找不到源代码文件 {source_code_file}")
            return
        
        # 创建并启动线程
        threads = []
        start_time = time.time()
        
        for i in range(self.num_users):
            thread = threading.Thread(
                target=self.worker,
                args=(i + 1, problem_id, language_id, source_code)
            )
            threads.append(thread)
            thread.start()
        
        # 等待所有线程完成
        for thread in threads:
            thread.join()
        
        total_time = time.time() - start_time
        
        # 打印统计结果
        self.print_statistics(total_time)
    
    def print_statistics(self, total_time):
        """打印统计信息"""
        print("\n" + "=" * 50)
        print("压力测试完成!")
        print("=" * 50)
        
        successful = len([r for r in self.results if r["status"] == "success"])
        failed = len(self.results) - successful
        
        print(f"总用户数: {self.num_users}")
        print(f"成功提交: {successful}")
        print(f"失败提交: {failed}")
        print(f"总耗时: {total_time:.2f} 秒")
        
        if successful > 0:
            response_times = [r["response_time"] for r in self.results if r["status"] == "success"]
            avg_response_time = sum(response_times) / len(response_times)
            max_response_time = max(response_times)
            min_response_time = min(response_times)
            
            print(f"平均响应时间: {avg_response_time:.2f} 秒")
            print(f"最小响应时间: {min_response_time:.2f} 秒")
            print(f"最大响应时间: {max_response_time:.2f} 秒")
            print(f"吞吐量: {successful / total_time:.2f} 提交/秒")

if __name__ == "__main__":
    # 配置参数 - 请根据你的实际情况修改
    CONFIG = {
        "base_url": "http://192.168.53.202:8080",  # DOMjudge 地址
        "username_prefix": "team",             # 用户名前缀
        "password": "123456",                # 用户密码
        "num_users": 10,                      # 用户数量
        "problem_id": "8",                     # 题目ID
        "language_id": "cpp",                  # 语言ID (cpp, java, python等)
        "source_code_file": "E://press/1.cpp"     # 源代码文件路径
    }
    
    # 创建测试器并运行
    tester = DOMjudgeStressTester(
        base_url=CONFIG["base_url"],
        username_prefix=CONFIG["username_prefix"],
        password=CONFIG["password"],
        num_users=CONFIG["num_users"]
    )
    
    tester.run_stress_test(
        problem_id=CONFIG["problem_id"],
        language_id=CONFIG["language_id"],
        source_code_file=CONFIG["source_code_file"]
    )

  • 写回答

3条回答 默认 最新

  • 阿里嘎多学长 2025-10-20 15:55
    关注

    阿里嘎多学长整理AIGC生成,因移动端显示问题导致当前答案未能完全显示,请使用PC端查看更加详细的解答过程

    解决方案

    根据你的描述,domjudge系统在压力测试时返回500错误,这可能是由于系统资源不足或配置问题导致的。以下是一些可能的解决方案:

    1. 检查系统资源: 确保系统有足够的内存和CPU资源来处理并行提交的压力测试。可以使用 tophtop 命令检查系统当前的资源使用情况。
    2. 调整docker-compose配置: 检查docker-compose配置文件是否正确配置,确保系统有足够的资源分配给domjudge容器。可以尝试增加容器的内存和CPU资源限制。
    3. 检查presstest.py脚本: 检查presstest.py脚本是否正确配置,确保脚本正确地模拟用户并行提交。可以尝试使用 pdb 调试脚本来检查是否有任何错误。
    4. 检查domjudge配置: 检查domjudge配置文件是否正确配置,确保系统的配置正确。可以尝试使用 domjudge-admin 命令来检查系统的配置。

    核心代码

    如果你需要调整docker-compose配置,可以尝试以下代码:

    version: '3'
    services:
      domjudge:
        image: domjudge/domjudge:8.3.1
        restart: always
        environment:
          - DOMJUDGE_MEM_LIMIT=1024m
          - DOMJUDGE_CPU_LIMIT=2
        ports:
          - "80:80"
    

    在上面的代码中,我们增加了 DOMJUDGE_MEM_LIMITDOMJUDGE_CPU_LIMIT 环境变量来限制domjudge容器的内存和CPU资源。

    如果你需要使用 pdb 调试presstest.py脚本,可以尝试以下代码:

    import pdb
    
    # ...
    
    pdb.set_trace()
    

    在上面的代码中,我们使用 pdb.set_trace() 来设置断点,允许我们使用 pdb 命令来调试脚本。

    评论

报告相同问题?

问题事件

  • 创建了问题 10月20日