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