Fix order of steps in install doc, add git_repositories_dir
[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 index
9     want_ancestor = @where[:script_version_descends_from]
10     if want_ancestor
11       # Check for missing commit_ancestor rows, and create them if
12       # possible.
13       @objects.
14         dup.
15         includes(:commit_ancestors). # I wish Rails would let me
16                                      # specify here which
17                                      # commit_ancestors I am
18                                      # interested in.
19         each do |o|
20         if o.commit_ancestors.
21             select { |ca| ca.ancestor == want_ancestor }.
22             empty? and !o.script_version.nil?
23           begin
24             o.commit_ancestors << CommitAncestor.find_or_create_by_descendant_and_ancestor(o.script_version, want_ancestor)
25           rescue
26           end
27         end
28         o.commit_ancestors.
29           select { |ca| ca.ancestor == want_ancestor }.
30           select(&:is).
31           first
32       end
33       # Now it is safe to do an .includes().where() because we are no
34       # longer interested in jobs that have other ancestors but not
35       # want_ancestor.
36       @objects = @objects.
37         includes(:commit_ancestors).
38         where('commit_ancestors.ancestor = ? and commit_ancestors.is = ?',
39               want_ancestor, true)
40     end
41     super
42   end
43
44   def cancel
45     reload_object_before_update
46     @object.update_attributes cancelled_at: Time.now
47     show
48   end
49
50   class LogStreamer
51     Q_UPDATE_INTERVAL = 12
52     def initialize(job, opts={})
53       @job = job
54       @opts = opts
55     end
56     def each
57       if @job.finished_at
58         yield "#{@job.uuid} finished at #{@job.finished_at}\n"
59         return
60       end
61       while not @job.started_at
62         # send a summary (job queue + available nodes) to the client
63         # every few seconds while waiting for the job to start
64         last_ack_at ||= Time.now - Q_UPDATE_INTERVAL - 1
65         if Time.now - last_ack_at >= Q_UPDATE_INTERVAL
66           nodes_in_state = {idle: 0, alloc: 0}
67           ActiveRecord::Base.uncached do
68             Node.where('hostname is not ?', nil).collect do |n|
69               if n.info[:slurm_state]
70                 nodes_in_state[n.info[:slurm_state]] ||= 0
71                 nodes_in_state[n.info[:slurm_state]] += 1
72               end
73             end
74           end
75           job_queue = Job.queue
76           n_queued_before_me = 0
77           job_queue.each do |j|
78             break if j.uuid == @job.uuid
79             n_queued_before_me += 1
80           end
81           yield "#{Time.now}" \
82             " job #{@job.uuid}" \
83             " queue_position #{n_queued_before_me}" \
84             " queue_size #{job_queue.size}" \
85             " nodes_idle #{nodes_in_state[:idle]}" \
86             " nodes_alloc #{nodes_in_state[:alloc]}\n"
87           last_ack_at = Time.now
88         end
89         sleep 3
90         ActiveRecord::Base.uncached do
91           @job.reload
92         end
93       end
94       @redis = Redis.new(:timeout => 0)
95       if @redis.exists @job.uuid
96         # A log buffer exists. Start by showing the last few KB.
97         @redis.
98           getrange(@job.uuid, 0 - [@opts[:buffer_size], 1].max, -1).
99           sub(/^[^\n]*\n?/, '').
100           split("\n").
101           each do |line|
102           yield "#{line}\n"
103         end
104       end
105       # TODO: avoid missing log entries between getrange() above and
106       # subscribe() below.
107       @redis.subscribe(@job.uuid) do |event|
108         event.message do |channel, msg|
109           if msg == "end"
110             @redis.unsubscribe @job.uuid
111           else
112             yield "#{msg}\n"
113           end
114         end
115       end
116     end
117   end
118
119   def self._log_tail_follow_requires_parameters
120     {
121       buffer_size: {type: 'integer', required: false, default: 2**13}
122     }
123   end
124   def log_tail_follow
125     if !@object.andand.uuid
126       return render_not_found
127     end
128     if client_accepts_plain_text_stream
129       self.response.headers['Last-Modified'] = Time.now.ctime.to_s
130       self.response_body = LogStreamer.new @object, {
131         buffer_size: (params[:buffer_size].to_i rescue 2**13)
132       }
133     else
134       render json: {
135         href: url_for(uuid: @object.uuid),
136         comment: ('To retrieve the log stream as plain text, ' +
137                   'use a request header like "Accept: text/plain"')
138       }
139     end
140   end
141
142   def queue
143     load_where_param
144     @where.merge!({
145                     started_at: nil,
146                     is_locked_by_uuid: nil,
147                     cancelled_at: nil
148                   })
149     params[:order] ||= 'priority desc, created_at'
150     find_objects_for_index
151     index
152   end
153
154   def self._queue_requires_parameters
155     self._index_requires_parameters
156   end
157 end