2 # Copyright (C) The Arvados Authors. All rights reserved.
4 # SPDX-License-Identifier: Apache-2.0
8 # Ward Vandewege <ward@curoverse.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 trollop
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
68 class ArvadosClient < Google::APIClient
70 if args.last.is_a? Hash
71 args.last[:headers] ||= {}
72 args.last[:headers]['Accept'] ||= 'application/json'
79 # read authentication data from arvados configuration file if present
81 config_file = File.expand_path('~/.config/arvados/settings.conf') rescue nil
82 if not config_file.nil? and File.exist? config_file then
83 File.open(config_file, 'r').each do |line|
86 if line.match('^\s*#') then
89 var, val = line.chomp.split('=', 2)
90 # allow environment settings to override config files.
94 warn "#{config_file}: #{lineno}: could not parse `#{line}'"
101 subcommands = %w(copy create edit get keep pipeline run tag ws)
103 def exec_bin bin, opts
104 bin_path = `which #{bin.shellescape}`.strip
106 raise "#{bin}: command not found"
111 def check_subcommands client, arvados, subcommand, global_opts, remaining_opts
114 arv_create client, arvados, global_opts, remaining_opts
116 arv_edit client, arvados, global_opts, remaining_opts
118 arv_get client, arvados, global_opts, remaining_opts
119 when 'copy', 'tag', 'ws', 'run'
120 exec_bin "arv-#{subcommand}", remaining_opts
122 @sub = remaining_opts.shift
123 if ['get', 'put', 'ls', 'normalize'].index @sub then
125 exec_bin "arv-#{@sub}", remaining_opts
126 elsif @sub == 'docker'
127 exec_bin "arv-keepdocker", remaining_opts
129 puts "Usage: arv keep [method] [--parameters]\n"
130 puts "Use 'arv keep [method] --help' to get more information about specific methods.\n\n"
131 puts "Available methods: ls, get, put, docker"
135 sub = remaining_opts.shift
137 exec_bin "arv-run-pipeline-instance", remaining_opts
139 puts "Usage: arv pipeline [method] [--parameters]\n"
140 puts "Use 'arv pipeline [method] --help' to get more information about specific methods.\n\n"
141 puts "Available methods: run"
147 def command_exists?(command)
148 File.executable?(command) || ENV['PATH'].split(':').any? {|folder| File.executable?(File.join(folder, command))}
155 [ENV["VISUAL"], ENV["EDITOR"], "nano", "vi"].each do |e|
156 editor ||= e if e and command_exists? e
159 abort "Could not find any editor to use, please set $VISUAL or $EDITOR to your desired editor."
166 if $?.exitstatus != 0
167 raise "Editor exited with status #{$?.exitstatus}"
171 def edit_and_commit_object initial_obj, tmp_stem, global_opts, &block
173 content = get_obj_content initial_obj, global_opts
175 tmp_file = Tempfile.new([tmp_stem, ".#{global_opts[:format]}"])
176 tmp_file.write(content)
183 run_editor tmp_file.path
186 newcontent = tmp_file.read()
189 # Strip lines starting with '#'
190 newcontent = newcontent.lines.select {|l| !l.start_with? '#'}.join
192 # Load the new object
193 newobj = case global_opts[:format]
197 YAML.load(newcontent)
199 abort "Unrecognized format #{global_opts[:format]}"
207 if e.is_a? Psych::SyntaxError
208 this_error = "YAML error parsing your input: #{e}"
209 elsif e.is_a? JSON::ParserError or e.is_a? Oj::ParseError
210 this_error = "JSON error parsing your input: #{e}"
211 elsif e.is_a? ArvadosAPIError
212 this_error = "API responded with error #{e}"
214 this_error = "#{e.class}: #{e}"
220 newcontent = tmp_file.read()
223 if newcontent == error_text or not can_retry
224 FileUtils::cp tmp_file.path, tmp_file.path + ".saved"
225 puts "File is unchanged, edit aborted." if can_retry
226 abort "Saved contents to " + tmp_file.path + ".saved"
230 error_text = this_error.to_s.lines.map {|l| '# ' + l}.join + "\n"
231 error_text += "# Please fix the error and try again.\n"
232 error_text += newcontent.lines.select {|l| !l.start_with? '#'}.join
233 tmp_file.write error_text
245 class ArvadosAPIError < RuntimeError
248 def check_response result
250 results = JSON.parse result.body
251 rescue JSON::ParserError, Oj::ParseError => e
252 raise "Failed to parse server response:\n" + e.to_s
255 if result.response.status != 200
256 raise ArvadosAPIError.new("#{result.response.status}: #{
257 ((results['errors'] && results['errors'].join('\n')) ||
258 Net::HTTPResponse::CODE_TO_OBJ[status.to_s].to_s.sub(/^Net::HTTP/, '').titleize)}")
264 def lookup_uuid_rsc arvados, uuid
265 m = /([a-z0-9]{5})-([a-z0-9]{5})-([a-z0-9]{15})/.match uuid
267 if /^[a-f0-9]{32}/.match uuid
268 abort "Arvados collections are not editable."
270 abort "'#{uuid}' does not appear to be an Arvados uuid"
275 arvados.discovery_document["resources"].each do |k,v|
276 klass = k.singularize.camelize
277 dig = Digest::MD5.hexdigest(klass).to_i(16).to_s(36)[-5..-1]
284 abort "Could not determine resource type #{m[2]}"
290 def fetch_rsc_obj client, arvados, rsc, uuid, remaining_opts
293 result = client.execute(:api_method => eval('arvados.' + rsc + '.get'),
294 :parameters => {"uuid" => uuid},
295 :authenticated => false,
297 authorization: 'OAuth2 '+ENV['ARVADOS_API_TOKEN']
299 obj = check_response result
301 abort "Server error: #{e}"
304 if remaining_opts.length > 0
305 obj.select! { |k, v| remaining_opts.include? k }
311 def get_obj_content obj, global_opts
312 content = case global_opts[:format]
314 Oj.dump(obj, :indent => 1)
318 abort "Unrecognized format #{global_opts[:format]}"
323 def arv_edit client, arvados, global_opts, remaining_opts
324 uuid = remaining_opts.shift
325 if uuid.nil? or uuid == "-h" or uuid == "--help"
327 puts "Usage: arv edit [uuid] [fields...]\n\n"
328 puts "Fetch the specified Arvados object, select the specified fields, \n"
329 puts "open an interactive text editor on a text representation (json or\n"
330 puts "yaml, use --format) and then update the object. Will use 'nano'\n"
331 puts "by default, customize with the EDITOR or VISUAL environment variable.\n"
335 rsc = lookup_uuid_rsc arvados, uuid
336 oldobj = fetch_rsc_obj client, arvados, rsc, uuid, remaining_opts
338 edit_and_commit_object oldobj, uuid, global_opts do |newobj|
339 newobj.select! {|k| newobj[k] != oldobj[k]}
341 result = client.execute(:api_method => eval('arvados.' + rsc + '.update'),
342 :parameters => {"uuid" => uuid},
343 :body_object => { rsc.singularize => newobj },
344 :authenticated => false,
346 authorization: 'OAuth2 '+ENV['ARVADOS_API_TOKEN']
348 results = check_response result
349 STDERR.puts "Updated object #{results['uuid']}"
351 STDERR.puts "Object is unchanged, did not update."
358 def arv_get client, arvados, global_opts, remaining_opts
359 uuid = remaining_opts.shift
360 if uuid.nil? or uuid == "-h" or uuid == "--help"
362 puts "Usage: arv [--format json|yaml] get [uuid] [fields...]\n\n"
363 puts "Fetch the specified Arvados object, select the specified fields,\n"
364 puts "and print a text representation.\n"
368 rsc = lookup_uuid_rsc arvados, uuid
369 obj = fetch_rsc_obj client, arvados, rsc, uuid, remaining_opts
370 content = get_obj_content obj, global_opts
376 def arv_create client, arvados, global_opts, remaining_opts
377 types = resource_types(arvados.discovery_document)
378 create_opts = Trollop::options do
379 opt :project_uuid, "Project uuid in which to create the object", :type => :string
380 stop_on resource_types(arvados.discovery_document)
383 object_type = remaining_opts.shift
385 abort "Missing resource type, must be one of #{types.join ', '}"
388 rsc = arvados.discovery_document["resources"].keys.select { |k| object_type == k.singularize }
390 abort "Could not determine resource type #{object_type}"
394 discovered_params = arvados.discovery_document["resources"][rsc]["methods"]["create"]["parameters"]
395 method_opts = Trollop::options do
397 banner "Usage: arv create [--project-uuid] #{object_type} [create parameters]"
399 banner "This method supports the following parameters:"
401 discovered_params.each do |k,v|
403 opts[:type] = v["type"].to_sym if v.include?("type")
404 if [:datetime, :text, :object, :array].index opts[:type]
405 opts[:type] = :string # else trollop bork
407 opts[:default] = v["default"] if v.include?("default")
408 opts[:default] = v["default"].to_i if opts[:type] == :integer
409 opts[:default] = to_boolean(v["default"]) if opts[:type] == :boolean
410 opts[:required] = true if v.include?("required") and v["required"]
412 description = ' ' + v["description"] if v.include?("description")
413 opt k.to_sym, description, opts
418 if create_opts[:project_uuid]
419 initial_obj["owner_uuid"] = create_opts[:project_uuid]
422 edit_and_commit_object initial_obj, "", global_opts do |newobj|
423 result = client.execute(:api_method => eval('arvados.' + rsc + '.create'),
424 :parameters => method_opts,
425 :body_object => {object_type => newobj},
426 :authenticated => false,
428 authorization: 'OAuth2 '+ENV['ARVADOS_API_TOKEN']
430 results = check_response result
431 puts "Created object #{results['uuid']}"
438 !!(s =~ /^(true|t|yes|y|1)$/i)
442 "Arvados command line client\n"
445 def help_methods(discovery_document, resource, method=nil)
447 banner += "Usage: arv #{resource} [method] [--parameters]\n"
448 banner += "Use 'arv #{resource} [method] --help' to get more information about specific methods.\n\n"
449 banner += "The #{resource} resource supports the following methods:"
451 discovery_document["resources"][resource.pluralize]["methods"].
454 if v.include? "description"
455 # add only the first line of the discovery doc description
456 description = ' ' + v["description"].split("\n").first.chomp
458 banner += " #{sprintf("%20s",k)}#{description}\n"
463 if not method.nil? and method != '--help' and method != '-h' then
464 abort "Unknown method #{method.inspect} " +
465 "for resource #{resource.inspect}"
470 def help_resources(option_parser, discovery_document, resource)
471 option_parser.educate
475 def resource_types discovery_document
476 resource_types = Array.new()
477 discovery_document["resources"].each do |k,v|
478 resource_types << k.singularize
483 def parse_arguments(discovery_document, subcommands)
484 resources_and_subcommands = resource_types(discovery_document) + subcommands
486 option_parser = Trollop::Parser.new do
489 banner "Usage: arv [--flags] subcommand|resource [method] [--parameters]"
491 banner "Available flags:"
493 opt :dry_run, "Don't actually do anything", :short => "-n"
494 opt :verbose, "Print some things on stderr"
496 "Set the output format. Must be one of json (default), yaml or uuid.",
499 opt :short, "Return only UUIDs (equivalent to --format=uuid)"
502 banner "Use 'arv subcommand|resource --help' to get more information about a particular command or resource."
504 banner "Available subcommands: #{subcommands.join(', ')}"
507 banner "Available resources: #{discovery_document['resources'].keys.map { |k| k.singularize }.join(', ')}"
510 banner "Additional options:"
512 conflicts :short, :format
513 stop_on resources_and_subcommands
516 global_opts = Trollop::with_standard_exception_handling option_parser do
517 o = option_parser.parse ARGV
520 unless %w(json yaml uuid).include?(global_opts[:format])
521 $stderr.puts "#{$0}: --format must be one of json, yaml or uuid."
522 $stderr.puts "Use #{$0} --help for more information."
526 if global_opts[:short]
527 global_opts[:format] = 'uuid'
530 resource = ARGV.shift
532 if not subcommands.include? resource
533 if not resources_and_subcommands.include?(resource)
534 puts "Resource or subcommand '#{resource}' is not recognized.\n\n" if !resource.nil?
535 help_resources(option_parser, discovery_document, resource)
539 if not (discovery_document["resources"][resource.pluralize]["methods"].
541 help_methods(discovery_document, resource, method)
544 discovered_params = discovery_document\
545 ["resources"][resource.pluralize]\
546 ["methods"][method]["parameters"]
547 method_opts = Trollop::options do
549 banner "Usage: arv #{resource} #{method} [--parameters]"
551 banner "This method supports the following parameters:"
553 discovered_params.each do |k,v|
555 opts[:type] = v["type"].to_sym if v.include?("type")
556 if [:datetime, :text, :object, :array].index opts[:type]
557 opts[:type] = :string # else trollop bork
559 opts[:default] = v["default"] if v.include?("default")
560 opts[:default] = v["default"].to_i if opts[:type] == :integer
561 opts[:default] = to_boolean(v["default"]) if opts[:type] == :boolean
562 opts[:required] = true if v.include?("required") and v["required"]
564 description = ' ' + v["description"] if v.include?("description")
565 opt k.to_sym, description, opts
568 body_object = discovery_document["resources"][resource.pluralize]["methods"][method]["request"]
569 if body_object and discovered_params[resource].nil?
571 if body_object["required"] == false
574 resource_opt_desc = "Either a string representing #{resource} as JSON or a filename from which to read #{resource} JSON (use '-' to read from stdin)."
576 resource_opt_desc += " This option must be specified."
578 opt resource.to_sym, resource_opt_desc, {
579 required: is_required,
585 discovered_params.merge({resource => {'type' => 'object'}}).each do |k,v|
587 if ['object', 'array'].index(v["type"]) and method_opts.has_key? k
588 if method_opts[k].andand.match /^\//
589 method_opts[k] = File.open method_opts[k], 'rb' do |f| f.read end
595 return resource, method, method_opts, global_opts, ARGV
604 ENV['ARVADOS_API_VERSION'] ||= 'v1'
606 if not ENV.include?('ARVADOS_API_HOST') or not ENV.include?('ARVADOS_API_TOKEN') then
608 ARVADOS_API_HOST and ARVADOS_API_TOKEN need to be defined as environment variables.
612 # do this if you're testing with a dev server and you don't care about SSL certificate checks:
613 if ENV['ARVADOS_API_HOST_INSECURE']
614 suppress_warnings { OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE }
618 client = ArvadosClient.new(:host => ENV['ARVADOS_API_HOST'], :application_name => 'arvados-cli', :application_version => '1.0')
619 arvados = client.discovered_api('arvados', ENV['ARVADOS_API_VERSION'])
620 rescue Exception => e
621 puts "Failed to connect to Arvados API server: #{e}"
625 # Parse arguments here
626 resource_schema, method, method_opts, global_opts, remaining_opts = parse_arguments(arvados.discovery_document, subcommands)
628 check_subcommands client, arvados, resource_schema, global_opts, remaining_opts
630 controller = resource_schema.pluralize
632 api_method = 'arvados.' + controller + '.' + method
634 if global_opts[:dry_run]
635 if global_opts[:verbose]
636 $stderr.puts "#{api_method} #{method_opts.inspect}"
641 request_parameters = {_profile:true}.merge(method_opts)
642 resource_body = request_parameters.delete(resource_schema.to_sym)
644 # check if resource_body is valid JSON by attempting to parse it
645 resource_body_is_json = true
647 # we don't actually need the results of the parsing,
648 # just checking for the JSON::ParserError exception
649 JSON.parse resource_body
650 rescue JSON::ParserError => e
651 resource_body_is_json = false
653 resource_body_is_readable_file = false
654 # if resource_body is not valid JSON, it should be a filename (or '-' for stdin)
655 if resource_body == '-'
656 resource_body_is_readable_file = true
657 resource_body_file = $stdin
658 elsif File.readable? resource_body
659 resource_body_is_readable_file = true
660 resource_body_file = File.open(resource_body, 'r')
662 if resource_body_is_json and resource_body_is_readable_file
663 abort "Argument specified for option '--#{resource_schema.to_sym}' is both valid JSON and a readable file. Please consider renaming the file: '#{resource_body}'"
664 elsif !resource_body_is_json and !resource_body_is_readable_file
665 if File.exists? resource_body
666 # specified file exists but is not readable
667 abort "Argument specified for option '--#{resource_schema.to_sym}' is an existing file but is not readable. Please check permissions on: '#{resource_body}'"
669 # specified file does not exist
670 abort "Argument specified for option '--#{resource_schema.to_sym}' is neither valid JSON nor an existing file: '#{resource_body}'"
672 elsif resource_body_is_readable_file
673 resource_body = resource_body_file.read()
675 # we don't actually need the results of the parsing,
676 # just checking for the JSON::ParserError exception
677 JSON.parse resource_body
678 rescue JSON::ParserError => e
679 abort "Contents of file '#{resource_body_file.path}' is not valid JSON: #{e}"
681 resource_body_file.close()
684 resource_schema => resource_body
692 'arvados.jobs.log_tail_follow'
694 # Special case for methods that respond with data streams rather
695 # than JSON (TODO: use the discovery document instead of a static
697 uri_s = eval(api_method).generate_uri(request_parameters)
698 Curl::Easy.perform(uri_s) do |curl|
699 curl.headers['Accept'] = 'text/plain'
700 curl.headers['Authorization'] = "OAuth2 #{ENV['ARVADOS_API_TOKEN']}"
701 if ENV['ARVADOS_API_HOST_INSECURE']
702 curl.ssl_verify_peer = false
703 curl.ssl_verify_host = false
705 if global_opts[:verbose]
706 curl.on_header { |data| $stderr.write data }
708 curl.on_body { |data| $stdout.write data }
712 result = client.execute(:api_method => eval(api_method),
713 :parameters => request_parameters,
714 :body_object => request_body,
715 :authenticated => false,
717 authorization: 'OAuth2 '+ENV['ARVADOS_API_TOKEN']
722 results = JSON.parse result.body
723 rescue JSON::ParserError => e
724 abort "Failed to parse server response:\n" + e.to_s
727 if results["errors"] then
728 abort "Error: #{results["errors"][0]}"
731 case global_opts[:format]
733 puts Oj.dump(results, :indent => 1)
737 if results["items"] and results["kind"].match /list$/i
738 results['items'].each do |i| puts i['uuid'] end
739 elsif results['uuid'].nil?
740 abort("Response did not include a uuid:\n" +
741 Oj.dump(results, :indent => 1) +