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