|
| 1 | +import os |
| 2 | +import datetime |
| 3 | +from threading import Timer |
| 4 | +from flask import url_for |
| 5 | +from src.config import app, db |
| 6 | +from src.utils import _get_system_info |
| 7 | +from src.logger import logger |
| 8 | +from src.models import MonitoredWebsite, GeneralSettings, SystemInformation |
| 9 | +from sqlalchemy.exc import SQLAlchemyError |
| 10 | +import requests |
| 11 | +from src.scripts.email_me import send_smtp_email |
| 12 | +from src.logger import logger |
| 13 | +from src.utils import render_template_from_file, ROOT_DIR |
| 14 | +from src.config import get_app_info |
| 15 | + |
| 16 | +# Dictionary to track the last known status of each website |
| 17 | +website_status = {} |
| 18 | + |
| 19 | +def send_mail(website_name, status, email_adress, email_alerts_enabled): |
| 20 | + """ |
| 21 | + Dummy function to simulate sending an email. |
| 22 | +
|
| 23 | + Args: |
| 24 | + website_name (str): The name or URL of the website. |
| 25 | + status (str): The status of the website, either 'DOWN' or 'UP'. |
| 26 | + """ |
| 27 | + # This is a dummy function, so no real email is sent. |
| 28 | + if email_alerts_enabled: |
| 29 | + context = { |
| 30 | + "website_status": status, # UP/DOWN |
| 31 | + "website_name": website_name, |
| 32 | + "checked_time": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"), |
| 33 | + "message": f"{website_name} is now {status}", |
| 34 | + "title": get_app_info()["title"], |
| 35 | + } |
| 36 | + website_status_template = os.path.join( |
| 37 | + ROOT_DIR, "src/templates/email_templates/website_monitor_status.html" |
| 38 | + ) |
| 39 | + email_subject = f"{website_name} is now {status}" |
| 40 | + email_body = render_template_from_file(website_status_template, **context) |
| 41 | + send_smtp_email(email_adress, email_subject, email_body, is_html=True) |
| 42 | + |
| 43 | + |
| 44 | +def update_website_status(website, status): |
| 45 | + """ |
| 46 | + Updates the status of the website and sends an email notification if the status has changed. |
| 47 | +
|
| 48 | + Args: |
| 49 | + website (MonitoredWebsite): The website object to update. |
| 50 | + status (str): The new status of the website. |
| 51 | + """ |
| 52 | + global website_status |
| 53 | + |
| 54 | + if website.id not in website_status: |
| 55 | + website_status[website.id] = "UP" # Initialize with UP status if not present |
| 56 | + |
| 57 | + if website_status[website.id] != status: |
| 58 | + send_mail( |
| 59 | + website.name, status, website.email_address, website.email_alerts_enabled |
| 60 | + ) |
| 61 | + website_status[website.id] = status |
| 62 | + |
| 63 | + |
| 64 | +def ping_website(website): |
| 65 | + """ |
| 66 | + Pings a single website and updates its status in the database. |
| 67 | +
|
| 68 | + Args: |
| 69 | + website (MonitoredWebsite): The website object to ping. |
| 70 | + """ |
| 71 | + with app.app_context(): |
| 72 | + try: |
| 73 | + # Check if the website is still active |
| 74 | + updated_website = MonitoredWebsite.query.get(website.id) |
| 75 | + if not updated_website or not updated_website.is_ping_active: |
| 76 | + logger.info( |
| 77 | + f"Website {website.name} is no longer active. Stopping monitoring." |
| 78 | + ) |
| 79 | + return |
| 80 | + |
| 81 | + logger.info( |
| 82 | + f"Pinging {website.name} (Interval: {website.ping_interval}s)..." |
| 83 | + ) |
| 84 | + response = requests.get(website.name, timeout=10) |
| 85 | + updated_website.last_ping_time = datetime.datetime.now() |
| 86 | + updated_website.ping_status_code = response.status_code |
| 87 | + |
| 88 | + new_status = "UP" if response.status_code == 200 else "DOWN" |
| 89 | + updated_website.ping_status = new_status |
| 90 | + |
| 91 | + # Update the website status |
| 92 | + db.session.commit() |
| 93 | + logger.info(f"Website {website.name} updated successfully.") |
| 94 | + |
| 95 | + # Determine if an email should be sent |
| 96 | + update_website_status(website, new_status) |
| 97 | + |
| 98 | + except requests.RequestException as req_err: |
| 99 | + updated_website.ping_status = "DOWN" |
| 100 | + logger.error(f"Failed to ping {website.name}: {req_err}", exc_info=True) |
| 101 | + db.session.rollback() |
| 102 | + |
| 103 | + except SQLAlchemyError as db_err: |
| 104 | + logger.error( |
| 105 | + f"Database commit error for {website.name}: {db_err}", exc_info=True |
| 106 | + ) |
| 107 | + db.session.rollback() |
| 108 | + |
| 109 | + finally: |
| 110 | + # Add more detailed logging for debugging |
| 111 | + if db.session.new or db.session.dirty: |
| 112 | + logger.warning( |
| 113 | + f"Database transaction not committed properly for {website.name}." |
| 114 | + ) |
| 115 | + |
| 116 | + # Schedule the next ping for this website |
| 117 | + Timer( |
| 118 | + updated_website.ping_interval, ping_website, args=[updated_website] |
| 119 | + ).start() |
| 120 | + |
| 121 | +def start_website_monitoring(): |
| 122 | + """ |
| 123 | + Periodically pings monitored websites based on individual ping intervals. |
| 124 | + """ |
| 125 | + with app.app_context(): |
| 126 | + try: |
| 127 | + while True: |
| 128 | + active_websites = MonitoredWebsite.query.filter_by( |
| 129 | + is_ping_active=True |
| 130 | + ).all() |
| 131 | + if not active_websites: |
| 132 | + logger.info("No active websites to monitor.") |
| 133 | + else: |
| 134 | + for website in active_websites: |
| 135 | + # Start pinging each website individually based on its ping interval |
| 136 | + Timer(0, ping_website, args=[website]).start() |
| 137 | + |
| 138 | + # Check for active websites periodically (every 30 seconds) |
| 139 | + Timer(30, start_website_monitoring).start() |
| 140 | + break # Break out of the loop to avoid creating a new thread infinitely |
| 141 | + |
| 142 | + except SQLAlchemyError as db_err: |
| 143 | + logger.error( |
| 144 | + f"Database error during website monitoring: {db_err}", exc_info=True |
| 145 | + ) |
| 146 | + except Exception as e: |
| 147 | + logger.error(f"Error during website monitoring: {e}", exc_info=True) |
0 commit comments