Merge branch 'master' into 4383-easy-install
[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'
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   when 'run'
154     exec `which arv-run`.strip, *remaining_opts
155   when 'tag'
156     exec `which arv-tag`.strip, *remaining_opts
157   when 'ws'
158     exec `which arv-ws`.strip, *remaining_opts
159   end
160 end
161
162 def arv_edit_save_tmp tmp
163   FileUtils::cp tmp.path, tmp.path + ".saved"
164   puts "Saved contents to " + tmp.path + ".saved"
165 end
166
167 def command_exists?(command)
168   ENV['PATH'].split(':').each {|folder| File.executable?(File.join(folder, command))}
169 end
170
171 def run_editor tmp_file, global_opts
172   need_edit = true
173   while need_edit
174     pid = Process::fork
175     if pid.nil?
176       editor = nil
177       [ENV["VISUAL"], ENV["EDITOR"], "nano", "vi"].each do |e|
178         editor ||= e if e and command_exists? e
179       end
180       if editor.nil?
181         puts "Could not find any editor to use, please set $VISUAL or $EDITOR to your desired editor."
182         exit 1
183       end
184       exec editor, tmp_file.path
185     else
186       Process.wait pid
187     end
188
189     if $?.exitstatus == 0
190       tmp_file.open
191       newcontent = tmp_file.read()
192
193       newobj = {}
194       begin
195         case global_opts[:format]
196         when 'json'
197           newobj = Oj.load(newcontent)
198         when 'yaml'
199           newobj = YAML.load(newcontent)
200         end
201         need_edit = false
202       rescue Exception => e
203         n = 1
204         newcontent.each_line do |line|
205           puts "#{n.to_s.rjust 4}  #{line}"
206           n += 1
207         end
208         puts "Parse error! " + e.to_s
209         puts "\nTry again (y/n)? "
210         yn = "X"
211         while not ["y", "Y", "n", "N"].include?(yn)
212           yn = $stdin.read 1
213         end
214         if yn == 'n' or yn == 'N'
215           arv_edit_save_tmp tmp_file
216           abort
217         end
218       end
219     else
220       puts "Editor exited with status #{$?.exitstatus}"
221       exit $?.exitstatus
222     end
223   end
224
225   newobj
226 end
227
228 def arv_edit client, arvados, global_opts, remaining_opts
229   uuid = remaining_opts.shift
230   if uuid.nil? or uuid == "-h" or uuid == "--help"
231     puts head_banner
232     puts "Usage: arv edit [uuid] [fields...]\n\n"
233     puts "Fetch the specified Arvados object, select the specified fields, \n"
234     puts "open an interactive text editor on a text representation (json or\n"
235     puts "yaml, use --format) and then update the object.  Will use 'nano'\n"
236     puts "by default, customize with the EDITOR or VISUAL environment variable.\n"
237     exit 255
238   end
239
240   if not $stdout.tty?
241     puts "Not connected to a TTY, cannot run interactive editor."
242     exit 1
243   end
244
245   # determine controller
246
247   m = /([a-z0-9]{5})-([a-z0-9]{5})-([a-z0-9]{15})/.match uuid
248   if !m
249     if /^[a-f0-9]{32}/.match uuid
250       abort "Arvados collections are not editable."
251     else
252       abort "#{n} does not appear to be an Arvados uuid"
253     end
254   end
255
256   rsc = nil
257   arvados.discovery_document["resources"].each do |k,v|
258     klass = k.singularize.camelize
259     dig = Digest::MD5.hexdigest(klass).to_i(16).to_s(36)[-5..-1]
260     if dig == m[2]
261       rsc = k
262     end
263   end
264
265   if rsc.nil?
266     abort "Could not determine resource type #{m[2]}"
267   end
268
269   api_method = 'arvados.' + rsc + '.get'
270
271   result = client.execute(:api_method => eval(api_method),
272                           :parameters => {"uuid" => uuid},
273                           :authenticated => false,
274                           :headers => {
275                             authorization: 'OAuth2 '+ENV['ARVADOS_API_TOKEN']
276                           })
277   begin
278     results = JSON.parse result.body
279   rescue JSON::ParserError => e
280     abort "Failed to parse server response:\n" + e.to_s
281   end
282
283   if remaining_opts.length > 0
284     results.select! { |k, v| remaining_opts.include? k }
285   end
286
287   content = ""
288
289   case global_opts[:format]
290   when 'json'
291     content = Oj.dump(results, :indent => 1)
292   when 'yaml'
293     content = results.to_yaml
294   end
295
296   tmp_file = Tempfile.new([uuid, "." + global_opts[:format]])
297   tmp_file.write(content)
298   tmp_file.close
299
300   newobj = run_editor tmp_file, global_opts
301
302   begin
303     if newobj != results
304       api_method = 'arvados.' + rsc + '.update'
305       dumped = Oj.dump(newobj)
306
307       begin
308         result = client.execute(:api_method => eval(api_method),
309                                 :parameters => {"uuid" => uuid},
310                                 :body_object => { rsc.singularize => dumped },
311                                 :authenticated => false,
312                                 :headers => {
313                                   authorization: 'OAuth2 '+ENV['ARVADOS_API_TOKEN']
314                                 })
315       rescue Exception => e
316         puts "Error communicating with server, error was #{e}"
317         puts "Update body was:"
318         puts dumped
319         arv_edit_save_tmp tmp_file
320         abort
321       end
322
323       begin
324         results = JSON.parse result.body
325       rescue JSON::ParserError => e
326         arv_edit_save_tmp tmp_file
327         abort "Failed to parse server response:\n" + e.to_s
328       end
329
330       if result.response.status != 200
331         puts "Update failed.  Server responded #{result.response.status}: #{results['errors']} "
332         puts "Update body was:"
333         puts dumped
334         arv_edit_save_tmp tmp_file
335         abort
336       end
337     else
338       puts "Object is unchanged, did not update."
339     end
340   ensure
341     tmp_file.close(true)
342   end
343
344   exit 0
345 end
346
347 def arv_create client, arvados, global_opts, remaining_opts
348   types = resource_types(arvados.discovery_document)
349   create_opts = Trollop::options do
350     opt :project_uuid, "Project uuid in which to create the object", :type => :string
351     stop_on resource_types(arvados.discovery_document)
352   end
353
354   object_type = remaining_opts.shift
355   if object_type.nil?
356     abort "Missing resource type, must be one of #{types.join ', '}"
357   end
358
359   rsc = arvados.discovery_document["resources"].keys.select { |k| object_type == k.singularize }
360   if rsc.empty?
361     abort "Could not determine resource type #{object_type}"
362   end
363   rsc = rsc.first
364
365   discovered_params = arvados.discovery_document["resources"][rsc]["methods"]["create"]["parameters"]
366   method_opts = Trollop::options do
367     banner head_banner
368     banner "Usage: arv create [--project-uuid] #{object_type} [create parameters]"
369     banner ""
370     banner "This method supports the following parameters:"
371     banner ""
372     discovered_params.each do |k,v|
373       opts = Hash.new()
374       opts[:type] = v["type"].to_sym if v.include?("type")
375       if [:datetime, :text, :object, :array].index opts[:type]
376         opts[:type] = :string                       # else trollop bork
377       end
378       opts[:default] = v["default"] if v.include?("default")
379       opts[:default] = v["default"].to_i if opts[:type] == :integer
380       opts[:default] = to_boolean(v["default"]) if opts[:type] == :boolean
381       opts[:required] = true if v.include?("required") and v["required"]
382       description = ''
383       description = '  ' + v["description"] if v.include?("description")
384       opt k.to_sym, description, opts
385     end
386   end
387
388
389   newobj = {}
390   if create_opts[:project_uuid]
391     newobj["owner_uuid"] = create_opts[:project_uuid]
392   end
393
394   case global_opts[:format]
395   when 'json'
396     content = Oj.dump(newobj, :indent => 1)
397   when 'yaml'
398     content = newobj.to_yaml
399   end
400
401   tmp_file = Tempfile.new(["", ".#{global_opts[:format]}"])
402   tmp_file.write(content)
403   tmp_file.close
404
405   newobj = run_editor tmp_file, global_opts
406
407   begin
408     api_method = 'arvados.' + rsc + '.create'
409     dumped = Oj.dump(newobj)
410
411     result = client.execute(:api_method => eval(api_method),
412                             :parameters => method_opts,
413                             :body_object => {object_type => newobj},
414                             :authenticated => false,
415                             :headers => {
416                               authorization: 'OAuth2 '+ENV['ARVADOS_API_TOKEN']
417                             })
418
419     begin
420       results = JSON.parse result.body
421     rescue JSON::ParserError => e
422       arv_edit_save_tmp tmp_file
423       abort "Failed to parse server response:\n" + e.to_s
424     end
425
426     if result.response.status != 200
427       puts "Create failed.  Server responded #{result.response.status}: #{results['errors']} "
428       puts "Create body was:"
429       puts dumped
430       arv_edit_save_tmp tmp_file
431       abort
432     end
433
434     begin
435       puts "Created object #{results['uuid']}"
436     rescue
437       arv_edit_save_tmp tmp_file
438       abort "Unexpected response:\n#{results}"
439     end
440   ensure
441     tmp_file.close(true)
442   end
443
444   exit 0
445 end
446
447 def to_boolean(s)
448   !!(s =~ /^(true|t|yes|y|1)$/i)
449 end
450
451 def head_banner
452   "Arvados command line client\n"
453 end
454
455 def help_methods(discovery_document, resource, method=nil)
456   banner = head_banner
457   banner += "Usage: arv #{resource} [method] [--parameters]\n"
458   banner += "Use 'arv #{resource} [method] --help' to get more information about specific methods.\n\n"
459   banner += "The #{resource} resource supports the following methods:"
460   banner += "\n\n"
461   discovery_document["resources"][resource.pluralize]["methods"].
462     each do |k,v|
463     description = ''
464     if v.include? "description"
465       # add only the first line of the discovery doc description
466       description = '  ' + v["description"].split("\n").first.chomp
467     end
468     banner += "   #{sprintf("%20s",k)}#{description}\n"
469   end
470   banner += "\n"
471   STDERR.puts banner
472
473   if not method.nil? and method != '--help' and method != '-h' then
474     abort "Unknown method #{method.inspect} " +
475                   "for resource #{resource.inspect}"
476   end
477   exit 255
478 end
479
480 def help_resources(option_parser, discovery_document, resource)
481   option_parser.educate
482   exit 255
483 end
484
485 def resource_types discovery_document
486   resource_types = Array.new()
487   discovery_document["resources"].each do |k,v|
488     resource_types << k.singularize
489   end
490   resource_types
491 end
492
493 def parse_arguments(discovery_document, subcommands)
494   resources_and_subcommands = resource_types(discovery_document) + subcommands
495
496   option_parser = Trollop::Parser.new do
497     version __FILE__
498     banner head_banner
499     banner "Usage: arv [--flags] subcommand|resource [method] [--parameters]"
500     banner ""
501     banner "Available flags:"
502
503     opt :dry_run, "Don't actually do anything", :short => "-n"
504     opt :verbose, "Print some things on stderr"
505     opt :format,
506         "Set the output format. Must be one of json (default), yaml or uuid.",
507         :type => :string,
508         :default => 'json'
509     opt :short, "Return only UUIDs (equivalent to --format=uuid)"
510
511     banner ""
512     banner "Use 'arv subcommand|resource --help' to get more information about a particular command or resource."
513     banner ""
514     banner "Available subcommands: #{subcommands.join(', ')}"
515     banner ""
516
517     banner "Available resources: #{discovery_document['resources'].keys.map { |k| k.singularize }.join(', ')}"
518
519     banner ""
520     banner "Additional options:"
521
522     conflicts :short, :format
523     stop_on resources_and_subcommands
524   end
525
526   global_opts = Trollop::with_standard_exception_handling option_parser do
527     o = option_parser.parse ARGV
528   end
529
530   unless %w(json yaml uuid).include?(global_opts[:format])
531     $stderr.puts "#{$0}: --format must be one of json, yaml or uuid."
532     $stderr.puts "Use #{$0} --help for more information."
533     abort
534   end
535
536   if global_opts[:short]
537     global_opts[:format] = 'uuid'
538   end
539
540   resource = ARGV.shift
541
542   if not subcommands.include? resource
543     if not resources_and_subcommands.include?(resource)
544       puts "Resource or subcommand '#{resource}' is not recognized.\n\n" if !resource.nil?
545       help_resources(option_parser, discovery_document, resource)
546     end
547
548     method = ARGV.shift
549     if not (discovery_document["resources"][resource.pluralize]["methods"].
550             include?(method))
551       help_methods(discovery_document, resource, method)
552     end
553
554     discovered_params = discovery_document\
555     ["resources"][resource.pluralize]\
556     ["methods"][method]["parameters"]
557     method_opts = Trollop::options do
558       banner head_banner
559       banner "Usage: arv #{resource} #{method} [--parameters]"
560       banner ""
561       banner "This method supports the following parameters:"
562       banner ""
563       discovered_params.each do |k,v|
564         opts = Hash.new()
565         opts[:type] = v["type"].to_sym if v.include?("type")
566         if [:datetime, :text, :object, :array].index opts[:type]
567           opts[:type] = :string                       # else trollop bork
568         end
569         opts[:default] = v["default"] if v.include?("default")
570         opts[:default] = v["default"].to_i if opts[:type] == :integer
571         opts[:default] = to_boolean(v["default"]) if opts[:type] == :boolean
572         opts[:required] = true if v.include?("required") and v["required"]
573         description = ''
574         description = '  ' + v["description"] if v.include?("description")
575         opt k.to_sym, description, opts
576       end
577
578       body_object = discovery_document["resources"][resource.pluralize]["methods"][method]["request"]
579       if body_object and discovered_params[resource].nil?
580         is_required = true
581         if body_object["required"] == false
582           is_required = false
583         end
584         opt resource.to_sym, "#{resource} (request body)", {
585           required: is_required,
586           type: :string
587         }
588       end
589     end
590
591     discovered_params.each do |k,v|
592       k = k.to_sym
593       if ['object', 'array'].index(v["type"]) and method_opts.has_key? k
594         if method_opts[k].andand.match /^\//
595           method_opts[k] = File.open method_opts[k], 'rb' do |f| f.read end
596         end
597       end
598     end
599   end
600
601   return resource, method, method_opts, global_opts, ARGV
602 end
603
604 #
605 # ENTRY POINT
606 #
607
608 init_config
609
610 ENV['ARVADOS_API_VERSION'] ||= 'v1'
611
612 if not ENV.include?('ARVADOS_API_HOST') or not ENV.include?('ARVADOS_API_TOKEN') then
613   abort <<-EOS
614 ARVADOS_API_HOST and ARVADOS_API_TOKEN need to be defined as environment variables.
615   EOS
616 end
617
618 # do this if you're testing with a dev server and you don't care about SSL certificate checks:
619 if ENV['ARVADOS_API_HOST_INSECURE']
620   suppress_warnings { OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE }
621 end
622
623 begin
624   client = ArvadosClient.new(:host => ENV['ARVADOS_API_HOST'], :application_name => 'arvados-cli', :application_version => '1.0')
625   arvados = client.discovered_api('arvados', ENV['ARVADOS_API_VERSION'])
626 rescue Exception => e
627   puts "Failed to connect to Arvados API server: #{e}"
628   exit 1
629 end
630
631 # Parse arguments here
632 resource_schema, method, method_opts, global_opts, remaining_opts = parse_arguments(arvados.discovery_document, subcommands)
633
634 check_subcommands client, arvados, resource_schema, global_opts, remaining_opts
635
636 controller = resource_schema.pluralize
637
638 api_method = 'arvados.' + controller + '.' + method
639
640 if global_opts[:dry_run]
641   if global_opts[:verbose]
642     $stderr.puts "#{api_method} #{method_opts.inspect}"
643   end
644   exit
645 end
646
647 request_parameters = {_profile:true}.merge(method_opts)
648 resource_body = request_parameters.delete(resource_schema.to_sym)
649 if resource_body
650   request_body = {
651     resource_schema => resource_body
652   }
653 else
654   request_body = nil
655 end
656
657 case api_method
658 when
659   'arvados.jobs.log_tail_follow'
660
661   # Special case for methods that respond with data streams rather
662   # than JSON (TODO: use the discovery document instead of a static
663   # list of methods)
664   uri_s = eval(api_method).generate_uri(request_parameters)
665   Curl::Easy.perform(uri_s) do |curl|
666     curl.headers['Accept'] = 'text/plain'
667     curl.headers['Authorization'] = "OAuth2 #{ENV['ARVADOS_API_TOKEN']}"
668     if ENV['ARVADOS_API_HOST_INSECURE']
669       curl.ssl_verify_peer = false
670       curl.ssl_verify_host = false
671     end
672     if global_opts[:verbose]
673       curl.on_header { |data| $stderr.write data }
674     end
675     curl.on_body { |data| $stdout.write data }
676   end
677   exit 0
678 else
679   result = client.execute(:api_method => eval(api_method),
680                           :parameters => request_parameters,
681                           :body_object => request_body,
682                           :authenticated => false,
683                           :headers => {
684                             authorization: 'OAuth2 '+ENV['ARVADOS_API_TOKEN']
685                           })
686 end
687
688 begin
689   results = JSON.parse result.body
690 rescue JSON::ParserError => e
691   abort "Failed to parse server response:\n" + e.to_s
692 end
693
694 if results["errors"] then
695   abort "Error: #{results["errors"][0]}"
696 end
697
698 case global_opts[:format]
699 when 'json'
700   puts Oj.dump(results, :indent => 1)
701 when 'yaml'
702   puts results.to_yaml
703 else
704   if results["items"] and results["kind"].match /list$/i
705     results['items'].each do |i| puts i['uuid'] end
706   elsif results['uuid'].nil?
707     abort("Response did not include a uuid:\n" +
708           Oj.dump(results, :indent => 1) +
709           "\n")
710   else
711     puts results['uuid']
712   end
713 end