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