2424from util .logging import info_message , warning_message
2525
2626
27- @shared_task (bind = True , autoretry_for = (OperationalError ,), retry_backoff = True , retry_kwargs = {'max_retries' : 5 })
27+ @shared_task (
28+ bind = True ,
29+ priority = 0 ,
30+ autoretry_for = (OperationalError ,),
31+ retry_backoff = True ,
32+ retry_kwargs = {'max_retries' : 5 }
33+ )
2834def process_report (self , report_id ):
2935 """ Task to process a single report
3036 """
3137 report = Report .objects .get (id = report_id )
32- lock_key = f'process_report_lock_{ report_id } '
33- # lock will expire after 1 hour
34- lock_expire = 60 * 60
38+ report_id_lock_key = f'process_report_id_lock_{ report_id } '
39+ if report .host :
40+ report_host_lock_key = f'process_report_host_lock_{ report .host } '
41+ else :
42+ report_host_lock_key = f'process_report_host_lock_{ report .report_ip } '
43+ # locks will expire after 2 hours
44+ lock_expire = 60 * 60 * 2
3545
36- if cache .add (lock_key , 'true' , lock_expire ):
46+ if cache .add (report_id_lock_key , 'true' , lock_expire ):
3747 try :
38- report .process ()
48+ processing_report_id = cache .get (report_host_lock_key )
49+ if processing_report_id :
50+ if processing_report_id > report .id :
51+ warning_message (f'Currently processing a newer report for { report .host } or { report .report_ip } , \
52+ marking report { report .id } as processed.' )
53+ report .processed = True
54+ report .save ()
55+ else :
56+ warning_message (f'Currently processing an older report for { report .host } or { report .report_ip } , \
57+ will skip processing this report.' )
58+ else :
59+ try :
60+ cache .set (report_host_lock_key , report .id , lock_expire )
61+ report .process ()
62+ finally :
63+ cache .delete (report_host_lock_key )
3964 finally :
40- cache .delete (lock_key )
65+ cache .delete (report_id_lock_key )
4166 else :
4267 warning_message (f'Already processing report { report_id } , skipping task.' )
4368
4469
45- @shared_task
70+ @shared_task ( priority = 1 )
4671def process_reports ():
4772 """ Task to process all unprocessed reports
4873 """
@@ -51,9 +76,9 @@ def process_reports():
5176 process_report .delay (report .id )
5277
5378
54- @shared_task
55- def clean_reports_with_no_hosts ():
56- """ Task to clean processed reports where the host no longer exists
79+ @shared_task ( priority = 2 )
80+ def remove_reports_with_no_hosts ():
81+ """ Task to remove processed reports where the host no longer exists
5782 """
5883 for report in Report .objects .filter (processed = True ):
5984 if not Host .objects .filter (hostname = report .host ).exists ():
0 commit comments