2 # Copyright (C) The Arvados Authors. All rights reserved.
4 # SPDX-License-Identifier: Apache-2.0
8 # Ward Vandewege <ward@curii.com>
13 if RUBY_VERSION < '1.9.3' then
15 #{$0.gsub(/^\.\//,'')} requires Ruby version 1.9.3 or higher.
25 rescue LoadError => error
26 abort "Error loading libraries: #{error}\n"
31 # Load the gems with more requirements first, so we respect any version
32 # constraints they put on gems loaded later.
33 require 'arvados/google_api_client'
34 require 'active_support/inflector'
39 rescue LoadError => error
42 Error loading gems: #{error}
44 Please install all required gems:
46 gem install arvados activesupport andand curb json oj optimist
51 # Search for 'ENTRY POINT' to see where things get going
53 ActiveSupport::Inflector.inflections do |inflect|
54 inflect.irregular 'specimen', 'specimens'
55 inflect.irregular 'human', 'humans'
60 original_verbosity = $VERBOSE
63 $VERBOSE = original_verbosity
69 # read authentication data from arvados configuration file if present
71 config_file = File.expand_path('~/.config/arvados/settings.conf') rescue nil
72 if not config_file.nil? and File.exist? config_file then
73 File.open(config_file, 'r').each do |line|
76 if line.match('^\s*#') then
79 var, val = line.chomp.split('=', 2)
80 # allow environment settings to override config files.
84 warn "#{config_file}: #{lineno}: could not parse `#{line}'"
91 subcommands = %w(copy create edit get keep tag ws)
93 def exec_bin bin, opts
94 bin_path = `which #{bin.shellescape}`.strip
96 raise "#{bin}: command not found"
101 def check_subcommands client, arvados, subcommand, global_opts, remaining_opts
104 arv_create client, arvados, global_opts, remaining_opts
106 arv_edit client, arvados, global_opts, remaining_opts
108 arv_get client, arvados, global_opts, remaining_opts
109 when 'copy', 'tag', 'ws'
110 exec_bin "arv-#{subcommand}", remaining_opts
112 @sub = remaining_opts.shift
113 if ['get', 'put', 'ls', 'normalize'].index @sub then
115 exec_bin "arv-#{@sub}", remaining_opts
116 elsif @sub == 'docker'
117 exec_bin "arv-keepdocker", remaining_opts
119 puts "Usage: arv keep [method] [--parameters]\n"
120 puts "Use 'arv keep [method] --help' to get more information about specific methods.\n\n"
121 puts "Available methods: ls, get, put, docker"
127 def command_exists?(command)
128 File.executable?(command) || ENV['PATH'].split(':').any? {|folder| File.executable?(File.join(folder, command))}
135 [ENV["VISUAL"], ENV["EDITOR"], "nano", "vi"].each do |e|
136 editor ||= e if e and command_exists? e
139 abort "Could not find any editor to use, please set $VISUAL or $EDITOR to your desired editor."
146 if $?.exitstatus != 0
147 raise "Editor exited with status #{$?.exitstatus}"
151 def edit_and_commit_object initial_obj, tmp_stem, global_opts, &block
153 content = get_obj_content initial_obj, global_opts
155 tmp_file = Tempfile.new([tmp_stem, ".#{global_opts[:format]}"])
156 tmp_file.write(content)
163 run_editor tmp_file.path
166 newcontent = tmp_file.read()
169 # Strip lines starting with '#'
170 newcontent = newcontent.lines.select {|l| !l.start_with? '#'}.join
172 # Load the new object
173 newobj = case global_opts[:format]
175 Oj.safe_load(newcontent)
177 YAML.load(newcontent)
179 abort "Unrecognized format #{global_opts[:format]}"
187 if e.is_a? Psych::SyntaxError
188 this_error = "YAML error parsing your input: #{e}"
189 elsif e.is_a? JSON::ParserError or e.is_a? Oj::ParseError
190 this_error = "JSON error parsing your input: #{e}"
191 elsif e.is_a? ArvadosAPIError
192 this_error = "API responded with error #{e}"
194 this_error = "#{e.class}: #{e}"
200 newcontent = tmp_file.read()
203 if newcontent == error_text or not can_retry
204 FileUtils::cp tmp_file.path, tmp_file.path + ".saved"
205 puts "File is unchanged, edit aborted." if can_retry
206 abort "Saved contents to " + tmp_file.path + ".saved"
210 error_text = this_error.to_s.lines.map {|l| '# ' + l}.join + "\n"
211 error_text += "# Please fix the error and try again.\n"
212 error_text += newcontent.lines.select {|l| !l.start_with? '#'}.join
213 tmp_file.write error_text
225 class ArvadosAPIError < RuntimeError
228 def check_response result
230 results = JSON.parse result.body
231 rescue JSON::ParserError, Oj::ParseError => e
232 raise "Failed to parse server response:\n" + e.to_s
235 if result.response.status != 200
236 raise ArvadosAPIError.new("#{result.response.status}: #{
237 ((results['errors'] && results['errors'].join('\n')) ||
238 Net::HTTPResponse::CODE_TO_OBJ[status.to_s].to_s.sub(/^Net::HTTP/, '').titleize)}")
244 def lookup_uuid_rsc arvados, uuid
245 m = /([a-z0-9]{5})-([a-z0-9]{5})-([a-z0-9]{15})/.match uuid
247 if /^[a-f0-9]{32}/.match uuid
248 abort "Arvados collections are not editable."
250 abort "'#{uuid}' does not appear to be an Arvados uuid"
255 arvados.discovery_document["resources"].each do |k,v|
256 klass = k.singularize.camelize
257 dig = Digest::MD5.hexdigest(klass).to_i(16).to_s(36)[-5..-1]
264 abort "Could not determine resource type #{m[2]}"
270 def fetch_rsc_obj client, arvados, rsc, uuid, remaining_opts
273 result = client.execute(:api_method => eval('arvados.' + rsc + '.get'),
274 :parameters => {"uuid" => uuid},
275 :authenticated => false,
277 authorization: 'Bearer '+ENV['ARVADOS_API_TOKEN']
279 obj = check_response result
281 abort "Server error: #{e}"
284 if remaining_opts.length > 0
285 obj.select! { |k, v| remaining_opts.include? k }
291 def get_obj_content obj, global_opts
292 content = case global_opts[:format]
294 Oj.dump(obj, :indent => 1)
298 abort "Unrecognized format #{global_opts[:format]}"
303 def arv_edit client, arvados, global_opts, remaining_opts
304 uuid = remaining_opts.shift
305 if uuid.nil? or uuid == "-h" or uuid == "--help"
307 puts "Usage: arv edit [uuid] [fields...]\n\n"
308 puts "Fetch the specified Arvados object, select the specified fields, \n"
309 puts "open an interactive text editor on a text representation (json or\n"
310 puts "yaml, use --format) and then update the object. Will use 'nano'\n"
311 puts "by default, customize with the EDITOR or VISUAL environment variable.\n"
315 rsc = lookup_uuid_rsc arvados, uuid
316 oldobj = fetch_rsc_obj client, arvados, rsc, uuid, remaining_opts
318 edit_and_commit_object oldobj, uuid, global_opts do |newobj|
319 newobj.select! {|k| newobj[k] != oldobj[k]}
321 result = client.execute(:api_method => eval('arvados.' + rsc + '.update'),
322 :parameters => {"uuid" => uuid},
323 :body_object => { rsc.singularize => newobj },
324 :authenticated => false,
326 authorization: 'Bearer '+ENV['ARVADOS_API_TOKEN']
328 results = check_response result
329 STDERR.puts "Updated object #{results['uuid']}"
331 STDERR.puts "Object is unchanged, did not update."
338 def arv_get client, arvados, global_opts, remaining_opts
339 uuid = remaining_opts.shift
340 if uuid.nil? or uuid == "-h" or uuid == "--help"
342 puts "Usage: arv [--format json|yaml] get [uuid] [fields...]\n\n"
343 puts "Fetch the specified Arvados object, select the specified fields,\n"
344 puts "and print a text representation.\n"
348 rsc = lookup_uuid_rsc arvados, uuid
349 obj = fetch_rsc_obj client, arvados, rsc, uuid, remaining_opts
350 content = get_obj_content obj, global_opts
356 def arv_create client, arvados, global_opts, remaining_opts
357 types = resource_types(arvados.discovery_document)
358 create_opts = Optimist::options do
359 opt :project_uuid, "Project uuid in which to create the object", :type => :string
360 stop_on resource_types(arvados.discovery_document)
363 object_type = remaining_opts.shift
365 abort "Missing resource type, must be one of #{types.join ', '}"
368 rsc = arvados.discovery_document["resources"].keys.select { |k| object_type == k.singularize }
370 abort "Could not determine resource type #{object_type}"
374 discovered_params = arvados.discovery_document["resources"][rsc]["methods"]["create"]["parameters"]
375 method_opts = Optimist::options do
377 banner "Usage: arv create [--project-uuid] #{object_type} [create parameters]"
379 banner "This method supports the following parameters:"
381 discovered_params.each do |k,v|
383 opts[:type] = v["type"].to_sym if v.include?("type")
384 if [:datetime, :text, :object, :array].index opts[:type]
385 opts[:type] = :string # else optimist bork
387 opts[:default] = v["default"] if v.include?("default")
388 opts[:default] = v["default"].to_i if opts[:type] == :integer
389 opts[:default] = to_boolean(v["default"]) if opts[:type] == :boolean
390 opts[:required] = true if v.include?("required") and v["required"]
392 description = ' ' + v["description"] if v.include?("description")
393 opt k.to_sym, description, opts
398 if create_opts[:project_uuid]
399 initial_obj["owner_uuid"] = create_opts[:project_uuid]
402 edit_and_commit_object initial_obj, "", global_opts do |newobj|
403 result = client.execute(:api_method => eval('arvados.' + rsc + '.create'),
404 :parameters => method_opts,
405 :body_object => {object_type => newobj},
406 :authenticated => false,
408 authorization: 'Bearer '+ENV['ARVADOS_API_TOKEN']
410 results = check_response result
411 puts "Created object #{results['uuid']}"
418 !!(s =~ /^(true|t|yes|y|1)$/i)
422 "Arvados command line client\n"
425 def help_methods(discovery_document, resource, method=nil)
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:"
431 discovery_document["resources"][resource.pluralize]["methods"].
434 if v.include? "description"
435 # add only the first line of the discovery doc description
436 description = ' ' + v["description"].split("\n").first.chomp
438 banner += " #{sprintf("%20s",k)}#{description}\n"
443 if not method.nil? and method != '--help' and method != '-h' then
444 abort "Unknown method #{method.inspect} " +
445 "for resource #{resource.inspect}"
450 def help_resources(option_parser, discovery_document, resource)
451 option_parser.educate
455 def resource_types discovery_document
456 resource_types = Array.new()
457 discovery_document["resources"].each do |k,v|
458 resource_types << k.singularize
463 def parse_arguments(discovery_document, subcommands)
464 resources_and_subcommands = resource_types(discovery_document) + subcommands
466 option_parser = Optimist::Parser.new do
469 banner "Usage: arv [--flags] subcommand|resource [method] [--parameters]"
471 banner "Available flags:"
473 opt :dry_run, "Don't actually do anything", :short => "-n"
474 opt :verbose, "Print some things on stderr"
476 "Set the output format. Must be one of json (default), yaml or uuid.",
479 opt :short, "Return only UUIDs (equivalent to --format=uuid)"
482 banner "Use 'arv subcommand|resource --help' to get more information about a particular command or resource."
484 banner "Available subcommands: #{subcommands.join(', ')}"
487 banner "Available resources: #{discovery_document['resources'].keys.map { |k| k.singularize }.join(', ')}"
490 banner "Additional options:"
492 conflicts :short, :format
493 stop_on resources_and_subcommands
496 global_opts = Optimist::with_standard_exception_handling option_parser do
497 o = option_parser.parse ARGV
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."
506 if global_opts[:short]
507 global_opts[:format] = 'uuid'
510 resource = ARGV.shift
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)
519 if not (discovery_document["resources"][resource.pluralize]["methods"].
521 help_methods(discovery_document, resource, method)
524 discovered_params = discovery_document\
525 ["resources"][resource.pluralize]\
526 ["methods"][method]["parameters"]
527 method_opts = Optimist::options do
529 banner "Usage: arv #{resource} #{method} [--parameters]"
531 banner "This method supports the following parameters:"
533 discovered_params.each do |k,v|
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 optimist bork
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"]
544 description = ' ' + v["description"] if v.include?("description")
545 opt k.to_sym, description, opts
548 body_object = discovery_document["resources"][resource.pluralize]["methods"][method]["request"]
549 if body_object and discovered_params[resource].nil?
551 if body_object["required"] == false
554 resource_opt_desc = "Either a string representing #{resource} as JSON or a filename from which to read #{resource} JSON (use '-' to read from stdin)."
556 resource_opt_desc += " This option must be specified."
558 opt resource.to_sym, resource_opt_desc, {
559 required: is_required,
565 discovered_params.merge({resource => {'type' => 'object'}}).each do |k,v|
567 if ['object', 'array'].index(v["type"]) and method_opts.has_key? k
568 if method_opts[k].andand.match /^\//
569 method_opts[k] = File.open method_opts[k], 'rb' do |f| f.read end
575 return resource, method, method_opts, global_opts, ARGV
584 ENV['ARVADOS_API_VERSION'] ||= 'v1'
586 if not ENV.include?('ARVADOS_API_HOST') or not ENV.include?('ARVADOS_API_TOKEN') then
588 ARVADOS_API_HOST and ARVADOS_API_TOKEN need to be defined as environment variables.
592 # do this if you're testing with a dev server and you don't care about SSL certificate checks:
593 if ENV['ARVADOS_API_HOST_INSECURE']
594 suppress_warnings { OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE }
598 client = Google::APIClient.new(:host => ENV['ARVADOS_API_HOST'], :application_name => 'arvados-cli', :application_version => '1.0')
599 arvados = client.discovered_api('arvados', ENV['ARVADOS_API_VERSION'])
600 rescue Exception => e
601 puts "Failed to connect to Arvados API server: #{e}"
605 # Parse arguments here
606 resource_schema, method, method_opts, global_opts, remaining_opts = parse_arguments(arvados.discovery_document, subcommands)
608 check_subcommands client, arvados, resource_schema, global_opts, remaining_opts
610 controller = resource_schema.pluralize
612 api_method = 'arvados.' + controller + '.' + method
614 if global_opts[:dry_run]
615 if global_opts[:verbose]
616 $stderr.puts "#{api_method} #{method_opts.inspect}"
621 request_parameters = {_profile:true}.merge(method_opts)
622 resource_body = request_parameters.delete(resource_schema.to_sym)
624 # check if resource_body is valid JSON by attempting to parse it
625 resource_body_is_json = true
627 # we don't actually need the results of the parsing,
628 # just checking for the JSON::ParserError exception
629 JSON.parse resource_body
630 rescue JSON::ParserError => e
631 resource_body_is_json = false
633 resource_body_is_readable_file = false
634 # if resource_body is not valid JSON, it should be a filename (or '-' for stdin)
635 if resource_body == '-'
636 resource_body_is_readable_file = true
637 resource_body_file = $stdin
638 elsif File.readable? resource_body
639 resource_body_is_readable_file = true
640 resource_body_file = File.open(resource_body, 'r')
642 if resource_body_is_json and resource_body_is_readable_file
643 abort "Argument specified for option '--#{resource_schema.to_sym}' is both valid JSON and a readable file. Please consider renaming the file: '#{resource_body}'"
644 elsif !resource_body_is_json and !resource_body_is_readable_file
645 if File.exists? resource_body
646 # specified file exists but is not readable
647 abort "Argument specified for option '--#{resource_schema.to_sym}' is an existing file but is not readable. Please check permissions on: '#{resource_body}'"
649 # specified file does not exist
650 abort "Argument specified for option '--#{resource_schema.to_sym}' is neither valid JSON nor an existing file: '#{resource_body}'"
652 elsif resource_body_is_readable_file
653 resource_body = resource_body_file.read()
655 # we don't actually need the results of the parsing,
656 # just checking for the JSON::ParserError exception
657 JSON.parse resource_body
658 rescue JSON::ParserError => e
659 abort "Contents of file '#{resource_body_file.path}' is not valid JSON: #{e}"
661 resource_body_file.close()
664 resource_schema => resource_body
672 'arvados.jobs.log_tail_follow'
674 # Special case for methods that respond with data streams rather
675 # than JSON (TODO: use the discovery document instead of a static
677 uri_s = eval(api_method).generate_uri(request_parameters)
678 Curl::Easy.perform(uri_s) do |curl|
679 curl.headers['Accept'] = 'text/plain'
680 curl.headers['Authorization'] = "Bearer #{ENV['ARVADOS_API_TOKEN']}"
681 if ENV['ARVADOS_API_HOST_INSECURE']
682 curl.ssl_verify_peer = false
683 curl.ssl_verify_host = false
685 if global_opts[:verbose]
686 curl.on_header { |data| $stderr.write data }
688 curl.on_body { |data| $stdout.write data }
692 result = client.execute(:api_method => eval(api_method),
693 :parameters => request_parameters,
694 :body_object => request_body,
695 :authenticated => false,
697 authorization: 'Bearer '+ENV['ARVADOS_API_TOKEN']
701 request_id = result.headers[:x_request_id]
703 results = JSON.parse result.body
704 rescue JSON::ParserError => e
705 err_msg = "Failed to parse server response:\n" + e.to_s
707 err_msg += "\nRequest ID: #{request_id or client.request_id}"
712 if results["errors"] then
713 err_message = results["errors"][0]
714 if request_id and !err_message.match(/.*req-[0-9a-zA-Z]{20}.*/)
715 err_message += " (#{request_id})"
717 abort "Error: #{err_message}"
720 case global_opts[:format]
722 puts Oj.dump(results, :indent => 1)
726 if results["items"] and results["kind"].match /list$/i
727 results['items'].each do |i| puts i['uuid'] end
728 elsif results['uuid'].nil?
729 abort("Response did not include a uuid:\n" +
730 Oj.dump(results, :indent => 1) +