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