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