Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

queue_monitor_task.py 2.7KB

5 месяцев назад
5 месяцев назад
5 месяцев назад
5 месяцев назад
5 месяцев назад
5 месяцев назад
5 месяцев назад
5 месяцев назад
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import logging
  2. from datetime import datetime
  3. import click
  4. from kombu.utils.url import parse_url # type: ignore
  5. from redis import Redis
  6. import app
  7. from configs import dify_config
  8. from extensions.ext_database import db
  9. from libs.email_i18n import EmailType, get_email_i18n_service
  10. redis_config = parse_url(dify_config.CELERY_BROKER_URL)
  11. celery_redis = Redis(
  12. host=redis_config.get("hostname") or "localhost",
  13. port=redis_config.get("port") or 6379,
  14. password=redis_config.get("password") or None,
  15. db=int(redis_config.get("virtual_host")) if redis_config.get("virtual_host") else 1,
  16. )
  17. @app.celery.task(queue="monitor")
  18. def queue_monitor_task():
  19. queue_name = "dataset"
  20. threshold = dify_config.QUEUE_MONITOR_THRESHOLD
  21. if threshold is None:
  22. logging.warning(click.style("QUEUE_MONITOR_THRESHOLD is not configured, skipping monitoring", fg="yellow"))
  23. return
  24. try:
  25. queue_length = celery_redis.llen(f"{queue_name}")
  26. logging.info(click.style(f"Start monitor {queue_name}", fg="green"))
  27. if queue_length is None:
  28. logging.error(
  29. click.style(f"Failed to get queue length for {queue_name} - Redis may be unavailable", fg="red")
  30. )
  31. return
  32. logging.info(click.style(f"Queue length: {queue_length}", fg="green"))
  33. if queue_length >= threshold:
  34. warning_msg = f"Queue {queue_name} task count exceeded the limit.: {queue_length}/{threshold}"
  35. logging.warning(click.style(warning_msg, fg="red"))
  36. alter_emails = dify_config.QUEUE_MONITOR_ALERT_EMAILS
  37. if alter_emails:
  38. to_list = alter_emails.split(",")
  39. email_service = get_email_i18n_service()
  40. for to in to_list:
  41. try:
  42. current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
  43. email_service.send_email(
  44. email_type=EmailType.QUEUE_MONITOR_ALERT,
  45. language_code="en-US",
  46. to=to,
  47. template_context={
  48. "queue_name": queue_name,
  49. "queue_length": queue_length,
  50. "threshold": threshold,
  51. "alert_time": current_time,
  52. },
  53. )
  54. except Exception as e:
  55. logging.exception(click.style("Exception occurred during sending email", fg="red"))
  56. except Exception as e:
  57. logging.exception(click.style("Exception occurred during queue monitoring", fg="red"))
  58. finally:
  59. if db.session.is_active:
  60. db.session.close()