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 return @discovery_documents["#{api}:#{version}"] ||=
58 # fetch new API discovery doc if stale
59 cached_doc = File.expand_path '~/.cache/arvados/discovery_uri.json'
60 if not File.exist?(cached_doc) or (Time.now - File.mtime(cached_doc)) > 86400
61 response = self.execute!(:http_method => :get,
62 :uri => self.discovery_uri(api, version),
63 :authenticated => false)
64 FileUtils.makedirs(File.dirname cached_doc)
65 File.open(cached_doc, 'w') do |f|
70 File.open(cached_doc) { |f| JSON.load f }
75 class ArvadosClient < Google::APIClient
77 if args.last.is_a? Hash
78 args.last[:headers] ||= {}
79 args.last[:headers]['Accept'] ||= 'application/json'
86 # read authentication data from arvados configuration file if present
88 config_file = File.expand_path('~/.config/arvados/settings.conf')
89 if File.exist? config_file then
90 File.open(config_file, 'r').each do |line|
93 if line.match('^\s*#') then
96 var, val = line.chomp.split('=', 2)
97 # allow environment settings to override config files.
101 warn "#{config_file}: #{lineno}: could not parse `#{line}'"
107 subcommands = %w(keep pipeline tag ws edit)
109 def check_subcommands client, arvados, subcommand, global_opts, remaining_opts
112 @sub = remaining_opts.shift
113 if ['get', 'put', 'ls', 'normalize'].index @sub then
115 exec `which arv-#{@sub}`.strip, *remaining_opts
116 elsif ['less', 'check'].index @sub then
118 exec `which wh#{@sub}`.strip, *remaining_opts
119 elsif @sub == 'docker'
120 exec `which arv-keepdocker`.strip, *remaining_opts
122 puts "Usage: arv keep [method] [--parameters]\n"
123 puts "Use 'arv keep [method] --help' to get more information about specific methods.\n\n"
124 puts "Available methods: ls, get, put, less, check, docker"
128 sub = remaining_opts.shift
130 exec `which arv-run-pipeline-instance`.strip, *remaining_opts
132 puts "Usage: arv pipeline [method] [--parameters]\n"
133 puts "Use 'arv pipeline [method] --help' to get more information about specific methods.\n\n"
134 puts "Available methods: run"
138 exec `which arv-tag`.strip, *remaining_opts
140 exec `which arv-ws`.strip, *remaining_opts
142 arv_edit client, arvados, global_opts, remaining_opts
146 def arv_edit_save_tmp tmp
147 FileUtils::cp tmp.path, tmp.path + ".saved"
148 puts "Saved contents to " + tmp.path + ".saved"
151 def arv_edit client, arvados, global_opts, remaining_opts
152 uuid = remaining_opts.shift
153 if uuid.nil? or uuid == "-h" or uuid == "--help"
155 puts "Usage: arv edit [uuid] [fields...]\n\n"
156 puts "Fetch the specified Arvados object, select the specified fields, \n"
157 puts "open an interactive text editor on a text representation (json or\n"
158 puts "yaml, use --format) and then update the object. Will use 'nano'\n"
159 puts "by default, customize with the EDITOR or VISUAL environment variable.\n"
164 puts "Not connected to a TTY, cannot run interactive editor."
168 # determine controller
170 m = /([a-z0-9]{5})-([a-z0-9]{5})-([a-z0-9]{15})/.match uuid
172 if /^[a-f0-9]{32}/.match uuid
173 abort "Arvados collections are not editable."
175 abort "#{n} does not appear to be an Arvados uuid"
180 arvados.discovery_document["resources"].each do |k,v|
181 klass = k.singularize.camelize
182 dig = Digest::MD5.hexdigest(klass).to_i(16).to_s(36)[-5..-1]
189 abort "Could not determine resource type #{m[2]}"
192 api_method = 'arvados.' + rsc + '.get'
194 result = client.execute(:api_method => eval(api_method),
195 :parameters => {"uuid" => uuid},
196 :authenticated => false,
198 authorization: 'OAuth2 '+ENV['ARVADOS_API_TOKEN']
201 results = JSON.parse result.body
202 rescue JSON::ParserError => e
203 abort "Failed to parse server response:\n" + e.to_s
206 if remaining_opts.length > 0
207 results.select! { |k, v| remaining_opts.include? k }
212 case global_opts[:format]
214 content = Oj.dump(results, :indent => 1)
216 content = results.to_yaml
221 tmp = Tempfile.new([uuid, "." + global_opts[:format]])
230 editor ||= ENV["VISUAL"]
231 editor ||= ENV["EDITOR"]
233 exec editor, tmp.path
238 if $?.exitstatus == 0
240 newcontent = tmp.read()
244 case global_opts[:format]
246 newobj = Oj.load(newcontent)
248 newobj = YAML.load(newcontent)
251 rescue Exception => e
252 puts "Parse error! " + e.to_s
254 newcontent.each_line do |line|
255 puts "#{n.to_s.rjust 4} #{line}"
258 puts "\nTry again (y/n)? "
260 while not ["y", "Y", "n", "N"].include?(yn)
263 if yn == 'n' or yn == 'N'
264 arv_edit_save_tmp tmp
269 puts "Editor exited with status #{$?.exitstatus}"
276 api_method = 'arvados.' + rsc + '.update'
277 dumped = Oj.dump(newobj)
280 result = client.execute(:api_method => eval(api_method),
281 :parameters => {"uuid" => uuid},
282 :body => { rsc.singularize => dumped },
283 :authenticated => false,
285 authorization: 'OAuth2 '+ENV['ARVADOS_API_TOKEN']
287 rescue Exception => e
288 puts "Error communicating with server, error was #{e}"
289 puts "Update body was:"
291 arv_edit_save_tmp tmp
296 results = JSON.parse result.body
297 rescue JSON::ParserError => e
298 abort "Failed to parse server response:\n" + e.to_s
301 if result.response.status != 200
302 puts "Update failed. Server responded #{result.response.status}: #{results['errors']} "
303 puts "Update body was:"
305 arv_edit_save_tmp tmp
309 puts "Object is unchanged, did not update."
319 !!(s =~ /^(true|t|yes|y|1)$/i)
323 "Arvados command line client\n"
326 def help_methods(discovery_document, resource, method=nil)
328 banner += "Usage: arv #{resource} [method] [--parameters]\n"
329 banner += "Use 'arv #{resource} [method] --help' to get more information about specific methods.\n\n"
330 banner += "The #{resource} resource supports the following methods:"
332 discovery_document["resources"][resource.pluralize]["methods"].
335 if v.include? "description"
336 # add only the first line of the discovery doc description
337 description = ' ' + v["description"].split("\n").first.chomp
339 banner += " #{sprintf("%20s",k)}#{description}\n"
344 if not method.nil? and method != '--help' and method != '-h' then
345 abort "Unknown method #{method.inspect} " +
346 "for resource #{resource.inspect}"
351 def help_resources(option_parser, discovery_document, resource)
352 option_parser.educate
354 if not resource.nil? and resource != '--help' then
355 Trollop::die "Unknown resource type #{resource.inspect}"
360 def parse_arguments(discovery_document, subcommands)
361 resource_types = Array.new()
362 discovery_document["resources"].each do |k,v|
363 resource_types << k.singularize
366 resource_types += subcommands
368 option_parser = Trollop::Parser.new do
371 banner "Usage: arv [--flags] subcommand|resource [method] [--parameters]"
373 banner "Available flags:"
375 opt :dry_run, "Don't actually do anything", :short => "-n"
376 opt :verbose, "Print some things on stderr"
378 "Set the output format. Must be one of json (default), yaml or uuid.",
381 opt :short, "Return only UUIDs (equivalent to --format=uuid)"
384 banner "Use 'arv subcommand|resource --help' to get more information about a particular command or resource."
386 banner "Available subcommands: #{subcommands.join(', ')}"
389 banner "Available resources: #{discovery_document['resources'].keys.map { |k| k.singularize }.join(', ')}"
392 banner "Additional options:"
394 conflicts :short, :format
395 stop_on resource_types
398 global_opts = Trollop::with_standard_exception_handling option_parser do
399 o = option_parser.parse ARGV
402 unless %w(json yaml uuid).include?(global_opts[:format])
403 $stderr.puts "#{$0}: --format must be one of json, yaml or uuid."
404 $stderr.puts "Use #{$0} --help for more information."
408 if global_opts[:short]
409 global_opts[:format] = 'uuid'
412 resource = ARGV.shift
414 if not subcommands.include? resource
415 if not resource_types.include?(resource)
416 puts "Resource or subcommand '#{resource}' is not recognized.\n\n" if !resource.nil?
417 help_resources(option_parser, discovery_document, resource)
421 if not (discovery_document["resources"][resource.pluralize]["methods"].
423 help_methods(discovery_document, resource, method)
426 discovered_params = discovery_document\
427 ["resources"][resource.pluralize]\
428 ["methods"][method]["parameters"]
429 method_opts = Trollop::options do
431 banner "Usage: arv #{resource} #{method} [--parameters]"
433 banner "This method supports the following parameters:"
435 discovered_params.each do |k,v|
437 opts[:type] = v["type"].to_sym if v.include?("type")
438 if [:datetime, :text, :object, :array].index opts[:type]
439 opts[:type] = :string # else trollop bork
441 opts[:default] = v["default"] if v.include?("default")
442 opts[:default] = v["default"].to_i if opts[:type] == :integer
443 opts[:default] = to_boolean(v["default"]) if opts[:type] == :boolean
444 opts[:required] = true if v.include?("required") and v["required"]
446 description = ' ' + v["description"] if v.include?("description")
447 opt k.to_sym, description, opts
450 body_object = discovery_document["resources"][resource.pluralize]["methods"][method]["request"]
451 if body_object and discovered_params[resource].nil?
453 if body_object["required"] == false
456 opt resource.to_sym, "#{resource} (request body)", {
457 required: is_required,
463 discovered_params.each do |k,v|
465 if ['object', 'array'].index(v["type"]) and method_opts.has_key? k
466 if method_opts[k].andand.match /^\//
467 method_opts[k] = File.open method_opts[k], 'rb' do |f| f.read end
473 return resource, method, method_opts, global_opts, ARGV
482 ENV['ARVADOS_API_VERSION'] ||= 'v1'
484 if not ENV.include?('ARVADOS_API_HOST') or not ENV.include?('ARVADOS_API_TOKEN') then
486 ARVADOS_API_HOST and ARVADOS_API_TOKEN need to be defined as environment variables.
490 # do this if you're testing with a dev server and you don't care about SSL certificate checks:
491 if ENV['ARVADOS_API_HOST_INSECURE']
492 suppress_warnings { OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE }
496 client = ArvadosClient.new(:host => ENV['ARVADOS_API_HOST'], :application_name => 'arvados-cli', :application_version => '1.0')
497 arvados = client.discovered_api('arvados', ENV['ARVADOS_API_VERSION'])
498 rescue Exception => e
499 puts "Failed to connect to Arvados API server: #{e}"
503 # Parse arguments here
504 resource_schema, method, method_opts, global_opts, remaining_opts = parse_arguments(arvados.discovery_document, subcommands)
506 check_subcommands client, arvados, resource_schema, global_opts, remaining_opts
508 controller = resource_schema.pluralize
510 api_method = 'arvados.' + controller + '.' + method
512 if global_opts[:dry_run]
513 if global_opts[:verbose]
514 $stderr.puts "#{api_method} #{method_opts.inspect}"
519 request_parameters = {_profile:true}.merge(method_opts)
520 resource_body = request_parameters.delete(resource_schema.to_sym)
523 resource_schema => resource_body
531 'arvados.jobs.log_tail_follow'
533 # Special case for methods that respond with data streams rather
534 # than JSON (TODO: use the discovery document instead of a static
536 uri_s = eval(api_method).generate_uri(request_parameters)
537 Curl::Easy.perform(uri_s) do |curl|
538 curl.headers['Accept'] = 'text/plain'
539 curl.headers['Authorization'] = "OAuth2 #{ENV['ARVADOS_API_TOKEN']}"
540 if ENV['ARVADOS_API_HOST_INSECURE']
541 curl.ssl_verify_peer = false
542 curl.ssl_verify_host = false
544 if global_opts[:verbose]
545 curl.on_header { |data| $stderr.write data }
547 curl.on_body { |data| $stdout.write data }
551 result = client.execute(:api_method => eval(api_method),
552 :parameters => request_parameters,
553 :body => request_body,
554 :authenticated => false,
556 authorization: 'OAuth2 '+ENV['ARVADOS_API_TOKEN']
561 results = JSON.parse result.body
562 rescue JSON::ParserError => e
563 abort "Failed to parse server response:\n" + e.to_s
566 if results["errors"] then
567 abort "Error: #{results["errors"][0]}"
570 case global_opts[:format]
572 puts Oj.dump(results, :indent => 1)
576 if results["items"] and results["kind"].match /list$/i
577 results['items'].each do |i| puts i['uuid'] end
578 elsif results['uuid'].nil?
579 abort("Response did not include a uuid:\n" +
580 Oj.dump(results, :indent => 1) +