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' rescue nil
61 if cached_doc.nil? or not File.exist?(cached_doc) or (Time.now - File.mtime(cached_doc)) > 86400
62 response = self.execute!(:http_method => :get,
63 :uri => self.discovery_uri(api, version),
64 :authenticated => false)
67 FileUtils.makedirs(File.dirname cached_doc)
68 File.open(cached_doc, 'w') do |f|
72 return JSON.load response.body
76 File.open(cached_doc) { |f| JSON.load f }
81 class ArvadosClient < Google::APIClient
83 if args.last.is_a? Hash
84 args.last[:headers] ||= {}
85 args.last[:headers]['Accept'] ||= 'application/json'
92 # read authentication data from arvados configuration file if present
94 config_file = File.expand_path('~/.config/arvados/settings.conf') rescue nil
95 if not config_file.nil? and File.exist? config_file then
96 File.open(config_file, 'r').each do |line|
99 if line.match('^\s*#') then
102 var, val = line.chomp.split('=', 2)
103 # allow environment settings to override config files.
107 warn "#{config_file}: #{lineno}: could not parse `#{line}'"
113 subcommands = %w(keep pipeline tag ws edit)
115 def check_subcommands client, arvados, subcommand, global_opts, remaining_opts
118 @sub = remaining_opts.shift
119 if ['get', 'put', 'ls', 'normalize'].index @sub then
121 exec `which arv-#{@sub}`.strip, *remaining_opts
122 elsif ['less', 'check'].index @sub then
124 exec `which wh#{@sub}`.strip, *remaining_opts
125 elsif @sub == 'docker'
126 exec `which arv-keepdocker`.strip, *remaining_opts
128 puts "Usage: arv keep [method] [--parameters]\n"
129 puts "Use 'arv keep [method] --help' to get more information about specific methods.\n\n"
130 puts "Available methods: ls, get, put, less, check, docker"
134 sub = remaining_opts.shift
136 exec `which arv-run-pipeline-instance`.strip, *remaining_opts
138 puts "Usage: arv pipeline [method] [--parameters]\n"
139 puts "Use 'arv pipeline [method] --help' to get more information about specific methods.\n\n"
140 puts "Available methods: run"
144 exec `which arv-tag`.strip, *remaining_opts
146 exec `which arv-ws`.strip, *remaining_opts
148 arv_edit client, arvados, global_opts, remaining_opts
152 def arv_edit_save_tmp tmp
153 FileUtils::cp tmp.path, tmp.path + ".saved"
154 puts "Saved contents to " + tmp.path + ".saved"
157 def arv_edit client, arvados, global_opts, remaining_opts
158 uuid = remaining_opts.shift
159 if uuid.nil? or uuid == "-h" or uuid == "--help"
161 puts "Usage: arv edit [uuid] [fields...]\n\n"
162 puts "Fetch the specified Arvados object, select the specified fields, \n"
163 puts "open an interactive text editor on a text representation (json or\n"
164 puts "yaml, use --format) and then update the object. Will use 'nano'\n"
165 puts "by default, customize with the EDITOR or VISUAL environment variable.\n"
170 puts "Not connected to a TTY, cannot run interactive editor."
174 # determine controller
176 m = /([a-z0-9]{5})-([a-z0-9]{5})-([a-z0-9]{15})/.match uuid
178 if /^[a-f0-9]{32}/.match uuid
179 abort "Arvados collections are not editable."
181 abort "#{n} does not appear to be an Arvados uuid"
186 arvados.discovery_document["resources"].each do |k,v|
187 klass = k.singularize.camelize
188 dig = Digest::MD5.hexdigest(klass).to_i(16).to_s(36)[-5..-1]
195 abort "Could not determine resource type #{m[2]}"
198 api_method = 'arvados.' + rsc + '.get'
200 result = client.execute(:api_method => eval(api_method),
201 :parameters => {"uuid" => uuid},
202 :authenticated => false,
204 authorization: 'OAuth2 '+ENV['ARVADOS_API_TOKEN']
207 results = JSON.parse result.body
208 rescue JSON::ParserError => e
209 abort "Failed to parse server response:\n" + e.to_s
212 if remaining_opts.length > 0
213 results.select! { |k, v| remaining_opts.include? k }
218 case global_opts[:format]
220 content = Oj.dump(results, :indent => 1)
222 content = results.to_yaml
227 tmp = Tempfile.new([uuid, "." + global_opts[:format]])
236 editor ||= ENV["VISUAL"]
237 editor ||= ENV["EDITOR"]
239 exec editor, tmp.path
244 if $?.exitstatus == 0
246 newcontent = tmp.read()
250 case global_opts[:format]
252 newobj = Oj.load(newcontent)
254 newobj = YAML.load(newcontent)
257 rescue Exception => e
258 puts "Parse error! " + e.to_s
260 newcontent.each_line do |line|
261 puts "#{n.to_s.rjust 4} #{line}"
264 puts "\nTry again (y/n)? "
266 while not ["y", "Y", "n", "N"].include?(yn)
269 if yn == 'n' or yn == 'N'
270 arv_edit_save_tmp tmp
275 puts "Editor exited with status #{$?.exitstatus}"
282 api_method = 'arvados.' + rsc + '.update'
283 dumped = Oj.dump(newobj)
286 result = client.execute(:api_method => eval(api_method),
287 :parameters => {"uuid" => uuid},
288 :body => { rsc.singularize => dumped },
289 :authenticated => false,
291 authorization: 'OAuth2 '+ENV['ARVADOS_API_TOKEN']
293 rescue Exception => e
294 puts "Error communicating with server, error was #{e}"
295 puts "Update body was:"
297 arv_edit_save_tmp tmp
302 results = JSON.parse result.body
303 rescue JSON::ParserError => e
304 abort "Failed to parse server response:\n" + e.to_s
307 if result.response.status != 200
308 puts "Update failed. Server responded #{result.response.status}: #{results['errors']} "
309 puts "Update body was:"
311 arv_edit_save_tmp tmp
315 puts "Object is unchanged, did not update."
325 !!(s =~ /^(true|t|yes|y|1)$/i)
329 "Arvados command line client\n"
332 def help_methods(discovery_document, resource, method=nil)
334 banner += "Usage: arv #{resource} [method] [--parameters]\n"
335 banner += "Use 'arv #{resource} [method] --help' to get more information about specific methods.\n\n"
336 banner += "The #{resource} resource supports the following methods:"
338 discovery_document["resources"][resource.pluralize]["methods"].
341 if v.include? "description"
342 # add only the first line of the discovery doc description
343 description = ' ' + v["description"].split("\n").first.chomp
345 banner += " #{sprintf("%20s",k)}#{description}\n"
350 if not method.nil? and method != '--help' and method != '-h' then
351 abort "Unknown method #{method.inspect} " +
352 "for resource #{resource.inspect}"
357 def help_resources(option_parser, discovery_document, resource)
358 option_parser.educate
360 if not resource.nil? and resource != '--help' then
361 Trollop::die "Unknown resource type #{resource.inspect}"
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) +