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