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