5 # Ward Vandewege <ward@curoverse.com>
10 if RUBY_VERSION < '1.9.3' then
12 #{$0.gsub(/^\.\//,'')} requires Ruby version 1.9.3 or higher.
22 rescue LoadError => error
23 abort "Error loading libraries: #{error}\n"
28 # Load the gems with more requirements first, so we respect any version
29 # constraints they put on gems loaded later.
30 require 'arvados/google_api_client'
31 require 'active_support/inflector'
36 rescue LoadError => error
39 Error loading gems: #{error}
41 Please install all required gems:
43 gem install arvados activesupport andand curb json oj trollop
48 # Search for 'ENTRY POINT' to see where things get going
50 ActiveSupport::Inflector.inflections do |inflect|
51 inflect.irregular 'specimen', 'specimens'
52 inflect.irregular 'human', 'humans'
57 original_verbosity = $VERBOSE
60 $VERBOSE = original_verbosity
65 class ArvadosClient < Google::APIClient
67 if args.last.is_a? Hash
68 args.last[:headers] ||= {}
69 args.last[:headers]['Accept'] ||= 'application/json'
76 # read authentication data from arvados configuration file if present
78 config_file = File.expand_path('~/.config/arvados/settings.conf') rescue nil
79 if not config_file.nil? and File.exist? config_file then
80 File.open(config_file, 'r').each do |line|
83 if line.match('^\s*#') then
86 var, val = line.chomp.split('=', 2)
87 # allow environment settings to override config files.
91 warn "#{config_file}: #{lineno}: could not parse `#{line}'"
98 subcommands = %w(copy create edit get keep pipeline run tag ws)
100 def exec_bin bin, opts
101 bin_path = `which #{bin.shellescape}`.strip
103 raise "#{bin}: command not found"
108 def check_subcommands client, arvados, subcommand, global_opts, remaining_opts
111 arv_create client, arvados, global_opts, remaining_opts
113 arv_edit client, arvados, global_opts, remaining_opts
115 arv_get client, arvados, global_opts, remaining_opts
116 when 'copy', 'tag', 'ws', 'run'
117 exec_bin "arv-#{subcommand}", remaining_opts
119 @sub = remaining_opts.shift
120 if ['get', 'put', 'ls', 'normalize'].index @sub then
122 exec_bin "arv-#{@sub}", remaining_opts
123 elsif @sub == 'docker'
124 exec_bin "arv-keepdocker", remaining_opts
126 puts "Usage: arv keep [method] [--parameters]\n"
127 puts "Use 'arv keep [method] --help' to get more information about specific methods.\n\n"
128 puts "Available methods: ls, get, put, docker"
132 sub = remaining_opts.shift
134 exec_bin "arv-run-pipeline-instance", remaining_opts
136 puts "Usage: arv pipeline [method] [--parameters]\n"
137 puts "Use 'arv pipeline [method] --help' to get more information about specific methods.\n\n"
138 puts "Available methods: run"
144 def command_exists?(command)
145 File.executable?(command) || ENV['PATH'].split(':').any? {|folder| File.executable?(File.join(folder, command))}
152 [ENV["VISUAL"], ENV["EDITOR"], "nano", "vi"].each do |e|
153 editor ||= e if e and command_exists? e
156 abort "Could not find any editor to use, please set $VISUAL or $EDITOR to your desired editor."
163 if $?.exitstatus != 0
164 raise "Editor exited with status #{$?.exitstatus}"
168 def edit_and_commit_object initial_obj, tmp_stem, global_opts, &block
170 content = get_obj_content initial_obj, global_opts
172 tmp_file = Tempfile.new([tmp_stem, ".#{global_opts[:format]}"])
173 tmp_file.write(content)
180 run_editor tmp_file.path
183 newcontent = tmp_file.read()
186 # Strip lines starting with '#'
187 newcontent = newcontent.lines.select {|l| !l.start_with? '#'}.join
189 # Load the new object
190 newobj = case global_opts[:format]
194 YAML.load(newcontent)
196 abort "Unrecognized format #{global_opts[:format]}"
204 if e.is_a? Psych::SyntaxError
205 this_error = "YAML error parsing your input: #{e}"
206 elsif e.is_a? JSON::ParserError or e.is_a? Oj::ParseError
207 this_error = "JSON error parsing your input: #{e}"
208 elsif e.is_a? ArvadosAPIError
209 this_error = "API responded with error #{e}"
211 this_error = "#{e.class}: #{e}"
217 newcontent = tmp_file.read()
220 if newcontent == error_text or not can_retry
221 FileUtils::cp tmp_file.path, tmp_file.path + ".saved"
222 puts "File is unchanged, edit aborted." if can_retry
223 abort "Saved contents to " + tmp_file.path + ".saved"
227 error_text = this_error.to_s.lines.map {|l| '# ' + l}.join + "\n"
228 error_text += "# Please fix the error and try again.\n"
229 error_text += newcontent.lines.select {|l| !l.start_with? '#'}.join
230 tmp_file.write error_text
242 class ArvadosAPIError < RuntimeError
245 def check_response result
247 results = JSON.parse result.body
248 rescue JSON::ParserError, Oj::ParseError => e
249 raise "Failed to parse server response:\n" + e.to_s
252 if result.response.status != 200
253 raise ArvadosAPIError.new("#{result.response.status}: #{
254 ((results['errors'] && results['errors'].join('\n')) ||
255 Net::HTTPResponse::CODE_TO_OBJ[status.to_s].to_s.sub(/^Net::HTTP/, '').titleize)}")
261 def lookup_uuid_rsc arvados, uuid
262 m = /([a-z0-9]{5})-([a-z0-9]{5})-([a-z0-9]{15})/.match uuid
264 if /^[a-f0-9]{32}/.match uuid
265 abort "Arvados collections are not editable."
267 abort "'#{uuid}' does not appear to be an Arvados uuid"
272 arvados.discovery_document["resources"].each do |k,v|
273 klass = k.singularize.camelize
274 dig = Digest::MD5.hexdigest(klass).to_i(16).to_s(36)[-5..-1]
281 abort "Could not determine resource type #{m[2]}"
287 def fetch_rsc_obj client, arvados, rsc, uuid, remaining_opts
290 result = client.execute(:api_method => eval('arvados.' + rsc + '.get'),
291 :parameters => {"uuid" => uuid},
292 :authenticated => false,
294 authorization: 'OAuth2 '+ENV['ARVADOS_API_TOKEN']
296 obj = check_response result
298 abort "Server error: #{e}"
301 if remaining_opts.length > 0
302 obj.select! { |k, v| remaining_opts.include? k }
308 def get_obj_content obj, global_opts
309 content = case global_opts[:format]
311 Oj.dump(obj, :indent => 1)
315 abort "Unrecognized format #{global_opts[:format]}"
320 def arv_edit client, arvados, global_opts, remaining_opts
321 uuid = remaining_opts.shift
322 if uuid.nil? or uuid == "-h" or uuid == "--help"
324 puts "Usage: arv edit [uuid] [fields...]\n\n"
325 puts "Fetch the specified Arvados object, select the specified fields, \n"
326 puts "open an interactive text editor on a text representation (json or\n"
327 puts "yaml, use --format) and then update the object. Will use 'nano'\n"
328 puts "by default, customize with the EDITOR or VISUAL environment variable.\n"
332 rsc = lookup_uuid_rsc arvados, uuid
333 oldobj = fetch_rsc_obj client, arvados, rsc, uuid, remaining_opts
335 edit_and_commit_object oldobj, uuid, global_opts do |newobj|
336 newobj.select! {|k| newobj[k] != oldobj[k]}
338 result = client.execute(:api_method => eval('arvados.' + rsc + '.update'),
339 :parameters => {"uuid" => uuid},
340 :body_object => { rsc.singularize => newobj },
341 :authenticated => false,
343 authorization: 'OAuth2 '+ENV['ARVADOS_API_TOKEN']
345 results = check_response result
346 STDERR.puts "Updated object #{results['uuid']}"
348 STDERR.puts "Object is unchanged, did not update."
355 def arv_get client, arvados, global_opts, remaining_opts
356 uuid = remaining_opts.shift
357 if uuid.nil? or uuid == "-h" or uuid == "--help"
359 puts "Usage: arv [--format json|yaml] get [uuid] [fields...]\n\n"
360 puts "Fetch the specified Arvados object, select the specified fields,\n"
361 puts "and print a text representation.\n"
365 rsc = lookup_uuid_rsc arvados, uuid
366 obj = fetch_rsc_obj client, arvados, rsc, uuid, remaining_opts
367 content = get_obj_content obj, global_opts
373 def arv_create client, arvados, global_opts, remaining_opts
374 types = resource_types(arvados.discovery_document)
375 create_opts = Trollop::options do
376 opt :project_uuid, "Project uuid in which to create the object", :type => :string
377 stop_on resource_types(arvados.discovery_document)
380 object_type = remaining_opts.shift
382 abort "Missing resource type, must be one of #{types.join ', '}"
385 rsc = arvados.discovery_document["resources"].keys.select { |k| object_type == k.singularize }
387 abort "Could not determine resource type #{object_type}"
391 discovered_params = arvados.discovery_document["resources"][rsc]["methods"]["create"]["parameters"]
392 method_opts = Trollop::options do
394 banner "Usage: arv create [--project-uuid] #{object_type} [create parameters]"
396 banner "This method supports the following parameters:"
398 discovered_params.each do |k,v|
400 opts[:type] = v["type"].to_sym if v.include?("type")
401 if [:datetime, :text, :object, :array].index opts[:type]
402 opts[:type] = :string # else trollop bork
404 opts[:default] = v["default"] if v.include?("default")
405 opts[:default] = v["default"].to_i if opts[:type] == :integer
406 opts[:default] = to_boolean(v["default"]) if opts[:type] == :boolean
407 opts[:required] = true if v.include?("required") and v["required"]
409 description = ' ' + v["description"] if v.include?("description")
410 opt k.to_sym, description, opts
415 if create_opts[:project_uuid]
416 initial_obj["owner_uuid"] = create_opts[:project_uuid]
419 edit_and_commit_object initial_obj, "", global_opts do |newobj|
420 result = client.execute(:api_method => eval('arvados.' + rsc + '.create'),
421 :parameters => method_opts,
422 :body_object => {object_type => newobj},
423 :authenticated => false,
425 authorization: 'OAuth2 '+ENV['ARVADOS_API_TOKEN']
427 results = check_response result
428 puts "Created object #{results['uuid']}"
435 !!(s =~ /^(true|t|yes|y|1)$/i)
439 "Arvados command line client\n"
442 def help_methods(discovery_document, resource, method=nil)
444 banner += "Usage: arv #{resource} [method] [--parameters]\n"
445 banner += "Use 'arv #{resource} [method] --help' to get more information about specific methods.\n\n"
446 banner += "The #{resource} resource supports the following methods:"
448 discovery_document["resources"][resource.pluralize]["methods"].
451 if v.include? "description"
452 # add only the first line of the discovery doc description
453 description = ' ' + v["description"].split("\n").first.chomp
455 banner += " #{sprintf("%20s",k)}#{description}\n"
460 if not method.nil? and method != '--help' and method != '-h' then
461 abort "Unknown method #{method.inspect} " +
462 "for resource #{resource.inspect}"
467 def help_resources(option_parser, discovery_document, resource)
468 option_parser.educate
472 def resource_types discovery_document
473 resource_types = Array.new()
474 discovery_document["resources"].each do |k,v|
475 resource_types << k.singularize
480 def parse_arguments(discovery_document, subcommands)
481 resources_and_subcommands = resource_types(discovery_document) + subcommands
483 option_parser = Trollop::Parser.new do
486 banner "Usage: arv [--flags] subcommand|resource [method] [--parameters]"
488 banner "Available flags:"
490 opt :dry_run, "Don't actually do anything", :short => "-n"
491 opt :verbose, "Print some things on stderr"
493 "Set the output format. Must be one of json (default), yaml or uuid.",
496 opt :short, "Return only UUIDs (equivalent to --format=uuid)"
499 banner "Use 'arv subcommand|resource --help' to get more information about a particular command or resource."
501 banner "Available subcommands: #{subcommands.join(', ')}"
504 banner "Available resources: #{discovery_document['resources'].keys.map { |k| k.singularize }.join(', ')}"
507 banner "Additional options:"
509 conflicts :short, :format
510 stop_on resources_and_subcommands
513 global_opts = Trollop::with_standard_exception_handling option_parser do
514 o = option_parser.parse ARGV
517 unless %w(json yaml uuid).include?(global_opts[:format])
518 $stderr.puts "#{$0}: --format must be one of json, yaml or uuid."
519 $stderr.puts "Use #{$0} --help for more information."
523 if global_opts[:short]
524 global_opts[:format] = 'uuid'
527 resource = ARGV.shift
529 if not subcommands.include? resource
530 if not resources_and_subcommands.include?(resource)
531 puts "Resource or subcommand '#{resource}' is not recognized.\n\n" if !resource.nil?
532 help_resources(option_parser, discovery_document, resource)
536 if not (discovery_document["resources"][resource.pluralize]["methods"].
538 help_methods(discovery_document, resource, method)
541 discovered_params = discovery_document\
542 ["resources"][resource.pluralize]\
543 ["methods"][method]["parameters"]
544 method_opts = Trollop::options do
546 banner "Usage: arv #{resource} #{method} [--parameters]"
548 banner "This method supports the following parameters:"
550 discovered_params.each do |k,v|
552 opts[:type] = v["type"].to_sym if v.include?("type")
553 if [:datetime, :text, :object, :array].index opts[:type]
554 opts[:type] = :string # else trollop bork
556 opts[:default] = v["default"] if v.include?("default")
557 opts[:default] = v["default"].to_i if opts[:type] == :integer
558 opts[:default] = to_boolean(v["default"]) if opts[:type] == :boolean
559 opts[:required] = true if v.include?("required") and v["required"]
561 description = ' ' + v["description"] if v.include?("description")
562 opt k.to_sym, description, opts
565 body_object = discovery_document["resources"][resource.pluralize]["methods"][method]["request"]
566 if body_object and discovered_params[resource].nil?
568 if body_object["required"] == false
571 resource_opt_desc = "Either a string representing #{resource} as JSON or a filename from which to read #{resource} JSON (use '-' to read from stdin)."
573 resource_opt_desc += " This option must be specified."
575 opt resource.to_sym, resource_opt_desc, {
576 required: is_required,
582 discovered_params.merge({resource => {'type' => 'object'}}).each do |k,v|
584 if ['object', 'array'].index(v["type"]) and method_opts.has_key? k
585 if method_opts[k].andand.match /^\//
586 method_opts[k] = File.open method_opts[k], 'rb' do |f| f.read end
592 return resource, method, method_opts, global_opts, ARGV
601 ENV['ARVADOS_API_VERSION'] ||= 'v1'
603 if not ENV.include?('ARVADOS_API_HOST') or not ENV.include?('ARVADOS_API_TOKEN') then
605 ARVADOS_API_HOST and ARVADOS_API_TOKEN need to be defined as environment variables.
609 # do this if you're testing with a dev server and you don't care about SSL certificate checks:
610 if ENV['ARVADOS_API_HOST_INSECURE']
611 suppress_warnings { OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE }
615 client = ArvadosClient.new(:host => ENV['ARVADOS_API_HOST'], :application_name => 'arvados-cli', :application_version => '1.0')
616 arvados = client.discovered_api('arvados', ENV['ARVADOS_API_VERSION'])
617 rescue Exception => e
618 puts "Failed to connect to Arvados API server: #{e}"
622 # Parse arguments here
623 resource_schema, method, method_opts, global_opts, remaining_opts = parse_arguments(arvados.discovery_document, subcommands)
625 check_subcommands client, arvados, resource_schema, global_opts, remaining_opts
627 controller = resource_schema.pluralize
629 api_method = 'arvados.' + controller + '.' + method
631 if global_opts[:dry_run]
632 if global_opts[:verbose]
633 $stderr.puts "#{api_method} #{method_opts.inspect}"
638 request_parameters = {_profile:true}.merge(method_opts)
639 resource_body = request_parameters.delete(resource_schema.to_sym)
641 # check if resource_body is valid JSON by attempting to parse it
642 resource_body_is_json = true
644 # we don't actually need the results of the parsing,
645 # just checking for the JSON::ParserError exception
646 JSON.parse resource_body
647 rescue JSON::ParserError => e
648 resource_body_is_json = false
650 resource_body_is_readable_file = false
651 # if resource_body is not valid JSON, it should be a filename (or '-' for stdin)
652 if resource_body == '-'
653 resource_body_is_readable_file = true
654 resource_body_file = $stdin
655 elsif File.readable? resource_body
656 resource_body_is_readable_file = true
657 resource_body_file = File.open(resource_body, 'r')
659 if resource_body_is_json and resource_body_is_readable_file
660 abort "Argument specified for option '--#{resource_schema.to_sym}' is both valid JSON and a readable file. Please consider renaming the file: '#{resource_body}'"
661 elsif !resource_body_is_json and !resource_body_is_readable_file
662 if File.exists? resource_body
663 # specified file exists but is not readable
664 abort "Argument specified for option '--#{resource_schema.to_sym}' is an existing file but is not readable. Please check permissions on: '#{resource_body}'"
666 # specified file does not exist
667 abort "Argument specified for option '--#{resource_schema.to_sym}' is neither valid JSON nor an existing file: '#{resource_body}'"
669 elsif resource_body_is_readable_file
670 resource_body = resource_body_file.read()
672 # we don't actually need the results of the parsing,
673 # just checking for the JSON::ParserError exception
674 JSON.parse resource_body
675 rescue JSON::ParserError => e
676 abort "Contents of file '#{resource_body_file.path}' is not valid JSON: #{e}"
678 resource_body_file.close()
681 resource_schema => resource_body
689 'arvados.jobs.log_tail_follow'
691 # Special case for methods that respond with data streams rather
692 # than JSON (TODO: use the discovery document instead of a static
694 uri_s = eval(api_method).generate_uri(request_parameters)
695 Curl::Easy.perform(uri_s) do |curl|
696 curl.headers['Accept'] = 'text/plain'
697 curl.headers['Authorization'] = "OAuth2 #{ENV['ARVADOS_API_TOKEN']}"
698 if ENV['ARVADOS_API_HOST_INSECURE']
699 curl.ssl_verify_peer = false
700 curl.ssl_verify_host = false
702 if global_opts[:verbose]
703 curl.on_header { |data| $stderr.write data }
705 curl.on_body { |data| $stdout.write data }
709 result = client.execute(:api_method => eval(api_method),
710 :parameters => request_parameters,
711 :body_object => request_body,
712 :authenticated => false,
714 authorization: 'OAuth2 '+ENV['ARVADOS_API_TOKEN']
719 results = JSON.parse result.body
720 rescue JSON::ParserError => e
721 abort "Failed to parse server response:\n" + e.to_s
724 if results["errors"] then
725 abort "Error: #{results["errors"][0]}"
728 case global_opts[:format]
730 puts Oj.dump(results, :indent => 1)
734 if results["items"] and results["kind"].match /list$/i
735 results['items'].each do |i| puts i['uuid'] end
736 elsif results['uuid'].nil?
737 abort("Response did not include a uuid:\n" +
738 Oj.dump(results, :indent => 1) +