1 require 'current_api_client'
2 require 'db_current_time'
5 extend CurrentApiClient
8 def self.delete_old(max_age:, max_batch:)
10 if !File.owned?(Rails.root.join('tmp'))
11 Rails.logger.warn("AuditLogs: not owner of #{Rails.root}/tmp, skipping")
14 lockfile = Rails.root.join('tmp', 'audit_logs.lock')
15 File.open(lockfile, File::RDWR|File::CREAT, 0600) do |f|
16 return unless f.flock(File::LOCK_NB|File::LOCK_EX)
18 sql = "select clock_timestamp() - interval '#{'%.9f' % max_age} seconds'"
19 threshold = ActiveRecord::Base.connection.select_value(sql).to_time.utc
20 Rails.logger.info "AuditLogs: deleting logs older than #{threshold}"
27 where('event_type in (?)', ['create', 'update', 'destroy', 'delete']).
28 where('created_at < ?', threshold).
31 did = Log.unscoped.where("id in (#{sql})").delete_all
34 Rails.logger.info "AuditLogs: deleted batch of #{did}"
37 Rails.logger.info "AuditLogs: deleted total #{did_total}"
42 def self.tidy_in_background
43 max_age = Rails.configuration.max_audit_log_age
44 max_batch = Rails.configuration.max_audit_log_delete_batch
45 return if max_age <= 0 || max_batch <= 0
47 exp = (max_age/14).seconds
49 Rails.cache.fetch('AuditLogs', expires_in: exp) do
55 Thread.current.abort_on_exception = false
57 delete_old(max_age: max_age, max_batch: max_batch)
59 Rails.logger.error "#{e.class}: #{e}\n#{e.backtrace.join("\n\t")}"
61 ActiveRecord::Base.connection.close