93 lines
2.6 KiB
Python
93 lines
2.6 KiB
Python
# essai transmission
|
||
import mysql.connector
|
||
from datetime import datetime, timedelta
|
||
import ovh
|
||
import os
|
||
from dotenv import load_dotenv
|
||
import logging
|
||
|
||
# Charger le .env
|
||
load_dotenv()
|
||
|
||
DB_CONFIG = {
|
||
'host': os.getenv('DB_HOST'),
|
||
'user': os.getenv('DB_USER'),
|
||
'password': os.getenv('DB_PASSWORD'),
|
||
'database': os.getenv('DB_NAME')
|
||
}
|
||
# Configurer le logger
|
||
logging.basicConfig(
|
||
filename='/var/log/watchdog_sondes.log',
|
||
level=logging.INFO,
|
||
format='%(asctime)s — %(levelname)s — %(message)s'
|
||
)
|
||
# SMS OVH
|
||
OVH_CLIENT = ovh.Client(
|
||
endpoint=os.getenv('OVH_ENDPOINT'),
|
||
application_key=os.getenv('OVH_APP_KEY'),
|
||
application_secret=os.getenv('OVH_APP_SECRET'),
|
||
consumer_key=os.getenv('OVH_CONSUMER_KEY')
|
||
)
|
||
|
||
OVH_SMS_ACCOUNT = os.getenv('OVH_SMS_ACCOUNT')
|
||
OVH_SMS_SENDER = os.getenv('OVH_SMS_SENDER')
|
||
ENVOI_SMS = os.getenv('ENVOI_SMS', '0') == '1'
|
||
|
||
DESTINATAIRE = os.getenv('PHONE_ADMIN')
|
||
SEUIL_MINUTES = 10
|
||
|
||
def verifier_table(cnx, table):
|
||
cursor = cnx.cursor()
|
||
query = f"SELECT MAX(Date) FROM {table};"
|
||
cursor.execute(query)
|
||
result = cursor.fetchone()[0]
|
||
cursor.close()
|
||
return result
|
||
|
||
def envoyer_sms(message):
|
||
if not ENVOI_SMS:
|
||
logging.debug(f"[DEBUG] ENVOI_SMS=0, pas d'envoi. Message :\n{message}")
|
||
return
|
||
try:
|
||
result = OVH_CLIENT.post(
|
||
f'/sms/{OVH_SMS_ACCOUNT}/jobs',
|
||
sender=OVH_SMS_SENDER,
|
||
message=message,
|
||
noStopClause=True,
|
||
receivers=[DESTINATAIRE]
|
||
)
|
||
logging.info(f"SMS envoyé avec job ID : {result['ids']}")
|
||
except Exception as e:
|
||
logging.error(f"Erreur lors de l’envoi du SMS : {e}")
|
||
|
||
def main():
|
||
now = datetime.now()
|
||
cnx = mysql.connector.connect(**DB_CONFIG)
|
||
|
||
problemes = []
|
||
for table in ['Saclay', 'Meudon']:
|
||
last_date = verifier_table(cnx, table)
|
||
if last_date is None:
|
||
problemes.append(f"{table} : aucune donnée jamais reçue.")
|
||
continue
|
||
|
||
delta = now - last_date
|
||
if delta > timedelta(minutes=SEUIL_MINUTES):
|
||
minutes = int(delta.total_seconds() / 60)
|
||
problemes.append(
|
||
f"{table} : aucune donnée depuis {minutes} min (dernière à {last_date.strftime('%H:%M:%S')})"
|
||
)
|
||
else:
|
||
logging.info(f"{table} OK — dernière donnée il y a {int(delta.total_seconds()/60)} min.")
|
||
|
||
cnx.close()
|
||
|
||
if problemes:
|
||
message = "[ALERTE] Données manquantes :\n" + "\n".join(problemes)
|
||
envoyer_sms(message)
|
||
else:
|
||
logging.info("Tout est OK, aucune alerte.")
|
||
|
||
if __name__ == "__main__":
|
||
main()
|