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