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