9898: add lock and unlock endpoints to containers_controller.
[arvados.git] / services / api / app / controllers / arvados / v1 / jobs_controller.rb
1 class Arvados::V1::JobsController < ApplicationController
2   accept_attribute_as_json :components, Hash
3   accept_attribute_as_json :script_parameters, Hash
4   accept_attribute_as_json :runtime_constraints, Hash
5   accept_attribute_as_json :tasks_summary, Hash
6   skip_before_filter :find_object_by_uuid, :only => [:queue, :queue_size]
7   skip_before_filter :render_404_if_no_object, :only => [:queue, :queue_size]
8
9   include DbCurrentTime
10
11   def create
12     [:repository, :script, :script_version, :script_parameters].each do |r|
13       if !resource_attrs[r]
14         return send_error("#{r} attribute must be specified",
15                           status: :unprocessable_entity)
16       end
17     end
18
19     # We used to ask for the minimum_, exclude_, and no_reuse params
20     # in the job resource. Now we advertise them as flags that alter
21     # the behavior of the create action.
22     [:minimum_script_version, :exclude_script_versions].each do |attr|
23       if resource_attrs.has_key? attr
24         params[attr] = resource_attrs.delete attr
25       end
26     end
27     if resource_attrs.has_key? :no_reuse
28       params[:find_or_create] = !resource_attrs.delete(:no_reuse)
29     end
30
31     return super if !params[:find_or_create]
32     return if !load_filters_param
33
34     if @filters.empty?  # Translate older creation parameters into filters.
35       @filters =
36         [["repository", "=", resource_attrs[:repository]],
37          ["script", "=", resource_attrs[:script]],
38          ["script_version", "not in git", params[:exclude_script_versions]],
39         ].reject { |filter| filter.last.nil? or filter.last.empty? }
40       if !params[:minimum_script_version].blank?
41         @filters << ["script_version", "in git",
42                      params[:minimum_script_version]]
43       else
44         add_default_git_filter("script_version", resource_attrs[:repository],
45                                resource_attrs[:script_version])
46       end
47       if image_search = resource_attrs[:runtime_constraints].andand["docker_image"]
48         if image_tag = resource_attrs[:runtime_constraints]["docker_image_tag"]
49           image_search += ":#{image_tag}"
50         end
51         image_locator = Collection.
52           for_latest_docker_image(image_search).andand.portable_data_hash
53       else
54         image_locator = nil
55       end
56       @filters << ["docker_image_locator", "=", image_locator]
57       if sdk_version = resource_attrs[:runtime_constraints].andand["arvados_sdk_version"]
58         add_default_git_filter("arvados_sdk_version", "arvados", sdk_version)
59       end
60       begin
61         load_job_specific_filters
62       rescue ArgumentError => error
63         return send_error(error.message)
64       end
65     end
66
67     # Check specified filters for some reasonableness.
68     filter_names = @filters.map { |f| f.first }.uniq
69     ["repository", "script"].each do |req_filter|
70       if not filter_names.include?(req_filter)
71         return send_error("#{req_filter} filter required")
72       end
73     end
74
75     # Search for a reusable Job, and return it if found.
76     @objects = Job.
77       readable_by(current_user).
78       where('state = ? or (owner_uuid = ? and state in (?))',
79             Job::Complete, current_user.uuid, [Job::Queued, Job::Running]).
80       where('script_parameters_digest = ?', Job.sorted_hash_digest(resource_attrs[:script_parameters])).
81       where('nondeterministic is distinct from ?', true).
82       order('state desc, created_at') # prefer Running jobs over Queued
83     apply_filters
84     @object = nil
85     incomplete_job = nil
86     @objects.each do |j|
87       if j.state != Job::Complete
88         # We'll use this if we don't find a job that has completed
89         incomplete_job ||= j
90         next
91       end
92
93       if @object == false
94         # We have already decided not to reuse any completed job
95         next
96       elsif @object
97         if @object.output != j.output
98           # If two matching jobs produced different outputs, run a new
99           # job (or use one that's already running/queued) instead of
100           # choosing one arbitrarily.
101           @object = false
102         end
103         # ...and that's the only thing we need to do once we've chosen
104         # an @object to reuse.
105       elsif !Collection.readable_by(current_user).find_by_portable_data_hash(j.output)
106         # As soon as the output we will end up returning (if any) is
107         # decided, check whether it will be visible to the user; if
108         # not, any further investigation of reusable jobs is futile.
109         return super
110       else
111         @object = j
112       end
113     end
114
115     @object ||= incomplete_job
116     if @object
117       show
118     else
119       super
120     end
121   end
122
123   def cancel
124     reload_object_before_update
125     @object.update_attributes! state: Job::Cancelled
126     show
127   end
128
129   def lock
130     @object.lock current_user.uuid
131     show
132   end
133
134   class LogStreamer
135     Q_UPDATE_INTERVAL = 12
136     def initialize(job, opts={})
137       @job = job
138       @opts = opts
139     end
140     def each
141       if @job.finished_at
142         yield "#{@job.uuid} finished at #{@job.finished_at}\n"
143         return
144       end
145       while not @job.started_at
146         # send a summary (job queue + available nodes) to the client
147         # every few seconds while waiting for the job to start
148         current_time = db_current_time
149         last_ack_at ||= current_time - Q_UPDATE_INTERVAL - 1
150         if current_time - last_ack_at >= Q_UPDATE_INTERVAL
151           nodes_in_state = {idle: 0, alloc: 0}
152           ActiveRecord::Base.uncached do
153             Node.where('hostname is not ?', nil).collect do |n|
154               if n.info[:slurm_state]
155                 nodes_in_state[n.info[:slurm_state]] ||= 0
156                 nodes_in_state[n.info[:slurm_state]] += 1
157               end
158             end
159           end
160           job_queue = Job.queue.select(:uuid)
161           n_queued_before_me = 0
162           job_queue.each do |j|
163             break if j.uuid == @job.uuid
164             n_queued_before_me += 1
165           end
166           yield "#{db_current_time}" \
167             " job #{@job.uuid}" \
168             " queue_position #{n_queued_before_me}" \
169             " queue_size #{job_queue.count}" \
170             " nodes_idle #{nodes_in_state[:idle]}" \
171             " nodes_alloc #{nodes_in_state[:alloc]}\n"
172           last_ack_at = db_current_time
173         end
174         sleep 3
175         ActiveRecord::Base.uncached do
176           @job.reload
177         end
178       end
179     end
180   end
181
182   def queue
183     params[:order] ||= ['priority desc', 'created_at']
184     load_limit_offset_order_params
185     load_where_param
186     @where.merge!({state: Job::Queued})
187     return if !load_filters_param
188     find_objects_for_index
189     index
190   end
191
192   def queue_size
193     # Users may not be allowed to see all the jobs in the queue, so provide a
194     # method to get just the queue size in order to get a gist of how busy the
195     # cluster is.
196     render :json => {:queue_size => Job.queue.size}
197   end
198
199   def self._create_requires_parameters
200     (super rescue {}).
201       merge({
202               find_or_create: {
203                 type: 'boolean', required: false, default: false
204               },
205               filters: {
206                 type: 'array', required: false
207               },
208               minimum_script_version: {
209                 type: 'string', required: false
210               },
211               exclude_script_versions: {
212                 type: 'array', required: false
213               },
214             })
215   end
216
217   def self._queue_requires_parameters
218     self._index_requires_parameters
219   end
220
221   protected
222
223   def add_default_git_filter(attr_name, repo_name, refspec)
224     # Add a filter to @filters for `attr_name` = the latest commit available
225     # in `repo_name` at `refspec`.  No filter is added if refspec can't be
226     # resolved.
227     commits = Commit.find_commit_range(repo_name, nil, refspec, nil)
228     if commit_hash = commits.first
229       @filters << [attr_name, "=", commit_hash]
230     end
231   end
232
233   def load_job_specific_filters
234     # Convert Job-specific @filters entries into general SQL filters.
235     script_info = {"repository" => nil, "script" => nil}
236     git_filters = Hash.new do |hash, key|
237       hash[key] = {"max_version" => "HEAD", "exclude_versions" => []}
238     end
239     @filters.select! do |(attr, operator, operand)|
240       if (script_info.has_key? attr) and (operator == "=")
241         if script_info[attr].nil?
242           script_info[attr] = operand
243         elsif script_info[attr] != operand
244           raise ArgumentError.new("incompatible #{attr} filters")
245         end
246       end
247       case operator
248       when "in git"
249         git_filters[attr]["min_version"] = operand
250         false
251       when "not in git"
252         git_filters[attr]["exclude_versions"] += Array.wrap(operand)
253         false
254       when "in docker", "not in docker"
255         image_hashes = Array.wrap(operand).flat_map do |search_term|
256           image_search, image_tag = search_term.split(':', 2)
257           Collection.
258             find_all_for_docker_image(image_search, image_tag, @read_users).
259             map(&:portable_data_hash)
260         end
261         @filters << [attr, operator.sub(/ docker$/, ""), image_hashes]
262         false
263       else
264         true
265       end
266     end
267
268     # Build a real script_version filter from any "not? in git" filters.
269     git_filters.each_pair do |attr, filter|
270       case attr
271       when "script_version"
272         script_info.each_pair do |key, value|
273           if value.nil?
274             raise ArgumentError.new("script_version filter needs #{key} filter")
275           end
276         end
277         filter["repository"] = script_info["repository"]
278         begin
279           filter["max_version"] = resource_attrs[:script_version]
280         rescue
281           # Using HEAD, set earlier by the hash default, is fine.
282         end
283       when "arvados_sdk_version"
284         filter["repository"] = "arvados"
285       else
286         raise ArgumentError.new("unknown attribute for git filter: #{attr}")
287       end
288       revisions = Commit.find_commit_range(filter["repository"],
289                                            filter["min_version"],
290                                            filter["max_version"],
291                                            filter["exclude_versions"])
292       if revisions.empty?
293         raise ArgumentError.
294           new("error searching #{filter['repository']} from " +
295               "'#{filter['min_version']}' to '#{filter['max_version']}', " +
296               "excluding #{filter['exclude_versions']}")
297       end
298       @filters.append([attr, "in", revisions])
299     end
300   end
301
302   def load_filters_param
303     begin
304       super
305       load_job_specific_filters
306     rescue ArgumentError => error
307       send_error(error.message)
308       false
309     else
310       true
311     end
312   end
313 end