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