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