5 # Ward Vandewege <ward@curoverse.com>
9 if RUBY_VERSION < '1.9.3' then
11 #{$0.gsub(/^\.\//,'')} requires Ruby version 1.9.3 or higher.
18 require 'google/api_client'
24 require 'active_support/inflector'
30 Please install all required gems:
32 gem install activesupport andand curb google-api-client json oj trollop yaml
37 # Search for 'ENTRY POINT' to see where things get going
39 ActiveSupport::Inflector.inflections do |inflect|
40 inflect.irregular 'specimen', 'specimens'
41 inflect.irregular 'human', 'humans'
46 original_verbosity = $VERBOSE
49 $VERBOSE = original_verbosity
54 class Google::APIClient
55 def discovery_document(api, version)
57 discovery_uri = self.discovery_uri(api, version)
58 discovery_uri_hash = Digest::MD5.hexdigest(discovery_uri)
59 return @discovery_documents[discovery_uri_hash] ||=
61 # fetch new API discovery doc if stale
62 cached_doc = File.expand_path "~/.cache/arvados/discovery-#{discovery_uri_hash}.json" rescue nil
64 if cached_doc.nil? or not File.exist?(cached_doc) or (Time.now - File.mtime(cached_doc)) > 86400
65 response = self.execute!(:http_method => :get,
66 :uri => discovery_uri,
67 :authenticated => false)
70 FileUtils.makedirs(File.dirname cached_doc)
71 File.open(cached_doc, 'w') do |f|
75 return JSON.load response.body
79 File.open(cached_doc) { |f| JSON.load f }
84 class ArvadosClient < Google::APIClient
86 if args.last.is_a? Hash
87 args.last[:headers] ||= {}
88 args.last[:headers]['Accept'] ||= 'application/json'
95 # read authentication data from arvados configuration file if present
97 config_file = File.expand_path('~/.config/arvados/settings.conf') rescue nil
98 if not config_file.nil? and File.exist? config_file then
99 File.open(config_file, 'r').each do |line|
102 if line.match('^\s*#') then
105 var, val = line.chomp.split('=', 2)
106 # allow environment settings to override config files.
110 warn "#{config_file}: #{lineno}: could not parse `#{line}'"
117 subcommands = %w(copy create edit keep pipeline run tag ws)
119 def check_subcommands client, arvados, subcommand, global_opts, remaining_opts
122 arv_create client, arvados, global_opts, remaining_opts
124 arv_edit client, arvados, global_opts, remaining_opts
125 when 'copy', 'tag', 'ws', 'run'
126 exec `which arv-#{subcommand}`.strip, *remaining_opts
128 @sub = remaining_opts.shift
129 if ['get', 'put', 'ls', 'normalize'].index @sub then
131 exec `which arv-#{@sub}`.strip, *remaining_opts
132 elsif ['less', 'check'].index @sub then
134 exec `which wh#{@sub}`.strip, *remaining_opts
135 elsif @sub == 'docker'
136 exec `which arv-keepdocker`.strip, *remaining_opts
138 puts "Usage: arv keep [method] [--parameters]\n"
139 puts "Use 'arv keep [method] --help' to get more information about specific methods.\n\n"
140 puts "Available methods: ls, get, put, less, check, docker"
144 sub = remaining_opts.shift
146 exec `which arv-run-pipeline-instance`.strip, *remaining_opts
148 puts "Usage: arv pipeline [method] [--parameters]\n"
149 puts "Use 'arv pipeline [method] --help' to get more information about specific methods.\n\n"
150 puts "Available methods: run"
156 def command_exists?(command)
157 File.executable?(command) || ENV['PATH'].split(':').select {|folder| File.executable?(File.join(folder, command))}.any?
164 [ENV["VISUAL"], ENV["EDITOR"], "nano", "vi"].each do |e|
165 editor ||= e if e and command_exists? e
168 abort "Could not find any editor to use, please set $VISUAL or $EDITOR to your desired editor."
175 if $?.exitstatus != 0
176 raise "Editor exited with status #{$?.exitstatus}"
180 def edit_and_commit_object initial_obj, tmp_stem, global_opts, &block
182 content = case global_opts[:format]
184 Oj.dump(initial_obj, :indent => 1)
188 abort "Unrecognized format #{global_opts[:format]}"
191 tmp_file = Tempfile.new([tmp_stem, ".#{global_opts[:format]}"])
192 tmp_file.write(content)
199 run_editor tmp_file.path
202 newcontent = tmp_file.read()
205 # Strip lines starting with '#'
206 newcontent = newcontent.lines.select {|l| !l.start_with? '#'}.join
208 # Load the new object
209 newobj = case global_opts[:format]
213 YAML.load(newcontent)
222 newcontent = tmp_file.read()
225 if newcontent == error_text
226 FileUtils::cp tmp_file.path, tmp_file.path + ".saved"
227 puts "File is unchanged, edit aborted."
228 abort "Saved contents to " + tmp_file.path + ".saved"
232 error_text = e.to_s.lines.map {|l| '# ' + l}.join + "\n"
233 error_text += "# Please fix the error and try again.\n"
234 error_text += newcontent.lines.select {|l| !l.start_with? '#'}.join
235 tmp_file.write error_text
247 def check_response result
249 results = JSON.parse result.body
250 rescue JSON::ParserError => e
251 raise "Failed to parse server response:\n" + e.to_s
254 if result.response.status != 200
255 raise "#{result.response.status}: " + (results['errors'] && results['errors'].join('\n') || "")
261 def arv_edit client, arvados, global_opts, remaining_opts
262 uuid = remaining_opts.shift
263 if uuid.nil? or uuid == "-h" or uuid == "--help"
265 puts "Usage: arv edit [uuid] [fields...]\n\n"
266 puts "Fetch the specified Arvados object, select the specified fields, \n"
267 puts "open an interactive text editor on a text representation (json or\n"
268 puts "yaml, use --format) and then update the object. Will use 'nano'\n"
269 puts "by default, customize with the EDITOR or VISUAL environment variable.\n"
274 puts "Not connected to a TTY, cannot run interactive editor."
278 # determine controller
280 m = /([a-z0-9]{5})-([a-z0-9]{5})-([a-z0-9]{15})/.match uuid
282 if /^[a-f0-9]{32}/.match uuid
283 abort "Arvados collections are not editable."
285 abort "#{uuid} does not appear to be an Arvados uuid"
290 arvados.discovery_document["resources"].each do |k,v|
291 klass = k.singularize.camelize
292 dig = Digest::MD5.hexdigest(klass).to_i(16).to_s(36)[-5..-1]
299 abort "Could not determine resource type #{m[2]}"
303 result = client.execute(:api_method => eval('arvados.' + rsc + '.get'),
304 :parameters => {"uuid" => uuid},
305 :authenticated => false,
307 authorization: 'OAuth2 '+ENV['ARVADOS_API_TOKEN']
309 oldobj = check_response result
311 abort "Server error: #{e}"
314 if remaining_opts.length > 0
315 oldobj.select! { |k, v| remaining_opts.include? k }
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: 'OAuth2 '+ENV['ARVADOS_API_TOKEN']
328 check_response result
330 puts "Object is unchanged, did not update."
337 def arv_create client, arvados, global_opts, remaining_opts
338 types = resource_types(arvados.discovery_document)
339 create_opts = Trollop::options do
340 opt :project_uuid, "Project uuid in which to create the object", :type => :string
341 stop_on resource_types(arvados.discovery_document)
344 object_type = remaining_opts.shift
346 abort "Missing resource type, must be one of #{types.join ', '}"
349 rsc = arvados.discovery_document["resources"].keys.select { |k| object_type == k.singularize }
351 abort "Could not determine resource type #{object_type}"
355 discovered_params = arvados.discovery_document["resources"][rsc]["methods"]["create"]["parameters"]
356 method_opts = Trollop::options do
358 banner "Usage: arv create [--project-uuid] #{object_type} [create parameters]"
360 banner "This method supports the following parameters:"
362 discovered_params.each do |k,v|
364 opts[:type] = v["type"].to_sym if v.include?("type")
365 if [:datetime, :text, :object, :array].index opts[:type]
366 opts[:type] = :string # else trollop bork
368 opts[:default] = v["default"] if v.include?("default")
369 opts[:default] = v["default"].to_i if opts[:type] == :integer
370 opts[:default] = to_boolean(v["default"]) if opts[:type] == :boolean
371 opts[:required] = true if v.include?("required") and v["required"]
373 description = ' ' + v["description"] if v.include?("description")
374 opt k.to_sym, description, opts
379 if create_opts[:project_uuid]
380 initial_obj["owner_uuid"] = create_opts[:project_uuid]
383 edit_and_commit_object initial_obj, "", global_opts do |newobj|
384 result = client.execute(:api_method => eval('arvados.' + rsc + '.create'),
385 :parameters => method_opts,
386 :body_object => {object_type => newobj},
387 :authenticated => false,
389 authorization: 'OAuth2 '+ENV['ARVADOS_API_TOKEN']
391 results = check_response result
392 puts "Created object #{results['uuid']}"
399 !!(s =~ /^(true|t|yes|y|1)$/i)
403 "Arvados command line client\n"
406 def help_methods(discovery_document, resource, method=nil)
408 banner += "Usage: arv #{resource} [method] [--parameters]\n"
409 banner += "Use 'arv #{resource} [method] --help' to get more information about specific methods.\n\n"
410 banner += "The #{resource} resource supports the following methods:"
412 discovery_document["resources"][resource.pluralize]["methods"].
415 if v.include? "description"
416 # add only the first line of the discovery doc description
417 description = ' ' + v["description"].split("\n").first.chomp
419 banner += " #{sprintf("%20s",k)}#{description}\n"
424 if not method.nil? and method != '--help' and method != '-h' then
425 abort "Unknown method #{method.inspect} " +
426 "for resource #{resource.inspect}"
431 def help_resources(option_parser, discovery_document, resource)
432 option_parser.educate
436 def resource_types discovery_document
437 resource_types = Array.new()
438 discovery_document["resources"].each do |k,v|
439 resource_types << k.singularize
444 def parse_arguments(discovery_document, subcommands)
445 resources_and_subcommands = resource_types(discovery_document) + subcommands
447 option_parser = Trollop::Parser.new do
450 banner "Usage: arv [--flags] subcommand|resource [method] [--parameters]"
452 banner "Available flags:"
454 opt :dry_run, "Don't actually do anything", :short => "-n"
455 opt :verbose, "Print some things on stderr"
457 "Set the output format. Must be one of json (default), yaml or uuid.",
460 opt :short, "Return only UUIDs (equivalent to --format=uuid)"
463 banner "Use 'arv subcommand|resource --help' to get more information about a particular command or resource."
465 banner "Available subcommands: #{subcommands.join(', ')}"
468 banner "Available resources: #{discovery_document['resources'].keys.map { |k| k.singularize }.join(', ')}"
471 banner "Additional options:"
473 conflicts :short, :format
474 stop_on resources_and_subcommands
477 global_opts = Trollop::with_standard_exception_handling option_parser do
478 o = option_parser.parse ARGV
481 unless %w(json yaml uuid).include?(global_opts[:format])
482 $stderr.puts "#{$0}: --format must be one of json, yaml or uuid."
483 $stderr.puts "Use #{$0} --help for more information."
487 if global_opts[:short]
488 global_opts[:format] = 'uuid'
491 resource = ARGV.shift
493 if not subcommands.include? resource
494 if not resources_and_subcommands.include?(resource)
495 puts "Resource or subcommand '#{resource}' is not recognized.\n\n" if !resource.nil?
496 help_resources(option_parser, discovery_document, resource)
500 if not (discovery_document["resources"][resource.pluralize]["methods"].
502 help_methods(discovery_document, resource, method)
505 discovered_params = discovery_document\
506 ["resources"][resource.pluralize]\
507 ["methods"][method]["parameters"]
508 method_opts = Trollop::options do
510 banner "Usage: arv #{resource} #{method} [--parameters]"
512 banner "This method supports the following parameters:"
514 discovered_params.each do |k,v|
516 opts[:type] = v["type"].to_sym if v.include?("type")
517 if [:datetime, :text, :object, :array].index opts[:type]
518 opts[:type] = :string # else trollop bork
520 opts[:default] = v["default"] if v.include?("default")
521 opts[:default] = v["default"].to_i if opts[:type] == :integer
522 opts[:default] = to_boolean(v["default"]) if opts[:type] == :boolean
523 opts[:required] = true if v.include?("required") and v["required"]
525 description = ' ' + v["description"] if v.include?("description")
526 opt k.to_sym, description, opts
529 body_object = discovery_document["resources"][resource.pluralize]["methods"][method]["request"]
530 if body_object and discovered_params[resource].nil?
532 if body_object["required"] == false
535 opt resource.to_sym, "#{resource} (request body)", {
536 required: is_required,
542 discovered_params.each do |k,v|
544 if ['object', 'array'].index(v["type"]) and method_opts.has_key? k
545 if method_opts[k].andand.match /^\//
546 method_opts[k] = File.open method_opts[k], 'rb' do |f| f.read end
552 return resource, method, method_opts, global_opts, ARGV
561 ENV['ARVADOS_API_VERSION'] ||= 'v1'
563 if not ENV.include?('ARVADOS_API_HOST') or not ENV.include?('ARVADOS_API_TOKEN') then
565 ARVADOS_API_HOST and ARVADOS_API_TOKEN need to be defined as environment variables.
569 # do this if you're testing with a dev server and you don't care about SSL certificate checks:
570 if ENV['ARVADOS_API_HOST_INSECURE']
571 suppress_warnings { OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE }
575 client = ArvadosClient.new(:host => ENV['ARVADOS_API_HOST'], :application_name => 'arvados-cli', :application_version => '1.0')
576 arvados = client.discovered_api('arvados', ENV['ARVADOS_API_VERSION'])
577 rescue Exception => e
578 puts "Failed to connect to Arvados API server: #{e}"
582 # Parse arguments here
583 resource_schema, method, method_opts, global_opts, remaining_opts = parse_arguments(arvados.discovery_document, subcommands)
585 check_subcommands client, arvados, resource_schema, global_opts, remaining_opts
587 controller = resource_schema.pluralize
589 api_method = 'arvados.' + controller + '.' + method
591 if global_opts[:dry_run]
592 if global_opts[:verbose]
593 $stderr.puts "#{api_method} #{method_opts.inspect}"
598 request_parameters = {_profile:true}.merge(method_opts)
599 resource_body = request_parameters.delete(resource_schema.to_sym)
602 resource_schema => resource_body
610 'arvados.jobs.log_tail_follow'
612 # Special case for methods that respond with data streams rather
613 # than JSON (TODO: use the discovery document instead of a static
615 uri_s = eval(api_method).generate_uri(request_parameters)
616 Curl::Easy.perform(uri_s) do |curl|
617 curl.headers['Accept'] = 'text/plain'
618 curl.headers['Authorization'] = "OAuth2 #{ENV['ARVADOS_API_TOKEN']}"
619 if ENV['ARVADOS_API_HOST_INSECURE']
620 curl.ssl_verify_peer = false
621 curl.ssl_verify_host = false
623 if global_opts[:verbose]
624 curl.on_header { |data| $stderr.write data }
626 curl.on_body { |data| $stdout.write data }
630 result = client.execute(:api_method => eval(api_method),
631 :parameters => request_parameters,
632 :body_object => request_body,
633 :authenticated => false,
635 authorization: 'OAuth2 '+ENV['ARVADOS_API_TOKEN']
640 results = JSON.parse result.body
641 rescue JSON::ParserError => e
642 abort "Failed to parse server response:\n" + e.to_s
645 if results["errors"] then
646 abort "Error: #{results["errors"][0]}"
649 case global_opts[:format]
651 puts Oj.dump(results, :indent => 1)
655 if results["items"] and results["kind"].match /list$/i
656 results['items'].each do |i| puts i['uuid'] end
657 elsif results['uuid'].nil?
658 abort("Response did not include a uuid:\n" +
659 Oj.dump(results, :indent => 1) +