@@ -384,137 +384,3 @@ def _maybe_restart_bot(self, bot):
384384 logger .info (f"Запланирован перезапуск бота { bot .name } после изменения обработчиков" )
385385 except Exception as e :
386386 logger .error (f"Ошибка планирования перезапуска бота { bot .id } : { e } " )
387-
388-
389- class BotControlViewSet (viewsets .ViewSet ):
390- """
391- ViewSet для массового управления ботами
392- """
393- permission_classes = [permissions .IsAuthenticated ]
394-
395- @action (detail = False , methods = ['post' ])
396- def bulk_start (self , request ):
397- """
398- Массовый запуск ботов
399- POST /api/control/bulk_start/
400- """
401- serializer = BotControlSerializer (data = request .data )
402-
403- if not serializer .is_valid ():
404- return Response (serializer .errors , status = status .HTTP_400_BAD_REQUEST )
405-
406- bot_ids = serializer .validated_data ['bot_ids' ]
407- results = []
408-
409- for bot_id in bot_ids :
410- try :
411- bot = TelegramBot .objects .get (id = bot_id )
412-
413- if not bot .is_active :
414- results .append ({'bot_id' : bot_id , 'status' : 'skipped' , 'reason' : 'not_active' })
415- continue
416-
417- if bot .is_running :
418- results .append ({'bot_id' : bot_id , 'status' : 'skipped' , 'reason' : 'already_running' })
419- continue
420-
421- task_id = BotService .start_bot (bot_id )
422- results .append ({'bot_id' : bot_id , 'status' : 'started' , 'task_id' : task_id })
423-
424- except TelegramBot .DoesNotExist :
425- results .append ({'bot_id' : bot_id , 'status' : 'error' , 'reason' : 'not_found' })
426- except Exception as e :
427- results .append ({'bot_id' : bot_id , 'status' : 'error' , 'reason' : str (e )})
428-
429- return Response ({'results' : results })
430-
431- @action (detail = False , methods = ['post' ])
432- def bulk_stop (self , request ):
433- """
434- Массовая остановка ботов
435- POST /api/control/bulk_stop/
436- """
437- serializer = BotControlSerializer (data = request .data )
438-
439- if not serializer .is_valid ():
440- return Response (serializer .errors , status = status .HTTP_400_BAD_REQUEST )
441-
442- bot_ids = serializer .validated_data ['bot_ids' ]
443- results = []
444-
445- for bot_id in bot_ids :
446- try :
447- bot = TelegramBot .objects .get (id = bot_id )
448-
449- if not bot .is_running :
450- results .append ({'bot_id' : bot_id , 'status' : 'skipped' , 'reason' : 'not_running' })
451- continue
452-
453- task_id = BotService .stop_bot (bot_id )
454- results .append ({'bot_id' : bot_id , 'status' : 'stopped' , 'task_id' : task_id })
455-
456- except TelegramBot .DoesNotExist :
457- results .append ({'bot_id' : bot_id , 'status' : 'error' , 'reason' : 'not_found' })
458- except Exception as e :
459- results .append ({'bot_id' : bot_id , 'status' : 'error' , 'reason' : str (e )})
460-
461- return Response ({'results' : results })
462-
463- class HealthCheckViewSet (viewsets .ViewSet ):
464- """
465- ViewSet для проверки здоровья системы
466- """
467- permission_classes = [permissions .AllowAny ]
468-
469- @action (detail = False , methods = ['get' ])
470- def health (self , request ):
471- """
472- Проверка здоровья приложения
473- GET /api/health/
474- """
475- from django .db import connection
476- from django .core .cache import cache
477- import redis
478-
479- checks = {
480- 'database' : False ,
481- 'cache' : False ,
482- 'celery' : False ,
483- 'overall' : False
484- }
485-
486- # Проверка базы данных
487- try :
488- with connection .cursor () as cursor :
489- cursor .execute ("SELECT 1" )
490- checks ['database' ] = True
491- except Exception as e :
492- logger .error (f"Database health check failed: { e } " )
493-
494- # Проверка кеша (Redis)
495- try :
496- cache .set ('health_check' , 'ok' , 10 )
497- checks ['cache' ] = cache .get ('health_check' ) == 'ok'
498- except Exception as e :
499- logger .error (f"Cache health check failed: { e } " )
500-
501- # Проверка Celery (опционально)
502- try :
503- # Простая проверка подключения к Redis
504- import redis
505- r = redis .Redis .from_url (settings .CELERY_BROKER_URL )
506- r .ping ()
507- checks ['celery' ] = True
508- except Exception as e :
509- logger .error (f"Celery health check failed: { e } " )
510-
511- # Общий статус
512- checks ['overall' ] = all ([checks ['database' ], checks ['cache' ]])
513-
514- status_code = status .HTTP_200_OK if checks ['overall' ] else status .HTTP_503_SERVICE_UNAVAILABLE
515-
516- return Response ({
517- 'status' : 'healthy' if checks ['overall' ] else 'unhealthy' ,
518- 'checks' : checks ,
519- 'timestamp' : timezone .now ().isoformat ()
520- }, status = status_code )
0 commit comments