"""状态检查任务""" import traceback from app.core.celery_app import celery_app from app.core.database import SessionLocal from app.services.check_service import CheckService @celery_app.task(bind=True) def check_all_devices(self): """检查所有设备状态""" db = SessionLocal() self.update_state(state='PROGRESS', meta={'current': 0, 'total': 0, 'status': '获取OLT列表...'}) try: service = CheckService(db) from app.models.device import OLTDevice olts = db.query(OLTDevice).all() total = len(olts) self.update_state(state='PROGRESS', meta={'current': 0, 'total': total, 'status': f'准备检查 {total} 个OLT...'}) results = [] errors = [] total_online = 0 total_offline = 0 for idx, olt in enumerate(olts): self.update_state(state='PROGRESS', meta={ 'current': idx, 'total': total, 'status': f'检查 OLT: {olt.location or olt.ip_address}...' }) try: result = service.update_status_only(olt.id) total_online += result.get('online', 0) total_offline += result.get('offline', 0) results.append({ 'olt_id': olt.id, 'olt_name': olt.location or olt.ip_address, 'online': result.get('online', 0), 'offline': result.get('offline', 0), 'success': True }) except Exception as e: errors.append({ 'olt_id': olt.id, 'olt_name': olt.location or olt.ip_address, 'error': str(e) }) results.append({ 'olt_id': olt.id, 'olt_name': olt.location or olt.ip_address, 'success': False, 'error': str(e) }) self.update_state(state='PROGRESS', meta={'current': total, 'total': total, 'status': '检查完成'}) return { 'success': True, 'total_olts': total, 'total_online': total_online, 'total_offline': total_offline, 'results': results, 'errors': errors } except Exception as e: return { 'success': False, 'error': str(e), 'traceback': traceback.format_exc() } finally: db.close()