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