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