Handle unexpected server responses better, clean up usage/help code
[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 if RUBY_VERSION < '1.9.3' then
8   abort <<-EOS
9 #{$0.gsub(/^\.\//,'')} requires Ruby version 1.9.3 or higher.
10   EOS
11 end
12
13 case ARGV[0]
14 when 'keep'
15   ARGV.shift
16   @sub = ARGV.shift
17   if ['get', 'put'].index @sub then
18     # Native Arvados
19     exec `which arv-#{@sub}`.strip, *ARGV
20   elsif ['ls', 'less', 'check'].index @sub then
21     # wh* shims
22     exec `which wh#{@sub}`.strip, *ARGV
23   else
24     puts "Usage: \n" +
25       "#{$0} keep ls\n" +
26       "#{$0} keep get\n" +
27       "#{$0} keep put\n" +
28       "#{$0} keep less\n" +
29       "#{$0} keep check\n"
30   end
31   abort
32 when 'pipeline'
33   ARGV.shift
34   @sub = ARGV.shift
35   if ['run'].index @sub then
36     exec `which arv-run-pipeline-instance`.strip, *ARGV
37   else
38     puts "Usage: \n" +
39       "#{$0} pipeline run [...]\n" +
40       "(see arv-run-pipeline-instance --help for details)\n"
41   end
42   abort
43 end
44
45 ENV['ARVADOS_API_VERSION'] ||= 'v1'
46
47 if not ENV.include?('ARVADOS_API_HOST') or not ENV.include?('ARVADOS_API_TOKEN') then
48   abort <<-EOS
49 ARVADOS_API_HOST and ARVADOS_API_TOKEN need to be defined as environment variables.
50   EOS
51 end
52
53 begin
54   require 'rubygems'
55   require 'google/api_client'
56   require 'json'
57   require 'pp'
58   require 'trollop'
59   require 'andand'
60   require 'oj'
61   require 'active_support/inflector'
62 rescue LoadError
63   abort <<-EOS
64
65 Please install all required gems: 
66
67   gem install google-api-client json trollop andand oj activesupport
68
69   EOS
70 end
71
72 ActiveSupport::Inflector.inflections do |inflect|
73   inflect.irregular 'specimen', 'specimens'
74   inflect.irregular 'human', 'humans'
75 end
76
77 module Kernel
78   def suppress_warnings
79     original_verbosity = $VERBOSE
80     $VERBOSE = nil
81     result = yield
82     $VERBOSE = original_verbosity
83     return result
84   end
85 end
86
87 # do this if you're testing with a dev server and you don't care about SSL certificate checks:
88 if ENV['ARVADOS_API_HOST_INSECURE']
89   suppress_warnings { OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE }
90 end
91
92 class Google::APIClient
93  def discovery_document(api, version)
94   api = api.to_s
95   return @discovery_documents["#{api}:#{version}"] ||= (begin
96     response = self.execute!(
97       :http_method => :get,
98       :uri => self.discovery_uri(api, version),
99       :authenticated => false
100     )
101     response.body.class == String ? JSON.parse(response.body) : response.body
102   end)
103  end
104 end
105
106 class ArvadosClient < Google::APIClient
107   def execute(*args)
108     if args.last.is_a? Hash
109       args.last[:headers] ||= {}
110       args.last[:headers]['Accept'] ||= 'application/json'
111     end
112     super(*args)
113   end
114 end
115
116 client = ArvadosClient.new(:host => ENV['ARVADOS_API_HOST'], :application_name => 'arvados-cli', :application_version => '1.0')
117 arvados = client.discovered_api('arvados', ENV['ARVADOS_API_VERSION'])
118
119 def to_boolean(s)
120   !!(s =~ /^(true|t|yes|y|1)$/i)
121 end
122
123 def help_methods(discovery_document, resource, method=nil)
124   banner = "\n"
125   banner += "The #{resource} resource type supports the following methods:"
126   banner += "\n\n"
127   discovery_document["resources"][resource.pluralize]["methods"].
128     each do |k,v|
129     description = ''
130     description = '  ' + v["description"] if v.include?("description")
131     banner += "   #{sprintf("%20s",k)}#{description}\n"
132   end
133   banner += "\n"
134   STDERR.puts banner
135   
136   if not method.nil? and method != '--help' then 
137     Trollop::die ("Unknown method #{method.inspect} " +
138                   "for resource #{resource.inspect}")
139   end
140   exit 255
141 end
142
143 def help_resources(discovery_document, resource)
144   banner = "\n"
145   banner += "This Arvados instance supports the following resource types:"
146   banner += "\n\n"
147   discovery_document["resources"].each do |k,v|
148     description = ''
149     if discovery_document["schemas"].include?(k.singularize.capitalize) and 
150         discovery_document["schemas"][k.singularize.capitalize].include?('description') then
151       description = '  ' + discovery_document["schemas"][k.singularize.capitalize]["description"]
152     end
153     banner += "   #{sprintf("%30s",k.singularize)}#{description}\n"
154   end
155   banner += "\n"
156   STDERR.puts banner
157
158   if not resource.nil? and resource != '--help' then 
159     Trollop::die "Unknown resource type #{resource.inspect}"
160   end
161   exit 255
162 end
163
164 def parse_arguments(discovery_document)
165   resource_types = Array.new()
166   resource_types << '--help'
167   discovery_document["resources"].each do |k,v|
168     resource_types << k.singularize
169   end
170
171   global_opts = Trollop::options do
172     banner "arvados cli client"
173     opt :dry_run, "Don't actually do anything", :short => "-n"
174     opt :verbose, "Print some things on stderr", :short => "-v"
175     opt :uuid, "Return the UUIDs of the objects in the response, one per line (default)", :short => nil
176     opt :json, "Return the entire response received from the API server, as a JSON object", :short => "-j"
177     opt :human, "Return the response received from the API server, as a JSON object with whitespace added for human consumption", :short => "-h"
178     opt :pretty, "Synonym of --human", :short => nil
179     stop_on resource_types
180   end
181   
182   resource = ARGV.shift
183   if resource == '--help' or not resource_types.include?(resource)
184     help_resources(discovery_document, resource)
185   end
186
187   method = ARGV.shift
188   if not (discovery_document["resources"][resource.pluralize]["methods"].
189           include?(method))
190     help_methods(discovery_document, resource, method)
191   end
192
193   discovered_params = discovery_document\
194     ["resources"][resource.pluralize]\
195     ["methods"][method]["parameters"]
196   method_opts = Trollop::options do
197     discovered_params.each do |k,v|
198       opts = Hash.new()
199       opts[:type] = v["type"].to_sym if v.include?("type")
200       if [:datetime, :text, :object, :array].index opts[:type]
201         opts[:type] = :string                       # else trollop bork
202       end
203       opts[:default] = v["default"] if v.include?("default")
204       opts[:default] = v["default"].to_i if opts[:type] == :integer
205       opts[:default] = to_boolean(v["default"]) if opts[:type] == :boolean
206       opts[:required] = true if v.include?("required") and v["required"]
207       description = ''
208       description = '  ' + v["description"] if v.include?("description")
209       opt k.to_sym, description, opts
210     end
211     body_object = discovery_document["resources"][resource.pluralize]["methods"][method]["request"]
212     if body_object and discovered_params[resource].nil?
213       is_required = true
214       if body_object["required"] == false
215         is_required = false
216       end
217       opt resource.to_sym, "#{resource} (request body)", required: is_required, type: :string
218     end
219   end
220   discovered_params.each do |k,v|
221     if ['object', 'array'].index(v["type"]) and method_opts.has_key? k
222       method_opts[k] = JSON.parse method_opts[k]
223     end
224   end
225   return resource, method, method_opts, global_opts, ARGV
226 end
227
228 resource_schema, method, method_opts, global_opts, remaining_opts = parse_arguments(arvados.discovery_document)
229 controller = resource_schema.pluralize
230
231 api_method = 'arvados.' + controller + '.' + method
232
233 if global_opts[:dry_run]
234   if global_opts[:verbose]
235     $stderr.puts "#{api_method} #{method_opts.inspect}"
236   end
237   exit
238 end
239
240 request_parameters = {}.merge(method_opts)
241 resource_body = request_parameters.delete(resource_schema.to_sym)
242 if resource_body
243   request_body = {
244     resource_schema => JSON.parse(resource_body)
245   }
246 else
247   request_body = {}
248 end
249 request_body[:api_token] = ENV['ARVADOS_API_TOKEN']
250 result = client.execute(:api_method => eval(api_method),
251                         :parameters => request_parameters,
252                         :body => request_body,
253                         :authenticated => false)
254 begin
255   results = JSON.parse result.body
256 rescue JSON::ParserError => e
257   abort "Failed to parse server response:\n" + e.to_s
258 end
259
260 if results["errors"] then
261   abort "Error: #{results["errors"][0]}"
262 end
263
264 if global_opts[:human] or global_opts[:pretty] then
265   puts Oj.dump(results, :indent => 1)
266 elsif global_opts[:json] then
267   puts Oj.dump(results)
268 elsif results["items"] and results["kind"].match /list$/i
269   results['items'].each do |i| puts i['uuid'] end
270 elsif results['uuid'].nil?
271   abort("Response did not include a uuid:\n" +
272         Oj.dump(results, :indent => 1) +
273         "\n")
274 else
275   puts results['uuid']
276 end