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'
29 Please install all required gems:
31 gem install activesupport andand curb google-api-client json oj trollop yaml
36 # Search for 'ENTRY POINT' to see where things get going
38 ActiveSupport::Inflector.inflections do |inflect|
39 inflect.irregular 'specimen', 'specimens'
40 inflect.irregular 'human', 'humans'
45 original_verbosity = $VERBOSE
48 $VERBOSE = original_verbosity
53 class Google::APIClient
54 def discovery_document(api, version)
56 discovery_uri = self.discovery_uri(api, version)
57 discovery_uri_hash = Digest::MD5.hexdigest(discovery_uri)
58 return @discovery_documents[discovery_uri_hash] ||=
60 # fetch new API discovery doc if stale
61 cached_doc = File.expand_path "~/.cache/arvados/discovery-#{discovery_uri_hash}.json" rescue nil
63 if cached_doc.nil? or not File.exist?(cached_doc) or (Time.now - File.mtime(cached_doc)) > 86400
64 response = self.execute!(:http_method => :get,
65 :uri => discovery_uri,
66 :authenticated => false)
69 FileUtils.makedirs(File.dirname cached_doc)
70 File.open(cached_doc, 'w') do |f|
74 return JSON.load response.body
78 File.open(cached_doc) { |f| JSON.load f }
83 class ArvadosClient < Google::APIClient
85 if args.last.is_a? Hash
86 args.last[:headers] ||= {}
87 args.last[:headers]['Accept'] ||= 'application/json'
94 # read authentication data from arvados configuration file if present
96 config_file = File.expand_path('~/.config/arvados/settings.conf') rescue nil
97 if not config_file.nil? and File.exist? config_file then
98 File.open(config_file, 'r').each do |line|
101 if line.match('^\s*#') then
104 var, val = line.chomp.split('=', 2)
105 # allow environment settings to override config files.
109 warn "#{config_file}: #{lineno}: could not parse `#{line}'"
115 subcommands = %w(keep pipeline run tag ws edit)
117 def check_subcommands client, arvados, subcommand, global_opts, remaining_opts
120 @sub = remaining_opts.shift
121 if ['get', 'put', 'ls', 'normalize'].index @sub then
123 exec `which arv-#{@sub}`.strip, *remaining_opts
124 elsif ['less', 'check'].index @sub then
126 exec `which wh#{@sub}`.strip, *remaining_opts
127 elsif @sub == 'docker'
128 exec `which arv-keepdocker`.strip, *remaining_opts
130 puts "Usage: arv keep [method] [--parameters]\n"
131 puts "Use 'arv keep [method] --help' to get more information about specific methods.\n\n"
132 puts "Available methods: ls, get, put, less, check, docker"
136 sub = remaining_opts.shift
138 exec `which arv-run-pipeline-instance`.strip, *remaining_opts
140 puts "Usage: arv pipeline [method] [--parameters]\n"
141 puts "Use 'arv pipeline [method] --help' to get more information about specific methods.\n\n"
142 puts "Available methods: run"
146 exec `which arv-run`.strip, *remaining_opts
148 exec `which arv-tag`.strip, *remaining_opts
150 exec `which arv-ws`.strip, *remaining_opts
152 arv_edit client, arvados, global_opts, remaining_opts
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 arv_edit client, arvados, global_opts, remaining_opts
162 uuid = remaining_opts.shift
163 if uuid.nil? or uuid == "-h" or uuid == "--help"
165 puts "Usage: arv edit [uuid] [fields...]\n\n"
166 puts "Fetch the specified Arvados object, select the specified fields, \n"
167 puts "open an interactive text editor on a text representation (json or\n"
168 puts "yaml, use --format) and then update the object. Will use 'nano'\n"
169 puts "by default, customize with the EDITOR or VISUAL environment variable.\n"
174 puts "Not connected to a TTY, cannot run interactive editor."
178 # determine controller
180 m = /([a-z0-9]{5})-([a-z0-9]{5})-([a-z0-9]{15})/.match uuid
182 if /^[a-f0-9]{32}/.match uuid
183 abort "Arvados collections are not editable."
185 abort "#{n} does not appear to be an Arvados uuid"
190 arvados.discovery_document["resources"].each do |k,v|
191 klass = k.singularize.camelize
192 dig = Digest::MD5.hexdigest(klass).to_i(16).to_s(36)[-5..-1]
199 abort "Could not determine resource type #{m[2]}"
202 api_method = 'arvados.' + rsc + '.get'
204 result = client.execute(:api_method => eval(api_method),
205 :parameters => {"uuid" => uuid},
206 :authenticated => false,
208 authorization: 'OAuth2 '+ENV['ARVADOS_API_TOKEN']
211 results = JSON.parse result.body
212 rescue JSON::ParserError => e
213 abort "Failed to parse server response:\n" + e.to_s
216 if remaining_opts.length > 0
217 results.select! { |k, v| remaining_opts.include? k }
222 case global_opts[:format]
224 content = Oj.dump(results, :indent => 1)
226 content = results.to_yaml
231 tmp = Tempfile.new([uuid, "." + global_opts[:format]])
240 editor ||= ENV["VISUAL"]
241 editor ||= ENV["EDITOR"]
243 exec editor, tmp.path
248 if $?.exitstatus == 0
250 newcontent = tmp.read()
254 case global_opts[:format]
256 newobj = Oj.load(newcontent)
258 newobj = YAML.load(newcontent)
261 rescue Exception => e
262 puts "Parse error! " + e.to_s
264 newcontent.each_line do |line|
265 puts "#{n.to_s.rjust 4} #{line}"
268 puts "\nTry again (y/n)? "
270 while not ["y", "Y", "n", "N"].include?(yn)
273 if yn == 'n' or yn == 'N'
274 arv_edit_save_tmp tmp
279 puts "Editor exited with status #{$?.exitstatus}"
286 api_method = 'arvados.' + rsc + '.update'
287 dumped = Oj.dump(newobj)
290 result = client.execute(:api_method => eval(api_method),
291 :parameters => {"uuid" => uuid},
292 :body => { rsc.singularize => dumped },
293 :authenticated => false,
295 authorization: 'OAuth2 '+ENV['ARVADOS_API_TOKEN']
297 rescue Exception => e
298 puts "Error communicating with server, error was #{e}"
299 puts "Update body was:"
301 arv_edit_save_tmp tmp
306 results = JSON.parse result.body
307 rescue JSON::ParserError => e
308 abort "Failed to parse server response:\n" + e.to_s
311 if result.response.status != 200
312 puts "Update failed. Server responded #{result.response.status}: #{results['errors']} "
313 puts "Update body was:"
315 arv_edit_save_tmp tmp
319 puts "Object is unchanged, did not update."
329 !!(s =~ /^(true|t|yes|y|1)$/i)
333 "Arvados command line client\n"
336 def help_methods(discovery_document, resource, method=nil)
338 banner += "Usage: arv #{resource} [method] [--parameters]\n"
339 banner += "Use 'arv #{resource} [method] --help' to get more information about specific methods.\n\n"
340 banner += "The #{resource} resource supports the following methods:"
342 discovery_document["resources"][resource.pluralize]["methods"].
345 if v.include? "description"
346 # add only the first line of the discovery doc description
347 description = ' ' + v["description"].split("\n").first.chomp
349 banner += " #{sprintf("%20s",k)}#{description}\n"
354 if not method.nil? and method != '--help' and method != '-h' then
355 abort "Unknown method #{method.inspect} " +
356 "for resource #{resource.inspect}"
361 def help_resources(option_parser, discovery_document, resource)
362 option_parser.educate
366 def parse_arguments(discovery_document, subcommands)
367 resource_types = Array.new()
368 discovery_document["resources"].each do |k,v|
369 resource_types << k.singularize
372 resource_types += subcommands
374 option_parser = Trollop::Parser.new do
377 banner "Usage: arv [--flags] subcommand|resource [method] [--parameters]"
379 banner "Available flags:"
381 opt :dry_run, "Don't actually do anything", :short => "-n"
382 opt :verbose, "Print some things on stderr"
384 "Set the output format. Must be one of json (default), yaml or uuid.",
387 opt :short, "Return only UUIDs (equivalent to --format=uuid)"
390 banner "Use 'arv subcommand|resource --help' to get more information about a particular command or resource."
392 banner "Available subcommands: #{subcommands.join(', ')}"
395 banner "Available resources: #{discovery_document['resources'].keys.map { |k| k.singularize }.join(', ')}"
398 banner "Additional options:"
400 conflicts :short, :format
401 stop_on resource_types
404 global_opts = Trollop::with_standard_exception_handling option_parser do
405 o = option_parser.parse ARGV
408 unless %w(json yaml uuid).include?(global_opts[:format])
409 $stderr.puts "#{$0}: --format must be one of json, yaml or uuid."
410 $stderr.puts "Use #{$0} --help for more information."
414 if global_opts[:short]
415 global_opts[:format] = 'uuid'
418 resource = ARGV.shift
420 if not subcommands.include? resource
421 if not resource_types.include?(resource)
422 puts "Resource or subcommand '#{resource}' is not recognized.\n\n" if !resource.nil?
423 help_resources(option_parser, discovery_document, resource)
427 if not (discovery_document["resources"][resource.pluralize]["methods"].
429 help_methods(discovery_document, resource, method)
432 discovered_params = discovery_document\
433 ["resources"][resource.pluralize]\
434 ["methods"][method]["parameters"]
435 method_opts = Trollop::options do
437 banner "Usage: arv #{resource} #{method} [--parameters]"
439 banner "This method supports the following parameters:"
441 discovered_params.each do |k,v|
443 opts[:type] = v["type"].to_sym if v.include?("type")
444 if [:datetime, :text, :object, :array].index opts[:type]
445 opts[:type] = :string # else trollop bork
447 opts[:default] = v["default"] if v.include?("default")
448 opts[:default] = v["default"].to_i if opts[:type] == :integer
449 opts[:default] = to_boolean(v["default"]) if opts[:type] == :boolean
450 opts[:required] = true if v.include?("required") and v["required"]
452 description = ' ' + v["description"] if v.include?("description")
453 opt k.to_sym, description, opts
456 body_object = discovery_document["resources"][resource.pluralize]["methods"][method]["request"]
457 if body_object and discovered_params[resource].nil?
459 if body_object["required"] == false
462 opt resource.to_sym, "#{resource} (request body)", {
463 required: is_required,
469 discovered_params.each do |k,v|
471 if ['object', 'array'].index(v["type"]) and method_opts.has_key? k
472 if method_opts[k].andand.match /^\//
473 method_opts[k] = File.open method_opts[k], 'rb' do |f| f.read end
479 return resource, method, method_opts, global_opts, ARGV
488 ENV['ARVADOS_API_VERSION'] ||= 'v1'
490 if not ENV.include?('ARVADOS_API_HOST') or not ENV.include?('ARVADOS_API_TOKEN') then
492 ARVADOS_API_HOST and ARVADOS_API_TOKEN need to be defined as environment variables.
496 # do this if you're testing with a dev server and you don't care about SSL certificate checks:
497 if ENV['ARVADOS_API_HOST_INSECURE']
498 suppress_warnings { OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE }
502 client = ArvadosClient.new(:host => ENV['ARVADOS_API_HOST'], :application_name => 'arvados-cli', :application_version => '1.0')
503 arvados = client.discovered_api('arvados', ENV['ARVADOS_API_VERSION'])
504 rescue Exception => e
505 puts "Failed to connect to Arvados API server: #{e}"
509 # Parse arguments here
510 resource_schema, method, method_opts, global_opts, remaining_opts = parse_arguments(arvados.discovery_document, subcommands)
512 check_subcommands client, arvados, resource_schema, global_opts, remaining_opts
514 controller = resource_schema.pluralize
516 api_method = 'arvados.' + controller + '.' + method
518 if global_opts[:dry_run]
519 if global_opts[:verbose]
520 $stderr.puts "#{api_method} #{method_opts.inspect}"
525 request_parameters = {_profile:true}.merge(method_opts)
526 resource_body = request_parameters.delete(resource_schema.to_sym)
529 resource_schema => resource_body
537 'arvados.jobs.log_tail_follow'
539 # Special case for methods that respond with data streams rather
540 # than JSON (TODO: use the discovery document instead of a static
542 uri_s = eval(api_method).generate_uri(request_parameters)
543 Curl::Easy.perform(uri_s) do |curl|
544 curl.headers['Accept'] = 'text/plain'
545 curl.headers['Authorization'] = "OAuth2 #{ENV['ARVADOS_API_TOKEN']}"
546 if ENV['ARVADOS_API_HOST_INSECURE']
547 curl.ssl_verify_peer = false
548 curl.ssl_verify_host = false
550 if global_opts[:verbose]
551 curl.on_header { |data| $stderr.write data }
553 curl.on_body { |data| $stdout.write data }
557 result = client.execute(:api_method => eval(api_method),
558 :parameters => request_parameters,
559 :body => request_body,
560 :authenticated => false,
562 authorization: 'OAuth2 '+ENV['ARVADOS_API_TOKEN']
567 results = JSON.parse result.body
568 rescue JSON::ParserError => e
569 abort "Failed to parse server response:\n" + e.to_s
572 if results["errors"] then
573 abort "Error: #{results["errors"][0]}"
576 case global_opts[:format]
578 puts Oj.dump(results, :indent => 1)
582 if results["items"] and results["kind"].match /list$/i
583 results['items'].each do |i| puts i['uuid'] end
584 elsif results['uuid'].nil?
585 abort("Response did not include a uuid:\n" +
586 Oj.dump(results, :indent => 1) +