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