Merge branch '2620-keep-serialize-io' (closes #2620)
[arvados.git] / services / api / app / models / job.rb
1 class Job < ArvadosModel
2   include AssignUuid
3   include KindAndEtag
4   include CommonApiTemplate
5   serialize :script_parameters, Hash
6   serialize :runtime_constraints, Hash
7   serialize :tasks_summary, Hash
8   before_create :ensure_unique_submit_id
9   before_create :ensure_script_version_is_commit
10   before_update :ensure_script_version_is_commit
11   after_commit :trigger_crunch_dispatch_if_cancelled, :on => :update
12
13   has_many :commit_ancestors, :foreign_key => :descendant, :primary_key => :script_version
14
15   class SubmitIdReused < StandardError
16   end
17
18   api_accessible :user, extend: :common do |t|
19     t.add :submit_id
20     t.add :priority
21     t.add :script
22     t.add :script_parameters
23     t.add :script_version
24     t.add :cancelled_at
25     t.add :cancelled_by_client_uuid
26     t.add :cancelled_by_user_uuid
27     t.add :started_at
28     t.add :finished_at
29     t.add :output
30     t.add :output_is_persistent
31     t.add :success
32     t.add :running
33     t.add :is_locked_by_uuid
34     t.add :log
35     t.add :runtime_constraints
36     t.add :tasks_summary
37     t.add :dependencies
38     t.add :log_stream_href
39     t.add :log_buffer
40     t.add :nondeterministic
41     t.add :repository
42   end
43
44   def assert_finished
45     update_attributes(finished_at: finished_at || Time.now,
46                       success: success.nil? ? false : success,
47                       running: false)
48   end
49
50   def log_stream_href
51     unless self.finished_at
52       "#{current_api_base}/#{self.class.to_s.pluralize.underscore}/#{self.uuid}/log_tail_follow"
53     end
54   end
55
56   def self.queue
57     self.where('started_at is ? and is_locked_by_uuid is ? and cancelled_at is ? and success is ?',
58                nil, nil, nil, nil).
59       order('priority desc, created_at')
60   end
61
62   def self.running
63     self.where('running = ?', true).
64       order('priority desc, created_at')
65   end
66
67   protected
68
69   def foreign_key_attributes
70     super + %w(output log)
71   end
72
73   def skip_uuid_read_permission_check
74     super + %w(cancelled_by_client_uuid)
75   end
76
77   def skip_uuid_existence_check
78     super + %w(output log)
79   end
80
81   def ensure_script_version_is_commit
82     if self.is_locked_by_uuid and self.started_at
83       # Apparently client has already decided to go for it. This is
84       # needed to run a local job using a local working directory
85       # instead of a commit-ish.
86       return true
87     end
88     if new_record? or script_version_changed?
89       sha1 = Commit.find_commit_range(current_user, self.repository, nil, self.script_version, nil)[0] rescue nil
90       if sha1
91         self.script_version = sha1
92       else
93         raise ArgumentError.new("Specified script_version does not resolve to a commit")
94       end
95     end
96   end
97
98   def ensure_unique_submit_id
99     if !submit_id.nil?
100       if Job.where('submit_id=?',self.submit_id).first
101         raise SubmitIdReused.new
102       end
103     end
104     true
105   end
106
107   def dependencies
108     deps = {}
109     queue = self.script_parameters.values
110     while not queue.empty?
111       queue = queue.flatten.compact.collect do |v|
112         if v.is_a? Hash
113           v.values
114         elsif v.is_a? String
115           v.match(/^(([0-9a-f]{32})\b(\+[^,]+)?,?)*$/) do |locator|
116             deps[locator.to_s] = true
117           end
118           nil
119         end
120       end
121     end
122     deps.keys
123   end
124
125   def permission_to_update
126     if is_locked_by_uuid_was and !(current_user and
127                                    (current_user.uuid == is_locked_by_uuid_was or
128                                     current_user.uuid == system_user.uuid))
129       if script_changed? or
130           script_parameters_changed? or
131           script_version_changed? or
132           (!cancelled_at_was.nil? and
133            (cancelled_by_client_uuid_changed? or
134             cancelled_by_user_uuid_changed? or
135             cancelled_at_changed?)) or
136           started_at_changed? or
137           finished_at_changed? or
138           running_changed? or
139           success_changed? or
140           output_changed? or
141           log_changed? or
142           tasks_summary_changed?
143         logger.warn "User #{current_user.uuid if current_user} tried to change protected job attributes on locked #{self.class.to_s} #{uuid_was}"
144         return false
145       end
146     end
147     if !is_locked_by_uuid_changed?
148       super
149     else
150       if !current_user
151         logger.warn "Anonymous user tried to change lock on #{self.class.to_s} #{uuid_was}"
152         false
153       elsif is_locked_by_uuid_was and is_locked_by_uuid_was != current_user.uuid
154         logger.warn "User #{current_user.uuid} tried to steal lock on #{self.class.to_s} #{uuid_was} from #{is_locked_by_uuid_was}"
155         false
156       elsif !is_locked_by_uuid.nil? and is_locked_by_uuid != current_user.uuid
157         logger.warn "User #{current_user.uuid} tried to lock #{self.class.to_s} #{uuid_was} with uuid #{is_locked_by_uuid}"
158         false
159       else
160         super
161       end
162     end
163   end
164
165   def update_modified_by_fields
166     if self.cancelled_at_changed?
167       # Ensure cancelled_at cannot be set to arbitrary non-now times,
168       # or changed once it is set.
169       if self.cancelled_at and not self.cancelled_at_was
170         self.cancelled_at = Time.now
171         self.cancelled_by_user_uuid = current_user.uuid
172         self.cancelled_by_client_uuid = current_api_client.uuid
173         @need_crunch_dispatch_trigger = true
174       else
175         self.cancelled_at = self.cancelled_at_was
176         self.cancelled_by_user_uuid = self.cancelled_by_user_uuid_was
177         self.cancelled_by_client_uuid = self.cancelled_by_client_uuid_was
178       end
179     end
180     super
181   end
182
183   def trigger_crunch_dispatch_if_cancelled
184     if @need_crunch_dispatch_trigger
185       File.open(Rails.configuration.crunch_refresh_trigger, 'wb') do
186         # That's all, just create/touch a file for crunch-job to see.
187       end
188     end
189   end
190
191   def log_buffer
192     begin
193       @@redis ||= Redis.new(:timeout => 0)
194       if @@redis.exists uuid
195         @@redis.getrange(uuid, 0 - 2**10, -1)
196       end
197     rescue Redis::CannotConnectError
198       return '(not available)'
199     end
200   end
201 end