2756: Display event log on pipeline_instance event log udpates.
[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                              :body => {
230                                :api_token => ENV['ARVADOS_API_TOKEN']
231                              },
232                              :authenticated => false)
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                                :api_token => ENV['ARVADOS_API_TOKEN'],
246                                :pipeline_instance => attributes
247                              },
248                              :authenticated => false)
249     j = JSON.parse result.body, :symbolize_names => true
250     unless j.is_a? Hash and j[:uuid]
251       abort "Failed to create pipeline_instance: #{j[:errors] rescue nil} #{j.inspect}"
252     end
253     debuglog "Created pipeline instance: #{j[:uuid]}"
254     self.new(j)
255   end
256   def save
257     result = $client.execute(:api_method => $arvados.pipeline_instances.update,
258                              :parameters => {
259                                :uuid => @pi[:uuid]
260                              },
261                              :body => {
262                                :api_token => ENV['ARVADOS_API_TOKEN'],
263                                :pipeline_instance => @attributes_to_update.to_json
264                              },
265                              :authenticated => false)
266     j = JSON.parse result.body, :symbolize_names => true
267     unless j.is_a? Hash and j[:uuid]
268       debuglog "Failed to save pipeline_instance: #{j[:errors] rescue nil}", 0
269       nil
270     else
271       @attributes_to_update = {}
272       @pi = j
273     end
274   end
275   def []=(x,y)
276     @attributes_to_update[x] = y
277     @pi[x] = y
278   end
279   def [](x)
280     @pi[x]
281   end
282   protected
283   def initialize(j)
284     @attributes_to_update = {}
285     @pi = j
286   end
287 end
288
289 class JobCache
290   def self.get(uuid)
291     @cache ||= {}
292     result = $client.execute(:api_method => $arvados.jobs.get,
293                              :parameters => {
294                                :api_token => ENV['ARVADOS_API_TOKEN'],
295                                :uuid => uuid
296                              },
297                              :authenticated => false)
298     @cache[uuid] = JSON.parse result.body, :symbolize_names => true
299   end
300   def self.where(conditions)
301     result = $client.execute(:api_method => $arvados.jobs.list,
302                              :parameters => {
303                                :api_token => ENV['ARVADOS_API_TOKEN'],
304                                :limit => 10000,
305                                :where => conditions.to_json
306                              },
307                              :authenticated => false)
308     list = JSON.parse result.body, :symbolize_names => true
309     if list and list[:items].is_a? Array
310       list[:items]
311     else
312       []
313     end
314   end
315   def self.create(job, create_params)
316     @cache ||= {}
317     result = $client.execute(:api_method => $arvados.jobs.create,
318                              :parameters => {
319                                :api_token => ENV['ARVADOS_API_TOKEN'],
320                                :job => job.to_json
321                              }.merge(create_params),
322                              :authenticated => false)
323     j = JSON.parse result.body, :symbolize_names => true
324     if j.is_a? Hash and j[:uuid]
325       @cache[j[:uuid]] = j
326     else
327       debuglog "create job: #{j[:errors] rescue nil} with attributes #{job}", 0
328       nil
329     end
330   end
331 end
332
333 class WhRunPipelineInstance
334   attr_reader :instance
335
336   def initialize(_options)
337     @options = _options
338   end
339
340   def fetch_template(template)
341     if template.match /[^-0-9a-z]/
342       # Doesn't look like a uuid -- use it as a filename.
343       @template = JSON.parse File.read(template), :symbolize_names => true
344       if !@template[:components]
345         abort ("#{$0}: Template loaded from #{template} " +
346                "does not have a \"components\" key")
347       end
348     else
349       result = $client.execute(:api_method => $arvados.pipeline_templates.get,
350                                :parameters => {
351                                  :api_token => ENV['ARVADOS_API_TOKEN'],
352                                  :uuid => template
353                                },
354                                :authenticated => false)
355       @template = JSON.parse result.body, :symbolize_names => true
356       if !@template[:uuid]
357         abort "#{$0}: fatal: failed to retrieve pipeline template #{template} #{@template[:errors].inspect rescue nil}"
358       end
359     end
360     self
361   end
362
363   def fetch_instance(instance_uuid)
364     @instance = PipelineInstance.find(instance_uuid)
365     @template = @instance
366     self
367   end
368
369   def apply_parameters(params_args)
370     params_args.shift if params_args[0] == '--'
371     params = {}
372     while !params_args.empty?
373       if (re = params_args[0].match /^(--)?([^-].*?)=(.+)/)
374         params[re[2]] = re[3]
375         params_args.shift
376       elsif params_args.size > 1
377         param = params_args.shift.sub /^--/, ''
378         params[param] = params_args.shift
379       else
380         abort "Syntax error: I do not know what to do with arg \"#{params_args[0]}\""
381       end
382     end
383
384     @components = @template[:components].dup
385
386     errors = []
387     @components.each do |componentname, component|
388       component[:script_parameters].each do |parametername, parameter|
389         parameter = { :value => parameter } unless parameter.is_a? Hash
390         value =
391           (params["#{componentname}::#{parametername}"] ||
392            parameter[:value] ||
393            (parameter[:output_of].nil? &&
394             (params[parametername.to_s] ||
395              parameter[:default])) ||
396            nil)
397         if value.nil? and
398             ![false,'false',0,'0'].index parameter[:required]
399           if parameter[:output_of]
400             next
401           end
402           errors << [componentname, parametername, "required parameter is missing"]
403         end
404         debuglog "parameter #{componentname}::#{parametername} == #{value}"
405         component[:script_parameters][parametername] = value
406       end
407     end
408     if !errors.empty?
409       abort "Errors:\n#{errors.collect { |c,p,e| "#{c}::#{p} - #{e}\n" }.join ""}"
410     end
411     debuglog "options=" + @options.pretty_inspect
412     self
413   end
414
415   def setup_instance
416     if $options[:submit]
417       @instance ||= PipelineInstance.
418         create(:components => @components,
419               :pipeline_template_uuid => @template[:uuid],
420               :state => 'New')
421     else
422       @instance ||= PipelineInstance.
423         create(:components => @components,
424              :pipeline_template_uuid => @template[:uuid],
425              :state => 'RunningOnClient')
426     end
427     self
428   end
429
430   def run
431     moretodo = true
432     interrupted = false
433
434     while moretodo
435       moretodo = false
436       @components.each do |cname, c|
437         job = nil
438         # Is the job satisfying this component already known to be
439         # finished? (Already meaning "before we query API server about
440         # the job's current state")
441         c_already_finished = (c[:job] &&
442                               c[:job][:uuid] &&
443                               !c[:job][:success].nil?)
444         if !c[:job] and
445             c[:script_parameters].select { |pname, p| p.is_a? Hash and p[:output_of]}.empty?
446           # No job yet associated with this component and is component inputs
447           # are fully specified (any output_of script_parameters are resolved
448           # to real value)
449           job = JobCache.create({
450             :script => c[:script],
451             :script_parameters => c[:script_parameters],
452             :script_version => c[:script_version],
453             :repository => c[:repository],
454             :nondeterministic => c[:nondeterministic],
455             :output_is_persistent => c[:output_is_persistent] || false,
456             # TODO: Delete the following three attributes when
457             # supporting pre-20140418 API servers is no longer
458             # important. New API servers take these as flags that
459             # control behavior of create, rather than job attributes.
460             :minimum_script_version => c[:minimum_script_version],
461             :exclude_script_versions => c[:exclude_minimum_script_versions],
462             :no_reuse => @options[:no_reuse] || c[:nondeterministic],
463           }, {
464             # This is the right place to put these attributes when
465             # dealing with new API servers.
466             :minimum_script_version => c[:minimum_script_version],
467             :exclude_script_versions => c[:exclude_minimum_script_versions],
468             :find_or_create => !(@options[:no_reuse] || c[:nondeterministic]),
469           })
470           if job
471             debuglog "component #{cname} new job #{job[:uuid]}"
472             c[:job] = job
473           else
474             debuglog "component #{cname} new job failed"
475           end
476         end
477
478         if c[:job] and c[:job][:uuid]
479           if (c[:job][:running] or
480               not (c[:job][:finished_at] or c[:job][:cancelled_at]))
481             # Job is running so update copy of job record
482             c[:job] = JobCache.get(c[:job][:uuid])
483           end
484
485           if c[:job][:success]
486             # Populate script_parameters of other components waiting for
487             # this job
488             @components.each do |c2name, c2|
489               c2[:script_parameters].each do |pname, p|
490                 if p.is_a? Hash and p[:output_of] == cname.to_s
491                   debuglog "parameter #{c2name}::#{pname} == #{c[:job][:output]}"
492                   c2[:script_parameters][pname] = c[:job][:output]
493                   moretodo = true
494                 end
495               end
496             end
497             unless c_already_finished
498               # This is my first time discovering that the job
499               # succeeded. (At the top of this loop, I was still
500               # waiting for it to finish.)
501               if c[:output_is_persistent]
502                 # I need to make sure a resources/wants link is in
503                 # place to protect the output from garbage
504                 # collection. (Normally Crunch does this for me, but
505                 # here I might be reusing the output of someone else's
506                 # job and I need to make sure it's understood that the
507                 # output is valuable to me, too.)
508                 wanted = c[:job][:output]
509                 debuglog "checking for existing persistence link for #{wanted}"
510                 @my_user_uuid ||= $arv.user.current[:uuid]
511                 links = $arv.link.list(limit: 1,
512                                        filters:
513                                        [%w(link_class = resources),
514                                         %w(name = wants),
515                                         %w(tail_uuid =) + [@my_user_uuid],
516                                         %w(head_uuid =) + [wanted]
517                                        ])[:items]
518                 if links.any?
519                   debuglog "link already exists, uuid #{links.first[:uuid]}"
520                 else
521                   newlink = $arv.link.create link: \
522                   {
523                     link_class: 'resources',
524                     name: 'wants',
525                     tail_kind: 'arvados#user',
526                     tail_uuid: @my_user_uuid,
527                     head_kind: 'arvados#collection',
528                     head_uuid: wanted
529                   }
530                   debuglog "added link, uuid #{newlink[:uuid]}"
531                 end
532               end
533             end
534           elsif c[:job][:running] ||
535               (!c[:job][:started_at] && !c[:job][:cancelled_at])
536             # Job is still running
537             moretodo = true
538           elsif c[:job][:cancelled_at]
539             debuglog "component #{cname} job #{c[:job][:uuid]} cancelled."
540           end
541         end
542       end
543       @instance[:components] = @components
544       report_status
545
546       if @options[:no_wait]
547         moretodo = false
548       end
549
550       if moretodo
551         begin
552           sleep 10
553         rescue Interrupt
554           debuglog "interrupt", 0
555           interrupted = true
556           break
557         end
558       end
559     end
560
561     ended = 0
562     succeeded = 0
563     failed = 0
564     @components.each do |cname, c|
565       if c[:job]
566         if c[:job][:finished_at]
567           ended += 1
568           if c[:job][:success] == true
569             succeeded += 1
570           elsif c[:job][:success] == false
571             failed += 1
572           end
573         end
574       end
575     end
576
577     success = (succeeded == @components.length)
578
579     if interrupted
580      if success
581         @instance[:state] = 'Complete'
582      else
583         @instance[:state] = 'Paused'
584       end
585     else
586       if ended == @components.length or failed > 0
587         @instance[:state] = success ? 'Complete' : 'Failed'
588       end
589     end
590
591     # set components_summary
592     components_summary = {"todo" => @components.length - ended, "done" => succeeded, "failed" => failed}
593     @instance[:components_summary] = components_summary
594
595     @instance.save
596   end
597
598   def cleanup
599     if @instance and @instance[:state] == 'RunningOnClient'
600       @instance[:state] = 'Paused'
601       @instance.save
602     end
603   end
604
605   def uuid
606     @instance[:uuid]
607   end
608
609   protected
610
611   def report_status
612     @instance.save
613
614     if @options[:status_json] != '/dev/null'
615       File.open(@options[:status_json], 'w') do |f|
616         f.puts @components.pretty_inspect
617       end
618     end
619
620     if @options[:status_text] != '/dev/null'
621       File.open(@options[:status_text], 'w') do |f|
622         f.puts ""
623         f.puts "#{Time.now} -- pipeline_instance #{@instance[:uuid]}"
624         namewidth = @components.collect { |cname, c| cname.size }.max
625         @components.each do |cname, c|
626           jstatus = if !c[:job]
627                       "-"
628                     elsif c[:job][:running]
629                       "#{c[:job][:tasks_summary].inspect}"
630                     elsif c[:job][:success]
631                       c[:job][:output]
632                     elsif c[:job][:cancelled_at]
633                       "cancelled #{c[:job][:cancelled_at]}"
634                     elsif c[:job][:finished_at]
635                       "failed #{c[:job][:finished_at]}"
636                     elsif c[:job][:started_at]
637                       "started #{c[:job][:started_at]}"
638                     else
639                       "queued #{c[:job][:created_at]}"
640                     end
641           f.puts "#{cname.to_s.ljust namewidth} #{c[:job] ? c[:job][:uuid] : '-'.ljust(27)} #{jstatus}"
642         end
643       end
644     end
645   end
646 end
647
648 runner = WhRunPipelineInstance.new($options)
649 begin
650   if $options[:template]
651     runner.fetch_template($options[:template])
652   else
653     runner.fetch_instance($options[:instance])
654   end
655   runner.apply_parameters(p.leftovers)
656   runner.setup_instance
657   if $options[:submit]
658     runner.instance.save
659     puts runner.instance[:uuid]
660   else
661     runner.run
662   end
663 rescue Exception => e
664   runner.cleanup
665   raise e
666 end