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