2986: Cleaned up arv cli help to be more helpful and consistent. refs #1667.
[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 # read authentication data from arvados configuration file if present
16 lineno = 0
17 config_file = File.expand_path('~/.config/arvados/settings.conf')
18 if File.exist? config_file then
19   File.open(config_file, 'r').each do |line|
20     lineno = lineno + 1
21     # skip comments
22     if line.match('^\s*#') then
23       next
24     end
25     var, val = line.chomp.split('=', 2)
26     # allow environment settings to override config files.
27     if var and val
28       ENV[var] ||= val
29     else
30       warn "#{config_file}: #{lineno}: could not parse `#{line}'"
31     end
32   end
33 end
34
35 subcommands = %w(keep pipeline tag ws)
36
37 case ARGV[0]
38 when 'keep'
39   ARGV.shift
40   @sub = ARGV.shift
41   if ['get', 'put', 'ls', 'normalize'].index @sub then
42     # Native Arvados
43     exec `which arv-#{@sub}`.strip, *ARGV
44   elsif ['less', 'check'].index @sub then
45     # wh* shims
46     exec `which wh#{@sub}`.strip, *ARGV
47   elsif @sub == 'docker'
48     exec `which arv-keepdocker`.strip, *ARGV
49   else
50     puts "Usage: \n" +
51       "#{$0} keep ls\n" +
52       "#{$0} keep get\n" +
53       "#{$0} keep put\n" +
54       "#{$0} keep less\n" +
55       "#{$0} keep check\n" +
56       "#{$0} keep docker\n"
57   end
58   abort
59 when 'pipeline'
60   ARGV.shift
61   @sub = ARGV.shift
62   if ['run'].index @sub then
63     exec `which arv-run-pipeline-instance`.strip, *ARGV
64   else
65     puts "Usage: \n" +
66       "#{$0} pipeline run [...]\n" +
67       "(see arv-run-pipeline-instance --help for details)\n"
68   end
69   abort
70 when 'tag'
71   ARGV.shift
72   exec `which arv-tag`.strip, *ARGV
73 when 'ws'
74   ARGV.shift
75   exec `which arv-ws`.strip, *ARGV
76 end
77
78 ENV['ARVADOS_API_VERSION'] ||= 'v1'
79
80 if not ENV.include?('ARVADOS_API_HOST') or not ENV.include?('ARVADOS_API_TOKEN') then
81   abort <<-EOS
82 ARVADOS_API_HOST and ARVADOS_API_TOKEN need to be defined as environment variables.
83   EOS
84 end
85
86 begin
87   require 'curb'
88   require 'rubygems'
89   require 'google/api_client'
90   require 'json'
91   require 'pp'
92   require 'trollop'
93   require 'andand'
94   require 'oj'
95   require 'active_support/inflector'
96   require 'yaml'
97 rescue LoadError
98   abort <<-EOS
99
100 Please install all required gems:
101
102   gem install activesupport andand curb google-api-client json oj trollop
103
104   EOS
105 end
106
107 ActiveSupport::Inflector.inflections do |inflect|
108   inflect.irregular 'specimen', 'specimens'
109   inflect.irregular 'human', 'humans'
110 end
111
112 module Kernel
113   def suppress_warnings
114     original_verbosity = $VERBOSE
115     $VERBOSE = nil
116     result = yield
117     $VERBOSE = original_verbosity
118     return result
119   end
120 end
121
122 # do this if you're testing with a dev server and you don't care about SSL certificate checks:
123 if ENV['ARVADOS_API_HOST_INSECURE']
124   suppress_warnings { OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE }
125 end
126
127 class Google::APIClient
128  def discovery_document(api, version)
129    api = api.to_s
130    return @discovery_documents["#{api}:#{version}"] ||=
131      begin
132        # fetch new API discovery doc if stale
133        cached_doc = File.expand_path '~/.cache/arvados/discovery_uri.json'
134        if not File.exist?(cached_doc) or (Time.now - File.mtime(cached_doc)) > 86400
135          response = self.execute!(:http_method => :get,
136                                   :uri => self.discovery_uri(api, version),
137                                   :authenticated => false)
138          FileUtils.makedirs(File.dirname cached_doc)
139          File.open(cached_doc, 'w') do |f|
140            f.puts response.body
141          end
142        end
143
144        File.open(cached_doc) { |f| JSON.load f }
145      end
146  end
147 end
148
149 class ArvadosClient < Google::APIClient
150   def execute(*args)
151     if args.last.is_a? Hash
152       args.last[:headers] ||= {}
153       args.last[:headers]['Accept'] ||= 'application/json'
154     end
155     super(*args)
156   end
157 end
158
159 begin
160   client = ArvadosClient.new(:host => ENV['ARVADOS_API_HOST'], :application_name => 'arvados-cli', :application_version => '1.0')
161   arvados = client.discovered_api('arvados', ENV['ARVADOS_API_VERSION'])
162 rescue Exception => e
163   puts "Failed to connect to Arvados API server: #{e}"
164   exit 1
165 end
166
167 def to_boolean(s)
168   !!(s =~ /^(true|t|yes|y|1)$/i)
169 end
170
171 def head_banner
172   "Arvados command line client\n"
173 end
174
175 def help_methods(discovery_document, resource, method=nil)
176   banner = head_banner
177   banner += "Usage: arv #{resource} [method] [--parameters]\n"
178   banner += "Use 'arv #{resource} [method] --help' to get more information about specific methods.\n\n"
179   banner += "The #{resource} resource supports the following methods:"
180   banner += "\n\n"
181   discovery_document["resources"][resource.pluralize]["methods"].
182     each do |k,v|
183     description = ''
184     if v.include? "description"
185       # add only the first line of the discovery doc description
186       description = '  ' + v["description"].split("\n").first.chomp
187     end
188     banner += "   #{sprintf("%20s",k)}#{description}\n"
189   end
190   banner += "\n"
191   STDERR.puts banner
192
193   if not method.nil? and method != '--help' and method != '-h' then
194     Trollop::die ("Unknown method #{method.inspect} " +
195                   "for resource #{resource.inspect}")
196   end
197   exit 255
198 end
199
200 def help_resources(option_parser, discovery_document, resource)
201   option_parser.educate
202
203   if not resource.nil? and resource != '--help' then
204     Trollop::die "Unknown resource type #{resource.inspect}"
205   end
206   exit 255
207 end
208
209 def parse_arguments(discovery_document, subcommands)
210   resource_types = Array.new()
211   discovery_document["resources"].each do |k,v|
212     resource_types << k.singularize
213   end
214
215   option_parser = Trollop::Parser.new do
216     version __FILE__
217     banner head_banner
218     banner "Usage: arv [--flags] subcommand|resource [method] [--parameters]"
219     banner ""
220     banner "Available flags:"
221
222     opt :dry_run, "Don't actually do anything", :short => "-n"
223     opt :verbose, "Print some things on stderr"
224     opt :format,
225         "Set the output format. Must be one of json (default), yaml or uuid.",
226         :type => :string,
227         :default => 'json'
228     opt :short, "Return only UUIDs (equivalent to --format=uuid)"
229     opt :resources, "Display list of resources known to this Arvados instance."
230
231     banner ""
232     banner "Use 'arv subcommand|resource --help' to get more information about a particular command or resource."
233     banner ""
234     banner "Available subcommands: #{subcommands.join(', ')}"
235     banner ""
236
237     banner "Available resources: #{discovery_document['resources'].keys.map { |k| k.singularize }.join(', ')}"
238
239     banner ""
240     banner "Additional options:"
241
242     conflicts :short, :format
243     stop_on resource_types
244   end
245
246   global_opts = Trollop::with_standard_exception_handling option_parser do
247     o = option_parser.parse ARGV
248   end
249
250   unless %w(json yaml uuid).include?(global_opts[:format])
251     $stderr.puts "#{$0}: --format must be one of json, yaml or uuid."
252     $stderr.puts "Use #{$0} --help for more information."
253     abort
254   end
255
256   if global_opts[:short]
257     global_opts[:format] = 'uuid'
258   end
259
260   resource = ARGV.shift
261   if global_opts[:resources] or not resource_types.include?(resource)
262     help_resources(option_parser, discovery_document, resource)
263   end
264
265   method = ARGV.shift
266   if not (discovery_document["resources"][resource.pluralize]["methods"].
267           include?(method))
268     help_methods(discovery_document, resource, method)
269   end
270
271   discovered_params = discovery_document\
272     ["resources"][resource.pluralize]\
273     ["methods"][method]["parameters"]
274   method_opts = Trollop::options do
275     banner head_banner
276     banner "Usage: arv #{resource} #{method} [--parameters]"
277     banner ""
278     banner "This method supports the following parameters:"
279     banner ""
280     discovered_params.each do |k,v|
281       opts = Hash.new()
282       opts[:type] = v["type"].to_sym if v.include?("type")
283       if [:datetime, :text, :object, :array].index opts[:type]
284         opts[:type] = :string                       # else trollop bork
285       end
286       opts[:default] = v["default"] if v.include?("default")
287       opts[:default] = v["default"].to_i if opts[:type] == :integer
288       opts[:default] = to_boolean(v["default"]) if opts[:type] == :boolean
289       opts[:required] = true if v.include?("required") and v["required"]
290       description = ''
291       description = '  ' + v["description"] if v.include?("description")
292       opt k.to_sym, description, opts
293     end
294
295     body_object = discovery_document["resources"][resource.pluralize]["methods"][method]["request"]
296     if body_object and discovered_params[resource].nil?
297       is_required = true
298       if body_object["required"] == false
299         is_required = false
300       end
301       opt resource.to_sym, "#{resource} (request body)", {
302         required: is_required,
303         type: :string
304       }
305     end
306   end
307
308   discovered_params.each do |k,v|
309     k = k.to_sym
310     if ['object', 'array'].index(v["type"]) and method_opts.has_key? k
311       if method_opts[k].andand.match /^\//
312         method_opts[k] = File.open method_opts[k], 'rb' do |f| f.read end
313       end
314     end
315   end
316   return resource, method, method_opts, global_opts, ARGV
317 end
318
319 # Parse arguments here
320 resource_schema, method, method_opts, global_opts, remaining_opts = parse_arguments(arvados.discovery_document, subcommands)
321 controller = resource_schema.pluralize
322
323 api_method = 'arvados.' + controller + '.' + method
324
325 if global_opts[:dry_run]
326   if global_opts[:verbose]
327     $stderr.puts "#{api_method} #{method_opts.inspect}"
328   end
329   exit
330 end
331
332 request_parameters = {_profile:true}.merge(method_opts)
333 resource_body = request_parameters.delete(resource_schema.to_sym)
334 if resource_body
335   request_body = {
336     resource_schema => resource_body
337   }
338 else
339   request_body = nil
340 end
341
342 case api_method
343 when
344   'arvados.jobs.log_tail_follow'
345
346   # Special case for methods that respond with data streams rather
347   # than JSON (TODO: use the discovery document instead of a static
348   # list of methods)
349   uri_s = eval(api_method).generate_uri(request_parameters)
350   Curl::Easy.perform(uri_s) do |curl|
351     curl.headers['Accept'] = 'text/plain'
352     curl.headers['Authorization'] = "OAuth2 #{ENV['ARVADOS_API_TOKEN']}"
353     if ENV['ARVADOS_API_HOST_INSECURE']
354       curl.ssl_verify_peer = false
355       curl.ssl_verify_host = false
356     end
357     if global_opts[:verbose]
358       curl.on_header { |data| $stderr.write data }
359     end
360     curl.on_body { |data| $stdout.write data }
361   end
362   exit 0
363 else
364   result = client.execute(:api_method => eval(api_method),
365                           :parameters => request_parameters,
366                           :body => request_body,
367                           :authenticated => false,
368                           :headers => {
369                             authorization: 'OAuth2 '+ENV['ARVADOS_API_TOKEN']
370                           })
371 end
372
373 begin
374   results = JSON.parse result.body
375 rescue JSON::ParserError => e
376   abort "Failed to parse server response:\n" + e.to_s
377 end
378
379 if results["errors"] then
380   abort "Error: #{results["errors"][0]}"
381 end
382
383 case global_opts[:format]
384 when 'json'
385   puts Oj.dump(results, :indent => 1)
386 when 'yaml'
387   puts results.to_yaml
388 else
389   if results["items"] and results["kind"].match /list$/i
390     results['items'].each do |i| puts i['uuid'] end
391   elsif results['uuid'].nil?
392     abort("Response did not include a uuid:\n" +
393           Oj.dump(results, :indent => 1) +
394           "\n")
395   else
396     puts results['uuid']
397   end
398 end