4924: Distinguish between errors the user can do something about (syntax errors
[arvados.git] / sdk / cli / bin / arv
1 #!/usr/bin/env ruby
2
3 # Arvados cli client
4 #
5 # Ward Vandewege <ward@curoverse.com>
6
7 require 'fileutils'
8
9 if RUBY_VERSION < '1.9.3' then
10   abort <<-EOS
11 #{$0.gsub(/^\.\//,'')} requires Ruby version 1.9.3 or higher.
12   EOS
13 end
14
15 begin
16   require 'curb'
17   require 'rubygems'
18   require 'google/api_client'
19   require 'json'
20   require 'pp'
21   require 'trollop'
22   require 'andand'
23   require 'oj'
24   require 'active_support/inflector'
25   require 'yaml'
26   require 'tempfile'
27 rescue LoadError
28   abort <<-EOS
29
30 Please install all required gems:
31
32   gem install activesupport andand curb google-api-client json oj trollop yaml
33
34   EOS
35 end
36
37 # Search for 'ENTRY POINT' to see where things get going
38
39 ActiveSupport::Inflector.inflections do |inflect|
40   inflect.irregular 'specimen', 'specimens'
41   inflect.irregular 'human', 'humans'
42 end
43
44 module Kernel
45   def suppress_warnings
46     original_verbosity = $VERBOSE
47     $VERBOSE = nil
48     result = yield
49     $VERBOSE = original_verbosity
50     return result
51   end
52 end
53
54 class Google::APIClient
55  def discovery_document(api, version)
56    api = api.to_s
57    discovery_uri = self.discovery_uri(api, version)
58    discovery_uri_hash = Digest::MD5.hexdigest(discovery_uri)
59    return @discovery_documents[discovery_uri_hash] ||=
60      begin
61        # fetch new API discovery doc if stale
62        cached_doc = File.expand_path "~/.cache/arvados/discovery-#{discovery_uri_hash}.json" rescue nil
63
64        if cached_doc.nil? or not File.exist?(cached_doc) or (Time.now - File.mtime(cached_doc)) > 86400
65          response = self.execute!(:http_method => :get,
66                                   :uri => discovery_uri,
67                                   :authenticated => false)
68
69          begin
70            FileUtils.makedirs(File.dirname cached_doc)
71            File.open(cached_doc, 'w') do |f|
72              f.puts response.body
73            end
74          rescue
75            return JSON.load response.body
76          end
77        end
78
79        File.open(cached_doc) { |f| JSON.load f }
80      end
81  end
82 end
83
84 class ArvadosClient < Google::APIClient
85   def execute(*args)
86     if args.last.is_a? Hash
87       args.last[:headers] ||= {}
88       args.last[:headers]['Accept'] ||= 'application/json'
89     end
90     super(*args)
91   end
92 end
93
94 def init_config
95   # read authentication data from arvados configuration file if present
96   lineno = 0
97   config_file = File.expand_path('~/.config/arvados/settings.conf') rescue nil
98   if not config_file.nil? and File.exist? config_file then
99     File.open(config_file, 'r').each do |line|
100       lineno = lineno + 1
101       # skip comments
102       if line.match('^\s*#') then
103         next
104       end
105       var, val = line.chomp.split('=', 2)
106       # allow environment settings to override config files.
107       if var and val
108         ENV[var] ||= val
109       else
110         warn "#{config_file}: #{lineno}: could not parse `#{line}'"
111       end
112     end
113   end
114 end
115
116
117 subcommands = %w(copy create edit keep pipeline run tag ws)
118
119 def check_subcommands client, arvados, subcommand, global_opts, remaining_opts
120   case subcommand
121   when 'create'
122     arv_create client, arvados, global_opts, remaining_opts
123   when 'edit'
124     arv_edit client, arvados, global_opts, remaining_opts
125   when 'copy', 'tag', 'ws', 'run'
126     exec `which arv-#{subcommand}`.strip, *remaining_opts
127   when 'keep'
128     @sub = remaining_opts.shift
129     if ['get', 'put', 'ls', 'normalize'].index @sub then
130       # Native Arvados
131       exec `which arv-#{@sub}`.strip, *remaining_opts
132     elsif ['less', 'check'].index @sub then
133       # wh* shims
134       exec `which wh#{@sub}`.strip, *remaining_opts
135     elsif @sub == 'docker'
136       exec `which arv-keepdocker`.strip, *remaining_opts
137     else
138       puts "Usage: arv keep [method] [--parameters]\n"
139       puts "Use 'arv keep [method] --help' to get more information about specific methods.\n\n"
140       puts "Available methods: ls, get, put, less, check, docker"
141     end
142     abort
143   when 'pipeline'
144     sub = remaining_opts.shift
145     if sub == 'run'
146       exec `which arv-run-pipeline-instance`.strip, *remaining_opts
147     else
148       puts "Usage: arv pipeline [method] [--parameters]\n"
149       puts "Use 'arv pipeline [method] --help' to get more information about specific methods.\n\n"
150       puts "Available methods: run"
151     end
152     abort
153   end
154 end
155
156 def command_exists?(command)
157   File.executable?(command) || ENV['PATH'].split(':').any? {|folder| File.executable?(File.join(folder, command))}
158 end
159
160 def run_editor path
161   pid = Process::fork
162   if pid.nil?
163     editor = nil
164     [ENV["VISUAL"], ENV["EDITOR"], "nano", "vi"].each do |e|
165       editor ||= e if e and command_exists? e
166     end
167     if editor.nil?
168       abort "Could not find any editor to use, please set $VISUAL or $EDITOR to your desired editor."
169     end
170     exec editor, path
171   else
172     Process.wait pid
173   end
174
175   if $?.exitstatus != 0
176     raise "Editor exited with status #{$?.exitstatus}"
177   end
178 end
179
180 def edit_and_commit_object initial_obj, tmp_stem, global_opts, &block
181
182   content = case global_opts[:format]
183             when 'json'
184               Oj.dump(initial_obj, :indent => 1)
185             when 'yaml'
186               initial_obj.to_yaml
187             else
188               abort "Unrecognized format #{global_opts[:format]}"
189             end
190
191   tmp_file = Tempfile.new([tmp_stem, ".#{global_opts[:format]}"])
192   tmp_file.write(content)
193   tmp_file.close
194
195   begin
196     error_text = ''
197     while true
198       begin
199         run_editor tmp_file.path
200
201         tmp_file.open
202         newcontent = tmp_file.read()
203         tmp_file.close
204
205         # Strip lines starting with '#'
206         newcontent = newcontent.lines.select {|l| !l.start_with? '#'}.join
207
208         # Load the new object
209         newobj = case global_opts[:format]
210                  when 'json'
211                    Oj.load(newcontent)
212                  when 'yaml'
213                    YAML.load(newcontent)
214                  end
215
216         yield newobj
217
218         break
219       rescue => e
220         can_retry = true
221         if e.is_a? Psych::SyntaxError
222           this_error = "YAML error parsing your input: #{e}"
223         elsif e.is_a? JSON::ParserError
224           this_error = "JSON error parsing your input: #{e}"
225         elsif e.is_a? HttpResponse
226           this_error = "API responded with error #{e.status}"
227         else
228           this_error = "#{e.class}: #{e}"
229           can_retry = false
230         end
231         puts this_error
232
233         tmp_file.open
234         newcontent = tmp_file.read()
235         tmp_file.close
236
237         if newcontent == error_text or not can_retry
238           FileUtils::cp tmp_file.path, tmp_file.path + ".saved"
239           puts "File is unchanged, edit aborted." if can_retry
240           abort "Saved contents to " + tmp_file.path + ".saved"
241         else
242           tmp_file.open
243           tmp_file.truncate 0
244           error_text = this_error.to_s.lines.map {|l| '# ' + l}.join + "\n"
245           error_text += "# Please fix the error and try again.\n"
246           error_text += newcontent.lines.select {|l| !l.start_with? '#'}.join
247           tmp_file.write error_text
248           tmp_file.close
249         end
250       end
251     end
252   ensure
253     tmp_file.close(true)
254   end
255
256   nil
257 end
258
259 class HttpResponse < RuntimeError
260   attr_reader :status
261   def initialize status
262     @status = status
263   end
264 end
265
266 def check_response result
267   begin
268     results = JSON.parse result.body
269   rescue JSON::ParserError => e
270     raise "Failed to parse server response:\n" + e.to_s
271   end
272
273   if result.response.status != 200
274     raise HttpResponse.new "#{result.response.status}: " + (results['errors'] && results['errors'].join('\n') || "")
275   end
276
277   results
278 end
279
280 def arv_edit client, arvados, global_opts, remaining_opts
281   uuid = remaining_opts.shift
282   if uuid.nil? or uuid == "-h" or uuid == "--help"
283     puts head_banner
284     puts "Usage: arv edit [uuid] [fields...]\n\n"
285     puts "Fetch the specified Arvados object, select the specified fields, \n"
286     puts "open an interactive text editor on a text representation (json or\n"
287     puts "yaml, use --format) and then update the object.  Will use 'nano'\n"
288     puts "by default, customize with the EDITOR or VISUAL environment variable.\n"
289     exit 255
290   end
291
292   if not $stdout.tty?
293     puts "Not connected to a TTY, cannot run interactive editor."
294     exit 1
295   end
296
297   # determine controller
298
299   m = /([a-z0-9]{5})-([a-z0-9]{5})-([a-z0-9]{15})/.match uuid
300   if !m
301     if /^[a-f0-9]{32}/.match uuid
302       abort "Arvados collections are not editable."
303     else
304       abort "'#{uuid}' does not appear to be an Arvados uuid"
305     end
306   end
307
308   rsc = nil
309   arvados.discovery_document["resources"].each do |k,v|
310     klass = k.singularize.camelize
311     dig = Digest::MD5.hexdigest(klass).to_i(16).to_s(36)[-5..-1]
312     if dig == m[2]
313       rsc = k
314     end
315   end
316
317   if rsc.nil?
318     abort "Could not determine resource type #{m[2]}"
319   end
320
321   begin
322     result = client.execute(:api_method => eval('arvados.' + rsc + '.get'),
323                             :parameters => {"uuid" => uuid},
324                             :authenticated => false,
325                             :headers => {
326                               authorization: 'OAuth2 '+ENV['ARVADOS_API_TOKEN']
327                             })
328     oldobj = check_response result
329   rescue => e
330     abort "Server error: #{e}"
331   end
332
333   if remaining_opts.length > 0
334     oldobj.select! { |k, v| remaining_opts.include? k }
335   end
336
337   edit_and_commit_object oldobj, uuid, global_opts do |newobj|
338     newobj.select! {|k| newobj[k] != oldobj[k]}
339     if !newobj.empty?
340       result = client.execute(:api_method => eval('arvados.' + rsc + '.update'),
341                      :parameters => {"uuid" => uuid},
342                      :body_object => { rsc.singularize => newobj },
343                      :authenticated => false,
344                      :headers => {
345                        authorization: 'OAuth2 '+ENV['ARVADOS_API_TOKEN']
346                      })
347       check_response result
348       puts "Updated object #{uuid}"
349     else
350       puts "Object is unchanged, did not update."
351     end
352   end
353
354   exit 0
355 end
356
357 def arv_create client, arvados, global_opts, remaining_opts
358   types = resource_types(arvados.discovery_document)
359   create_opts = Trollop::options do
360     opt :project_uuid, "Project uuid in which to create the object", :type => :string
361     stop_on resource_types(arvados.discovery_document)
362   end
363
364   object_type = remaining_opts.shift
365   if object_type.nil?
366     abort "Missing resource type, must be one of #{types.join ', '}"
367   end
368
369   rsc = arvados.discovery_document["resources"].keys.select { |k| object_type == k.singularize }
370   if rsc.empty?
371     abort "Could not determine resource type #{object_type}"
372   end
373   rsc = rsc.first
374
375   discovered_params = arvados.discovery_document["resources"][rsc]["methods"]["create"]["parameters"]
376   method_opts = Trollop::options do
377     banner head_banner
378     banner "Usage: arv create [--project-uuid] #{object_type} [create parameters]"
379     banner ""
380     banner "This method supports the following parameters:"
381     banner ""
382     discovered_params.each do |k,v|
383       opts = Hash.new()
384       opts[:type] = v["type"].to_sym if v.include?("type")
385       if [:datetime, :text, :object, :array].index opts[:type]
386         opts[:type] = :string                       # else trollop bork
387       end
388       opts[:default] = v["default"] if v.include?("default")
389       opts[:default] = v["default"].to_i if opts[:type] == :integer
390       opts[:default] = to_boolean(v["default"]) if opts[:type] == :boolean
391       opts[:required] = true if v.include?("required") and v["required"]
392       description = ''
393       description = '  ' + v["description"] if v.include?("description")
394       opt k.to_sym, description, opts
395     end
396   end
397
398   initial_obj = {}
399   if create_opts[:project_uuid]
400     initial_obj["owner_uuid"] = create_opts[:project_uuid]
401   end
402
403   edit_and_commit_object initial_obj, "", global_opts do |newobj|
404     result = client.execute(:api_method => eval('arvados.' + rsc + '.create'),
405                    :parameters => method_opts,
406                    :body_object => {object_type => newobj},
407                    :authenticated => false,
408                    :headers => {
409                      authorization: 'OAuth2 '+ENV['ARVADOS_API_TOKEN']
410                    })
411     results = check_response result
412     puts "Created object #{results['uuid']}"
413   end
414
415   exit 0
416 end
417
418 def to_boolean(s)
419   !!(s =~ /^(true|t|yes|y|1)$/i)
420 end
421
422 def head_banner
423   "Arvados command line client\n"
424 end
425
426 def help_methods(discovery_document, resource, method=nil)
427   banner = head_banner
428   banner += "Usage: arv #{resource} [method] [--parameters]\n"
429   banner += "Use 'arv #{resource} [method] --help' to get more information about specific methods.\n\n"
430   banner += "The #{resource} resource supports the following methods:"
431   banner += "\n\n"
432   discovery_document["resources"][resource.pluralize]["methods"].
433     each do |k,v|
434     description = ''
435     if v.include? "description"
436       # add only the first line of the discovery doc description
437       description = '  ' + v["description"].split("\n").first.chomp
438     end
439     banner += "   #{sprintf("%20s",k)}#{description}\n"
440   end
441   banner += "\n"
442   STDERR.puts banner
443
444   if not method.nil? and method != '--help' and method != '-h' then
445     abort "Unknown method #{method.inspect} " +
446                   "for resource #{resource.inspect}"
447   end
448   exit 255
449 end
450
451 def help_resources(option_parser, discovery_document, resource)
452   option_parser.educate
453   exit 255
454 end
455
456 def resource_types discovery_document
457   resource_types = Array.new()
458   discovery_document["resources"].each do |k,v|
459     resource_types << k.singularize
460   end
461   resource_types
462 end
463
464 def parse_arguments(discovery_document, subcommands)
465   resources_and_subcommands = resource_types(discovery_document) + subcommands
466
467   option_parser = Trollop::Parser.new do
468     version __FILE__
469     banner head_banner
470     banner "Usage: arv [--flags] subcommand|resource [method] [--parameters]"
471     banner ""
472     banner "Available flags:"
473
474     opt :dry_run, "Don't actually do anything", :short => "-n"
475     opt :verbose, "Print some things on stderr"
476     opt :format,
477         "Set the output format. Must be one of json (default), yaml or uuid.",
478         :type => :string,
479         :default => 'json'
480     opt :short, "Return only UUIDs (equivalent to --format=uuid)"
481
482     banner ""
483     banner "Use 'arv subcommand|resource --help' to get more information about a particular command or resource."
484     banner ""
485     banner "Available subcommands: #{subcommands.join(', ')}"
486     banner ""
487
488     banner "Available resources: #{discovery_document['resources'].keys.map { |k| k.singularize }.join(', ')}"
489
490     banner ""
491     banner "Additional options:"
492
493     conflicts :short, :format
494     stop_on resources_and_subcommands
495   end
496
497   global_opts = Trollop::with_standard_exception_handling option_parser do
498     o = option_parser.parse ARGV
499   end
500
501   unless %w(json yaml uuid).include?(global_opts[:format])
502     $stderr.puts "#{$0}: --format must be one of json, yaml or uuid."
503     $stderr.puts "Use #{$0} --help for more information."
504     abort
505   end
506
507   if global_opts[:short]
508     global_opts[:format] = 'uuid'
509   end
510
511   resource = ARGV.shift
512
513   if not subcommands.include? resource
514     if not resources_and_subcommands.include?(resource)
515       puts "Resource or subcommand '#{resource}' is not recognized.\n\n" if !resource.nil?
516       help_resources(option_parser, discovery_document, resource)
517     end
518
519     method = ARGV.shift
520     if not (discovery_document["resources"][resource.pluralize]["methods"].
521             include?(method))
522       help_methods(discovery_document, resource, method)
523     end
524
525     discovered_params = discovery_document\
526     ["resources"][resource.pluralize]\
527     ["methods"][method]["parameters"]
528     method_opts = Trollop::options do
529       banner head_banner
530       banner "Usage: arv #{resource} #{method} [--parameters]"
531       banner ""
532       banner "This method supports the following parameters:"
533       banner ""
534       discovered_params.each do |k,v|
535         opts = Hash.new()
536         opts[:type] = v["type"].to_sym if v.include?("type")
537         if [:datetime, :text, :object, :array].index opts[:type]
538           opts[:type] = :string                       # else trollop bork
539         end
540         opts[:default] = v["default"] if v.include?("default")
541         opts[:default] = v["default"].to_i if opts[:type] == :integer
542         opts[:default] = to_boolean(v["default"]) if opts[:type] == :boolean
543         opts[:required] = true if v.include?("required") and v["required"]
544         description = ''
545         description = '  ' + v["description"] if v.include?("description")
546         opt k.to_sym, description, opts
547       end
548
549       body_object = discovery_document["resources"][resource.pluralize]["methods"][method]["request"]
550       if body_object and discovered_params[resource].nil?
551         is_required = true
552         if body_object["required"] == false
553           is_required = false
554         end
555         opt resource.to_sym, "#{resource} (request body)", {
556           required: is_required,
557           type: :string
558         }
559       end
560     end
561
562     discovered_params.each do |k,v|
563       k = k.to_sym
564       if ['object', 'array'].index(v["type"]) and method_opts.has_key? k
565         if method_opts[k].andand.match /^\//
566           method_opts[k] = File.open method_opts[k], 'rb' do |f| f.read end
567         end
568       end
569     end
570   end
571
572   return resource, method, method_opts, global_opts, ARGV
573 end
574
575 #
576 # ENTRY POINT
577 #
578
579 init_config
580
581 ENV['ARVADOS_API_VERSION'] ||= 'v1'
582
583 if not ENV.include?('ARVADOS_API_HOST') or not ENV.include?('ARVADOS_API_TOKEN') then
584   abort <<-EOS
585 ARVADOS_API_HOST and ARVADOS_API_TOKEN need to be defined as environment variables.
586   EOS
587 end
588
589 # do this if you're testing with a dev server and you don't care about SSL certificate checks:
590 if ENV['ARVADOS_API_HOST_INSECURE']
591   suppress_warnings { OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE }
592 end
593
594 begin
595   client = ArvadosClient.new(:host => ENV['ARVADOS_API_HOST'], :application_name => 'arvados-cli', :application_version => '1.0')
596   arvados = client.discovered_api('arvados', ENV['ARVADOS_API_VERSION'])
597 rescue Exception => e
598   puts "Failed to connect to Arvados API server: #{e}"
599   exit 1
600 end
601
602 # Parse arguments here
603 resource_schema, method, method_opts, global_opts, remaining_opts = parse_arguments(arvados.discovery_document, subcommands)
604
605 check_subcommands client, arvados, resource_schema, global_opts, remaining_opts
606
607 controller = resource_schema.pluralize
608
609 api_method = 'arvados.' + controller + '.' + method
610
611 if global_opts[:dry_run]
612   if global_opts[:verbose]
613     $stderr.puts "#{api_method} #{method_opts.inspect}"
614   end
615   exit
616 end
617
618 request_parameters = {_profile:true}.merge(method_opts)
619 resource_body = request_parameters.delete(resource_schema.to_sym)
620 if resource_body
621   request_body = {
622     resource_schema => resource_body
623   }
624 else
625   request_body = nil
626 end
627
628 case api_method
629 when
630   'arvados.jobs.log_tail_follow'
631
632   # Special case for methods that respond with data streams rather
633   # than JSON (TODO: use the discovery document instead of a static
634   # list of methods)
635   uri_s = eval(api_method).generate_uri(request_parameters)
636   Curl::Easy.perform(uri_s) do |curl|
637     curl.headers['Accept'] = 'text/plain'
638     curl.headers['Authorization'] = "OAuth2 #{ENV['ARVADOS_API_TOKEN']}"
639     if ENV['ARVADOS_API_HOST_INSECURE']
640       curl.ssl_verify_peer = false
641       curl.ssl_verify_host = false
642     end
643     if global_opts[:verbose]
644       curl.on_header { |data| $stderr.write data }
645     end
646     curl.on_body { |data| $stdout.write data }
647   end
648   exit 0
649 else
650   result = client.execute(:api_method => eval(api_method),
651                           :parameters => request_parameters,
652                           :body_object => request_body,
653                           :authenticated => false,
654                           :headers => {
655                             authorization: 'OAuth2 '+ENV['ARVADOS_API_TOKEN']
656                           })
657 end
658
659 begin
660   results = JSON.parse result.body
661 rescue JSON::ParserError => e
662   abort "Failed to parse server response:\n" + e.to_s
663 end
664
665 if results["errors"] then
666   abort "Error: #{results["errors"][0]}"
667 end
668
669 case global_opts[:format]
670 when 'json'
671   puts Oj.dump(results, :indent => 1)
672 when 'yaml'
673   puts results.to_yaml
674 else
675   if results["items"] and results["kind"].match /list$/i
676     results['items'].each do |i| puts i['uuid'] end
677   elsif results['uuid'].nil?
678     abort("Response did not include a uuid:\n" +
679           Oj.dump(results, :indent => 1) +
680           "\n")
681   else
682     puts results['uuid']
683   end
684 end