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