17417: Add arm64 packages for our Golang components.
[arvados.git] / sdk / cli / bin / arv
1 #!/usr/bin/env ruby
2 # Copyright (C) The Arvados Authors. All rights reserved.
3 #
4 # SPDX-License-Identifier: Apache-2.0
5
6 # Arvados cli client
7 #
8 # Ward Vandewege <ward@curoverse.com>
9
10 require 'fileutils'
11 require 'shellwords'
12
13 if RUBY_VERSION < '1.9.3' then
14   abort <<-EOS
15 #{$0.gsub(/^\.\//,'')} requires Ruby version 1.9.3 or higher.
16   EOS
17 end
18
19 begin
20   require 'json'
21   require 'net/http'
22   require 'pp'
23   require 'tempfile'
24   require 'yaml'
25 rescue LoadError => error
26   abort "Error loading libraries: #{error}\n"
27 end
28
29 begin
30   require 'rubygems'
31   # Load the gems with more requirements first, so we respect any version
32   # constraints they put on gems loaded later.
33   require 'arvados/google_api_client'
34   require 'active_support/inflector'
35   require 'andand'
36   require 'curb'
37   require 'oj'
38   require 'optimist'
39 rescue LoadError => error
40   abort <<-EOS
41
42 Error loading gems: #{error}
43
44 Please install all required gems:
45
46   gem install arvados activesupport andand curb json oj optimist
47
48   EOS
49 end
50
51 # Search for 'ENTRY POINT' to see where things get going
52
53 ActiveSupport::Inflector.inflections do |inflect|
54   inflect.irregular 'specimen', 'specimens'
55   inflect.irregular 'human', 'humans'
56 end
57
58 module Kernel
59   def suppress_warnings
60     original_verbosity = $VERBOSE
61     $VERBOSE = nil
62     result = yield
63     $VERBOSE = original_verbosity
64     return result
65   end
66 end
67
68 class ArvadosClient < Google::APIClient
69   def execute(*args)
70     if args.last.is_a? Hash
71       args.last[:headers] ||= {}
72       args.last[:headers]['Accept'] ||= 'application/json'
73     end
74     super(*args)
75   end
76 end
77
78 def init_config
79   # read authentication data from arvados configuration file if present
80   lineno = 0
81   config_file = File.expand_path('~/.config/arvados/settings.conf') rescue nil
82   if not config_file.nil? and File.exist? config_file then
83     File.open(config_file, 'r').each do |line|
84       lineno = lineno + 1
85       # skip comments
86       if line.match('^\s*#') then
87         next
88       end
89       var, val = line.chomp.split('=', 2)
90       # allow environment settings to override config files.
91       if var and val
92         ENV[var] ||= val
93       else
94         warn "#{config_file}: #{lineno}: could not parse `#{line}'"
95       end
96     end
97   end
98 end
99
100
101 subcommands = %w(copy create edit get keep pipeline run tag ws)
102
103 def exec_bin bin, opts
104   bin_path = `which #{bin.shellescape}`.strip
105   if bin_path.empty?
106     raise "#{bin}: command not found"
107   end
108   exec bin_path, *opts
109 end
110
111 def check_subcommands client, arvados, subcommand, global_opts, remaining_opts
112   case subcommand
113   when 'create'
114     arv_create client, arvados, global_opts, remaining_opts
115   when 'edit'
116     arv_edit client, arvados, global_opts, remaining_opts
117   when 'get'
118     arv_get client, arvados, global_opts, remaining_opts
119   when 'copy', 'tag', 'ws', 'run'
120     exec_bin "arv-#{subcommand}", remaining_opts
121   when 'keep'
122     @sub = remaining_opts.shift
123     if ['get', 'put', 'ls', 'normalize'].index @sub then
124       # Native Arvados
125       exec_bin "arv-#{@sub}", remaining_opts
126     elsif @sub == 'docker'
127       exec_bin "arv-keepdocker", remaining_opts
128     else
129       puts "Usage: arv keep [method] [--parameters]\n"
130       puts "Use 'arv keep [method] --help' to get more information about specific methods.\n\n"
131       puts "Available methods: ls, get, put, docker"
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   rsc = lookup_uuid_rsc arvados, uuid
326   oldobj = fetch_rsc_obj client, arvados, rsc, uuid, remaining_opts
327
328   edit_and_commit_object oldobj, uuid, global_opts do |newobj|
329     newobj.select! {|k| newobj[k] != oldobj[k]}
330     if !newobj.empty?
331       result = client.execute(:api_method => eval('arvados.' + rsc + '.update'),
332                      :parameters => {"uuid" => uuid},
333                      :body_object => { rsc.singularize => newobj },
334                      :authenticated => false,
335                      :headers => {
336                        authorization: 'OAuth2 '+ENV['ARVADOS_API_TOKEN']
337                      })
338       results = check_response result
339       STDERR.puts "Updated object #{results['uuid']}"
340     else
341       STDERR.puts "Object is unchanged, did not update."
342     end
343   end
344
345   exit 0
346 end
347
348 def arv_get client, arvados, global_opts, remaining_opts
349   uuid = remaining_opts.shift
350   if uuid.nil? or uuid == "-h" or uuid == "--help"
351     puts head_banner
352     puts "Usage: arv [--format json|yaml] get [uuid] [fields...]\n\n"
353     puts "Fetch the specified Arvados object, select the specified fields,\n"
354     puts "and print a text representation.\n"
355     exit 255
356   end
357
358   rsc = lookup_uuid_rsc arvados, uuid
359   obj = fetch_rsc_obj client, arvados, rsc, uuid, remaining_opts
360   content = get_obj_content obj, global_opts
361
362   puts content
363   exit 0
364 end
365
366 def arv_create client, arvados, global_opts, remaining_opts
367   types = resource_types(arvados.discovery_document)
368   create_opts = Optimist::options do
369     opt :project_uuid, "Project uuid in which to create the object", :type => :string
370     stop_on resource_types(arvados.discovery_document)
371   end
372
373   object_type = remaining_opts.shift
374   if object_type.nil?
375     abort "Missing resource type, must be one of #{types.join ', '}"
376   end
377
378   rsc = arvados.discovery_document["resources"].keys.select { |k| object_type == k.singularize }
379   if rsc.empty?
380     abort "Could not determine resource type #{object_type}"
381   end
382   rsc = rsc.first
383
384   discovered_params = arvados.discovery_document["resources"][rsc]["methods"]["create"]["parameters"]
385   method_opts = Optimist::options do
386     banner head_banner
387     banner "Usage: arv create [--project-uuid] #{object_type} [create parameters]"
388     banner ""
389     banner "This method supports the following parameters:"
390     banner ""
391     discovered_params.each do |k,v|
392       opts = Hash.new()
393       opts[:type] = v["type"].to_sym if v.include?("type")
394       if [:datetime, :text, :object, :array].index opts[:type]
395         opts[:type] = :string                       # else optimist bork
396       end
397       opts[:default] = v["default"] if v.include?("default")
398       opts[:default] = v["default"].to_i if opts[:type] == :integer
399       opts[:default] = to_boolean(v["default"]) if opts[:type] == :boolean
400       opts[:required] = true if v.include?("required") and v["required"]
401       description = ''
402       description = '  ' + v["description"] if v.include?("description")
403       opt k.to_sym, description, opts
404     end
405   end
406
407   initial_obj = {}
408   if create_opts[:project_uuid]
409     initial_obj["owner_uuid"] = create_opts[:project_uuid]
410   end
411
412   edit_and_commit_object initial_obj, "", global_opts do |newobj|
413     result = client.execute(:api_method => eval('arvados.' + rsc + '.create'),
414                    :parameters => method_opts,
415                    :body_object => {object_type => newobj},
416                    :authenticated => false,
417                    :headers => {
418                      authorization: 'OAuth2 '+ENV['ARVADOS_API_TOKEN']
419                    })
420     results = check_response result
421     puts "Created object #{results['uuid']}"
422   end
423
424   exit 0
425 end
426
427 def to_boolean(s)
428   !!(s =~ /^(true|t|yes|y|1)$/i)
429 end
430
431 def head_banner
432   "Arvados command line client\n"
433 end
434
435 def help_methods(discovery_document, resource, method=nil)
436   banner = head_banner
437   banner += "Usage: arv #{resource} [method] [--parameters]\n"
438   banner += "Use 'arv #{resource} [method] --help' to get more information about specific methods.\n\n"
439   banner += "The #{resource} resource supports the following methods:"
440   banner += "\n\n"
441   discovery_document["resources"][resource.pluralize]["methods"].
442     each do |k,v|
443     description = ''
444     if v.include? "description"
445       # add only the first line of the discovery doc description
446       description = '  ' + v["description"].split("\n").first.chomp
447     end
448     banner += "   #{sprintf("%20s",k)}#{description}\n"
449   end
450   banner += "\n"
451   STDERR.puts banner
452
453   if not method.nil? and method != '--help' and method != '-h' then
454     abort "Unknown method #{method.inspect} " +
455                   "for resource #{resource.inspect}"
456   end
457   exit 255
458 end
459
460 def help_resources(option_parser, discovery_document, resource)
461   option_parser.educate
462   exit 255
463 end
464
465 def resource_types discovery_document
466   resource_types = Array.new()
467   discovery_document["resources"].each do |k,v|
468     resource_types << k.singularize
469   end
470   resource_types
471 end
472
473 def parse_arguments(discovery_document, subcommands)
474   resources_and_subcommands = resource_types(discovery_document) + subcommands
475
476   option_parser = Optimist::Parser.new do
477     version __FILE__
478     banner head_banner
479     banner "Usage: arv [--flags] subcommand|resource [method] [--parameters]"
480     banner ""
481     banner "Available flags:"
482
483     opt :dry_run, "Don't actually do anything", :short => "-n"
484     opt :verbose, "Print some things on stderr"
485     opt :format,
486         "Set the output format. Must be one of json (default), yaml or uuid.",
487         :type => :string,
488         :default => 'json'
489     opt :short, "Return only UUIDs (equivalent to --format=uuid)"
490
491     banner ""
492     banner "Use 'arv subcommand|resource --help' to get more information about a particular command or resource."
493     banner ""
494     banner "Available subcommands: #{subcommands.join(', ')}"
495     banner ""
496
497     banner "Available resources: #{discovery_document['resources'].keys.map { |k| k.singularize }.join(', ')}"
498
499     banner ""
500     banner "Additional options:"
501
502     conflicts :short, :format
503     stop_on resources_and_subcommands
504   end
505
506   global_opts = Optimist::with_standard_exception_handling option_parser do
507     o = option_parser.parse ARGV
508   end
509
510   unless %w(json yaml uuid).include?(global_opts[:format])
511     $stderr.puts "#{$0}: --format must be one of json, yaml or uuid."
512     $stderr.puts "Use #{$0} --help for more information."
513     abort
514   end
515
516   if global_opts[:short]
517     global_opts[:format] = 'uuid'
518   end
519
520   resource = ARGV.shift
521
522   if not subcommands.include? resource
523     if not resources_and_subcommands.include?(resource)
524       puts "Resource or subcommand '#{resource}' is not recognized.\n\n" if !resource.nil?
525       help_resources(option_parser, discovery_document, resource)
526     end
527
528     method = ARGV.shift
529     if not (discovery_document["resources"][resource.pluralize]["methods"].
530             include?(method))
531       help_methods(discovery_document, resource, method)
532     end
533
534     discovered_params = discovery_document\
535     ["resources"][resource.pluralize]\
536     ["methods"][method]["parameters"]
537     method_opts = Optimist::options do
538       banner head_banner
539       banner "Usage: arv #{resource} #{method} [--parameters]"
540       banner ""
541       banner "This method supports the following parameters:"
542       banner ""
543       discovered_params.each do |k,v|
544         opts = Hash.new()
545         opts[:type] = v["type"].to_sym if v.include?("type")
546         if [:datetime, :text, :object, :array].index opts[:type]
547           opts[:type] = :string                       # else optimist bork
548         end
549         opts[:default] = v["default"] if v.include?("default")
550         opts[:default] = v["default"].to_i if opts[:type] == :integer
551         opts[:default] = to_boolean(v["default"]) if opts[:type] == :boolean
552         opts[:required] = true if v.include?("required") and v["required"]
553         description = ''
554         description = '  ' + v["description"] if v.include?("description")
555         opt k.to_sym, description, opts
556       end
557
558       body_object = discovery_document["resources"][resource.pluralize]["methods"][method]["request"]
559       if body_object and discovered_params[resource].nil?
560         is_required = true
561         if body_object["required"] == false
562           is_required = false
563         end
564         resource_opt_desc = "Either a string representing #{resource} as JSON or a filename from which to read #{resource} JSON (use '-' to read from stdin)."
565         if is_required
566           resource_opt_desc += " This option must be specified."
567         end
568         opt resource.to_sym, resource_opt_desc, {
569           required: is_required,
570           type: :string
571         }
572       end
573     end
574
575     discovered_params.merge({resource => {'type' => 'object'}}).each do |k,v|
576       k = k.to_sym
577       if ['object', 'array'].index(v["type"]) and method_opts.has_key? k
578         if method_opts[k].andand.match /^\//
579           method_opts[k] = File.open method_opts[k], 'rb' do |f| f.read end
580         end
581       end
582     end
583   end
584
585   return resource, method, method_opts, global_opts, ARGV
586 end
587
588 #
589 # ENTRY POINT
590 #
591
592 init_config
593
594 ENV['ARVADOS_API_VERSION'] ||= 'v1'
595
596 if not ENV.include?('ARVADOS_API_HOST') or not ENV.include?('ARVADOS_API_TOKEN') then
597   abort <<-EOS
598 ARVADOS_API_HOST and ARVADOS_API_TOKEN need to be defined as environment variables.
599   EOS
600 end
601
602 # do this if you're testing with a dev server and you don't care about SSL certificate checks:
603 if ENV['ARVADOS_API_HOST_INSECURE']
604   suppress_warnings { OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE }
605 end
606
607 begin
608   client = ArvadosClient.new(:host => ENV['ARVADOS_API_HOST'], :application_name => 'arvados-cli', :application_version => '1.0')
609   arvados = client.discovered_api('arvados', ENV['ARVADOS_API_VERSION'])
610 rescue Exception => e
611   puts "Failed to connect to Arvados API server: #{e}"
612   exit 1
613 end
614
615 # Parse arguments here
616 resource_schema, method, method_opts, global_opts, remaining_opts = parse_arguments(arvados.discovery_document, subcommands)
617
618 check_subcommands client, arvados, resource_schema, global_opts, remaining_opts
619
620 controller = resource_schema.pluralize
621
622 api_method = 'arvados.' + controller + '.' + method
623
624 if global_opts[:dry_run]
625   if global_opts[:verbose]
626     $stderr.puts "#{api_method} #{method_opts.inspect}"
627   end
628   exit
629 end
630
631 request_parameters = {_profile:true}.merge(method_opts)
632 resource_body = request_parameters.delete(resource_schema.to_sym)
633 if resource_body
634   # check if resource_body is valid JSON by attempting to parse it
635   resource_body_is_json = true
636   begin
637     # we don't actually need the results of the parsing,
638     # just checking for the JSON::ParserError exception
639     JSON.parse resource_body
640   rescue JSON::ParserError => e
641     resource_body_is_json = false
642   end
643   resource_body_is_readable_file = false
644   # if resource_body is not valid JSON, it should be a filename (or '-' for stdin)
645   if resource_body == '-'
646     resource_body_is_readable_file = true
647     resource_body_file = $stdin
648   elsif File.readable? resource_body
649       resource_body_is_readable_file = true
650       resource_body_file = File.open(resource_body, 'r')
651   end
652   if resource_body_is_json and resource_body_is_readable_file
653     abort "Argument specified for option '--#{resource_schema.to_sym}' is both valid JSON and a readable file. Please consider renaming the file: '#{resource_body}'"
654   elsif !resource_body_is_json and !resource_body_is_readable_file
655     if File.exists? resource_body
656       # specified file exists but is not readable
657       abort "Argument specified for option '--#{resource_schema.to_sym}' is an existing file but is not readable. Please check permissions on: '#{resource_body}'"
658     else
659       # specified file does not exist
660       abort "Argument specified for option '--#{resource_schema.to_sym}' is neither valid JSON nor an existing file: '#{resource_body}'"
661     end
662   elsif resource_body_is_readable_file
663     resource_body = resource_body_file.read()
664     begin
665       # we don't actually need the results of the parsing,
666       # just checking for the JSON::ParserError exception
667       JSON.parse resource_body
668     rescue JSON::ParserError => e
669       abort "Contents of file '#{resource_body_file.path}' is not valid JSON: #{e}"
670     end
671     resource_body_file.close()
672   end
673   request_body = {
674     resource_schema => resource_body
675   }
676 else
677   request_body = nil
678 end
679
680 case api_method
681 when
682   'arvados.jobs.log_tail_follow'
683
684   # Special case for methods that respond with data streams rather
685   # than JSON (TODO: use the discovery document instead of a static
686   # list of methods)
687   uri_s = eval(api_method).generate_uri(request_parameters)
688   Curl::Easy.perform(uri_s) do |curl|
689     curl.headers['Accept'] = 'text/plain'
690     curl.headers['Authorization'] = "OAuth2 #{ENV['ARVADOS_API_TOKEN']}"
691     if ENV['ARVADOS_API_HOST_INSECURE']
692       curl.ssl_verify_peer = false
693       curl.ssl_verify_host = false
694     end
695     if global_opts[:verbose]
696       curl.on_header { |data| $stderr.write data }
697     end
698     curl.on_body { |data| $stdout.write data }
699   end
700   exit 0
701 else
702   result = client.execute(:api_method => eval(api_method),
703                           :parameters => request_parameters,
704                           :body_object => request_body,
705                           :authenticated => false,
706                           :headers => {
707                             authorization: 'OAuth2 '+ENV['ARVADOS_API_TOKEN']
708                           })
709 end
710
711 begin
712   results = JSON.parse result.body
713 rescue JSON::ParserError => e
714   abort "Failed to parse server response:\n" + e.to_s
715 end
716
717 if results["errors"] then
718   abort "Error: #{results["errors"][0]}"
719 end
720
721 case global_opts[:format]
722 when 'json'
723   puts Oj.dump(results, :indent => 1)
724 when 'yaml'
725   puts results.to_yaml
726 else
727   if results["items"] and results["kind"].match /list$/i
728     results['items'].each do |i| puts i['uuid'] end
729   elsif results['uuid'].nil?
730     abort("Response did not include a uuid:\n" +
731           Oj.dump(results, :indent => 1) +
732           "\n")
733   else
734     puts results['uuid']
735   end
736 end