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