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