2891: Refactor Workbench API token filters.
[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 begin
16   require 'curb'
17   require 'rubygems'
18   require 'google/api_client'
19   require 'json'
20   require 'pp'
21   require 'trollop'
22   require 'andand'
23   require 'oj'
24   require 'active_support/inflector'
25   require 'yaml'
26 rescue LoadError
27   abort <<-EOS
28
29 Please install all required gems:
30
31   gem install activesupport andand curb google-api-client json oj trollop yaml
32
33   EOS
34 end
35
36 # Search for 'ENTRY POINT' to see where things get going
37
38 ActiveSupport::Inflector.inflections do |inflect|
39   inflect.irregular 'specimen', 'specimens'
40   inflect.irregular 'human', 'humans'
41 end
42
43 module Kernel
44   def suppress_warnings
45     original_verbosity = $VERBOSE
46     $VERBOSE = nil
47     result = yield
48     $VERBOSE = original_verbosity
49     return result
50   end
51 end
52
53 class Google::APIClient
54  def discovery_document(api, version)
55    api = api.to_s
56    return @discovery_documents["#{api}:#{version}"] ||=
57      begin
58        # fetch new API discovery doc if stale
59        cached_doc = File.expand_path '~/.cache/arvados/discovery_uri.json'
60        if not File.exist?(cached_doc) or (Time.now - File.mtime(cached_doc)) > 86400
61          response = self.execute!(:http_method => :get,
62                                   :uri => self.discovery_uri(api, version),
63                                   :authenticated => false)
64          FileUtils.makedirs(File.dirname cached_doc)
65          File.open(cached_doc, 'w') do |f|
66            f.puts response.body
67          end
68        end
69
70        File.open(cached_doc) { |f| JSON.load f }
71      end
72  end
73 end
74
75 class ArvadosClient < Google::APIClient
76   def execute(*args)
77     if args.last.is_a? Hash
78       args.last[:headers] ||= {}
79       args.last[:headers]['Accept'] ||= 'application/json'
80     end
81     super(*args)
82   end
83 end
84
85 def init_config
86   # read authentication data from arvados configuration file if present
87   lineno = 0
88   config_file = File.expand_path('~/.config/arvados/settings.conf')
89   if File.exist? config_file then
90     File.open(config_file, 'r').each do |line|
91       lineno = lineno + 1
92       # skip comments
93       if line.match('^\s*#') then
94         next
95       end
96       var, val = line.chomp.split('=', 2)
97       # allow environment settings to override config files.
98       if var and val
99         ENV[var] ||= val
100       else
101         warn "#{config_file}: #{lineno}: could not parse `#{line}'"
102       end
103     end
104   end
105 end
106
107 subcommands = %w(keep pipeline tag ws edit)
108
109 def check_subcommands client, arvados, subcommand, global_opts, remaining_opts
110   case subcommand
111   when 'keep'
112     @sub = remaining_opts.shift
113     if ['get', 'put', 'ls', 'normalize'].index @sub then
114       # Native Arvados
115       exec `which arv-#{@sub}`.strip, *remaining_opts
116     elsif ['less', 'check'].index @sub then
117       # wh* shims
118       exec `which wh#{@sub}`.strip, *remaining_opts
119     elsif @sub == 'docker'
120       exec `which arv-keepdocker`.strip, *remaining_opts
121     else
122       puts "Usage: arv keep [method] [--parameters]\n"
123       puts "Use 'arv keep [method] --help' to get more information about specific methods.\n\n"
124       puts "Available methods: ls, get, put, less, check, docker"
125     end
126     abort
127   when 'pipeline'
128     sub = remaining_opts.shift
129     if sub == 'run'
130       exec `which arv-run-pipeline-instance`.strip, *remaining_opts
131     else
132       puts "Usage: arv pipeline [method] [--parameters]\n"
133       puts "Use 'arv pipeline [method] --help' to get more information about specific methods.\n\n"
134       puts "Available methods: run"
135     end
136     abort
137   when 'tag'
138     exec `which arv-tag`.strip, *remaining_opts
139   when 'ws'
140     exec `which arv-ws`.strip, *remaining_opts
141   when 'edit'
142     arv_edit client, arvados, global_opts, remaining_opts
143   end
144 end
145
146 def arv_edit client, arvados, global_opts, remaining_opts
147   n = remaining_opts.shift
148   if n.nil? or n == "-h" or n == "--help"
149     puts head_banner
150     puts "Usage: arv edit [uuid] [fields...]\n\n"
151     puts "Fetch the specified Arvados object, select the specified fields, \n"
152     puts "open an interactive text editor on a text representation (json or\n"
153     puts "yaml, use --format) and then update the object.  Will use 'nano'\n"
154     puts "by default, customize with the EDITOR or VISUAL environment variable.\n"
155     exit 255
156   end
157
158   if not $stdout.tty?
159     puts "Not connected to a TTY, cannot run interactive editor."
160     exit 1
161   end
162
163   # determine controller
164
165   m = /([a-z0-9]{5})-([a-z0-9]{5})-([a-z0-9]{15})/.match n
166   if !m
167     if /^[a-f0-9]{32}/.match n
168       abort "Arvados collections are not editable."
169     else
170       abort "#{n} does not appear to be an Arvados uuid"
171     end
172   end
173
174   rsc = nil
175   arvados.discovery_document["resources"].each do |k,v|
176     klass = k.singularize.camelize
177     dig = Digest::MD5.hexdigest(klass).to_i(16).to_s(36)[-5..-1]
178     if dig == m[2]
179       rsc = k
180     end
181   end
182
183   if rsc.nil?
184     abort "Could not determine resource type #{m[2]}"
185   end
186
187   api_method = 'arvados.' + rsc + '.get'
188
189   result = client.execute(:api_method => eval(api_method),
190                           :parameters => {"uuid" => n},
191                           :authenticated => false,
192                           :headers => {
193                             authorization: 'OAuth2 '+ENV['ARVADOS_API_TOKEN']
194                           })
195   begin
196     results = JSON.parse result.body
197   rescue JSON::ParserError => e
198     abort "Failed to parse server response:\n" + e.to_s
199   end
200
201   if remaining_opts.length > 0
202     results.select! { |k, v| remaining_opts.include? k }
203   end
204
205   content = ""
206
207   case global_opts[:format]
208   when 'json'
209     content = Oj.dump(results, :indent => 1)
210   when 'yaml'
211     content = results.to_yaml
212   end
213
214   require 'tempfile'
215
216   tmp = Tempfile.new([n, "." + global_opts[:format]])
217   tmp.write(content)
218   tmp.close
219
220   need_edit = true
221
222   while need_edit
223     pid = Process::fork
224     if pid.nil?
225       editor ||= ENV["VISUAL"]
226       editor ||= ENV["EDITOR"]
227       editor ||= "nano"
228       exec editor, tmp.path
229     else
230       Process.wait pid
231     end
232
233     if $?.exitstatus == 0
234       tmp.open
235       newcontent = tmp.read()
236
237       newobj = {}
238       begin
239         case global_opts[:format]
240         when 'json'
241           newobj = Oj.load(newcontent)
242         when 'yaml'
243           newobj = YAML.load(newcontent)
244         end
245         need_edit = false
246       rescue Exception => e
247         puts "Parse error! " + e.to_s
248         n = 1
249         newcontent.each_line do |line|
250           puts "#{n.to_s.rjust 4}  #{line}"
251           n += 1
252         end
253         puts "\nTry again (y/n)? "
254         yn = $stdin.read 1
255         if yn == 'n' or yn == 'N'
256           exit 1
257         end
258       end
259     else
260       puts "Editor exited with status #{$?.exitstatus}"
261       exit $?.exitstatus
262     end
263   end
264
265   tmp.close(true)
266
267   if newobj != results
268     api_method = 'arvados.' + rsc + '.update'
269     dumped = Oj.dump(newobj)
270     result = client.execute(:api_method => eval(api_method),
271                             :parameters => {"uuid" => n, rsc.singularize => dumped},
272                             :authenticated => false,
273                             :headers => {
274                               authorization: 'OAuth2 '+ENV['ARVADOS_API_TOKEN']
275                             })
276
277     begin
278       results = JSON.parse result.body
279     rescue JSON::ParserError => e
280       abort "Failed to parse server response:\n" + e.to_s
281     end
282
283     if result.response.status != 200
284       puts "Update failed.  Server responded #{result.response.status}: #{results['errors']} "
285       puts "Update body was:"
286       puts dumped
287     end
288   else
289     puts "Object is unchanged, did not update."
290   end
291
292   exit 0
293 end
294
295 def to_boolean(s)
296   !!(s =~ /^(true|t|yes|y|1)$/i)
297 end
298
299 def head_banner
300   "Arvados command line client\n"
301 end
302
303 def help_methods(discovery_document, resource, method=nil)
304   banner = head_banner
305   banner += "Usage: arv #{resource} [method] [--parameters]\n"
306   banner += "Use 'arv #{resource} [method] --help' to get more information about specific methods.\n\n"
307   banner += "The #{resource} resource supports the following methods:"
308   banner += "\n\n"
309   discovery_document["resources"][resource.pluralize]["methods"].
310     each do |k,v|
311     description = ''
312     if v.include? "description"
313       # add only the first line of the discovery doc description
314       description = '  ' + v["description"].split("\n").first.chomp
315     end
316     banner += "   #{sprintf("%20s",k)}#{description}\n"
317   end
318   banner += "\n"
319   STDERR.puts banner
320
321   if not method.nil? and method != '--help' and method != '-h' then
322     abort "Unknown method #{method.inspect} " +
323                   "for resource #{resource.inspect}"
324   end
325   exit 255
326 end
327
328 def help_resources(option_parser, discovery_document, resource)
329   option_parser.educate
330
331   if not resource.nil? and resource != '--help' then
332     Trollop::die "Unknown resource type #{resource.inspect}"
333   end
334   exit 255
335 end
336
337 def parse_arguments(discovery_document, subcommands)
338   resource_types = Array.new()
339   discovery_document["resources"].each do |k,v|
340     resource_types << k.singularize
341   end
342
343   resource_types += subcommands
344
345   option_parser = Trollop::Parser.new do
346     version __FILE__
347     banner head_banner
348     banner "Usage: arv [--flags] subcommand|resource [method] [--parameters]"
349     banner ""
350     banner "Available flags:"
351
352     opt :dry_run, "Don't actually do anything", :short => "-n"
353     opt :verbose, "Print some things on stderr"
354     opt :format,
355         "Set the output format. Must be one of json (default), yaml or uuid.",
356         :type => :string,
357         :default => 'json'
358     opt :short, "Return only UUIDs (equivalent to --format=uuid)"
359
360     banner ""
361     banner "Use 'arv subcommand|resource --help' to get more information about a particular command or resource."
362     banner ""
363     banner "Available subcommands: #{subcommands.join(', ')}"
364     banner ""
365
366     banner "Available resources: #{discovery_document['resources'].keys.map { |k| k.singularize }.join(', ')}"
367
368     banner ""
369     banner "Additional options:"
370
371     conflicts :short, :format
372     stop_on resource_types
373   end
374
375   global_opts = Trollop::with_standard_exception_handling option_parser do
376     o = option_parser.parse ARGV
377   end
378
379   unless %w(json yaml uuid).include?(global_opts[:format])
380     $stderr.puts "#{$0}: --format must be one of json, yaml or uuid."
381     $stderr.puts "Use #{$0} --help for more information."
382     abort
383   end
384
385   if global_opts[:short]
386     global_opts[:format] = 'uuid'
387   end
388
389   resource = ARGV.shift
390
391   if not subcommands.include? resource
392     if not resource_types.include?(resource)
393       puts "Resource or subcommand '#{resource}' is not recognized.\n\n" if !resource.nil?
394       help_resources(option_parser, discovery_document, resource)
395     end
396
397     method = ARGV.shift
398     if not (discovery_document["resources"][resource.pluralize]["methods"].
399             include?(method))
400       help_methods(discovery_document, resource, method)
401     end
402
403     discovered_params = discovery_document\
404     ["resources"][resource.pluralize]\
405     ["methods"][method]["parameters"]
406     method_opts = Trollop::options do
407       banner head_banner
408       banner "Usage: arv #{resource} #{method} [--parameters]"
409       banner ""
410       banner "This method supports the following parameters:"
411       banner ""
412       discovered_params.each do |k,v|
413         opts = Hash.new()
414         opts[:type] = v["type"].to_sym if v.include?("type")
415         if [:datetime, :text, :object, :array].index opts[:type]
416           opts[:type] = :string                       # else trollop bork
417         end
418         opts[:default] = v["default"] if v.include?("default")
419         opts[:default] = v["default"].to_i if opts[:type] == :integer
420         opts[:default] = to_boolean(v["default"]) if opts[:type] == :boolean
421         opts[:required] = true if v.include?("required") and v["required"]
422         description = ''
423         description = '  ' + v["description"] if v.include?("description")
424         opt k.to_sym, description, opts
425       end
426
427       body_object = discovery_document["resources"][resource.pluralize]["methods"][method]["request"]
428       if body_object and discovered_params[resource].nil?
429         is_required = true
430         if body_object["required"] == false
431           is_required = false
432         end
433         opt resource.to_sym, "#{resource} (request body)", {
434           required: is_required,
435           type: :string
436         }
437       end
438     end
439
440     discovered_params.each do |k,v|
441       k = k.to_sym
442       if ['object', 'array'].index(v["type"]) and method_opts.has_key? k
443         if method_opts[k].andand.match /^\//
444           method_opts[k] = File.open method_opts[k], 'rb' do |f| f.read end
445         end
446       end
447     end
448   end
449
450   return resource, method, method_opts, global_opts, ARGV
451 end
452
453 #
454 # ENTRY POINT
455 #
456
457 init_config
458
459 ENV['ARVADOS_API_VERSION'] ||= 'v1'
460
461 if not ENV.include?('ARVADOS_API_HOST') or not ENV.include?('ARVADOS_API_TOKEN') then
462   abort <<-EOS
463 ARVADOS_API_HOST and ARVADOS_API_TOKEN need to be defined as environment variables.
464   EOS
465 end
466
467 # do this if you're testing with a dev server and you don't care about SSL certificate checks:
468 if ENV['ARVADOS_API_HOST_INSECURE']
469   suppress_warnings { OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE }
470 end
471
472 begin
473   client = ArvadosClient.new(:host => ENV['ARVADOS_API_HOST'], :application_name => 'arvados-cli', :application_version => '1.0')
474   arvados = client.discovered_api('arvados', ENV['ARVADOS_API_VERSION'])
475 rescue Exception => e
476   puts "Failed to connect to Arvados API server: #{e}"
477   exit 1
478 end
479
480 # Parse arguments here
481 resource_schema, method, method_opts, global_opts, remaining_opts = parse_arguments(arvados.discovery_document, subcommands)
482
483 check_subcommands client, arvados, resource_schema, global_opts, remaining_opts
484
485 controller = resource_schema.pluralize
486
487 api_method = 'arvados.' + controller + '.' + method
488
489 if global_opts[:dry_run]
490   if global_opts[:verbose]
491     $stderr.puts "#{api_method} #{method_opts.inspect}"
492   end
493   exit
494 end
495
496 request_parameters = {_profile:true}.merge(method_opts)
497 resource_body = request_parameters.delete(resource_schema.to_sym)
498 if resource_body
499   request_body = {
500     resource_schema => resource_body
501   }
502 else
503   request_body = nil
504 end
505
506 case api_method
507 when
508   'arvados.jobs.log_tail_follow'
509
510   # Special case for methods that respond with data streams rather
511   # than JSON (TODO: use the discovery document instead of a static
512   # list of methods)
513   uri_s = eval(api_method).generate_uri(request_parameters)
514   Curl::Easy.perform(uri_s) do |curl|
515     curl.headers['Accept'] = 'text/plain'
516     curl.headers['Authorization'] = "OAuth2 #{ENV['ARVADOS_API_TOKEN']}"
517     if ENV['ARVADOS_API_HOST_INSECURE']
518       curl.ssl_verify_peer = false
519       curl.ssl_verify_host = false
520     end
521     if global_opts[:verbose]
522       curl.on_header { |data| $stderr.write data }
523     end
524     curl.on_body { |data| $stdout.write data }
525   end
526   exit 0
527 else
528   result = client.execute(:api_method => eval(api_method),
529                           :parameters => request_parameters,
530                           :body => request_body,
531                           :authenticated => false,
532                           :headers => {
533                             authorization: 'OAuth2 '+ENV['ARVADOS_API_TOKEN']
534                           })
535 end
536
537 begin
538   results = JSON.parse result.body
539 rescue JSON::ParserError => e
540   abort "Failed to parse server response:\n" + e.to_s
541 end
542
543 if results["errors"] then
544   abort "Error: #{results["errors"][0]}"
545 end
546
547 case global_opts[:format]
548 when 'json'
549   puts Oj.dump(results, :indent => 1)
550 when 'yaml'
551   puts results.to_yaml
552 else
553   if results["items"] and results["kind"].match /list$/i
554     results['items'].each do |i| puts i['uuid'] end
555   elsif results['uuid'].nil?
556     abort("Response did not include a uuid:\n" +
557           Oj.dump(results, :indent => 1) +
558           "\n")
559   else
560     puts results['uuid']
561   end
562 end