gitlab-org--gitlab-foss/app/models/ci/pipeline_schedule.rb

89 lines
2.6 KiB
Ruby
Raw Normal View History

# frozen_string_literal: true
module Ci
class PipelineSchedule < ApplicationRecord
extend Gitlab::Ci::Model
include Importable
include StripAttribute
belongs_to :project
belongs_to :owner, class_name: 'User'
has_one :last_pipeline, -> { order(id: :desc) }, class_name: 'Ci::Pipeline'
has_many :pipelines
has_many :variables, class_name: 'Ci::PipelineScheduleVariable', validate: false
2017-03-30 07:59:20 -04:00
validates :cron, unless: :importing?, cron: true, presence: { unless: :importing? }
validates :cron_timezone, cron_timezone: true, presence: { unless: :importing? }
validates :ref, presence: { unless: :importing? }
validates :description, presence: true
2017-07-05 11:45:26 -04:00
validates :variables, variable_duplicates: true
2017-04-06 05:52:48 -04:00
before_save :set_next_run_at
strip_attributes :cron
2017-04-07 08:47:29 -04:00
scope :active, -> { where(active: true) }
scope :inactive, -> { where(active: false) }
scope :runnable_schedules, -> { active.where("next_run_at < ?", Time.now) }
scope :preloaded, -> { preload(:owner, :project) }
accepts_nested_attributes_for :variables, allow_destroy: true
alias_attribute :real_next_run, :next_run_at
def owned_by?(current_user)
owner == current_user
end
2017-05-12 14:37:09 -04:00
def own!(user)
2017-05-16 10:58:22 -04:00
update(owner: user)
2017-05-12 14:37:09 -04:00
end
def inactive?
!active?
end
2017-04-07 08:47:29 -04:00
def deactivate!
update_attribute(:active, false)
end
##
# The `next_run_at` column is set to the actual execution date of `PipelineScheduleWorker`.
# This way, a schedule like `*/1 * * * *` won't be triggered in a short interval
# when PipelineScheduleWorker runs irregularly by Sidekiq Memory Killer.
2017-04-06 05:52:48 -04:00
def set_next_run_at
now = Time.zone.now
ideal_next_run = ideal_next_run_from(now)
self.next_run_at = if ideal_next_run == cron_worker_next_run_from(now)
ideal_next_run
else
cron_worker_next_run_from(ideal_next_run)
end
2017-04-06 05:52:48 -04:00
end
def schedule_next_run!
2017-04-06 05:52:48 -04:00
save! # with set_next_run_at
2017-04-06 08:01:30 -04:00
rescue ActiveRecord::RecordInvalid
update_column(:next_run_at, nil) # update without validation
end
2017-04-06 15:02:19 -04:00
2017-06-27 03:55:27 -04:00
def job_variables
variables&.map(&:to_runner_variable) || []
end
private
def ideal_next_run_from(start_time)
Gitlab::Ci::CronParser.new(cron, cron_timezone)
.next_time_from(start_time)
end
def cron_worker_next_run_from(start_time)
Gitlab::Ci::CronParser.new(Settings.cron_jobs['pipeline_schedule_worker']['cron'],
Time.zone.name)
.next_time_from(start_time)
end
end
end