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