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}'"
116 subcommands = %w(create edit keep pipeline run tag ws)
118 def check_subcommands client, arvados, subcommand, global_opts, remaining_opts
121 arv_create client, arvados, global_opts, remaining_opts
123 arv_edit client, arvados, global_opts, remaining_opts
125 @sub = remaining_opts.shift
126 if ['get', 'put', 'ls', 'normalize'].index @sub then
128 exec `which arv-#{@sub}`.strip, *remaining_opts
129 elsif ['less', 'check'].index @sub then
131 exec `which wh#{@sub}`.strip, *remaining_opts
132 elsif @sub == 'docker'
133 exec `which arv-keepdocker`.strip, *remaining_opts
135 puts "Usage: arv keep [method] [--parameters]\n"
136 puts "Use 'arv keep [method] --help' to get more information about specific methods.\n\n"
137 puts "Available methods: ls, get, put, less, check, docker"
141 sub = remaining_opts.shift
143 exec `which arv-run-pipeline-instance`.strip, *remaining_opts
145 puts "Usage: arv pipeline [method] [--parameters]\n"
146 puts "Use 'arv pipeline [method] --help' to get more information about specific methods.\n\n"
147 puts "Available methods: run"
151 exec `which arv-run`.strip, *remaining_opts
153 exec `which arv-tag`.strip, *remaining_opts
155 exec `which arv-ws`.strip, *remaining_opts
159 def arv_edit_save_tmp tmp
160 FileUtils::cp tmp.path, tmp.path + ".saved"
161 puts "Saved contents to " + tmp.path + ".saved"
164 def command_exists?(command)
165 ENV['PATH'].split(':').each {|folder| File.executable?(File.join(folder, command))}
168 def run_editor tmp_file, global_opts
174 [ENV["VISUAL"], ENV["EDITOR"], "nano", "vi"].each do |e|
175 editor ||= e if e and command_exists? e
178 puts "Could not find any editor to use, please set $VISUAL or $EDITOR to your desired editor."
181 exec editor, tmp_file.path
186 if $?.exitstatus == 0
188 newcontent = tmp_file.read()
192 case global_opts[:format]
194 newobj = Oj.load(newcontent)
196 newobj = YAML.load(newcontent)
199 rescue Exception => e
201 newcontent.each_line do |line|
202 puts "#{n.to_s.rjust 4} #{line}"
205 puts "Parse error! " + e.to_s
206 puts "\nTry again (y/n)? "
208 while not ["y", "Y", "n", "N"].include?(yn)
211 if yn == 'n' or yn == 'N'
212 arv_edit_save_tmp tmp_file
217 puts "Editor exited with status #{$?.exitstatus}"
225 def arv_edit client, arvados, global_opts, remaining_opts
226 uuid = remaining_opts.shift
227 if uuid.nil? or uuid == "-h" or uuid == "--help"
229 puts "Usage: arv edit [uuid] [fields...]\n\n"
230 puts "Fetch the specified Arvados object, select the specified fields, \n"
231 puts "open an interactive text editor on a text representation (json or\n"
232 puts "yaml, use --format) and then update the object. Will use 'nano'\n"
233 puts "by default, customize with the EDITOR or VISUAL environment variable.\n"
238 puts "Not connected to a TTY, cannot run interactive editor."
242 # determine controller
244 m = /([a-z0-9]{5})-([a-z0-9]{5})-([a-z0-9]{15})/.match uuid
246 if /^[a-f0-9]{32}/.match uuid
247 abort "Arvados collections are not editable."
249 abort "#{n} does not appear to be an Arvados uuid"
254 arvados.discovery_document["resources"].each do |k,v|
255 klass = k.singularize.camelize
256 dig = Digest::MD5.hexdigest(klass).to_i(16).to_s(36)[-5..-1]
263 abort "Could not determine resource type #{m[2]}"
266 api_method = 'arvados.' + rsc + '.get'
268 result = client.execute(:api_method => eval(api_method),
269 :parameters => {"uuid" => uuid},
270 :authenticated => false,
272 authorization: 'OAuth2 '+ENV['ARVADOS_API_TOKEN']
275 results = JSON.parse result.body
276 rescue JSON::ParserError => e
277 abort "Failed to parse server response:\n" + e.to_s
280 if remaining_opts.length > 0
281 results.select! { |k, v| remaining_opts.include? k }
286 case global_opts[:format]
288 content = Oj.dump(results, :indent => 1)
290 content = results.to_yaml
293 tmp_file = Tempfile.new([uuid, "." + global_opts[:format]])
294 tmp_file.write(content)
297 newobj = run_editor tmp_file, global_opts
301 api_method = 'arvados.' + rsc + '.update'
302 dumped = Oj.dump(newobj)
305 result = client.execute(:api_method => eval(api_method),
306 :parameters => {"uuid" => uuid},
307 :body => { rsc.singularize => dumped },
308 :authenticated => false,
310 authorization: 'OAuth2 '+ENV['ARVADOS_API_TOKEN']
312 rescue Exception => e
313 puts "Error communicating with server, error was #{e}"
314 puts "Update body was:"
316 arv_edit_save_tmp tmp_file
321 results = JSON.parse result.body
322 rescue JSON::ParserError => e
323 arv_edit_save_tmp tmp_file
324 abort "Failed to parse server response:\n" + e.to_s
327 if result.response.status != 200
328 puts "Update failed. Server responded #{result.response.status}: #{results['errors']} "
329 puts "Update body was:"
331 arv_edit_save_tmp tmp_file
335 puts "Object is unchanged, did not update."
344 def arv_create client, arvados, global_opts, remaining_opts
345 types = resource_types(arvados.discovery_document)
346 create_opts = Trollop::options do
347 opt :project_uuid, "Project uuid in which to create the object", :type => :string
348 stop_on resource_types(arvados.discovery_document)
351 object_type = remaining_opts.shift
353 abort "Missing resource type, must be one of #{types.join ', '}"
356 rsc = arvados.discovery_document["resources"].keys.select { |k| object_type == k.singularize }
358 abort "Could not determine resource type #{object_type}"
362 discovered_params = arvados.discovery_document["resources"][rsc]["methods"]["create"]["parameters"]
363 method_opts = Trollop::options do
365 banner "Usage: arv create [--project-uuid] #{object_type} [create parameters]"
367 banner "This method supports the following parameters:"
369 discovered_params.each do |k,v|
371 opts[:type] = v["type"].to_sym if v.include?("type")
372 if [:datetime, :text, :object, :array].index opts[:type]
373 opts[:type] = :string # else trollop bork
375 opts[:default] = v["default"] if v.include?("default")
376 opts[:default] = v["default"].to_i if opts[:type] == :integer
377 opts[:default] = to_boolean(v["default"]) if opts[:type] == :boolean
378 opts[:required] = true if v.include?("required") and v["required"]
380 description = ' ' + v["description"] if v.include?("description")
381 opt k.to_sym, description, opts
387 if create_opts[:project_uuid]
388 newobj["owner_uuid"] = create_opts[:project_uuid]
391 case global_opts[:format]
393 content = Oj.dump(newobj, :indent => 1)
395 content = newobj.to_yaml
398 tmp_file = Tempfile.new(["", ".#{global_opts[:format]}"])
399 tmp_file.write(content)
402 newobj = run_editor tmp_file, global_opts
405 api_method = 'arvados.' + rsc + '.create'
406 dumped = Oj.dump(newobj)
408 result = client.execute(:api_method => eval(api_method),
409 :parameters => method_opts,
410 :body_object => {object_type => newobj},
411 :authenticated => false,
413 authorization: 'OAuth2 '+ENV['ARVADOS_API_TOKEN']
417 results = JSON.parse result.body
418 rescue JSON::ParserError => e
419 arv_edit_save_tmp tmp_file
420 abort "Failed to parse server response:\n" + e.to_s
423 if result.response.status != 200
424 puts "Create failed. Server responded #{result.response.status}: #{results['errors']} "
425 puts "Create body was:"
427 arv_edit_save_tmp tmp_file
432 puts "Created object #{results['uuid']}"
434 arv_edit_save_tmp tmp_file
435 abort "Unexpected response:\n#{results}"
445 !!(s =~ /^(true|t|yes|y|1)$/i)
449 "Arvados command line client\n"
452 def help_methods(discovery_document, resource, method=nil)
454 banner += "Usage: arv #{resource} [method] [--parameters]\n"
455 banner += "Use 'arv #{resource} [method] --help' to get more information about specific methods.\n\n"
456 banner += "The #{resource} resource supports the following methods:"
458 discovery_document["resources"][resource.pluralize]["methods"].
461 if v.include? "description"
462 # add only the first line of the discovery doc description
463 description = ' ' + v["description"].split("\n").first.chomp
465 banner += " #{sprintf("%20s",k)}#{description}\n"
470 if not method.nil? and method != '--help' and method != '-h' then
471 abort "Unknown method #{method.inspect} " +
472 "for resource #{resource.inspect}"
477 def help_resources(option_parser, discovery_document, resource)
478 option_parser.educate
482 def resource_types discovery_document
483 resource_types = Array.new()
484 discovery_document["resources"].each do |k,v|
485 resource_types << k.singularize
490 def parse_arguments(discovery_document, subcommands)
491 resources_and_subcommands = resource_types(discovery_document) + subcommands
493 option_parser = Trollop::Parser.new do
496 banner "Usage: arv [--flags] subcommand|resource [method] [--parameters]"
498 banner "Available flags:"
500 opt :dry_run, "Don't actually do anything", :short => "-n"
501 opt :verbose, "Print some things on stderr"
503 "Set the output format. Must be one of json (default), yaml or uuid.",
506 opt :short, "Return only UUIDs (equivalent to --format=uuid)"
509 banner "Use 'arv subcommand|resource --help' to get more information about a particular command or resource."
511 banner "Available subcommands: #{subcommands.join(', ')}"
514 banner "Available resources: #{discovery_document['resources'].keys.map { |k| k.singularize }.join(', ')}"
517 banner "Additional options:"
519 conflicts :short, :format
520 stop_on resources_and_subcommands
523 global_opts = Trollop::with_standard_exception_handling option_parser do
524 o = option_parser.parse ARGV
527 unless %w(json yaml uuid).include?(global_opts[:format])
528 $stderr.puts "#{$0}: --format must be one of json, yaml or uuid."
529 $stderr.puts "Use #{$0} --help for more information."
533 if global_opts[:short]
534 global_opts[:format] = 'uuid'
537 resource = ARGV.shift
539 if not subcommands.include? resource
540 if not resources_and_subcommands.include?(resource)
541 puts "Resource or subcommand '#{resource}' is not recognized.\n\n" if !resource.nil?
542 help_resources(option_parser, discovery_document, resource)
546 if not (discovery_document["resources"][resource.pluralize]["methods"].
548 help_methods(discovery_document, resource, method)
551 discovered_params = discovery_document\
552 ["resources"][resource.pluralize]\
553 ["methods"][method]["parameters"]
554 method_opts = Trollop::options do
556 banner "Usage: arv #{resource} #{method} [--parameters]"
558 banner "This method supports the following parameters:"
560 discovered_params.each do |k,v|
562 opts[:type] = v["type"].to_sym if v.include?("type")
563 if [:datetime, :text, :object, :array].index opts[:type]
564 opts[:type] = :string # else trollop bork
566 opts[:default] = v["default"] if v.include?("default")
567 opts[:default] = v["default"].to_i if opts[:type] == :integer
568 opts[:default] = to_boolean(v["default"]) if opts[:type] == :boolean
569 opts[:required] = true if v.include?("required") and v["required"]
571 description = ' ' + v["description"] if v.include?("description")
572 opt k.to_sym, description, opts
575 body_object = discovery_document["resources"][resource.pluralize]["methods"][method]["request"]
576 if body_object and discovered_params[resource].nil?
578 if body_object["required"] == false
581 opt resource.to_sym, "#{resource} (request body)", {
582 required: is_required,
588 discovered_params.each do |k,v|
590 if ['object', 'array'].index(v["type"]) and method_opts.has_key? k
591 if method_opts[k].andand.match /^\//
592 method_opts[k] = File.open method_opts[k], 'rb' do |f| f.read end
598 return resource, method, method_opts, global_opts, ARGV
607 ENV['ARVADOS_API_VERSION'] ||= 'v1'
609 if not ENV.include?('ARVADOS_API_HOST') or not ENV.include?('ARVADOS_API_TOKEN') then
611 ARVADOS_API_HOST and ARVADOS_API_TOKEN need to be defined as environment variables.
615 # do this if you're testing with a dev server and you don't care about SSL certificate checks:
616 if ENV['ARVADOS_API_HOST_INSECURE']
617 suppress_warnings { OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE }
621 client = ArvadosClient.new(:host => ENV['ARVADOS_API_HOST'], :application_name => 'arvados-cli', :application_version => '1.0')
622 arvados = client.discovered_api('arvados', ENV['ARVADOS_API_VERSION'])
623 rescue Exception => e
624 puts "Failed to connect to Arvados API server: #{e}"
628 # Parse arguments here
629 resource_schema, method, method_opts, global_opts, remaining_opts = parse_arguments(arvados.discovery_document, subcommands)
631 check_subcommands client, arvados, resource_schema, global_opts, remaining_opts
633 controller = resource_schema.pluralize
635 api_method = 'arvados.' + controller + '.' + method
637 if global_opts[:dry_run]
638 if global_opts[:verbose]
639 $stderr.puts "#{api_method} #{method_opts.inspect}"
644 request_parameters = {_profile:true}.merge(method_opts)
645 resource_body = request_parameters.delete(resource_schema.to_sym)
648 resource_schema => resource_body
656 'arvados.jobs.log_tail_follow'
658 # Special case for methods that respond with data streams rather
659 # than JSON (TODO: use the discovery document instead of a static
661 uri_s = eval(api_method).generate_uri(request_parameters)
662 Curl::Easy.perform(uri_s) do |curl|
663 curl.headers['Accept'] = 'text/plain'
664 curl.headers['Authorization'] = "OAuth2 #{ENV['ARVADOS_API_TOKEN']}"
665 if ENV['ARVADOS_API_HOST_INSECURE']
666 curl.ssl_verify_peer = false
667 curl.ssl_verify_host = false
669 if global_opts[:verbose]
670 curl.on_header { |data| $stderr.write data }
672 curl.on_body { |data| $stdout.write data }
676 result = client.execute(:api_method => eval(api_method),
677 :parameters => request_parameters,
678 :body => request_body,
679 :authenticated => false,
681 authorization: 'OAuth2 '+ENV['ARVADOS_API_TOKEN']
686 results = JSON.parse result.body
687 rescue JSON::ParserError => e
688 abort "Failed to parse server response:\n" + e.to_s
691 if results["errors"] then
692 abort "Error: #{results["errors"][0]}"
695 case global_opts[:format]
697 puts Oj.dump(results, :indent => 1)
701 if results["items"] and results["kind"].match /list$/i
702 results['items'].each do |i| puts i['uuid'] end
703 elsif results['uuid'].nil?
704 abort("Response did not include a uuid:\n" +
705 Oj.dump(results, :indent => 1) +