5 # Ward Vandewege <ward@clinicalfuture.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 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-tag`.strip, *remaining_opts
148 exec `which arv-ws`.strip, *remaining_opts
150 arv_edit client, arvados, global_opts, remaining_opts
154 def arv_edit_save_tmp tmp
155 FileUtils::cp tmp.path, tmp.path + ".saved"
156 puts "Saved contents to " + tmp.path + ".saved"
159 def arv_edit client, arvados, global_opts, remaining_opts
160 uuid = remaining_opts.shift
161 if uuid.nil? or uuid == "-h" or uuid == "--help"
163 puts "Usage: arv edit [uuid] [fields...]\n\n"
164 puts "Fetch the specified Arvados object, select the specified fields, \n"
165 puts "open an interactive text editor on a text representation (json or\n"
166 puts "yaml, use --format) and then update the object. Will use 'nano'\n"
167 puts "by default, customize with the EDITOR or VISUAL environment variable.\n"
172 puts "Not connected to a TTY, cannot run interactive editor."
176 # determine controller
178 m = /([a-z0-9]{5})-([a-z0-9]{5})-([a-z0-9]{15})/.match uuid
180 if /^[a-f0-9]{32}/.match uuid
181 abort "Arvados collections are not editable."
183 abort "#{n} does not appear to be an Arvados uuid"
188 arvados.discovery_document["resources"].each do |k,v|
189 klass = k.singularize.camelize
190 dig = Digest::MD5.hexdigest(klass).to_i(16).to_s(36)[-5..-1]
197 abort "Could not determine resource type #{m[2]}"
200 api_method = 'arvados.' + rsc + '.get'
202 result = client.execute(:api_method => eval(api_method),
203 :parameters => {"uuid" => uuid},
204 :authenticated => false,
206 authorization: 'OAuth2 '+ENV['ARVADOS_API_TOKEN']
209 results = JSON.parse result.body
210 rescue JSON::ParserError => e
211 abort "Failed to parse server response:\n" + e.to_s
214 if remaining_opts.length > 0
215 results.select! { |k, v| remaining_opts.include? k }
220 case global_opts[:format]
222 content = Oj.dump(results, :indent => 1)
224 content = results.to_yaml
229 tmp = Tempfile.new([uuid, "." + global_opts[:format]])
238 editor ||= ENV["VISUAL"]
239 editor ||= ENV["EDITOR"]
241 exec editor, tmp.path
246 if $?.exitstatus == 0
248 newcontent = tmp.read()
252 case global_opts[:format]
254 newobj = Oj.load(newcontent)
256 newobj = YAML.load(newcontent)
259 rescue Exception => e
260 puts "Parse error! " + e.to_s
262 newcontent.each_line do |line|
263 puts "#{n.to_s.rjust 4} #{line}"
266 puts "\nTry again (y/n)? "
268 while not ["y", "Y", "n", "N"].include?(yn)
271 if yn == 'n' or yn == 'N'
272 arv_edit_save_tmp tmp
277 puts "Editor exited with status #{$?.exitstatus}"
284 api_method = 'arvados.' + rsc + '.update'
285 dumped = Oj.dump(newobj)
288 result = client.execute(:api_method => eval(api_method),
289 :parameters => {"uuid" => uuid},
290 :body => { rsc.singularize => dumped },
291 :authenticated => false,
293 authorization: 'OAuth2 '+ENV['ARVADOS_API_TOKEN']
295 rescue Exception => e
296 puts "Error communicating with server, error was #{e}"
297 puts "Update body was:"
299 arv_edit_save_tmp tmp
304 results = JSON.parse result.body
305 rescue JSON::ParserError => e
306 abort "Failed to parse server response:\n" + e.to_s
309 if result.response.status != 200
310 puts "Update failed. Server responded #{result.response.status}: #{results['errors']} "
311 puts "Update body was:"
313 arv_edit_save_tmp tmp
317 puts "Object is unchanged, did not update."
327 !!(s =~ /^(true|t|yes|y|1)$/i)
331 "Arvados command line client\n"
334 def help_methods(discovery_document, resource, method=nil)
336 banner += "Usage: arv #{resource} [method] [--parameters]\n"
337 banner += "Use 'arv #{resource} [method] --help' to get more information about specific methods.\n\n"
338 banner += "The #{resource} resource supports the following methods:"
340 discovery_document["resources"][resource.pluralize]["methods"].
343 if v.include? "description"
344 # add only the first line of the discovery doc description
345 description = ' ' + v["description"].split("\n").first.chomp
347 banner += " #{sprintf("%20s",k)}#{description}\n"
352 if not method.nil? and method != '--help' and method != '-h' then
353 abort "Unknown method #{method.inspect} " +
354 "for resource #{resource.inspect}"
359 def help_resources(option_parser, discovery_document, resource)
360 option_parser.educate
362 if not resource.nil? and resource != '--help' then
363 Trollop::die "Unknown resource type #{resource.inspect}"
368 def parse_arguments(discovery_document, subcommands)
369 resource_types = Array.new()
370 discovery_document["resources"].each do |k,v|
371 resource_types << k.singularize
374 resource_types += subcommands
376 option_parser = Trollop::Parser.new do
379 banner "Usage: arv [--flags] subcommand|resource [method] [--parameters]"
381 banner "Available flags:"
383 opt :dry_run, "Don't actually do anything", :short => "-n"
384 opt :verbose, "Print some things on stderr"
386 "Set the output format. Must be one of json (default), yaml or uuid.",
389 opt :short, "Return only UUIDs (equivalent to --format=uuid)"
392 banner "Use 'arv subcommand|resource --help' to get more information about a particular command or resource."
394 banner "Available subcommands: #{subcommands.join(', ')}"
397 banner "Available resources: #{discovery_document['resources'].keys.map { |k| k.singularize }.join(', ')}"
400 banner "Additional options:"
402 conflicts :short, :format
403 stop_on resource_types
406 global_opts = Trollop::with_standard_exception_handling option_parser do
407 o = option_parser.parse ARGV
410 unless %w(json yaml uuid).include?(global_opts[:format])
411 $stderr.puts "#{$0}: --format must be one of json, yaml or uuid."
412 $stderr.puts "Use #{$0} --help for more information."
416 if global_opts[:short]
417 global_opts[:format] = 'uuid'
420 resource = ARGV.shift
422 if not subcommands.include? resource
423 if not resource_types.include?(resource)
424 puts "Resource or subcommand '#{resource}' is not recognized.\n\n" if !resource.nil?
425 help_resources(option_parser, discovery_document, resource)
429 if not (discovery_document["resources"][resource.pluralize]["methods"].
431 help_methods(discovery_document, resource, method)
434 discovered_params = discovery_document\
435 ["resources"][resource.pluralize]\
436 ["methods"][method]["parameters"]
437 method_opts = Trollop::options do
439 banner "Usage: arv #{resource} #{method} [--parameters]"
441 banner "This method supports the following parameters:"
443 discovered_params.each do |k,v|
445 opts[:type] = v["type"].to_sym if v.include?("type")
446 if [:datetime, :text, :object, :array].index opts[:type]
447 opts[:type] = :string # else trollop bork
449 opts[:default] = v["default"] if v.include?("default")
450 opts[:default] = v["default"].to_i if opts[:type] == :integer
451 opts[:default] = to_boolean(v["default"]) if opts[:type] == :boolean
452 opts[:required] = true if v.include?("required") and v["required"]
454 description = ' ' + v["description"] if v.include?("description")
455 opt k.to_sym, description, opts
458 body_object = discovery_document["resources"][resource.pluralize]["methods"][method]["request"]
459 if body_object and discovered_params[resource].nil?
461 if body_object["required"] == false
464 opt resource.to_sym, "#{resource} (request body)", {
465 required: is_required,
471 discovered_params.each do |k,v|
473 if ['object', 'array'].index(v["type"]) and method_opts.has_key? k
474 if method_opts[k].andand.match /^\//
475 method_opts[k] = File.open method_opts[k], 'rb' do |f| f.read end
481 return resource, method, method_opts, global_opts, ARGV
490 ENV['ARVADOS_API_VERSION'] ||= 'v1'
492 if not ENV.include?('ARVADOS_API_HOST') or not ENV.include?('ARVADOS_API_TOKEN') then
494 ARVADOS_API_HOST and ARVADOS_API_TOKEN need to be defined as environment variables.
498 # do this if you're testing with a dev server and you don't care about SSL certificate checks:
499 if ENV['ARVADOS_API_HOST_INSECURE']
500 suppress_warnings { OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE }
504 client = ArvadosClient.new(:host => ENV['ARVADOS_API_HOST'], :application_name => 'arvados-cli', :application_version => '1.0')
505 arvados = client.discovered_api('arvados', ENV['ARVADOS_API_VERSION'])
506 rescue Exception => e
507 puts "Failed to connect to Arvados API server: #{e}"
511 # Parse arguments here
512 resource_schema, method, method_opts, global_opts, remaining_opts = parse_arguments(arvados.discovery_document, subcommands)
514 check_subcommands client, arvados, resource_schema, global_opts, remaining_opts
516 controller = resource_schema.pluralize
518 api_method = 'arvados.' + controller + '.' + method
520 if global_opts[:dry_run]
521 if global_opts[:verbose]
522 $stderr.puts "#{api_method} #{method_opts.inspect}"
527 request_parameters = {_profile:true}.merge(method_opts)
528 resource_body = request_parameters.delete(resource_schema.to_sym)
531 resource_schema => resource_body
539 'arvados.jobs.log_tail_follow'
541 # Special case for methods that respond with data streams rather
542 # than JSON (TODO: use the discovery document instead of a static
544 uri_s = eval(api_method).generate_uri(request_parameters)
545 Curl::Easy.perform(uri_s) do |curl|
546 curl.headers['Accept'] = 'text/plain'
547 curl.headers['Authorization'] = "OAuth2 #{ENV['ARVADOS_API_TOKEN']}"
548 if ENV['ARVADOS_API_HOST_INSECURE']
549 curl.ssl_verify_peer = false
550 curl.ssl_verify_host = false
552 if global_opts[:verbose]
553 curl.on_header { |data| $stderr.write data }
555 curl.on_body { |data| $stdout.write data }
559 result = client.execute(:api_method => eval(api_method),
560 :parameters => request_parameters,
561 :body => request_body,
562 :authenticated => false,
564 authorization: 'OAuth2 '+ENV['ARVADOS_API_TOKEN']
569 results = JSON.parse result.body
570 rescue JSON::ParserError => e
571 abort "Failed to parse server response:\n" + e.to_s
574 if results["errors"] then
575 abort "Error: #{results["errors"][0]}"
578 case global_opts[:format]
580 puts Oj.dump(results, :indent => 1)
584 if results["items"] and results["kind"].match /list$/i
585 results['items'].each do |i| puts i['uuid'] end
586 elsif results['uuid'].nil?
587 abort("Response did not include a uuid:\n" +
588 Oj.dump(results, :indent => 1) +