Merge branch 'master' into 3112-report-bug
[arvados.git] / services / api / app / controllers / arvados / v1 / jobs_controller.rb
1 class Arvados::V1::JobsController < ApplicationController
2   accept_attribute_as_json :script_parameters, Hash
3   accept_attribute_as_json :runtime_constraints, Hash
4   accept_attribute_as_json :tasks_summary, Hash
5   skip_before_filter :find_object_by_uuid, :only => :queue
6   skip_before_filter :render_404_if_no_object, :only => :queue
7
8   def create
9     [:repository, :script, :script_version, :script_parameters].each do |r|
10       if !resource_attrs[r]
11         return send_error("#{r} attribute must be specified",
12                           status: :unprocessable_entity)
13       end
14     end
15
16     # We used to ask for the minimum_, exclude_, and no_reuse params
17     # in the job resource. Now we advertise them as flags that alter
18     # the behavior of the create action.
19     [:minimum_script_version, :exclude_script_versions].each do |attr|
20       if resource_attrs.has_key? attr
21         params[attr] = resource_attrs.delete attr
22       end
23     end
24     if resource_attrs.has_key? :no_reuse
25       params[:find_or_create] = !resource_attrs.delete(:no_reuse)
26     end
27
28     if params[:find_or_create]
29       return if false.equal?(load_filters_param)
30       if @filters.empty?  # Translate older creation parameters into filters.
31         @filters =
32           [["repository", "=", resource_attrs[:repository]],
33            ["script", "=", resource_attrs[:script]],
34            ["script_version", "in git",
35             params[:minimum_script_version] || resource_attrs[:script_version]],
36            ["script_version", "not in git", params[:exclude_script_versions]],
37           ].reject { |filter| filter.last.nil? }
38         if image_search = resource_attrs[:runtime_constraints].andand["docker_image"]
39           if image_tag = resource_attrs[:runtime_constraints]["docker_image_tag"]
40             image_search += ":#{image_tag}"
41           end
42           @filters.append(["docker_image_locator", "in docker", image_search])
43         else
44           @filters.append(["docker_image_locator", "=", nil])
45         end
46         begin
47           load_job_specific_filters
48         rescue ArgumentError => error
49           return send_error(error.message)
50         end
51       end
52
53       # Check specified filters for some reasonableness.
54       filter_names = @filters.map { |f| f.first }.uniq
55       ["repository", "script"].each do |req_filter|
56         if not filter_names.include?(req_filter)
57           return send_error("#{req_filter} filter required")
58         end
59       end
60
61       # Search for a reusable Job, and return it if found.
62       @objects = Job.readable_by(current_user)
63       apply_filters
64       @object = nil
65       incomplete_job = nil
66       @objects.each do |j|
67         if j.nondeterministic != true and
68             ((j.success == true and j.output != nil) or j.running == true) and
69             j.script_parameters == resource_attrs[:script_parameters]
70           if j.running && j.owner_uuid == current_user.uuid
71             # We'll use this if we don't find a job that has completed
72             incomplete_job ||= j
73           else
74             if Collection.readable_by(current_user).find_by_uuid(j.output)
75               # Record the first job in the list
76               if !@object
77                 @object = j
78               end
79               # Ensure that all candidate jobs actually did produce the same output
80               if @object.output != j.output
81                 @object = nil
82                 break
83               end
84             end
85           end
86         end
87         @object ||= incomplete_job
88         if @object
89           return show
90         end
91       end
92     end
93
94     super
95   end
96
97   def cancel
98     reload_object_before_update
99     @object.update_attributes! cancelled_at: Time.now
100     show
101   end
102
103   class LogStreamer
104     Q_UPDATE_INTERVAL = 12
105     def initialize(job, opts={})
106       @job = job
107       @opts = opts
108     end
109     def each
110       if @job.finished_at
111         yield "#{@job.uuid} finished at #{@job.finished_at}\n"
112         return
113       end
114       while not @job.started_at
115         # send a summary (job queue + available nodes) to the client
116         # every few seconds while waiting for the job to start
117         last_ack_at ||= Time.now - Q_UPDATE_INTERVAL - 1
118         if Time.now - last_ack_at >= Q_UPDATE_INTERVAL
119           nodes_in_state = {idle: 0, alloc: 0}
120           ActiveRecord::Base.uncached do
121             Node.where('hostname is not ?', nil).collect do |n|
122               if n.info[:slurm_state]
123                 nodes_in_state[n.info[:slurm_state]] ||= 0
124                 nodes_in_state[n.info[:slurm_state]] += 1
125               end
126             end
127           end
128           job_queue = Job.queue
129           n_queued_before_me = 0
130           job_queue.each do |j|
131             break if j.uuid == @job.uuid
132             n_queued_before_me += 1
133           end
134           yield "#{Time.now}" \
135             " job #{@job.uuid}" \
136             " queue_position #{n_queued_before_me}" \
137             " queue_size #{job_queue.size}" \
138             " nodes_idle #{nodes_in_state[:idle]}" \
139             " nodes_alloc #{nodes_in_state[:alloc]}\n"
140           last_ack_at = Time.now
141         end
142         sleep 3
143         ActiveRecord::Base.uncached do
144           @job.reload
145         end
146       end
147     end
148   end
149
150   def queue
151     params[:order] ||= ['priority desc', 'created_at']
152     load_limit_offset_order_params
153     load_where_param
154     @where.merge!({
155                     started_at: nil,
156                     is_locked_by_uuid: nil,
157                     cancelled_at: nil,
158                     success: nil
159                   })
160     return if false.equal?(load_filters_param)
161     find_objects_for_index
162     index
163   end
164
165   def self._create_requires_parameters
166     (super rescue {}).
167       merge({
168               find_or_create: {
169                 type: 'boolean', required: false, default: false
170               },
171               filters: {
172                 type: 'array', required: false
173               },
174               minimum_script_version: {
175                 type: 'string', required: false
176               },
177               exclude_script_versions: {
178                 type: 'array', required: false
179               },
180             })
181   end
182
183   def self._queue_requires_parameters
184     self._index_requires_parameters
185   end
186
187   protected
188
189   def load_job_specific_filters
190     # Convert Job-specific @filters entries into general SQL filters.
191     script_info = {"repository" => nil, "script" => nil}
192     script_range = {"exclude_versions" => []}
193     @filters.select! do |filter|
194       if (script_info.has_key? filter[0]) and (filter[1] == "=")
195         if script_info[filter[0]].nil?
196           script_info[filter[0]] = filter[2]
197         elsif script_info[filter[0]] != filter[2]
198           raise ArgumentError.new("incompatible #{filter[0]} filters")
199         end
200       end
201       case filter[0..1]
202       when ["script_version", "in git"]
203         script_range["min_version"] = filter.last
204         false
205       when ["script_version", "not in git"]
206         begin
207           script_range["exclude_versions"] += filter.last
208         rescue TypeError
209           script_range["exclude_versions"] << filter.last
210         end
211         false
212       when ["docker_image_locator", "in docker"], ["docker_image_locator", "not in docker"]
213         filter[1].sub!(/ docker$/, '')
214         search_list = filter[2].is_a?(Enumerable) ? filter[2] : [filter[2]]
215         filter[2] = search_list.flat_map do |search_term|
216           image_search, image_tag = search_term.split(':', 2)
217           Collection.uuids_for_docker_image(image_search, image_tag, @read_users)
218         end
219         true
220       else
221         true
222       end
223     end
224
225     # Build a real script_version filter from any "not? in git" filters.
226     if (script_range.size > 1) or script_range["exclude_versions"].any?
227       script_info.each_pair do |key, value|
228         if value.nil?
229           raise ArgumentError.new("script_version filter needs #{key} filter")
230         end
231       end
232       last_version = begin resource_attrs[:script_version] rescue "HEAD" end
233       version_range = Commit.find_commit_range(current_user,
234                                                script_info["repository"],
235                                                script_range["min_version"],
236                                                last_version,
237                                                script_range["exclude_versions"])
238       if version_range.nil?
239         raise ArgumentError.
240           new(["error searching #{script_info['repository']} from",
241                "#{script_range['min_version']} to #{last_version},",
242                "excluding #{script_range['exclude_versions']}"].join(" "))
243       end
244       @filters.append(["script_version", "in", version_range])
245     end
246   end
247
248   def load_filters_param
249     begin
250       super
251       load_job_specific_filters
252     rescue ArgumentError => error
253       send_error(error.message)
254       false
255     end
256   end
257 end