2762: Merge branch 'master' into 2762-owner-uuid-integrity
[arvados.git] / sdk / cli / bin / arv-run-pipeline-instance
1 #!/usr/bin/env ruby
2
3 # == Synopsis
4 #
5 #  arv-run-pipeline-instance --template pipeline-template-uuid [options] [--] [parameters]
6 #  arv-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 # [--submit] 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] Do not reuse existing jobs to satisfy pipeline
32 #              components. Submit a new job for every component.
33 #
34 # [--debug] Print extra debugging information on stderr.
35 #
36 # [--debug-level N] Increase amount of debugging information. Default
37 #                   1, possible range 0..3.
38 #
39 # [--status-text path] Print plain text status report to a file or
40 #                      fifo. Default: /dev/stdout
41 #
42 # [--status-json path] Print JSON status report to a file or
43 #                      fifo. Default: /dev/null
44 #
45 # == Parameters
46 #
47 # [param_name=param_value]
48 #
49 # [param_name param_value] Set (or override) the default value for
50 #                          every parameter with the given name.
51 #
52 # [component_name::param_name=param_value]
53 # [component_name::param_name param_value]
54 # [--component_name::param_name=param_value]
55 # [--component_name::param_name param_value] Set the value of a
56 #                                            parameter for a single
57 #                                            component.
58 #
59 class WhRunPipelineInstance
60 end
61
62 $application_version = 1.0
63
64 if RUBY_VERSION < '1.9.3' then
65   abort <<-EOS
66 #{$0.gsub(/^\.\//,'')} requires Ruby version 1.9.3 or higher.
67   EOS
68 end
69
70 $arvados_api_version = ENV['ARVADOS_API_VERSION'] || 'v1'
71 $arvados_api_host = ENV['ARVADOS_API_HOST'] or
72   abort "#{$0}: fatal: ARVADOS_API_HOST environment variable not set."
73 $arvados_api_token = ENV['ARVADOS_API_TOKEN'] or
74   abort "#{$0}: fatal: ARVADOS_API_TOKEN environment variable not set."
75
76 begin
77   require 'arvados'
78   require 'rubygems'
79   require 'json'
80   require 'pp'
81   require 'trollop'
82   require 'google/api_client'
83 rescue LoadError => l
84   puts $:
85   abort <<-EOS
86 #{$0}: fatal: #{l.message}
87 Some runtime dependencies may be missing.
88 Try: gem install arvados pp google-api-client json trollop
89   EOS
90 end
91
92 def debuglog(message, verbosity=1)
93   $stderr.puts "#{File.split($0).last} #{$$}: #{message}" if $debuglevel >= verbosity
94 end
95
96 module Kernel
97   def suppress_warnings
98     original_verbosity = $VERBOSE
99     $VERBOSE = nil
100     result = yield
101     $VERBOSE = original_verbosity
102     return result
103   end
104 end
105
106 if $arvados_api_host.match /local/
107   # You probably don't care about SSL certificate checks if you're
108   # testing with a dev server.
109   suppress_warnings { OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE }
110 end
111
112 class Google::APIClient
113   def discovery_document(api, version)
114     api = api.to_s
115     return @discovery_documents["#{api}:#{version}"] ||=
116       begin
117         response = self.execute!(
118                                  :http_method => :get,
119                                  :uri => self.discovery_uri(api, version),
120                                  :authenticated => false
121                                  )
122         response.body.class == String ? JSON.parse(response.body) : response.body
123       end
124   end
125 end
126
127
128 # Parse command line options (the kind that control the behavior of
129 # this program, that is, not the pipeline component parameters).
130
131 p = Trollop::Parser.new do
132   version __FILE__
133   opt(:dry_run,
134       "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.",
135       :type => :boolean,
136       :short => :n)
137   opt(:status_text,
138       "Store plain text status in given file.",
139       :short => :none,
140       :type => :string,
141       :default => '/dev/stdout')
142   opt(:status_json,
143       "Store json-formatted pipeline in given file.",
144       :short => :none,
145       :type => :string,
146       :default => '/dev/null')
147   opt(:no_wait,
148       "Do not wait for jobs to finish. Just look up status, submit new jobs if needed, and exit.",
149       :short => :none,
150       :type => :boolean)
151   opt(:no_reuse,
152       "Do not reuse existing jobs to satisfy pipeline components. Submit a new job for every component.",
153       :short => :none,
154       :type => :boolean)
155   opt(:debug,
156       "Print extra debugging information on stderr.",
157       :type => :boolean)
158   opt(:debug_level,
159       "Set debug verbosity level.",
160       :short => :none,
161       :type => :integer)
162   opt(:template,
163       "UUID of pipeline template, or path to local pipeline template file.",
164       :short => :none,
165       :type => :string)
166   opt(:instance,
167       "UUID of pipeline instance.",
168       :short => :none,
169       :type => :string)
170   opt(:submit,
171       "Do not try to satisfy any components. Just create a pipeline instance and output its UUID.",
172       :short => :none,
173       :type => :boolean)
174   opt(:run_here,
175       "Manage the pipeline in process.",
176       :short => :none,
177       :type => :boolean)
178   stop_on [:'--']
179 end
180 $options = Trollop::with_standard_exception_handling p do
181   p.parse ARGV
182 end
183 $debuglevel = $options[:debug_level] || ($options[:debug] && 1) || 0
184
185 if $options[:instance]
186   if $options[:template] or $options[:submit]
187     abort "#{$0}: syntax error: --instance cannot be combined with --template or --submit."
188   end
189 elsif not $options[:template]
190   abort "#{$0}: syntax error: you must supply a --template or --instance."
191 end
192
193 if $options[:run_here] == $options[:submit]
194   abort "#{$0}: syntax error: you must supply either --run-here or --submit."
195 end
196
197 # Suppress SSL certificate checks if ARVADOS_API_HOST_INSECURE
198
199 module Kernel
200   def suppress_warnings
201     original_verbosity = $VERBOSE
202     $VERBOSE = nil
203     result = yield
204     $VERBOSE = original_verbosity
205     return result
206   end
207 end
208
209 if ENV['ARVADOS_API_HOST_INSECURE']
210   suppress_warnings { OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE }
211 end
212
213 # Set up the API client.
214
215 $client ||= Google::APIClient.
216   new(:host => $arvados_api_host,
217       :application_name => File.split($0).last,
218       :application_version => $application_version.to_s)
219 $arvados = $client.discovered_api('arvados', $arvados_api_version)
220 $arv = Arvados.new api_version: 'v1'
221
222
223 class PipelineInstance
224   def self.find(uuid)
225     result = $client.execute(:api_method => $arvados.pipeline_instances.get,
226                              :parameters => {
227                                :uuid => uuid
228                              },
229                              :authenticated => false,
230                              :headers => {
231                                authorization: 'OAuth2 '+ENV['ARVADOS_API_TOKEN']
232                              })
233     j = JSON.parse result.body, :symbolize_names => true
234     unless j.is_a? Hash and j[:uuid]
235       debuglog "Failed to get pipeline_instance: #{j[:errors] rescue nil}", 0
236       nil
237     else
238       debuglog "Retrieved pipeline_instance #{j[:uuid]}"
239       self.new(j)
240     end
241   end
242   def self.create(attributes)
243     result = $client.execute(:api_method => $arvados.pipeline_instances.create,
244                              :body => {
245                                :pipeline_instance => attributes
246                              },
247                              :authenticated => false,
248                              :headers => {
249                                authorization: 'OAuth2 '+ENV['ARVADOS_API_TOKEN']
250                              })
251     j = JSON.parse result.body, :symbolize_names => true
252     unless j.is_a? Hash and j[:uuid]
253       abort "Failed to create pipeline_instance: #{j[:errors] rescue nil} #{j.inspect}"
254     end
255     debuglog "Created pipeline instance: #{j[:uuid]}"
256     self.new(j)
257   end
258   def save
259     result = $client.execute(:api_method => $arvados.pipeline_instances.update,
260                              :parameters => {
261                                :uuid => @pi[:uuid]
262                              },
263                              :body => {
264                                :pipeline_instance => @attributes_to_update.to_json
265                              },
266                              :authenticated => false,
267                              :headers => {
268                                authorization: 'OAuth2 '+ENV['ARVADOS_API_TOKEN']
269                              })
270     j = JSON.parse result.body, :symbolize_names => true
271     unless j.is_a? Hash and j[:uuid]
272       debuglog "Failed to save pipeline_instance: #{j[:errors] rescue nil}", 0
273       nil
274     else
275       @attributes_to_update = {}
276       @pi = j
277     end
278   end
279   def []=(x,y)
280     @attributes_to_update[x] = y
281     @pi[x] = y
282   end
283   def [](x)
284     @pi[x]
285   end
286   protected
287   def initialize(j)
288     @attributes_to_update = {}
289     @pi = j
290   end
291 end
292
293 class JobCache
294   def self.get(uuid)
295     @cache ||= {}
296     result = $client.execute(:api_method => $arvados.jobs.get,
297                              :parameters => {
298                                :uuid => uuid
299                              },
300                              :authenticated => false,
301                              :headers => {
302                                authorization: 'OAuth2 '+ENV['ARVADOS_API_TOKEN']
303                              })
304     @cache[uuid] = JSON.parse result.body, :symbolize_names => true
305   end
306   def self.where(conditions)
307     result = $client.execute(:api_method => $arvados.jobs.list,
308                              :parameters => {
309                                :limit => 10000,
310                                :where => conditions.to_json
311                              },
312                              :authenticated => false,
313                              :headers => {
314                                authorization: 'OAuth2 '+ENV['ARVADOS_API_TOKEN']
315                              })
316     list = JSON.parse result.body, :symbolize_names => true
317     if list and list[:items].is_a? Array
318       list[:items]
319     else
320       []
321     end
322   end
323   def self.create(job, create_params)
324     @cache ||= {}
325     result = $client.execute(:api_method => $arvados.jobs.create,
326                              :body => {
327                                :job => job.to_json
328                              }.merge(create_params),
329                              :authenticated => false,
330                              :headers => {
331                                authorization: 'OAuth2 '+ENV['ARVADOS_API_TOKEN']
332                              })
333     j = JSON.parse result.body, :symbolize_names => true
334     if j.is_a? Hash and j[:uuid]
335       @cache[j[:uuid]] = j
336     else
337       debuglog "create job: #{j[:errors] rescue nil} with attributes #{job}", 0
338       nil
339     end
340   end
341 end
342
343 class WhRunPipelineInstance
344   attr_reader :instance
345
346   def initialize(_options)
347     @options = _options
348   end
349
350   def fetch_template(template)
351     if template.match /[^-0-9a-z]/
352       # Doesn't look like a uuid -- use it as a filename.
353       @template = JSON.parse File.read(template), :symbolize_names => true
354       if !@template[:components]
355         abort ("#{$0}: Template loaded from #{template} " +
356                "does not have a \"components\" key")
357       end
358     else
359       result = $client.execute(:api_method => $arvados.pipeline_templates.get,
360                                :parameters => {
361                                  :uuid => template
362                                },
363                                :authenticated => false,
364                                :headers => {
365                                  authorization: 'OAuth2 '+ENV['ARVADOS_API_TOKEN']
366                                })
367       @template = JSON.parse result.body, :symbolize_names => true
368       if !@template[:uuid]
369         abort "#{$0}: fatal: failed to retrieve pipeline template #{template} #{@template[:errors].inspect rescue nil}"
370       end
371     end
372     self
373   end
374
375   def fetch_instance(instance_uuid)
376     @instance = PipelineInstance.find(instance_uuid)
377     @template = @instance
378     self
379   end
380
381   def apply_parameters(params_args)
382     params_args.shift if params_args[0] == '--'
383     params = {}
384     while !params_args.empty?
385       if (re = params_args[0].match /^(--)?([^-].*?)=(.+)/)
386         params[re[2]] = re[3]
387         params_args.shift
388       elsif params_args.size > 1
389         param = params_args.shift.sub /^--/, ''
390         params[param] = params_args.shift
391       else
392         abort "Syntax error: I do not know what to do with arg \"#{params_args[0]}\""
393       end
394     end
395
396     @components = @template[:components].dup
397
398     errors = []
399     @components.each do |componentname, component|
400       component[:script_parameters].each do |parametername, parameter|
401         parameter = { :value => parameter } unless parameter.is_a? Hash
402         value =
403           (params["#{componentname}::#{parametername}"] ||
404            parameter[:value] ||
405            (parameter[:output_of].nil? &&
406             (params[parametername.to_s] ||
407              parameter[:default])) ||
408            nil)
409         if value.nil? and
410             ![false,'false',0,'0'].index parameter[:required]
411           if parameter[:output_of]
412             next
413           end
414           errors << [componentname, parametername, "required parameter is missing"]
415         end
416         debuglog "parameter #{componentname}::#{parametername} == #{value}"
417         component[:script_parameters][parametername] = value
418       end
419     end
420     if !errors.empty?
421       abort "Errors:\n#{errors.collect { |c,p,e| "#{c}::#{p} - #{e}\n" }.join ""}"
422     end
423     debuglog "options=" + @options.pretty_inspect
424     self
425   end
426
427   def setup_instance
428     if $options[:submit]
429       @instance ||= PipelineInstance.
430         create(:components => @components,
431               :pipeline_template_uuid => @template[:uuid],
432               :state => 'New')
433     else
434       @instance ||= PipelineInstance.
435         create(:components => @components,
436              :pipeline_template_uuid => @template[:uuid],
437              :state => 'RunningOnClient')
438     end
439     self
440   end
441
442   def run
443     moretodo = true
444     interrupted = false
445
446     while moretodo
447       moretodo = false
448       @components.each do |cname, c|
449         job = nil
450         # Is the job satisfying this component already known to be
451         # finished? (Already meaning "before we query API server about
452         # the job's current state")
453         c_already_finished = (c[:job] &&
454                               c[:job][:uuid] &&
455                               !c[:job][:success].nil?)
456         if !c[:job] and
457             c[:script_parameters].select { |pname, p| p.is_a? Hash and p[:output_of]}.empty?
458           # No job yet associated with this component and is component inputs
459           # are fully specified (any output_of script_parameters are resolved
460           # to real value)
461           job = JobCache.create({
462             :script => c[:script],
463             :script_parameters => c[:script_parameters],
464             :script_version => c[:script_version],
465             :repository => c[:repository],
466             :nondeterministic => c[:nondeterministic],
467             :output_is_persistent => c[:output_is_persistent] || false,
468             # TODO: Delete the following three attributes when
469             # supporting pre-20140418 API servers is no longer
470             # important. New API servers take these as flags that
471             # control behavior of create, rather than job attributes.
472             :minimum_script_version => c[:minimum_script_version],
473             :exclude_script_versions => c[:exclude_minimum_script_versions],
474             :no_reuse => @options[:no_reuse] || c[:nondeterministic],
475           }, {
476             # This is the right place to put these attributes when
477             # dealing with new API servers.
478             :minimum_script_version => c[:minimum_script_version],
479             :exclude_script_versions => c[:exclude_minimum_script_versions],
480             :find_or_create => !(@options[:no_reuse] || c[:nondeterministic]),
481           })
482           if job
483             debuglog "component #{cname} new job #{job[:uuid]}"
484             c[:job] = job
485           else
486             debuglog "component #{cname} new job failed"
487           end
488         end
489
490         if c[:job] and c[:job][:uuid]
491           if (c[:job][:running] or
492               not (c[:job][:finished_at] or c[:job][:cancelled_at]))
493             # Job is running so update copy of job record
494             c[:job] = JobCache.get(c[:job][:uuid])
495           end
496
497           if c[:job][:success]
498             # Populate script_parameters of other components waiting for
499             # this job
500             @components.each do |c2name, c2|
501               c2[:script_parameters].each do |pname, p|
502                 if p.is_a? Hash and p[:output_of] == cname.to_s
503                   debuglog "parameter #{c2name}::#{pname} == #{c[:job][:output]}"
504                   c2[:script_parameters][pname] = c[:job][:output]
505                   moretodo = true
506                 end
507               end
508             end
509             unless c_already_finished
510               # This is my first time discovering that the job
511               # succeeded. (At the top of this loop, I was still
512               # waiting for it to finish.)
513               if c[:output_is_persistent]
514                 # I need to make sure a resources/wants link is in
515                 # place to protect the output from garbage
516                 # collection. (Normally Crunch does this for me, but
517                 # here I might be reusing the output of someone else's
518                 # job and I need to make sure it's understood that the
519                 # output is valuable to me, too.)
520                 wanted = c[:job][:output]
521                 debuglog "checking for existing persistence link for #{wanted}"
522                 @my_user_uuid ||= $arv.user.current[:uuid]
523                 links = $arv.link.list(limit: 1,
524                                        filters:
525                                        [%w(link_class = resources),
526                                         %w(name = wants),
527                                         %w(tail_uuid =) + [@my_user_uuid],
528                                         %w(head_uuid =) + [wanted]
529                                        ])[:items]
530                 if links.any?
531                   debuglog "link already exists, uuid #{links.first[:uuid]}"
532                 else
533                   newlink = $arv.link.create link: \
534                   {
535                     link_class: 'resources',
536                     name: 'wants',
537                     tail_kind: 'arvados#user',
538                     tail_uuid: @my_user_uuid,
539                     head_kind: 'arvados#collection',
540                     head_uuid: wanted
541                   }
542                   debuglog "added link, uuid #{newlink[:uuid]}"
543                 end
544               end
545             end
546           elsif c[:job][:running] ||
547               (!c[:job][:started_at] && !c[:job][:cancelled_at])
548             # Job is still running
549             moretodo = true
550           elsif c[:job][:cancelled_at]
551             debuglog "component #{cname} job #{c[:job][:uuid]} cancelled."
552           end
553         end
554       end
555       @instance[:components] = @components
556       report_status
557
558       if @options[:no_wait]
559         moretodo = false
560       end
561
562       if moretodo
563         begin
564           sleep 10
565         rescue Interrupt
566           debuglog "interrupt", 0
567           interrupted = true
568           break
569         end
570       end
571     end
572
573     ended = 0
574     succeeded = 0
575     failed = 0
576     @components.each do |cname, c|
577       if c[:job]
578         if c[:job][:finished_at]
579           ended += 1
580           if c[:job][:success] == true
581             succeeded += 1
582           elsif c[:job][:success] == false
583             failed += 1
584           end
585         end
586       end
587     end
588
589     success = (succeeded == @components.length)
590
591     if interrupted
592      if success
593         @instance[:state] = 'Complete'
594      else
595         @instance[:state] = 'Paused'
596       end
597     else
598       if ended == @components.length or failed > 0
599         @instance[:state] = success ? 'Complete' : 'Failed'
600       end
601     end
602
603     # set components_summary
604     components_summary = {"todo" => @components.length - ended, "done" => succeeded, "failed" => failed}
605     @instance[:components_summary] = components_summary
606
607     @instance.save
608   end
609
610   def cleanup
611     if @instance and @instance[:state] == 'RunningOnClient'
612       @instance[:state] = 'Paused'
613       @instance.save
614     end
615   end
616
617   def uuid
618     @instance[:uuid]
619   end
620
621   protected
622
623   def report_status
624     @instance.save
625
626     if @options[:status_json] != '/dev/null'
627       File.open(@options[:status_json], 'w') do |f|
628         f.puts @components.pretty_inspect
629       end
630     end
631
632     if @options[:status_text] != '/dev/null'
633       File.open(@options[:status_text], 'w') do |f|
634         f.puts ""
635         f.puts "#{Time.now} -- pipeline_instance #{@instance[:uuid]}"
636         namewidth = @components.collect { |cname, c| cname.size }.max
637         @components.each do |cname, c|
638           jstatus = if !c[:job]
639                       "-"
640                     elsif c[:job][:running]
641                       "#{c[:job][:tasks_summary].inspect}"
642                     elsif c[:job][:success]
643                       c[:job][:output]
644                     elsif c[:job][:cancelled_at]
645                       "cancelled #{c[:job][:cancelled_at]}"
646                     elsif c[:job][:finished_at]
647                       "failed #{c[:job][:finished_at]}"
648                     elsif c[:job][:started_at]
649                       "started #{c[:job][:started_at]}"
650                     else
651                       "queued #{c[:job][:created_at]}"
652                     end
653           f.puts "#{cname.to_s.ljust namewidth} #{c[:job] ? c[:job][:uuid] : '-'.ljust(27)} #{jstatus}"
654         end
655       end
656     end
657   end
658 end
659
660 runner = WhRunPipelineInstance.new($options)
661 begin
662   if $options[:template]
663     runner.fetch_template($options[:template])
664   else
665     runner.fetch_instance($options[:instance])
666   end
667   runner.apply_parameters(p.leftovers)
668   runner.setup_instance
669   if $options[:submit]
670     runner.instance.save
671     puts runner.instance[:uuid]
672   else
673     runner.run
674   end
675 rescue Exception => e
676   runner.cleanup
677   raise e
678 end