From c031813662f332e56ad1f6f27ca778f485e03407 Mon Sep 17 00:00:00 2001 From: Martin Abente Date: Thu, 31 Mar 2011 15:10:24 +0000 Subject: Only one instance of mailer script can run at once --- diff --git a/reports_mailer.py b/reports_mailer.py index efac0de..19edbb9 100755 --- a/reports_mailer.py +++ b/reports_mailer.py @@ -19,6 +19,7 @@ import os import sys import json import time +import fcntl import smtplib import logging import zipfile @@ -91,7 +92,6 @@ def compress_directory(report_path, report_name): temp_file.seek(0) return temp_file.read() - def prepare_message(subject, body, report_path, report_name): message = MIMEMultipart() message['Subject'] = subject @@ -207,10 +207,27 @@ def load_configuration(config): SMTP_SERVER = config.get('mailer', 'smtp_server') SMTP_PORT = config.get('mailer', 'smtp_port') +def already_running(lockfile): + descriptor = os.open(lockfile, os.O_CREAT|os.O_TRUNC|os.O_WRONLY) + + try: + fcntl.lockf(descriptor, fcntl.LOCK_EX|fcntl.LOCK_NB) + except IOError: + return True + + return False + def main(): - config = ConfigParser() script_path = os.path.abspath(__file__) - config_path = os.path.join(os.path.dirname(script_path), 'config.ini') + script_directory_path = os.path.dirname(script_path) + + lockfile = os.path.join(script_directory_path, '.lock') + if already_running(lockfile): + print 'Can\'t run script, because it is already running.' + sys.exit(-1) + + config = ConfigParser() + config_path = os.path.join(script_directory_path, 'config.ini') if len(config.read(config_path)) == 0: print 'Can\'t load configuration file.' -- cgit v0.9.1