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