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