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 arv_edit_save_tmp tmp
157 FileUtils::cp tmp.path, tmp.path + ".saved"
158 puts "Saved contents to " + tmp.path + ".saved"
161 def command_exists?(command)
162 ENV['PATH'].split(':').each {|folder| File.executable?(File.join(folder, command))}
165 def run_editor tmp_file, global_opts
171 [ENV["VISUAL"], ENV["EDITOR"], "nano", "vi"].each do |e|
172 editor ||= e if e and command_exists? e
175 puts "Could not find any editor to use, please set $VISUAL or $EDITOR to your desired editor."
178 exec editor, tmp_file.path
183 if $?.exitstatus == 0
185 newcontent = tmp_file.read()
189 case global_opts[:format]
191 newobj = Oj.load(newcontent)
193 newobj = YAML.load(newcontent)
196 rescue Exception => e
198 newcontent.each_line do |line|
199 puts "#{n.to_s.rjust 4} #{line}"
202 puts "Parse error! " + e.to_s
203 puts "\nTry again (y/n)? "
205 while not ["y", "Y", "n", "N"].include?(yn)
208 if yn == 'n' or yn == 'N'
209 arv_edit_save_tmp tmp_file
214 puts "Editor exited with status #{$?.exitstatus}"
222 def arv_edit client, arvados, global_opts, remaining_opts
223 uuid = remaining_opts.shift
224 if uuid.nil? or uuid == "-h" or uuid == "--help"
226 puts "Usage: arv edit [uuid] [fields...]\n\n"
227 puts "Fetch the specified Arvados object, select the specified fields, \n"
228 puts "open an interactive text editor on a text representation (json or\n"
229 puts "yaml, use --format) and then update the object. Will use 'nano'\n"
230 puts "by default, customize with the EDITOR or VISUAL environment variable.\n"
235 puts "Not connected to a TTY, cannot run interactive editor."
239 # determine controller
241 m = /([a-z0-9]{5})-([a-z0-9]{5})-([a-z0-9]{15})/.match uuid
243 if /^[a-f0-9]{32}/.match uuid
244 abort "Arvados collections are not editable."
246 abort "#{n} does not appear to be an Arvados uuid"
251 arvados.discovery_document["resources"].each do |k,v|
252 klass = k.singularize.camelize
253 dig = Digest::MD5.hexdigest(klass).to_i(16).to_s(36)[-5..-1]
260 abort "Could not determine resource type #{m[2]}"
263 api_method = 'arvados.' + rsc + '.get'
265 result = client.execute(:api_method => eval(api_method),
266 :parameters => {"uuid" => uuid},
267 :authenticated => false,
269 authorization: 'OAuth2 '+ENV['ARVADOS_API_TOKEN']
272 results = JSON.parse result.body
273 rescue JSON::ParserError => e
274 abort "Failed to parse server response:\n" + e.to_s
277 if remaining_opts.length > 0
278 results.select! { |k, v| remaining_opts.include? k }
283 case global_opts[:format]
285 content = Oj.dump(results, :indent => 1)
287 content = results.to_yaml
290 tmp_file = Tempfile.new([uuid, "." + global_opts[:format]])
291 tmp_file.write(content)
294 newobj = run_editor tmp_file, global_opts
298 api_method = 'arvados.' + rsc + '.update'
299 dumped = Oj.dump(newobj)
302 result = client.execute(:api_method => eval(api_method),
303 :parameters => {"uuid" => uuid},
304 :body_object => { rsc.singularize => dumped },
305 :authenticated => false,
307 authorization: 'OAuth2 '+ENV['ARVADOS_API_TOKEN']
309 rescue Exception => e
310 puts "Error communicating with server, error was #{e}"
311 puts "Update body was:"
313 arv_edit_save_tmp tmp_file
318 results = JSON.parse result.body
319 rescue JSON::ParserError => e
320 arv_edit_save_tmp tmp_file
321 abort "Failed to parse server response:\n" + e.to_s
324 if result.response.status != 200
325 puts "Update failed. Server responded #{result.response.status}: #{results['errors']} "
326 puts "Update body was:"
328 arv_edit_save_tmp tmp_file
332 puts "Object is unchanged, did not update."
341 def arv_create client, arvados, global_opts, remaining_opts
342 types = resource_types(arvados.discovery_document)
343 create_opts = Trollop::options do
344 opt :project_uuid, "Project uuid in which to create the object", :type => :string
345 stop_on resource_types(arvados.discovery_document)
348 object_type = remaining_opts.shift
350 abort "Missing resource type, must be one of #{types.join ', '}"
353 rsc = arvados.discovery_document["resources"].keys.select { |k| object_type == k.singularize }
355 abort "Could not determine resource type #{object_type}"
359 discovered_params = arvados.discovery_document["resources"][rsc]["methods"]["create"]["parameters"]
360 method_opts = Trollop::options do
362 banner "Usage: arv create [--project-uuid] #{object_type} [create parameters]"
364 banner "This method supports the following parameters:"
366 discovered_params.each do |k,v|
368 opts[:type] = v["type"].to_sym if v.include?("type")
369 if [:datetime, :text, :object, :array].index opts[:type]
370 opts[:type] = :string # else trollop bork
372 opts[:default] = v["default"] if v.include?("default")
373 opts[:default] = v["default"].to_i if opts[:type] == :integer
374 opts[:default] = to_boolean(v["default"]) if opts[:type] == :boolean
375 opts[:required] = true if v.include?("required") and v["required"]
377 description = ' ' + v["description"] if v.include?("description")
378 opt k.to_sym, description, opts
384 if create_opts[:project_uuid]
385 newobj["owner_uuid"] = create_opts[:project_uuid]
388 case global_opts[:format]
390 content = Oj.dump(newobj, :indent => 1)
392 content = newobj.to_yaml
395 tmp_file = Tempfile.new(["", ".#{global_opts[:format]}"])
396 tmp_file.write(content)
399 newobj = run_editor tmp_file, global_opts
402 api_method = 'arvados.' + rsc + '.create'
403 dumped = Oj.dump(newobj)
405 result = client.execute(:api_method => eval(api_method),
406 :parameters => method_opts,
407 :body_object => {object_type => newobj},
408 :authenticated => false,
410 authorization: 'OAuth2 '+ENV['ARVADOS_API_TOKEN']
414 results = JSON.parse result.body
415 rescue JSON::ParserError => e
416 arv_edit_save_tmp tmp_file
417 abort "Failed to parse server response:\n" + e.to_s
420 if result.response.status != 200
421 puts "Create failed. Server responded #{result.response.status}: #{results['errors']} "
422 puts "Create body was:"
424 arv_edit_save_tmp tmp_file
429 puts "Created object #{results['uuid']}"
431 arv_edit_save_tmp tmp_file
432 abort "Unexpected response:\n#{results}"
442 !!(s =~ /^(true|t|yes|y|1)$/i)
446 "Arvados command line client\n"
449 def help_methods(discovery_document, resource, method=nil)
451 banner += "Usage: arv #{resource} [method] [--parameters]\n"
452 banner += "Use 'arv #{resource} [method] --help' to get more information about specific methods.\n\n"
453 banner += "The #{resource} resource supports the following methods:"
455 discovery_document["resources"][resource.pluralize]["methods"].
458 if v.include? "description"
459 # add only the first line of the discovery doc description
460 description = ' ' + v["description"].split("\n").first.chomp
462 banner += " #{sprintf("%20s",k)}#{description}\n"
467 if not method.nil? and method != '--help' and method != '-h' then
468 abort "Unknown method #{method.inspect} " +
469 "for resource #{resource.inspect}"
474 def help_resources(option_parser, discovery_document, resource)
475 option_parser.educate
479 def resource_types discovery_document
480 resource_types = Array.new()
481 discovery_document["resources"].each do |k,v|
482 resource_types << k.singularize
487 def parse_arguments(discovery_document, subcommands)
488 resources_and_subcommands = resource_types(discovery_document) + subcommands
490 option_parser = Trollop::Parser.new do
493 banner "Usage: arv [--flags] subcommand|resource [method] [--parameters]"
495 banner "Available flags:"
497 opt :dry_run, "Don't actually do anything", :short => "-n"
498 opt :verbose, "Print some things on stderr"
500 "Set the output format. Must be one of json (default), yaml or uuid.",
503 opt :short, "Return only UUIDs (equivalent to --format=uuid)"
506 banner "Use 'arv subcommand|resource --help' to get more information about a particular command or resource."
508 banner "Available subcommands: #{subcommands.join(', ')}"
511 banner "Available resources: #{discovery_document['resources'].keys.map { |k| k.singularize }.join(', ')}"
514 banner "Additional options:"
516 conflicts :short, :format
517 stop_on resources_and_subcommands
520 global_opts = Trollop::with_standard_exception_handling option_parser do
521 o = option_parser.parse ARGV
524 unless %w(json yaml uuid).include?(global_opts[:format])
525 $stderr.puts "#{$0}: --format must be one of json, yaml or uuid."
526 $stderr.puts "Use #{$0} --help for more information."
530 if global_opts[:short]
531 global_opts[:format] = 'uuid'
534 resource = ARGV.shift
536 if not subcommands.include? resource
537 if not resources_and_subcommands.include?(resource)
538 puts "Resource or subcommand '#{resource}' is not recognized.\n\n" if !resource.nil?
539 help_resources(option_parser, discovery_document, resource)
543 if not (discovery_document["resources"][resource.pluralize]["methods"].
545 help_methods(discovery_document, resource, method)
548 discovered_params = discovery_document\
549 ["resources"][resource.pluralize]\
550 ["methods"][method]["parameters"]
551 method_opts = Trollop::options do
553 banner "Usage: arv #{resource} #{method} [--parameters]"
555 banner "This method supports the following parameters:"
557 discovered_params.each do |k,v|
559 opts[:type] = v["type"].to_sym if v.include?("type")
560 if [:datetime, :text, :object, :array].index opts[:type]
561 opts[:type] = :string # else trollop bork
563 opts[:default] = v["default"] if v.include?("default")
564 opts[:default] = v["default"].to_i if opts[:type] == :integer
565 opts[:default] = to_boolean(v["default"]) if opts[:type] == :boolean
566 opts[:required] = true if v.include?("required") and v["required"]
568 description = ' ' + v["description"] if v.include?("description")
569 opt k.to_sym, description, opts
572 body_object = discovery_document["resources"][resource.pluralize]["methods"][method]["request"]
573 if body_object and discovered_params[resource].nil?
575 if body_object["required"] == false
578 opt resource.to_sym, "#{resource} (request body)", {
579 required: is_required,
585 discovered_params.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)
645 resource_schema => resource_body
653 'arvados.jobs.log_tail_follow'
655 # Special case for methods that respond with data streams rather
656 # than JSON (TODO: use the discovery document instead of a static
658 uri_s = eval(api_method).generate_uri(request_parameters)
659 Curl::Easy.perform(uri_s) do |curl|
660 curl.headers['Accept'] = 'text/plain'
661 curl.headers['Authorization'] = "OAuth2 #{ENV['ARVADOS_API_TOKEN']}"
662 if ENV['ARVADOS_API_HOST_INSECURE']
663 curl.ssl_verify_peer = false
664 curl.ssl_verify_host = false
666 if global_opts[:verbose]
667 curl.on_header { |data| $stderr.write data }
669 curl.on_body { |data| $stdout.write data }
673 result = client.execute(:api_method => eval(api_method),
674 :parameters => request_parameters,
675 :body_object => request_body,
676 :authenticated => false,
678 authorization: 'OAuth2 '+ENV['ARVADOS_API_TOKEN']
683 results = JSON.parse result.body
684 rescue JSON::ParserError => e
685 abort "Failed to parse server response:\n" + e.to_s
688 if results["errors"] then
689 abort "Error: #{results["errors"][0]}"
692 case global_opts[:format]
694 puts Oj.dump(results, :indent => 1)
698 if results["items"] and results["kind"].match /list$/i
699 results['items'].each do |i| puts i['uuid'] end
700 elsif results['uuid'].nil?
701 abort("Response did not include a uuid:\n" +
702 Oj.dump(results, :indent => 1) +