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.
15 # read authentication data from arvados configuration file if present
17 config_file = File.expand_path('~/.config/arvados/settings.conf')
18 if File.exist? config_file then
19 File.open(config_file, 'r').each do |line|
22 if line.match('^\s*#') then
25 var, val = line.chomp.split('=', 2)
26 # allow environment settings to override config files.
30 warn "#{config_file}: #{lineno}: could not parse `#{line}'"
39 if ['get', 'put', 'ls', 'normalize'].index @sub then
41 exec `which arv-#{@sub}`.strip, *ARGV
42 elsif ['less', 'check'].index @sub then
44 exec `which wh#{@sub}`.strip, *ARGV
45 elsif @sub == 'docker'
46 exec `which arv-keepdocker`.strip, *ARGV
53 "#{$0} keep check\n" +
60 if ['run'].index @sub then
61 exec `which arv-run-pipeline-instance`.strip, *ARGV
64 "#{$0} pipeline run [...]\n" +
65 "(see arv-run-pipeline-instance --help for details)\n"
70 exec `which arv-tag`.strip, *ARGV
73 exec `which arv-ws`.strip, *ARGV
76 ENV['ARVADOS_API_VERSION'] ||= 'v1'
78 if not ENV.include?('ARVADOS_API_HOST') or not ENV.include?('ARVADOS_API_TOKEN') then
80 ARVADOS_API_HOST and ARVADOS_API_TOKEN need to be defined as environment variables.
87 require 'google/api_client'
93 require 'active_support/inflector'
98 Please install all required gems:
100 gem install activesupport andand curb google-api-client json oj trollop
105 ActiveSupport::Inflector.inflections do |inflect|
106 inflect.irregular 'specimen', 'specimens'
107 inflect.irregular 'human', 'humans'
111 def suppress_warnings
112 original_verbosity = $VERBOSE
115 $VERBOSE = original_verbosity
120 # do this if you're testing with a dev server and you don't care about SSL certificate checks:
121 if ENV['ARVADOS_API_HOST_INSECURE']
122 suppress_warnings { OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE }
125 class Google::APIClient
126 def discovery_document(api, version)
128 return @discovery_documents["#{api}:#{version}"] ||=
130 # fetch new API discovery doc if stale
131 cached_doc = File.expand_path '~/.cache/arvados/discovery_uri.json'
132 if not File.exist?(cached_doc) or (Time.now - File.mtime(cached_doc)) > 86400
133 response = self.execute!(:http_method => :get,
134 :uri => self.discovery_uri(api, version),
135 :authenticated => false)
136 FileUtils.makedirs(File.dirname cached_doc)
137 File.open(cached_doc, 'w') do |f|
142 File.open(cached_doc) { |f| JSON.load f }
147 class ArvadosClient < Google::APIClient
149 if args.last.is_a? Hash
150 args.last[:headers] ||= {}
151 args.last[:headers]['Accept'] ||= 'application/json'
158 client = ArvadosClient.new(:host => ENV['ARVADOS_API_HOST'], :application_name => 'arvados-cli', :application_version => '1.0')
159 arvados = client.discovered_api('arvados', ENV['ARVADOS_API_VERSION'])
160 rescue Exception => e
161 puts "Failed to connect to Arvados API server: #{e}"
166 !!(s =~ /^(true|t|yes|y|1)$/i)
169 def help_methods(discovery_document, resource, method=nil)
171 banner += "The #{resource} resource type supports the following methods:"
173 discovery_document["resources"][resource.pluralize]["methods"].
176 if v.include? "description"
177 # add only the first line of the discovery doc description
178 description = ' ' + v["description"].split("\n").first.chomp
180 banner += " #{sprintf("%20s",k)}#{description}\n"
185 if not method.nil? and method != '--help' then
186 Trollop::die ("Unknown method #{method.inspect} " +
187 "for resource #{resource.inspect}")
192 def help_resources(discovery_document, resource)
194 banner += "This Arvados instance supports the following resource types:"
196 discovery_document["resources"].each do |k,v|
198 resource_info = discovery_document["schemas"][k.singularize.capitalize]
199 if resource_info and resource_info.include?('description')
200 # add only the first line of the discovery doc description
201 description = ' ' + resource_info["description"].split("\n").first.chomp
203 banner += " #{sprintf("%30s",k.singularize)}#{description}\n"
208 if not resource.nil? and resource != '--help' then
209 Trollop::die "Unknown resource type #{resource.inspect}"
214 def parse_arguments(discovery_document)
215 resource_types = Array.new()
216 discovery_document["resources"].each do |k,v|
217 resource_types << k.singularize
220 global_opts = Trollop::options do
222 banner "arv: the Arvados CLI tool"
223 opt :dry_run, "Don't actually do anything", :short => "-n"
224 opt :verbose, "Print some things on stderr"
226 "Set the output format. Must be one of json (default), yaml or uuid.",
229 opt :short, "Return only UUIDs (equivalent to --format=uuid)"
230 opt :resources, "Display list of resources known to this Arvados instance."
231 conflicts :short, :format
232 stop_on resource_types
235 unless %w(json yaml uuid).include?(global_opts[:format])
236 $stderr.puts "#{$0}: --format must be one of json, yaml or uuid."
237 $stderr.puts "Use #{$0} --help for more information."
241 if global_opts[:short]
242 global_opts[:format] = 'uuid'
245 resource = ARGV.shift
246 if global_opts[:resources] or not resource_types.include?(resource)
247 help_resources(discovery_document, resource)
251 if not (discovery_document["resources"][resource.pluralize]["methods"].
253 help_methods(discovery_document, resource, method)
256 discovered_params = discovery_document\
257 ["resources"][resource.pluralize]\
258 ["methods"][method]["parameters"]
259 method_opts = Trollop::options do
260 discovered_params.each do |k,v|
262 opts[:type] = v["type"].to_sym if v.include?("type")
263 if [:datetime, :text, :object, :array].index opts[:type]
264 opts[:type] = :string # else trollop bork
266 opts[:default] = v["default"] if v.include?("default")
267 opts[:default] = v["default"].to_i if opts[:type] == :integer
268 opts[:default] = to_boolean(v["default"]) if opts[:type] == :boolean
269 opts[:required] = true if v.include?("required") and v["required"]
271 description = ' ' + v["description"] if v.include?("description")
272 opt k.to_sym, description, opts
274 body_object = discovery_document["resources"][resource.pluralize]["methods"][method]["request"]
275 if body_object and discovered_params[resource].nil?
277 if body_object["required"] == false
280 opt resource.to_sym, "#{resource} (request body)", {
281 required: is_required,
287 discovered_params.each do |k,v|
289 if ['object', 'array'].index(v["type"]) and method_opts.has_key? k
290 if method_opts[k].andand.match /^\//
291 method_opts[k] = File.open method_opts[k], 'rb' do |f| f.read end
295 return resource, method, method_opts, global_opts, ARGV
298 resource_schema, method, method_opts, global_opts, remaining_opts = parse_arguments(arvados.discovery_document)
299 controller = resource_schema.pluralize
301 api_method = 'arvados.' + controller + '.' + method
303 if global_opts[:dry_run]
304 if global_opts[:verbose]
305 $stderr.puts "#{api_method} #{method_opts.inspect}"
310 request_parameters = {_profile:true}.merge(method_opts)
311 resource_body = request_parameters.delete(resource_schema.to_sym)
314 resource_schema => resource_body
322 'arvados.jobs.log_tail_follow'
324 # Special case for methods that respond with data streams rather
325 # than JSON (TODO: use the discovery document instead of a static
327 uri_s = eval(api_method).generate_uri(request_parameters)
328 Curl::Easy.perform(uri_s) do |curl|
329 curl.headers['Accept'] = 'text/plain'
330 curl.headers['Authorization'] = "OAuth2 #{ENV['ARVADOS_API_TOKEN']}"
331 if ENV['ARVADOS_API_HOST_INSECURE']
332 curl.ssl_verify_peer = false
333 curl.ssl_verify_host = false
335 if global_opts[:verbose]
336 curl.on_header { |data| $stderr.write data }
338 curl.on_body { |data| $stdout.write data }
342 result = client.execute(:api_method => eval(api_method),
343 :parameters => request_parameters,
344 :body => request_body,
345 :authenticated => false,
347 authorization: 'OAuth2 '+ENV['ARVADOS_API_TOKEN']
352 results = JSON.parse result.body
353 rescue JSON::ParserError => e
354 abort "Failed to parse server response:\n" + e.to_s
357 if results["errors"] then
358 abort "Error: #{results["errors"][0]}"
361 case global_opts[:format]
363 puts Oj.dump(results, :indent => 1)
367 if results["items"] and results["kind"].match /list$/i
368 results['items'].each do |i| puts i['uuid'] end
369 elsif results['uuid'].nil?
370 abort("Response did not include a uuid:\n" +
371 Oj.dump(results, :indent => 1) +