Output a blank line between pipeline status updates. closes #2182
[arvados.git] / sdk / cli / bin / arv-run-pipeline-instance
1 #!/usr/bin/env ruby
2
3 # == Synopsis
4 #
5 #  wh-run-pipeline-instance --template pipeline-template-uuid [options] [--] [parameters]
6 #  wh-run-pipeline-instance --instance pipeline-instance-uuid [options]
7 #
8 # Satisfy a pipeline template by finding or submitting a mapreduce job
9 # for each pipeline component.
10 #
11 # == Options
12 #
13 # [--template uuid] Use the specified pipeline template.
14 #
15 # [--template path] Load the pipeline template from the specified
16 #                   local file.
17 #
18 # [--instance uuid] Use the specified pipeline instance.
19 #
20 # [-n, --dry-run] Do not start any new jobs or wait for existing jobs
21 #                 to finish. Just find out whether jobs are finished,
22 #                 queued, or running for each component
23 #
24 # [--create-instance-only] Do not try to satisfy any components. Just
25 #                          create an instance, print its UUID to
26 #                          stdout, and exit.
27 #
28 # [--no-wait] Make only as much progress as possible without entering
29 #             a sleep/poll loop.
30 #
31 # [--no-reuse-finished] Do not reuse existing outputs to satisfy
32 #                       pipeline components. Always submit a new job
33 #                       or use an existing job which has not yet
34 #                       finished.
35 #
36 # [--no-reuse] Do not reuse existing jobs to satisfy pipeline
37 #              components. Submit a new job for every component.
38 #
39 # [--debug] Print extra debugging information on stderr.
40 #
41 # [--debug-level N] Increase amount of debugging information. Default
42 #                   1, possible range 0..3.
43 #
44 # [--status-text path] Print plain text status report to a file or
45 #                      fifo. Default: /dev/stdout
46 #
47 # [--status-json path] Print JSON status report to a file or
48 #                      fifo. Default: /dev/null
49 #
50 # == Parameters
51 #
52 # [param_name=param_value]
53 #
54 # [param_name param_value] Set (or override) the default value for
55 #                          every parameter with the given name.
56 #
57 # [component_name::param_name=param_value]
58 # [component_name::param_name param_value]
59 # [--component_name::param_name=param_value]
60 # [--component_name::param_name param_value] Set the value of a
61 #                                            parameter for a single
62 #                                            component.
63 #
64 class WhRunPipelineInstance
65 end
66
67 $application_version = 1.0
68
69 if RUBY_VERSION < '1.9.3' then
70   abort <<-EOS
71 #{$0.gsub(/^\.\//,'')} requires Ruby version 1.9.3 or higher.
72   EOS
73 end
74
75 $arvados_api_version = ENV['ARVADOS_API_VERSION'] || 'v1'
76 $arvados_api_host = ENV['ARVADOS_API_HOST'] or
77   abort "#{$0}: fatal: ARVADOS_API_HOST environment variable not set."
78 $arvados_api_token = ENV['ARVADOS_API_TOKEN'] or
79   abort "#{$0}: fatal: ARVADOS_API_TOKEN environment variable not set."
80
81 begin
82   require 'rubygems'
83   require 'google/api_client'
84   require 'json'
85   require 'pp'
86   require 'trollop'
87 rescue LoadError
88   abort <<-EOS
89 #{$0}: fatal: some runtime dependencies are missing.
90 Try: gem install pp google-api-client json trollop
91   EOS
92 end
93
94 def debuglog(message, verbosity=1)
95   $stderr.puts "#{File.split($0).last} #{$$}: #{message}" if $debuglevel >= verbosity
96 end
97
98 module Kernel
99   def suppress_warnings
100     original_verbosity = $VERBOSE
101     $VERBOSE = nil
102     result = yield
103     $VERBOSE = original_verbosity
104     return result
105   end
106 end
107
108 if $arvados_api_host.match /local/
109   # You probably don't care about SSL certificate checks if you're
110   # testing with a dev server.
111   suppress_warnings { OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE }
112 end
113
114 class Google::APIClient
115   def discovery_document(api, version)
116     api = api.to_s
117     return @discovery_documents["#{api}:#{version}"] ||=
118       begin
119         response = self.execute!(
120                                  :http_method => :get,
121                                  :uri => self.discovery_uri(api, version),
122                                  :authenticated => false
123                                  )
124         response.body.class == String ? JSON.parse(response.body) : response.body
125       end
126   end
127 end
128
129
130 # Parse command line options (the kind that control the behavior of
131 # this program, that is, not the pipeline component parameters).
132
133 p = Trollop::Parser.new do
134   opt(:dry_run,
135       "Do not start any new jobs or wait for existing jobs to finish. Just find out whether jobs are finished, queued, or running for each component.",
136       :type => :boolean,
137       :short => :n)
138   opt(:status_text,
139       "Store plain text status in given file.",
140       :short => :none,
141       :type => :string,
142       :default => '/dev/stdout')
143   opt(:status_json,
144       "Store json-formatted pipeline in given file.",
145       :short => :none,
146       :type => :string,
147       :default => '/dev/null')
148   opt(:no_wait,
149       "Do not wait for jobs to finish. Just look up status, submit new jobs if needed, and exit.",
150       :short => :none,
151       :type => :boolean)
152   opt(:no_reuse_finished,
153       "Do not reuse existing outputs to satisfy pipeline components. Always submit a new job or use an existing job which has not yet finished.",
154       :short => :none,
155       :type => :boolean)
156   opt(:no_reuse,
157       "Do not reuse existing jobs to satisfy pipeline components. Submit a new job for every component.",
158       :short => :none,
159       :type => :boolean)
160   opt(:debug,
161       "Print extra debugging information on stderr.",
162       :type => :boolean)
163   opt(:debug_level,
164       "Set debug verbosity level.",
165       :short => :none,
166       :type => :integer)
167   opt(:template,
168       "UUID of pipeline template, or path to local pipeline template file.",
169       :short => :none,
170       :type => :string)
171   opt(:instance,
172       "UUID of pipeline instance.",
173       :short => :none,
174       :type => :string)
175   opt(:create_instance_only,
176       "Do not try to satisfy any components. Just create a pipeline instance and output its UUID.",
177       :short => :none,
178       :type => :boolean)
179   stop_on [:'--']
180 end
181 $options = Trollop::with_standard_exception_handling p do
182   p.parse ARGV
183 end
184 $debuglevel = $options[:debug_level] || ($options[:debug] && 1) || 0
185
186 if $options[:instance]
187   if $options[:template] or $options[:create_instance_only]
188     abort "#{$0}: syntax error: --instance cannot be combined with --template or --create-instance-only."
189   end
190 elsif not $options[:template]
191   abort "#{$0}: syntax error: you must supply a --template or --instance."
192 end
193
194 # Set up the API client.
195
196 $client ||= Google::APIClient.
197   new(:host => $arvados_api_host,
198       :application_name => File.split($0).last,
199       :application_version => $application_version.to_s)
200 $arvados = $client.discovered_api('arvados', $arvados_api_version)
201
202
203 class PipelineInstance
204   def self.find(uuid)
205     result = $client.execute(:api_method => $arvados.pipeline_instances.get,
206                              :parameters => {
207                                :uuid => uuid
208                              },
209                              :body => {
210                                :api_token => ENV['ARVADOS_API_TOKEN']
211                              },
212                              :authenticated => false)
213     j = JSON.parse result.body, :symbolize_names => true
214     unless j.is_a? Hash and j[:uuid]
215       debuglog "Failed to get pipeline_instance: #{j[:errors] rescue nil}", 0
216       nil
217     else
218       debuglog "Retrieved pipeline_instance #{j[:uuid]}"
219       self.new(j)
220     end
221   end
222   def self.create(attributes)
223     result = $client.execute(:api_method => $arvados.pipeline_instances.create,
224                              :body => {
225                                :api_token => ENV['ARVADOS_API_TOKEN'],
226                                :pipeline_instance => attributes
227                              },
228                              :authenticated => false)
229     j = JSON.parse result.body, :symbolize_names => true
230     unless j.is_a? Hash and j[:uuid]
231       abort "Failed to create pipeline_instance: #{j[:errors] rescue nil} #{j.inspect}"
232     end
233     debuglog "Created pipeline instance: #{j[:uuid]}"
234     self.new(j)
235   end
236   def save
237     result = $client.execute(:api_method => $arvados.pipeline_instances.update,
238                              :parameters => {
239                                :uuid => @pi[:uuid]
240                              },
241                              :body => {
242                                :api_token => ENV['ARVADOS_API_TOKEN'],
243                                :pipeline_instance => @attributes_to_update.to_json
244                              },
245                              :authenticated => false)
246     j = JSON.parse result.body, :symbolize_names => true
247     unless j.is_a? Hash and j[:uuid]
248       debuglog "Failed to save pipeline_instance: #{j[:errors] rescue nil}", 0
249       nil
250     else
251       @attributes_to_update = {}
252       @pi = j
253     end
254   end
255   def []=(x,y)
256     @attributes_to_update[x] = y
257     @pi[x] = y
258   end
259   def [](x)
260     @pi[x]
261   end
262   protected
263   def initialize(j)
264     @attributes_to_update = {}
265     @pi = j
266   end
267 end
268
269 class JobCache
270   def self.get(uuid)
271     @cache ||= {}
272     result = $client.execute(:api_method => $arvados.jobs.get,
273                              :parameters => {
274                                :api_token => ENV['ARVADOS_API_TOKEN'],
275                                :uuid => uuid
276                              },
277                              :authenticated => false)
278     @cache[uuid] = JSON.parse result.body, :symbolize_names => true
279   end
280   def self.where(conditions)
281     result = $client.execute(:api_method => $arvados.jobs.list,
282                              :parameters => {
283                                :api_token => ENV['ARVADOS_API_TOKEN'],
284                                :limit => 10000,
285                                :where => conditions.to_json
286                              },
287                              :authenticated => false)
288     list = JSON.parse result.body, :symbolize_names => true
289     if list and list[:items].is_a? Array
290       list[:items]
291     else
292       []
293     end
294   end
295   def self.create(attributes)
296     @cache ||= {}
297     result = $client.execute(:api_method => $arvados.jobs.create,
298                              :parameters => {
299                                :api_token => ENV['ARVADOS_API_TOKEN'],
300                                :job => attributes.to_json
301                              },
302                              :authenticated => false)
303     j = JSON.parse result.body, :symbolize_names => true
304     if j.is_a? Hash and j[:uuid]
305       @cache[j[:uuid]] = j
306     else
307       debuglog "create job: #{j[:errors] rescue nil}", 0
308       nil
309     end
310   end
311 end
312
313 class WhRunPipelineInstance
314   attr_reader :instance
315
316   def initialize(_options)
317     @options = _options
318   end
319
320   def fetch_template(template)
321     if template.match /[^-0-9a-z]/
322       # Doesn't look like a uuid -- use it as a filename.
323       @template = JSON.parse File.read(template), :symbolize_names => true
324       if !@template[:components]
325         abort ("#{$0}: Template loaded from #{template} " +
326                "does not have a \"components\" key")
327       end
328     else
329       result = $client.execute(:api_method => $arvados.pipeline_templates.get,
330                                :parameters => {
331                                  :api_token => ENV['ARVADOS_API_TOKEN'],
332                                  :uuid => template
333                                },
334                                :authenticated => false)
335       @template = JSON.parse result.body, :symbolize_names => true
336       if !@template[:uuid]
337         abort "#{$0}: fatal: failed to retrieve pipeline template #{template} #{@template[:errors].inspect rescue nil}"
338       end
339     end
340     self
341   end
342
343   def fetch_instance(instance_uuid)
344     @instance = PipelineInstance.find(instance_uuid)
345     @template = @instance
346     self
347   end
348
349   def apply_parameters(params_args)
350     params_args.shift if params_args[0] == '--'
351     params = {}
352     while !params_args.empty?
353       if (re = params_args[0].match /^(--)?([^-].*?)=(.+)/)
354         params[re[2]] = re[3]
355         params_args.shift
356       elsif params_args.size > 1
357         param = params_args.shift.sub /^--/, ''
358         params[param] = params_args.shift
359       else
360         abort "Syntax error: I do not know what to do with arg \"#{params_args[0]}\""
361       end
362     end
363
364     @components = @template[:components].dup
365
366     errors = []
367     @components.each do |componentname, component|
368       component[:script_parameters].each do |parametername, parameter|
369         parameter = { :value => parameter } unless parameter.is_a? Hash
370         value =
371           (params["#{componentname}::#{parametername}"] ||
372            parameter[:value] ||
373            (parameter[:output_of].nil? &&
374             (params[parametername.to_s] ||
375              parameter[:default])) ||
376            nil)
377         if value.nil? and
378             ![false,'false',0,'0'].index parameter[:required]
379           if parameter[:output_of]
380             next
381           end
382           errors << [componentname, parametername, "required parameter is missing"]
383         end
384         debuglog "parameter #{componentname}::#{parametername} == #{value}"
385         component[:script_parameters][parametername] = value
386       end
387     end
388     if !errors.empty?
389       abort "Errors:\n#{errors.collect { |c,p,e| "#{c}::#{p} - #{e}\n" }.join ""}"
390     end
391     debuglog "options=" + @options.pretty_inspect
392     self
393   end
394
395   def setup_instance
396     @instance ||= PipelineInstance.
397       create(:components => @components,
398              :pipeline_template_uuid => @template[:uuid],
399              :active => true)
400     self
401   end
402
403   def run
404     moretodo = true
405     while moretodo
406       moretodo = false
407       @components.each do |cname, c|
408         job = nil
409         if !c[:job] and
410             c[:script_parameters].select { |pname, p| p.is_a? Hash }.empty?
411           # Job is fully specified (all parameter values are present) but
412           # no particular job has been found.
413
414           debuglog "component #{cname} ready to satisfy."
415
416           c.delete :wait
417           second_place_job = nil # satisfies component, but not finished yet
418
419           (@options[:no_reuse] ? [] : JobCache.
420            where(script: c[:script],
421                  script_parameters: c[:script_parameters],
422                  script_version_descends_from: c[:script_version])
423            ).each do |candidate_job|
424             candidate_params_downcase = Hash[candidate_job[:script_parameters].
425                                              map { |k,v| [k.downcase,v] }]
426             c_params_downcase = Hash[c[:script_parameters].
427                                      map { |k,v| [k.downcase,v] }]
428
429             debuglog "component #{cname} considering job #{candidate_job[:uuid]} version #{candidate_job[:script_version]} parameters #{candidate_params_downcase.inspect}", 3
430
431             unless candidate_params_downcase == c_params_downcase
432               next
433             end
434
435             if c[:script_version] !=
436                 candidate_job[:script_version][0,c[:script_version].length]
437               debuglog "component #{cname} would be satisfied by job #{candidate_job[:uuid]} if script_version matched.", 2
438               next
439             end
440
441             unless candidate_job[:success] || candidate_job[:running] ||
442                 (!candidate_job[:started_at] && !candidate_job[:cancelled_at])
443               debuglog "component #{cname} would be satisfied by job #{candidate_job[:uuid]} if it were running or successful.", 2
444               next
445             end
446
447             if candidate_job[:success]
448               unless @options[:no_reuse_finished]
449                 job = candidate_job
450                 debuglog "component #{cname} satisfied by job #{job[:uuid]} version #{job[:script_version]}"
451                 c[:job] = job
452               end
453             else
454               second_place_job ||= candidate_job
455             end
456             break
457           end
458           if not c[:job] and second_place_job
459             job = second_place_job
460             debuglog "component #{cname} satisfied by job #{job[:uuid]} version #{job[:script_version]}"
461             c[:job] = job
462           end
463           if not c[:job]
464             debuglog "component #{cname} not satisfied by any existing job."
465             if !@options[:dry_run]
466               debuglog "component #{cname} new job."
467               job = JobCache.create(:script => c[:script],
468                                     :script_parameters => c[:script_parameters],
469                                     :runtime_constraints => c[:runtime_constraints] || {},
470                                     :script_version => c[:script_version] || 'master')
471               if job
472                 debuglog "component #{cname} new job #{job[:uuid]}"
473                 c[:job] = job
474               else
475                 debuglog "component #{cname} new job failed"
476               end
477             end
478           end
479         else
480           c[:wait] = true
481         end
482         if c[:job] and c[:job][:uuid]
483           if (c[:job][:running] or
484               not (c[:job][:finished_at] or c[:job][:cancelled_at]))
485             c[:job] = JobCache.get(c[:job][:uuid])
486           end
487           if c[:job][:success]
488             # Populate script_parameters of other components waiting for
489             # this job
490             @components.each do |c2name, c2|
491               c2[:script_parameters].each do |pname, p|
492                 if p.is_a? Hash and p[:output_of] == cname.to_s
493                   debuglog "parameter #{c2name}::#{pname} == #{c[:job][:output]}"
494                   c2[:script_parameters][pname] = c[:job][:output]
495                 end
496               end
497             end
498           elsif c[:job][:running] ||
499               (!c[:job][:started_at] && !c[:job][:cancelled_at])
500             moretodo ||= !@options[:no_wait]
501           elsif c[:job][:cancelled_at]
502             debuglog "component #{cname} job #{c[:job][:uuid]} cancelled."
503           end
504         end
505       end
506       @instance[:components] = @components
507       @instance[:active] = moretodo
508       report_status
509       if moretodo
510         begin
511           sleep 10
512         rescue Interrupt
513           debuglog "interrupt", 0
514           abort
515         end
516       end
517     end
518     @instance[:success] = @components.reject { |cname,c| c[:job] and c[:job][:success] }.empty?
519     @instance.save
520   end
521
522   def cleanup
523     if @instance
524       @instance[:active] = false
525       @instance.save
526     end
527   end
528
529   def uuid
530     @instance[:uuid]
531   end
532
533   protected
534
535   def report_status
536     @instance.save
537
538     if @options[:status_json] != '/dev/null'
539       File.open(@options[:status_json], 'w') do |f|
540         f.puts @components.pretty_inspect
541       end
542     end
543
544     if @options[:status_text] != '/dev/null'
545       File.open(@options[:status_text], 'w') do |f|
546         f.puts ""
547         f.puts "#{Time.now} -- pipeline_instance #{@instance[:uuid]}"
548         namewidth = @components.collect { |cname, c| cname.size }.max
549         @components.each do |cname, c|
550           jstatus = if !c[:job]
551                       "-"
552                     elsif c[:job][:running]
553                       "#{c[:job][:tasks_summary].inspect}"
554                     elsif c[:job][:success]
555                       c[:job][:output]
556                     elsif c[:job][:cancelled_at]
557                       "cancelled #{c[:job][:cancelled_at]}"
558                     elsif c[:job][:finished_at]
559                       "failed #{c[:job][:finished_at]}"
560                     elsif c[:job][:started_at]
561                       "started #{c[:job][:started_at]}"
562                     else
563                       "queued #{c[:job][:created_at]}"
564                     end
565           f.puts "#{cname.to_s.ljust namewidth} #{c[:job] ? c[:job][:uuid] : '-'.ljust(27)} #{jstatus}"
566         end
567       end
568     end
569   end
570 end
571
572 runner = WhRunPipelineInstance.new($options)
573 begin
574   if $options[:template]
575     runner.fetch_template($options[:template])
576   else
577     runner.fetch_instance($options[:instance])
578   end
579   runner.apply_parameters(p.leftovers)
580   runner.setup_instance
581   if $options[:create_instance_only]
582     runner.instance.save
583     puts runner.instance[:uuid]
584   else
585     runner.run
586   end
587 rescue Exception => e
588   runner.cleanup
589   raise e
590 end