Skip to content

Commit

Permalink
Merge pull request ManageIQ#16863 from yrudman/added-before-safe-to-m…
Browse files Browse the repository at this point in the history
…iq-task-to-initialize-strted_on

Added before_save to MiqTask to initialize MiqTask#started_on when task become active
  • Loading branch information
Fryguy authored Jan 22, 2018
2 parents 2718c7d + 0c8969b commit d992f98
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
7 changes: 5 additions & 2 deletions app/models/miq_task.rb
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ class MiqTask < ApplicationRecord
before_validation :initialize_attributes, :on => :create

before_destroy :check_active, :check_associations
before_save :ensure_started

virtual_has_one :task_results
virtual_attribute :state_or_status, :string, :arel => (lambda do |t|
Expand All @@ -49,6 +50,10 @@ class MiqTask < ApplicationRecord
scope :no_status_selected, -> { running.where.not(:status => %(Ok Error Warn)) }
scope :with_status_in, ->(s, *rest) { rest.reduce(MiqTask.send(s)) { |chain, r| chain.or(MiqTask.send(r)) } }

def ensure_started
self.started_on ||= Time.now.utc if state == STATE_ACTIVE
end

def self.update_status_for_timed_out_active_tasks
MiqTask.active.timed_out.no_associated_job.find_each do |task|
task.update_status(STATE_FINISHED, STATUS_ERROR,
Expand Down Expand Up @@ -100,7 +105,6 @@ def update_status(state, status, message)
self.status = status
self.message = message
self.state = state
self.started_on ||= Time.now.utc if state == STATE_ACTIVE
self.miq_server ||= MiqServer.my_server

save!
Expand Down Expand Up @@ -176,7 +180,6 @@ def self.state_active(taskid)

def state_active
self.state = STATE_ACTIVE
self.started_on ||= Time.now.utc
self.miq_server ||= MiqServer.my_server

save!
Expand Down
14 changes: 14 additions & 0 deletions spec/models/miq_task_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -330,6 +330,20 @@
end
end

context "before save callback" do
describe "#started" do
let(:task) { FactoryGirl.create(:miq_task_plain) }

it "initilizes 'started_on' attribute if task become Active " do
expect(task.started_on).to be nil
Timecop.freeze do
task.update_attributes!(:state => MiqTask::STATE_ACTIVE)
expect(task.started_on).to eq Time.now.utc
end
end
end
end

describe "#update_status" do
let(:miq_task) { FactoryGirl.create(:miq_task_plain) }

Expand Down

0 comments on commit d992f98

Please sign in to comment.