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