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.
19 require 'arvados/google_api_client'
25 require 'active_support/inflector'
32 Please install all required gems:
34 gem install activesupport andand curb google-api-client json oj trollop yaml
39 # Search for 'ENTRY POINT' to see where things get going
41 ActiveSupport::Inflector.inflections do |inflect|
42 inflect.irregular 'specimen', 'specimens'
43 inflect.irregular 'human', 'humans'
48 original_verbosity = $VERBOSE
51 $VERBOSE = original_verbosity
56 class ArvadosClient < Google::APIClient
58 if args.last.is_a? Hash
59 args.last[:headers] ||= {}
60 args.last[:headers]['Accept'] ||= 'application/json'
67 # read authentication data from arvados configuration file if present
69 config_file = File.expand_path('~/.config/arvados/settings.conf') rescue nil
70 if not config_file.nil? and File.exist? config_file then
71 File.open(config_file, 'r').each do |line|
74 if line.match('^\s*#') then
77 var, val = line.chomp.split('=', 2)
78 # allow environment settings to override config files.
82 warn "#{config_file}: #{lineno}: could not parse `#{line}'"
89 subcommands = %w(copy create edit get keep pipeline run tag ws)
91 def exec_bin bin, opts
92 bin_path = `which #{bin.shellescape}`.strip
94 raise "#{bin}: command not found"
99 def check_subcommands client, arvados, subcommand, global_opts, remaining_opts
102 arv_create client, arvados, global_opts, remaining_opts
104 arv_edit client, arvados, global_opts, remaining_opts
106 arv_get client, arvados, global_opts, remaining_opts
107 when 'copy', 'tag', 'ws', 'run'
108 exec_bin "arv-#{subcommand}", remaining_opts
110 @sub = remaining_opts.shift
111 if ['get', 'put', 'ls', 'normalize'].index @sub then
113 exec_bin "arv-#{@sub}", remaining_opts
114 elsif @sub == 'docker'
115 exec_bin "arv-keepdocker", remaining_opts
117 puts "Usage: arv keep [method] [--parameters]\n"
118 puts "Use 'arv keep [method] --help' to get more information about specific methods.\n\n"
119 puts "Available methods: ls, get, put, docker"
123 sub = remaining_opts.shift
125 exec_bin "arv-run-pipeline-instance", remaining_opts
127 puts "Usage: arv pipeline [method] [--parameters]\n"
128 puts "Use 'arv pipeline [method] --help' to get more information about specific methods.\n\n"
129 puts "Available methods: run"
135 def command_exists?(command)
136 File.executable?(command) || ENV['PATH'].split(':').any? {|folder| File.executable?(File.join(folder, command))}
143 [ENV["VISUAL"], ENV["EDITOR"], "nano", "vi"].each do |e|
144 editor ||= e if e and command_exists? e
147 abort "Could not find any editor to use, please set $VISUAL or $EDITOR to your desired editor."
154 if $?.exitstatus != 0
155 raise "Editor exited with status #{$?.exitstatus}"
159 def edit_and_commit_object initial_obj, tmp_stem, global_opts, &block
161 content = get_obj_content initial_obj, global_opts
163 tmp_file = Tempfile.new([tmp_stem, ".#{global_opts[:format]}"])
164 tmp_file.write(content)
171 run_editor tmp_file.path
174 newcontent = tmp_file.read()
177 # Strip lines starting with '#'
178 newcontent = newcontent.lines.select {|l| !l.start_with? '#'}.join
180 # Load the new object
181 newobj = case global_opts[:format]
185 YAML.load(newcontent)
187 abort "Unrecognized format #{global_opts[:format]}"
195 if e.is_a? Psych::SyntaxError
196 this_error = "YAML error parsing your input: #{e}"
197 elsif e.is_a? JSON::ParserError or e.is_a? Oj::ParseError
198 this_error = "JSON error parsing your input: #{e}"
199 elsif e.is_a? ArvadosAPIError
200 this_error = "API responded with error #{e}"
202 this_error = "#{e.class}: #{e}"
208 newcontent = tmp_file.read()
211 if newcontent == error_text or not can_retry
212 FileUtils::cp tmp_file.path, tmp_file.path + ".saved"
213 puts "File is unchanged, edit aborted." if can_retry
214 abort "Saved contents to " + tmp_file.path + ".saved"
218 error_text = this_error.to_s.lines.map {|l| '# ' + l}.join + "\n"
219 error_text += "# Please fix the error and try again.\n"
220 error_text += newcontent.lines.select {|l| !l.start_with? '#'}.join
221 tmp_file.write error_text
233 class ArvadosAPIError < RuntimeError
236 def check_response result
238 results = JSON.parse result.body
239 rescue JSON::ParserError, Oj::ParseError => e
240 raise "Failed to parse server response:\n" + e.to_s
243 if result.response.status != 200
244 raise ArvadosAPIError.new("#{result.response.status}: #{
245 ((results['errors'] && results['errors'].join('\n')) ||
246 Net::HTTPResponse::CODE_TO_OBJ[status.to_s].to_s.sub(/^Net::HTTP/, '').titleize)}")
252 def lookup_uuid_rsc arvados, uuid
253 m = /([a-z0-9]{5})-([a-z0-9]{5})-([a-z0-9]{15})/.match uuid
255 if /^[a-f0-9]{32}/.match uuid
256 abort "Arvados collections are not editable."
258 abort "'#{uuid}' does not appear to be an Arvados uuid"
263 arvados.discovery_document["resources"].each do |k,v|
264 klass = k.singularize.camelize
265 dig = Digest::MD5.hexdigest(klass).to_i(16).to_s(36)[-5..-1]
272 abort "Could not determine resource type #{m[2]}"
278 def fetch_rsc_obj client, arvados, rsc, uuid, remaining_opts
281 result = client.execute(:api_method => eval('arvados.' + rsc + '.get'),
282 :parameters => {"uuid" => uuid},
283 :authenticated => false,
285 authorization: 'OAuth2 '+ENV['ARVADOS_API_TOKEN']
287 obj = check_response result
289 abort "Server error: #{e}"
292 if remaining_opts.length > 0
293 obj.select! { |k, v| remaining_opts.include? k }
299 def get_obj_content obj, global_opts
300 content = case global_opts[:format]
302 Oj.dump(obj, :indent => 1)
306 abort "Unrecognized format #{global_opts[:format]}"
311 def arv_edit client, arvados, global_opts, remaining_opts
312 uuid = remaining_opts.shift
313 if uuid.nil? or uuid == "-h" or uuid == "--help"
315 puts "Usage: arv edit [uuid] [fields...]\n\n"
316 puts "Fetch the specified Arvados object, select the specified fields, \n"
317 puts "open an interactive text editor on a text representation (json or\n"
318 puts "yaml, use --format) and then update the object. Will use 'nano'\n"
319 puts "by default, customize with the EDITOR or VISUAL environment variable.\n"
323 rsc = lookup_uuid_rsc arvados, uuid
324 oldobj = fetch_rsc_obj client, arvados, rsc, uuid, remaining_opts
326 edit_and_commit_object oldobj, uuid, global_opts do |newobj|
327 newobj.select! {|k| newobj[k] != oldobj[k]}
329 result = client.execute(:api_method => eval('arvados.' + rsc + '.update'),
330 :parameters => {"uuid" => uuid},
331 :body_object => { rsc.singularize => newobj },
332 :authenticated => false,
334 authorization: 'OAuth2 '+ENV['ARVADOS_API_TOKEN']
336 results = check_response result
337 STDERR.puts "Updated object #{results['uuid']}"
339 STDERR.puts "Object is unchanged, did not update."
346 def arv_get client, arvados, global_opts, remaining_opts
347 uuid = remaining_opts.shift
348 if uuid.nil? or uuid == "-h" or uuid == "--help"
350 puts "Usage: arv [--format json|yaml] get [uuid] [fields...]\n\n"
351 puts "Fetch the specified Arvados object, select the specified fields,\n"
352 puts "and print a text representation.\n"
356 rsc = lookup_uuid_rsc arvados, uuid
357 obj = fetch_rsc_obj client, arvados, rsc, uuid, remaining_opts
358 content = get_obj_content obj, global_opts
364 def arv_create client, arvados, global_opts, remaining_opts
365 types = resource_types(arvados.discovery_document)
366 create_opts = Trollop::options do
367 opt :project_uuid, "Project uuid in which to create the object", :type => :string
368 stop_on resource_types(arvados.discovery_document)
371 object_type = remaining_opts.shift
373 abort "Missing resource type, must be one of #{types.join ', '}"
376 rsc = arvados.discovery_document["resources"].keys.select { |k| object_type == k.singularize }
378 abort "Could not determine resource type #{object_type}"
382 discovered_params = arvados.discovery_document["resources"][rsc]["methods"]["create"]["parameters"]
383 method_opts = Trollop::options do
385 banner "Usage: arv create [--project-uuid] #{object_type} [create parameters]"
387 banner "This method supports the following parameters:"
389 discovered_params.each do |k,v|
391 opts[:type] = v["type"].to_sym if v.include?("type")
392 if [:datetime, :text, :object, :array].index opts[:type]
393 opts[:type] = :string # else trollop bork
395 opts[:default] = v["default"] if v.include?("default")
396 opts[:default] = v["default"].to_i if opts[:type] == :integer
397 opts[:default] = to_boolean(v["default"]) if opts[:type] == :boolean
398 opts[:required] = true if v.include?("required") and v["required"]
400 description = ' ' + v["description"] if v.include?("description")
401 opt k.to_sym, description, opts
406 if create_opts[:project_uuid]
407 initial_obj["owner_uuid"] = create_opts[:project_uuid]
410 edit_and_commit_object initial_obj, "", global_opts do |newobj|
411 result = client.execute(:api_method => eval('arvados.' + rsc + '.create'),
412 :parameters => method_opts,
413 :body_object => {object_type => newobj},
414 :authenticated => false,
416 authorization: 'OAuth2 '+ENV['ARVADOS_API_TOKEN']
418 results = check_response result
419 puts "Created object #{results['uuid']}"
426 !!(s =~ /^(true|t|yes|y|1)$/i)
430 "Arvados command line client\n"
433 def help_methods(discovery_document, resource, method=nil)
435 banner += "Usage: arv #{resource} [method] [--parameters]\n"
436 banner += "Use 'arv #{resource} [method] --help' to get more information about specific methods.\n\n"
437 banner += "The #{resource} resource supports the following methods:"
439 discovery_document["resources"][resource.pluralize]["methods"].
442 if v.include? "description"
443 # add only the first line of the discovery doc description
444 description = ' ' + v["description"].split("\n").first.chomp
446 banner += " #{sprintf("%20s",k)}#{description}\n"
451 if not method.nil? and method != '--help' and method != '-h' then
452 abort "Unknown method #{method.inspect} " +
453 "for resource #{resource.inspect}"
458 def help_resources(option_parser, discovery_document, resource)
459 option_parser.educate
463 def resource_types discovery_document
464 resource_types = Array.new()
465 discovery_document["resources"].each do |k,v|
466 resource_types << k.singularize
471 def parse_arguments(discovery_document, subcommands)
472 resources_and_subcommands = resource_types(discovery_document) + subcommands
474 option_parser = Trollop::Parser.new do
477 banner "Usage: arv [--flags] subcommand|resource [method] [--parameters]"
479 banner "Available flags:"
481 opt :dry_run, "Don't actually do anything", :short => "-n"
482 opt :verbose, "Print some things on stderr"
484 "Set the output format. Must be one of json (default), yaml or uuid.",
487 opt :short, "Return only UUIDs (equivalent to --format=uuid)"
490 banner "Use 'arv subcommand|resource --help' to get more information about a particular command or resource."
492 banner "Available subcommands: #{subcommands.join(', ')}"
495 banner "Available resources: #{discovery_document['resources'].keys.map { |k| k.singularize }.join(', ')}"
498 banner "Additional options:"
500 conflicts :short, :format
501 stop_on resources_and_subcommands
504 global_opts = Trollop::with_standard_exception_handling option_parser do
505 o = option_parser.parse ARGV
508 unless %w(json yaml uuid).include?(global_opts[:format])
509 $stderr.puts "#{$0}: --format must be one of json, yaml or uuid."
510 $stderr.puts "Use #{$0} --help for more information."
514 if global_opts[:short]
515 global_opts[:format] = 'uuid'
518 resource = ARGV.shift
520 if not subcommands.include? resource
521 if not resources_and_subcommands.include?(resource)
522 puts "Resource or subcommand '#{resource}' is not recognized.\n\n" if !resource.nil?
523 help_resources(option_parser, discovery_document, resource)
527 if not (discovery_document["resources"][resource.pluralize]["methods"].
529 help_methods(discovery_document, resource, method)
532 discovered_params = discovery_document\
533 ["resources"][resource.pluralize]\
534 ["methods"][method]["parameters"]
535 method_opts = Trollop::options do
537 banner "Usage: arv #{resource} #{method} [--parameters]"
539 banner "This method supports the following parameters:"
541 discovered_params.each do |k,v|
543 opts[:type] = v["type"].to_sym if v.include?("type")
544 if [:datetime, :text, :object, :array].index opts[:type]
545 opts[:type] = :string # else trollop bork
547 opts[:default] = v["default"] if v.include?("default")
548 opts[:default] = v["default"].to_i if opts[:type] == :integer
549 opts[:default] = to_boolean(v["default"]) if opts[:type] == :boolean
550 opts[:required] = true if v.include?("required") and v["required"]
552 description = ' ' + v["description"] if v.include?("description")
553 opt k.to_sym, description, opts
556 body_object = discovery_document["resources"][resource.pluralize]["methods"][method]["request"]
557 if body_object and discovered_params[resource].nil?
559 if body_object["required"] == false
562 opt resource.to_sym, "#{resource} (request body)", {
563 required: is_required,
569 discovered_params.each do |k,v|
571 if ['object', 'array'].index(v["type"]) and method_opts.has_key? k
572 if method_opts[k].andand.match /^\//
573 method_opts[k] = File.open method_opts[k], 'rb' do |f| f.read end
579 return resource, method, method_opts, global_opts, ARGV
588 ENV['ARVADOS_API_VERSION'] ||= 'v1'
590 if not ENV.include?('ARVADOS_API_HOST') or not ENV.include?('ARVADOS_API_TOKEN') then
592 ARVADOS_API_HOST and ARVADOS_API_TOKEN need to be defined as environment variables.
596 # do this if you're testing with a dev server and you don't care about SSL certificate checks:
597 if ENV['ARVADOS_API_HOST_INSECURE']
598 suppress_warnings { OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE }
602 client = ArvadosClient.new(:host => ENV['ARVADOS_API_HOST'], :application_name => 'arvados-cli', :application_version => '1.0')
603 arvados = client.discovered_api('arvados', ENV['ARVADOS_API_VERSION'])
604 rescue Exception => e
605 puts "Failed to connect to Arvados API server: #{e}"
609 # Parse arguments here
610 resource_schema, method, method_opts, global_opts, remaining_opts = parse_arguments(arvados.discovery_document, subcommands)
612 check_subcommands client, arvados, resource_schema, global_opts, remaining_opts
614 controller = resource_schema.pluralize
616 api_method = 'arvados.' + controller + '.' + method
618 if global_opts[:dry_run]
619 if global_opts[:verbose]
620 $stderr.puts "#{api_method} #{method_opts.inspect}"
625 request_parameters = {_profile:true}.merge(method_opts)
626 resource_body = request_parameters.delete(resource_schema.to_sym)
629 resource_schema => resource_body
637 'arvados.jobs.log_tail_follow'
639 # Special case for methods that respond with data streams rather
640 # than JSON (TODO: use the discovery document instead of a static
642 uri_s = eval(api_method).generate_uri(request_parameters)
643 Curl::Easy.perform(uri_s) do |curl|
644 curl.headers['Accept'] = 'text/plain'
645 curl.headers['Authorization'] = "OAuth2 #{ENV['ARVADOS_API_TOKEN']}"
646 if ENV['ARVADOS_API_HOST_INSECURE']
647 curl.ssl_verify_peer = false
648 curl.ssl_verify_host = false
650 if global_opts[:verbose]
651 curl.on_header { |data| $stderr.write data }
653 curl.on_body { |data| $stdout.write data }
657 result = client.execute(:api_method => eval(api_method),
658 :parameters => request_parameters,
659 :body_object => request_body,
660 :authenticated => false,
662 authorization: 'OAuth2 '+ENV['ARVADOS_API_TOKEN']
667 results = JSON.parse result.body
668 rescue JSON::ParserError => e
669 abort "Failed to parse server response:\n" + e.to_s
672 if results["errors"] then
673 abort "Error: #{results["errors"][0]}"
676 case global_opts[:format]
678 puts Oj.dump(results, :indent => 1)
682 if results["items"] and results["kind"].match /list$/i
683 results['items'].each do |i| puts i['uuid'] end
684 elsif results['uuid'].nil?
685 abort("Response did not include a uuid:\n" +
686 Oj.dump(results, :indent => 1) +