tasks.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576
  1. """
  2. Task Management API endpoints
  3. Provides endpoints for:
  4. - GET /api/tasks - Get paginated list of tasks with status filtering
  5. - POST /api/tasks/create - Create a new scan task
  6. - GET /api/tasks/detail - Get task details
  7. - POST /api/tasks/delete - Delete a task
  8. - GET /api/tasks/logs - Get task logs with pagination
  9. Requirements: 3.1, 3.4
  10. """
  11. import os
  12. from flask import jsonify, request, current_app
  13. from werkzeug.utils import secure_filename
  14. from app import db
  15. from app.api import api_bp
  16. from app.models import Task, TaskLog, AWSCredential, UserCredential
  17. from app.services import login_required, admin_required, get_current_user_from_context, check_credential_access
  18. from app.errors import ValidationError, NotFoundError, AuthorizationError
  19. ALLOWED_IMAGE_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif', 'bmp'}
  20. def allowed_file(filename: str) -> bool:
  21. """Check if file extension is allowed for network diagram"""
  22. return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_IMAGE_EXTENSIONS
  23. @api_bp.route('/tasks', methods=['GET'])
  24. @login_required
  25. def get_tasks():
  26. """
  27. Get paginated list of tasks with optional status filtering.
  28. Query Parameters:
  29. page: Page number (default: 1)
  30. page_size: Items per page (default: 20, max: 100)
  31. status: Optional filter by status (pending, running, completed, failed)
  32. Returns:
  33. JSON with 'data' array and 'pagination' object
  34. """
  35. current_user = get_current_user_from_context()
  36. # Get pagination parameters
  37. page = request.args.get('page', 1, type=int)
  38. # Support both pageSize (frontend) and page_size (backend convention)
  39. page_size = request.args.get('pageSize', type=int) or request.args.get('page_size', type=int) or 20
  40. page_size = min(page_size, 100)
  41. status = request.args.get('status', type=str)
  42. # Validate pagination
  43. if page < 1:
  44. page = 1
  45. if page_size < 1:
  46. page_size = 20
  47. # Build query based on user role
  48. if current_user.role in ['admin', 'power_user']:
  49. query = Task.query
  50. else:
  51. # Regular users can only see their own tasks
  52. query = Task.query.filter_by(created_by=current_user.id)
  53. # Apply status filter if provided
  54. if status and status in ['pending', 'running', 'completed', 'failed']:
  55. query = query.filter_by(status=status)
  56. # Order by created_at descending
  57. query = query.order_by(Task.created_at.desc())
  58. # Get total count
  59. total = query.count()
  60. total_pages = (total + page_size - 1) // page_size if total > 0 else 1
  61. # Apply pagination
  62. tasks = query.offset((page - 1) * page_size).limit(page_size).all()
  63. return jsonify({
  64. 'data': [task.to_dict() for task in tasks],
  65. 'pagination': {
  66. 'page': page,
  67. 'page_size': page_size,
  68. 'total': total,
  69. 'total_pages': total_pages
  70. }
  71. }), 200
  72. @api_bp.route('/tasks/create', methods=['POST'])
  73. @login_required
  74. def create_task():
  75. """
  76. Create a new scan task.
  77. Request Body (JSON or multipart/form-data):
  78. name: Task name (required)
  79. credential_ids: List of credential IDs to use (required)
  80. regions: List of AWS regions to scan (required)
  81. project_metadata: Project metadata object (required)
  82. - clientName: Client name (required)
  83. - projectName: Project name (required)
  84. - bdManager: BD Manager name (optional)
  85. - bdManagerEmail: BD Manager email (optional)
  86. - solutionsArchitect: Solutions Architect name (optional)
  87. - solutionsArchitectEmail: Solutions Architect email (optional)
  88. - cloudEngineer: Cloud Engineer name (optional)
  89. - cloudEngineerEmail: Cloud Engineer email (optional)
  90. network_diagram: Network diagram image file (optional, multipart only)
  91. Returns:
  92. JSON with created task details and task_id
  93. """
  94. current_user = get_current_user_from_context()
  95. # Handle both JSON and multipart/form-data
  96. if request.content_type and 'multipart/form-data' in request.content_type:
  97. data = request.form.to_dict()
  98. # Parse JSON fields from form data
  99. import json
  100. if 'credential_ids' in data:
  101. data['credential_ids'] = json.loads(data['credential_ids'])
  102. if 'regions' in data:
  103. data['regions'] = json.loads(data['regions'])
  104. if 'project_metadata' in data:
  105. data['project_metadata'] = json.loads(data['project_metadata'])
  106. network_diagram = request.files.get('network_diagram')
  107. else:
  108. data = request.get_json() or {}
  109. network_diagram = None
  110. # Validate required fields
  111. if not data.get('name'):
  112. raise ValidationError(
  113. message="Task name is required",
  114. details={"missing_fields": ["name"]}
  115. )
  116. credential_ids = data.get('credential_ids', [])
  117. if not credential_ids or not isinstance(credential_ids, list) or len(credential_ids) == 0:
  118. raise ValidationError(
  119. message="At least one credential must be selected",
  120. details={"missing_fields": ["credential_ids"]}
  121. )
  122. regions = data.get('regions', [])
  123. if not regions or not isinstance(regions, list) or len(regions) == 0:
  124. raise ValidationError(
  125. message="At least one region must be selected",
  126. details={"missing_fields": ["regions"]}
  127. )
  128. project_metadata = data.get('project_metadata', {})
  129. if not isinstance(project_metadata, dict):
  130. raise ValidationError(
  131. message="Project metadata must be an object",
  132. details={"field": "project_metadata", "reason": "invalid_type"}
  133. )
  134. # Validate required project metadata fields
  135. required_metadata = ['clientName', 'projectName']
  136. missing_metadata = [field for field in required_metadata if not project_metadata.get(field)]
  137. if missing_metadata:
  138. raise ValidationError(
  139. message="Missing required project metadata fields",
  140. details={"missing_fields": missing_metadata}
  141. )
  142. # Validate credential access for regular users
  143. for cred_id in credential_ids:
  144. if not check_credential_access(current_user, cred_id):
  145. raise AuthorizationError(
  146. message=f"Access denied to credential {cred_id}",
  147. details={"credential_id": cred_id, "reason": "not_assigned"}
  148. )
  149. # Verify credential exists and is active
  150. credential = db.session.get(AWSCredential, cred_id)
  151. if not credential:
  152. raise NotFoundError(
  153. message=f"Credential {cred_id} not found",
  154. details={"credential_id": cred_id}
  155. )
  156. if not credential.is_active:
  157. raise ValidationError(
  158. message=f"Credential {cred_id} is not active",
  159. details={"credential_id": cred_id, "reason": "inactive"}
  160. )
  161. # Handle network diagram upload
  162. network_diagram_path = None
  163. if network_diagram and network_diagram.filename:
  164. if not allowed_file(network_diagram.filename):
  165. raise ValidationError(
  166. message="Invalid file type for network diagram. Allowed: png, jpg, jpeg, gif, bmp",
  167. details={"field": "network_diagram", "reason": "invalid_file_type"}
  168. )
  169. # Save the file
  170. uploads_folder = current_app.config.get('UPLOAD_FOLDER', 'uploads')
  171. os.makedirs(uploads_folder, exist_ok=True)
  172. filename = secure_filename(network_diagram.filename)
  173. # Add timestamp to avoid conflicts
  174. import time
  175. filename = f"{int(time.time())}_{filename}"
  176. network_diagram_path = os.path.join(uploads_folder, filename)
  177. network_diagram.save(network_diagram_path)
  178. # Store path in project metadata
  179. project_metadata['network_diagram_path'] = network_diagram_path
  180. # Create task
  181. task = Task(
  182. name=data['name'].strip(),
  183. status='pending',
  184. progress=0,
  185. created_by=current_user.id
  186. )
  187. task.credential_ids = credential_ids
  188. task.regions = regions
  189. task.project_metadata = project_metadata
  190. db.session.add(task)
  191. db.session.commit()
  192. # Dispatch to Celery
  193. celery_task = None
  194. try:
  195. # 先测试Redis连接
  196. import redis
  197. print(f"🔍 测试Redis连接...")
  198. r = redis.Redis(host='localhost', port=6379, db=0)
  199. r.ping()
  200. print(f"✅ Redis连接成功")
  201. # 导入并初始化Celery应用
  202. from app.celery_app import celery_app, init_celery
  203. init_celery(current_app._get_current_object())
  204. print(f"✅ Celery初始化完成, broker: {celery_app.conf.broker_url}")
  205. # 导入Celery任务
  206. from app.tasks.scan_tasks import scan_aws_resources
  207. print(f"✅ 任务模块导入成功")
  208. # 提交任务
  209. print(f"🔍 提交任务到Celery队列...")
  210. celery_task = scan_aws_resources.delay(
  211. task_id=task.id,
  212. credential_ids=credential_ids,
  213. regions=regions,
  214. project_metadata=project_metadata
  215. )
  216. print(f"✅ 任务已提交: {celery_task.id}")
  217. except redis.ConnectionError as e:
  218. # Redis连接失败,删除已创建的任务并返回错误
  219. db.session.delete(task)
  220. db.session.commit()
  221. raise ValidationError(
  222. message="Redis服务不可用,无法创建任务。请确保Redis服务已启动。",
  223. details={"error": str(e)}
  224. )
  225. except Exception as e:
  226. # 其他错误
  227. db.session.delete(task)
  228. db.session.commit()
  229. raise ValidationError(
  230. message="任务提交失败",
  231. details={"error": str(e), "error_type": type(e).__name__}
  232. )
  233. # Store Celery task ID
  234. task.celery_task_id = celery_task.id
  235. db.session.commit()
  236. return jsonify({
  237. 'message': 'Task created successfully',
  238. 'task': task.to_dict(),
  239. 'celery_task_id': celery_task.id
  240. }), 201
  241. @api_bp.route('/tasks/detail', methods=['GET'])
  242. @login_required
  243. def get_task_detail():
  244. """
  245. Get task details including current status and progress.
  246. Query Parameters:
  247. id: Task ID (required)
  248. Returns:
  249. JSON with task details
  250. """
  251. current_user = get_current_user_from_context()
  252. task_id = request.args.get('id', type=int)
  253. if not task_id:
  254. raise ValidationError(
  255. message="Task ID is required",
  256. details={"missing_fields": ["id"]}
  257. )
  258. task = db.session.get(Task, task_id)
  259. if not task:
  260. raise NotFoundError(
  261. message="Task not found",
  262. details={"task_id": task_id}
  263. )
  264. # Check access for regular users
  265. if current_user.role == 'user' and task.created_by != current_user.id:
  266. raise AuthorizationError(
  267. message="Access denied",
  268. details={"reason": "not_owner"}
  269. )
  270. # Get task details with additional info
  271. task_dict = task.to_dict()
  272. # Add report info if available
  273. if task.report:
  274. task_dict['report'] = task.report.to_dict()
  275. # Add error count
  276. error_count = TaskLog.query.filter_by(task_id=task_id, level='error').count()
  277. task_dict['error_count'] = error_count
  278. # Get Celery task status if running
  279. if task.status == 'running' and task.celery_task_id:
  280. from celery.result import AsyncResult
  281. from app.celery_app import celery_app
  282. result = AsyncResult(task.celery_task_id, app=celery_app)
  283. if result.state == 'PROGRESS':
  284. task_dict['celery_progress'] = result.info
  285. return jsonify(task_dict), 200
  286. @api_bp.route('/tasks/delete', methods=['POST'])
  287. @login_required
  288. def delete_task():
  289. """
  290. Delete a task and its associated logs and report.
  291. Request Body:
  292. id: Task ID (required)
  293. Returns:
  294. JSON with success message
  295. """
  296. current_user = get_current_user_from_context()
  297. data = request.get_json() or {}
  298. task_id = data.get('id')
  299. if not task_id:
  300. raise ValidationError(
  301. message="Task ID is required",
  302. details={"missing_fields": ["id"]}
  303. )
  304. task = db.session.get(Task, task_id)
  305. if not task:
  306. raise NotFoundError(
  307. message="Task not found",
  308. details={"task_id": task_id}
  309. )
  310. # Check access - only admin or task owner can delete
  311. if current_user.role != 'admin' and task.created_by != current_user.id:
  312. raise AuthorizationError(
  313. message="Access denied",
  314. details={"reason": "not_owner_or_admin"}
  315. )
  316. # Cannot delete running tasks
  317. if task.status == 'running':
  318. raise ValidationError(
  319. message="Cannot delete a running task",
  320. details={"task_id": task_id, "status": task.status}
  321. )
  322. # Delete associated report file if exists
  323. if task.report and task.report.file_path:
  324. try:
  325. if os.path.exists(task.report.file_path):
  326. os.remove(task.report.file_path)
  327. except OSError:
  328. pass # File may already be deleted
  329. # Delete task (cascade will handle logs and report)
  330. db.session.delete(task)
  331. db.session.commit()
  332. return jsonify({
  333. 'message': 'Task deleted successfully'
  334. }), 200
  335. @api_bp.route('/tasks/logs', methods=['GET'])
  336. @login_required
  337. def get_task_logs():
  338. """
  339. Get paginated task logs.
  340. Query Parameters:
  341. id: Task ID (required)
  342. page: Page number (default: 1)
  343. page_size: Items per page (default: 20, max: 100)
  344. level: Optional filter by log level (info, warning, error)
  345. Returns:
  346. JSON with 'data' array and 'pagination' object
  347. Requirements:
  348. - 8.3: Display error logs associated with task
  349. """
  350. current_user = get_current_user_from_context()
  351. task_id = request.args.get('id', type=int)
  352. if not task_id:
  353. raise ValidationError(
  354. message="Task ID is required",
  355. details={"missing_fields": ["id"]}
  356. )
  357. task = db.session.get(Task, task_id)
  358. if not task:
  359. raise NotFoundError(
  360. message="Task not found",
  361. details={"task_id": task_id}
  362. )
  363. # Check access for regular users
  364. if current_user.role == 'user' and task.created_by != current_user.id:
  365. raise AuthorizationError(
  366. message="Access denied",
  367. details={"reason": "not_owner"}
  368. )
  369. # Get pagination parameters
  370. page = request.args.get('page', 1, type=int)
  371. # Support both pageSize (frontend) and page_size (backend convention)
  372. page_size = request.args.get('pageSize', type=int) or request.args.get('page_size', type=int) or 20
  373. page_size = min(page_size, 100)
  374. level = request.args.get('level', type=str)
  375. # Validate pagination
  376. if page < 1:
  377. page = 1
  378. if page_size < 1:
  379. page_size = 20
  380. # Build query
  381. query = TaskLog.query.filter_by(task_id=task_id)
  382. # Apply level filter if provided
  383. if level and level in ['info', 'warning', 'error']:
  384. query = query.filter_by(level=level)
  385. # Order by created_at descending
  386. query = query.order_by(TaskLog.created_at.desc())
  387. # Get total count
  388. total = query.count()
  389. total_pages = (total + page_size - 1) // page_size if total > 0 else 1
  390. # Apply pagination
  391. logs = query.offset((page - 1) * page_size).limit(page_size).all()
  392. return jsonify({
  393. 'data': [log.to_dict() for log in logs],
  394. 'pagination': {
  395. 'page': page,
  396. 'page_size': page_size,
  397. 'total': total,
  398. 'total_pages': total_pages
  399. }
  400. }), 200
  401. @api_bp.route('/tasks/errors', methods=['GET'])
  402. @login_required
  403. def get_task_errors():
  404. """
  405. Get error logs for a specific task.
  406. This is a convenience endpoint that returns only error-level logs
  407. with full details including stack traces.
  408. Query Parameters:
  409. id: Task ID (required)
  410. page: Page number (default: 1)
  411. page_size: Items per page (default: 20, max: 100)
  412. Returns:
  413. JSON with 'data' array containing error logs and 'pagination' object
  414. Requirements:
  415. - 8.2: Record error details in task record
  416. - 8.3: Display error logs associated with task
  417. """
  418. current_user = get_current_user_from_context()
  419. task_id = request.args.get('id', type=int)
  420. if not task_id:
  421. raise ValidationError(
  422. message="Task ID is required",
  423. details={"missing_fields": ["id"]}
  424. )
  425. task = db.session.get(Task, task_id)
  426. if not task:
  427. raise NotFoundError(
  428. message="Task not found",
  429. details={"task_id": task_id}
  430. )
  431. # Check access for regular users
  432. if current_user.role == 'user' and task.created_by != current_user.id:
  433. raise AuthorizationError(
  434. message="Access denied",
  435. details={"reason": "not_owner"}
  436. )
  437. # Get pagination parameters
  438. page = request.args.get('page', 1, type=int)
  439. # Support both pageSize (frontend) and page_size (backend convention)
  440. page_size = request.args.get('pageSize', type=int) or request.args.get('page_size', type=int) or 20
  441. page_size = min(page_size, 100)
  442. # Validate pagination
  443. if page < 1:
  444. page = 1
  445. if page_size < 1:
  446. page_size = 20
  447. # Build query for error logs only
  448. query = TaskLog.query.filter_by(task_id=task_id, level='error')
  449. # Order by created_at descending
  450. query = query.order_by(TaskLog.created_at.desc())
  451. # Get total count
  452. total = query.count()
  453. total_pages = (total + page_size - 1) // page_size if total > 0 else 1
  454. # Apply pagination
  455. logs = query.offset((page - 1) * page_size).limit(page_size).all()
  456. # Build response with full error details
  457. error_data = []
  458. for log in logs:
  459. log_dict = log.to_dict()
  460. # Ensure details are included for error analysis
  461. error_data.append(log_dict)
  462. return jsonify({
  463. 'data': error_data,
  464. 'pagination': {
  465. 'page': page,
  466. 'page_size': page_size,
  467. 'total': total,
  468. 'total_pages': total_pages
  469. },
  470. 'summary': {
  471. 'total_errors': total,
  472. 'task_status': task.status
  473. }
  474. }), 200