2017-03-22 14:54:49 -04:00
|
|
|
module Ci
|
2017-03-29 07:49:47 -04:00
|
|
|
class TriggerSchedule < ActiveRecord::Base
|
2017-03-22 14:54:49 -04:00
|
|
|
extend Ci::Model
|
|
|
|
|
|
|
|
acts_as_paranoid
|
|
|
|
|
|
|
|
belongs_to :project
|
2017-03-29 07:49:47 -04:00
|
|
|
belongs_to :trigger
|
2017-03-22 14:54:49 -04:00
|
|
|
|
2017-03-30 07:59:20 -04:00
|
|
|
delegate :ref, to: :trigger
|
|
|
|
|
2017-03-29 14:33:23 -04:00
|
|
|
validates :trigger, presence: true
|
|
|
|
validates :cron, presence: true
|
|
|
|
validates :cron_time_zone, presence: true
|
|
|
|
validate :check_cron
|
|
|
|
validate :check_ref
|
|
|
|
|
|
|
|
after_create :schedule_next_run!
|
|
|
|
|
2017-03-22 14:54:49 -04:00
|
|
|
def schedule_next_run!
|
2017-03-30 14:16:24 -04:00
|
|
|
puts "cron: #{cron.inspect} | cron_time_zone: #{cron_time_zone.inspect}"
|
2017-03-22 14:54:49 -04:00
|
|
|
next_time = Ci::CronParser.new(cron, cron_time_zone).next_time_from_now
|
2017-03-23 11:18:13 -04:00
|
|
|
if next_time.present?
|
2017-03-29 14:33:23 -04:00
|
|
|
update!(next_run_at: next_time)
|
2017-03-23 11:18:13 -04:00
|
|
|
end
|
2017-03-22 14:54:49 -04:00
|
|
|
end
|
|
|
|
|
2017-03-30 14:16:24 -04:00
|
|
|
def real_next_run(worker_cron: nil, worker_time_zone: nil)
|
|
|
|
puts "worker_cron: #{worker_cron.inspect} | worker_time_zone: #{worker_time_zone.inspect}"
|
|
|
|
worker_cron = Settings.cron_jobs['trigger_schedule_worker']['cron'] unless worker_cron.present?
|
|
|
|
worker_time_zone = Time.zone.name unless worker_time_zone.present?
|
|
|
|
worker_next_time = Ci::CronParser.new(worker_cron, worker_time_zone).next_time_from_now
|
|
|
|
|
|
|
|
puts "next_run_at: #{next_run_at.inspect} | worker_next_time: #{worker_next_time.inspect}"
|
|
|
|
if next_run_at > worker_next_time
|
|
|
|
next_run_at
|
|
|
|
else
|
|
|
|
worker_next_time
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2017-03-29 14:33:23 -04:00
|
|
|
private
|
|
|
|
|
|
|
|
def check_cron
|
|
|
|
cron_parser = Ci::CronParser.new(cron, cron_time_zone)
|
|
|
|
is_valid_cron, is_valid_cron_time_zone = cron_parser.validation
|
|
|
|
|
|
|
|
if !is_valid_cron
|
|
|
|
self.errors.add(:cron, " is invalid syntax")
|
|
|
|
elsif !is_valid_cron_time_zone
|
|
|
|
self.errors.add(:cron_time_zone, " is invalid timezone")
|
|
|
|
elsif (cron_parser.next_time_from_now - Time.now).abs < 1.hour
|
|
|
|
self.errors.add(:cron, " can not be less than 1 hour")
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def check_ref
|
2017-03-30 14:16:24 -04:00
|
|
|
if !ref.present?
|
2017-03-29 14:33:23 -04:00
|
|
|
self.errors.add(:ref, " is empty")
|
2017-03-30 14:16:24 -04:00
|
|
|
elsif project.repository.ref_exists?(ref)
|
2017-03-29 14:33:23 -04:00
|
|
|
self.errors.add(:ref, " does not exist")
|
|
|
|
end
|
|
|
|
end
|
2017-03-22 14:54:49 -04:00
|
|
|
end
|
|
|
|
end
|