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