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