b133a7783d4beb35afa310a1a2c169b323c6834f
[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 ~/.config/arvados if present
14 lineno = 0
15 config_file = File.expand_path('~/.config/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     if v.include? "description"
156       # add only the first line of the discovery doc description
157       description = '  ' + v["description"].split("\n").first.chomp
158     end
159     banner += "   #{sprintf("%20s",k)}#{description}\n"
160   end
161   banner += "\n"
162   STDERR.puts banner
163   
164   if not method.nil? and method != '--help' then 
165     Trollop::die ("Unknown method #{method.inspect} " +
166                   "for resource #{resource.inspect}")
167   end
168   exit 255
169 end
170
171 def help_resources(discovery_document, resource)
172   banner = "\n"
173   banner += "This Arvados instance supports the following resource types:"
174   banner += "\n\n"
175   discovery_document["resources"].each do |k,v|
176     description = ''
177     resource_info = discovery_document["schemas"][k.singularize.capitalize]
178     if resource_info and resource_info.include?('description')
179       # add only the first line of the discovery doc description
180       description = '  ' + resource_info["description"].split("\n").first.chomp
181     end
182     banner += "   #{sprintf("%30s",k.singularize)}#{description}\n"
183   end
184   banner += "\n"
185   STDERR.puts banner
186
187   if not resource.nil? and resource != '--help' then 
188     Trollop::die "Unknown resource type #{resource.inspect}"
189   end
190   exit 255
191 end
192
193 def parse_arguments(discovery_document)
194   resource_types = Array.new()
195   discovery_document["resources"].each do |k,v|
196     resource_types << k.singularize
197   end
198
199   global_opts = Trollop::options do
200     banner "arv: the Arvados CLI tool"
201     opt :dry_run, "Don't actually do anything", :short => "-n"
202     opt :verbose, "Print some things on stderr"
203     opt :format,
204         "Set the output format. Must be one of json (default), yaml or uuid.",
205         :type => :string,
206         :default => 'json'
207     opt :short, "Return only UUIDs (equivalent to --format=uuid)"
208     opt :resources, "Display list of resources known to this Arvados instance."
209     conflicts :short, :format
210     stop_on resource_types
211   end
212
213   unless %w(json yaml uuid).include?(global_opts[:format])
214     $stderr.puts "#{$0}: --format must be one of json, yaml or uuid."
215     $stderr.puts "Use #{$0} --help for more information."
216     abort
217   end
218
219   if global_opts[:short]
220     global_opts[:format] = 'uuid'
221   end
222
223   resource = ARGV.shift
224   if global_opts[:resources] or not resource_types.include?(resource)
225     help_resources(discovery_document, resource)
226   end
227
228   method = ARGV.shift
229   if not (discovery_document["resources"][resource.pluralize]["methods"].
230           include?(method))
231     help_methods(discovery_document, resource, method)
232   end
233
234   discovered_params = discovery_document\
235     ["resources"][resource.pluralize]\
236     ["methods"][method]["parameters"]
237   method_opts = Trollop::options do
238     discovered_params.each do |k,v|
239       opts = Hash.new()
240       opts[:type] = v["type"].to_sym if v.include?("type")
241       if [:datetime, :text, :object, :array].index opts[:type]
242         opts[:type] = :string                       # else trollop bork
243       end
244       opts[:default] = v["default"] if v.include?("default")
245       opts[:default] = v["default"].to_i if opts[:type] == :integer
246       opts[:default] = to_boolean(v["default"]) if opts[:type] == :boolean
247       opts[:required] = true if v.include?("required") and v["required"]
248       description = ''
249       description = '  ' + v["description"] if v.include?("description")
250       opt k.to_sym, description, opts
251     end
252     body_object = discovery_document["resources"][resource.pluralize]["methods"][method]["request"]
253     if body_object and discovered_params[resource].nil?
254       is_required = true
255       if body_object["required"] == false
256         is_required = false
257       end
258       opt resource.to_sym, "#{resource} (request body)", {
259         required: is_required,
260         type: :string
261       }
262       discovered_params[resource.to_sym] = body_object
263     end
264   end
265
266   discovered_params.each do |k,v|
267     k = k.to_sym
268     if ['object', 'array'].index(v["type"]) and method_opts.has_key? k
269       if method_opts[k].andand.match /^\//
270         method_opts[k] = File.open method_opts[k], 'rb' do |f| f.read end
271       end
272     end
273   end
274   return resource, method, method_opts, global_opts, ARGV
275 end
276
277 resource_schema, method, method_opts, global_opts, remaining_opts = parse_arguments(arvados.discovery_document)
278 controller = resource_schema.pluralize
279
280 api_method = 'arvados.' + controller + '.' + method
281
282 if global_opts[:dry_run]
283   if global_opts[:verbose]
284     $stderr.puts "#{api_method} #{method_opts.inspect}"
285   end
286   exit
287 end
288
289 request_parameters = {}.merge(method_opts)
290 resource_body = request_parameters.delete(resource_schema.to_sym)
291 if resource_body
292   request_body = {
293     resource_schema => resource_body
294   }
295 else
296   request_body = {}
297 end
298
299 case api_method
300 when
301   'arvados.users.event_stream',
302   'arvados.jobs.log_stream',
303   'arvados.jobs.log_tail_follow'
304
305   # Special case for methods that respond with data streams rather
306   # than JSON (TODO: use the discovery document instead of a static
307   # list of methods)
308   uri_s = eval(api_method).generate_uri(request_parameters)
309   Curl::Easy.perform(uri_s) do |curl|
310     curl.headers['Accept'] = 'text/plain'
311     curl.headers['Authorization'] = "OAuth2 #{ENV['ARVADOS_API_TOKEN']}"
312     if ENV['ARVADOS_API_HOST_INSECURE']
313       curl.ssl_verify_peer = false 
314       curl.ssl_verify_host = false
315     end
316     if global_opts[:verbose]
317       curl.on_header { |data| $stderr.write data }
318     end
319     curl.on_body { |data| $stdout.write data }
320   end
321   exit 0
322 else
323   request_body[:api_token] = ENV['ARVADOS_API_TOKEN']
324   request_body[:_profile] = true
325   result = client.execute(:api_method => eval(api_method),
326                           :parameters => request_parameters,
327                           :body => request_body,
328                           :authenticated => false)
329 end
330
331 begin
332   results = JSON.parse result.body
333 rescue JSON::ParserError => e
334   abort "Failed to parse server response:\n" + e.to_s
335 end
336
337 if results["errors"] then
338   abort "Error: #{results["errors"][0]}"
339 end
340
341 case global_opts[:format]
342 when 'json'
343   puts Oj.dump(results, :indent => 1)
344 when 'yaml'
345   puts results.to_yaml
346 else
347   if results["items"] and results["kind"].match /list$/i
348     results['items'].each do |i| puts i['uuid'] end
349   elsif results['uuid'].nil?
350     abort("Response did not include a uuid:\n" +
351           Oj.dump(results, :indent => 1) +
352           "\n")
353   else
354     puts results['uuid']
355   end
356 end
357
358