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 client, arvados, global_opts, remaining_opts
147 n = remaining_opts.shift
148 if n.nil? or n == "-h" or n == "--help"
150 puts "Usage: arv edit [uuid] [fields...]\n\n"
151 puts "Fetch the specified Arvados object, select the specified fields, \n"
152 puts "open an interactive text editor on a text representation (json or\n"
153 puts "yaml, use --format) and then update the object. Will use 'nano'\n"
154 puts "by default, customize with the EDITOR or VISUAL environment variable.\n"
159 puts "Not connected to a TTY, cannot run interactive editor."
163 # determine controller
165 m = /([a-z0-9]{5})-([a-z0-9]{5})-([a-z0-9]{15})/.match n
167 if /^[a-f0-9]{32}/.match n
168 abort "Arvados collections are not editable."
170 abort "#{n} does not appear to be an Arvados uuid"
175 arvados.discovery_document["resources"].each do |k,v|
176 klass = k.singularize.camelize
177 dig = Digest::MD5.hexdigest(klass).to_i(16).to_s(36)[-5..-1]
184 abort "Could not determine resource type #{m[2]}"
187 api_method = 'arvados.' + rsc + '.get'
189 result = client.execute(:api_method => eval(api_method),
190 :parameters => {"uuid" => n},
191 :authenticated => false,
193 authorization: 'OAuth2 '+ENV['ARVADOS_API_TOKEN']
196 results = JSON.parse result.body
197 rescue JSON::ParserError => e
198 abort "Failed to parse server response:\n" + e.to_s
201 if remaining_opts.length > 0
202 results.select! { |k, v| remaining_opts.include? k }
207 case global_opts[:format]
209 content = Oj.dump(results, :indent => 1)
211 content = results.to_yaml
216 tmp = Tempfile.new([n, "." + global_opts[:format]])
225 editor ||= ENV["VISUAL"]
226 editor ||= ENV["EDITOR"]
228 exec editor, tmp.path
233 if $?.exitstatus == 0
235 newcontent = tmp.read()
239 case global_opts[:format]
241 newobj = Oj.load(newcontent)
243 newobj = YAML.load(newcontent)
246 rescue Exception => e
247 puts "Parse error! " + e.to_s
249 newcontent.each_line do |line|
250 puts "#{n.to_s.rjust 4} #{line}"
253 puts "\nTry again (y/n)? "
255 if yn == 'n' or yn == 'N'
260 puts "Editor exited with status #{$?.exitstatus}"
268 api_method = 'arvados.' + rsc + '.update'
269 dumped = Oj.dump(newobj)
270 result = client.execute(:api_method => eval(api_method),
271 :parameters => {"uuid" => n, rsc.singularize => dumped},
272 :authenticated => false,
274 authorization: 'OAuth2 '+ENV['ARVADOS_API_TOKEN']
278 results = JSON.parse result.body
279 rescue JSON::ParserError => e
280 abort "Failed to parse server response:\n" + e.to_s
283 if result.response.status != 200
284 puts "Update failed. Server responded #{result.response.status}: #{results['errors']} "
285 puts "Update body was:"
289 puts "Object is unchanged, did not update."
296 !!(s =~ /^(true|t|yes|y|1)$/i)
300 "Arvados command line client\n"
303 def help_methods(discovery_document, resource, method=nil)
305 banner += "Usage: arv #{resource} [method] [--parameters]\n"
306 banner += "Use 'arv #{resource} [method] --help' to get more information about specific methods.\n\n"
307 banner += "The #{resource} resource supports the following methods:"
309 discovery_document["resources"][resource.pluralize]["methods"].
312 if v.include? "description"
313 # add only the first line of the discovery doc description
314 description = ' ' + v["description"].split("\n").first.chomp
316 banner += " #{sprintf("%20s",k)}#{description}\n"
321 if not method.nil? and method != '--help' and method != '-h' then
322 abort "Unknown method #{method.inspect} " +
323 "for resource #{resource.inspect}"
328 def help_resources(option_parser, discovery_document, resource)
329 option_parser.educate
331 if not resource.nil? and resource != '--help' then
332 Trollop::die "Unknown resource type #{resource.inspect}"
337 def parse_arguments(discovery_document, subcommands)
338 resource_types = Array.new()
339 discovery_document["resources"].each do |k,v|
340 resource_types << k.singularize
343 resource_types += subcommands
345 option_parser = Trollop::Parser.new do
348 banner "Usage: arv [--flags] subcommand|resource [method] [--parameters]"
350 banner "Available flags:"
352 opt :dry_run, "Don't actually do anything", :short => "-n"
353 opt :verbose, "Print some things on stderr"
355 "Set the output format. Must be one of json (default), yaml or uuid.",
358 opt :short, "Return only UUIDs (equivalent to --format=uuid)"
361 banner "Use 'arv subcommand|resource --help' to get more information about a particular command or resource."
363 banner "Available subcommands: #{subcommands.join(', ')}"
366 banner "Available resources: #{discovery_document['resources'].keys.map { |k| k.singularize }.join(', ')}"
369 banner "Additional options:"
371 conflicts :short, :format
372 stop_on resource_types
375 global_opts = Trollop::with_standard_exception_handling option_parser do
376 o = option_parser.parse ARGV
379 unless %w(json yaml uuid).include?(global_opts[:format])
380 $stderr.puts "#{$0}: --format must be one of json, yaml or uuid."
381 $stderr.puts "Use #{$0} --help for more information."
385 if global_opts[:short]
386 global_opts[:format] = 'uuid'
389 resource = ARGV.shift
391 if not subcommands.include? resource
392 if not resource_types.include?(resource)
393 puts "Resource or subcommand '#{resource}' is not recognized.\n\n" if !resource.nil?
394 help_resources(option_parser, discovery_document, resource)
398 if not (discovery_document["resources"][resource.pluralize]["methods"].
400 help_methods(discovery_document, resource, method)
403 discovered_params = discovery_document\
404 ["resources"][resource.pluralize]\
405 ["methods"][method]["parameters"]
406 method_opts = Trollop::options do
408 banner "Usage: arv #{resource} #{method} [--parameters]"
410 banner "This method supports the following parameters:"
412 discovered_params.each do |k,v|
414 opts[:type] = v["type"].to_sym if v.include?("type")
415 if [:datetime, :text, :object, :array].index opts[:type]
416 opts[:type] = :string # else trollop bork
418 opts[:default] = v["default"] if v.include?("default")
419 opts[:default] = v["default"].to_i if opts[:type] == :integer
420 opts[:default] = to_boolean(v["default"]) if opts[:type] == :boolean
421 opts[:required] = true if v.include?("required") and v["required"]
423 description = ' ' + v["description"] if v.include?("description")
424 opt k.to_sym, description, opts
427 body_object = discovery_document["resources"][resource.pluralize]["methods"][method]["request"]
428 if body_object and discovered_params[resource].nil?
430 if body_object["required"] == false
433 opt resource.to_sym, "#{resource} (request body)", {
434 required: is_required,
440 discovered_params.each do |k,v|
442 if ['object', 'array'].index(v["type"]) and method_opts.has_key? k
443 if method_opts[k].andand.match /^\//
444 method_opts[k] = File.open method_opts[k], 'rb' do |f| f.read end
450 return resource, method, method_opts, global_opts, ARGV
459 ENV['ARVADOS_API_VERSION'] ||= 'v1'
461 if not ENV.include?('ARVADOS_API_HOST') or not ENV.include?('ARVADOS_API_TOKEN') then
463 ARVADOS_API_HOST and ARVADOS_API_TOKEN need to be defined as environment variables.
467 # do this if you're testing with a dev server and you don't care about SSL certificate checks:
468 if ENV['ARVADOS_API_HOST_INSECURE']
469 suppress_warnings { OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE }
473 client = ArvadosClient.new(:host => ENV['ARVADOS_API_HOST'], :application_name => 'arvados-cli', :application_version => '1.0')
474 arvados = client.discovered_api('arvados', ENV['ARVADOS_API_VERSION'])
475 rescue Exception => e
476 puts "Failed to connect to Arvados API server: #{e}"
480 # Parse arguments here
481 resource_schema, method, method_opts, global_opts, remaining_opts = parse_arguments(arvados.discovery_document, subcommands)
483 check_subcommands client, arvados, resource_schema, global_opts, remaining_opts
485 controller = resource_schema.pluralize
487 api_method = 'arvados.' + controller + '.' + method
489 if global_opts[:dry_run]
490 if global_opts[:verbose]
491 $stderr.puts "#{api_method} #{method_opts.inspect}"
496 request_parameters = {_profile:true}.merge(method_opts)
497 resource_body = request_parameters.delete(resource_schema.to_sym)
500 resource_schema => resource_body
508 'arvados.jobs.log_tail_follow'
510 # Special case for methods that respond with data streams rather
511 # than JSON (TODO: use the discovery document instead of a static
513 uri_s = eval(api_method).generate_uri(request_parameters)
514 Curl::Easy.perform(uri_s) do |curl|
515 curl.headers['Accept'] = 'text/plain'
516 curl.headers['Authorization'] = "OAuth2 #{ENV['ARVADOS_API_TOKEN']}"
517 if ENV['ARVADOS_API_HOST_INSECURE']
518 curl.ssl_verify_peer = false
519 curl.ssl_verify_host = false
521 if global_opts[:verbose]
522 curl.on_header { |data| $stderr.write data }
524 curl.on_body { |data| $stdout.write data }
528 result = client.execute(:api_method => eval(api_method),
529 :parameters => request_parameters,
530 :body => request_body,
531 :authenticated => false,
533 authorization: 'OAuth2 '+ENV['ARVADOS_API_TOKEN']
538 results = JSON.parse result.body
539 rescue JSON::ParserError => e
540 abort "Failed to parse server response:\n" + e.to_s
543 if results["errors"] then
544 abort "Error: #{results["errors"][0]}"
547 case global_opts[:format]
549 puts Oj.dump(results, :indent => 1)
553 if results["items"] and results["kind"].match /list$/i
554 results['items'].each do |i| puts i['uuid'] end
555 elsif results['uuid'].nil?
556 abort("Response did not include a uuid:\n" +
557 Oj.dump(results, :indent => 1) +