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
57 if ['run'].index @sub then
58 exec `which arv-run-pipeline-instance`.strip, *ARGV
61 "#{$0} pipeline run [...]\n" +
62 "(see arv-run-pipeline-instance --help for details)\n"
67 exec `which arv-tag`.strip, *ARGV
70 ENV['ARVADOS_API_VERSION'] ||= 'v1'
72 if not ENV.include?('ARVADOS_API_HOST') or not ENV.include?('ARVADOS_API_TOKEN') then
74 ARVADOS_API_HOST and ARVADOS_API_TOKEN need to be defined as environment variables.
81 require 'google/api_client'
87 require 'active_support/inflector'
92 Please install all required gems:
94 gem install activesupport andand curb google-api-client json oj trollop
99 ActiveSupport::Inflector.inflections do |inflect|
100 inflect.irregular 'specimen', 'specimens'
101 inflect.irregular 'human', 'humans'
105 def suppress_warnings
106 original_verbosity = $VERBOSE
109 $VERBOSE = original_verbosity
114 # do this if you're testing with a dev server and you don't care about SSL certificate checks:
115 if ENV['ARVADOS_API_HOST_INSECURE']
116 suppress_warnings { OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE }
119 class Google::APIClient
120 def discovery_document(api, version)
122 return @discovery_documents["#{api}:#{version}"] ||=
124 # fetch new API discovery doc if stale
125 cached_doc = File.expand_path '~/.cache/arvados/discovery_uri.json'
126 if not File.exist?(cached_doc) or (Time.now - File.mtime(cached_doc)) > 86400
127 response = self.execute!(:http_method => :get,
128 :uri => self.discovery_uri(api, version),
129 :authenticated => false)
130 FileUtils.makedirs(File.dirname cached_doc)
131 File.open(cached_doc, 'w') do |f|
136 File.open(cached_doc) { |f| JSON.load f }
141 class ArvadosClient < Google::APIClient
143 if args.last.is_a? Hash
144 args.last[:headers] ||= {}
145 args.last[:headers]['Accept'] ||= 'application/json'
151 client = ArvadosClient.new(:host => ENV['ARVADOS_API_HOST'], :application_name => 'arvados-cli', :application_version => '1.0')
152 arvados = client.discovered_api('arvados', ENV['ARVADOS_API_VERSION'])
155 !!(s =~ /^(true|t|yes|y|1)$/i)
158 def help_methods(discovery_document, resource, method=nil)
160 banner += "The #{resource} resource type supports the following methods:"
162 discovery_document["resources"][resource.pluralize]["methods"].
165 if v.include? "description"
166 # add only the first line of the discovery doc description
167 description = ' ' + v["description"].split("\n").first.chomp
169 banner += " #{sprintf("%20s",k)}#{description}\n"
174 if not method.nil? and method != '--help' then
175 Trollop::die ("Unknown method #{method.inspect} " +
176 "for resource #{resource.inspect}")
181 def help_resources(discovery_document, resource)
183 banner += "This Arvados instance supports the following resource types:"
185 discovery_document["resources"].each do |k,v|
187 resource_info = discovery_document["schemas"][k.singularize.capitalize]
188 if resource_info and resource_info.include?('description')
189 # add only the first line of the discovery doc description
190 description = ' ' + resource_info["description"].split("\n").first.chomp
192 banner += " #{sprintf("%30s",k.singularize)}#{description}\n"
197 if not resource.nil? and resource != '--help' then
198 Trollop::die "Unknown resource type #{resource.inspect}"
203 def parse_arguments(discovery_document)
204 resource_types = Array.new()
205 discovery_document["resources"].each do |k,v|
206 resource_types << k.singularize
209 global_opts = Trollop::options do
211 banner "arv: the Arvados CLI tool"
212 opt :dry_run, "Don't actually do anything", :short => "-n"
213 opt :verbose, "Print some things on stderr"
215 "Set the output format. Must be one of json (default), yaml or uuid.",
218 opt :short, "Return only UUIDs (equivalent to --format=uuid)"
219 opt :resources, "Display list of resources known to this Arvados instance."
220 conflicts :short, :format
221 stop_on resource_types
224 unless %w(json yaml uuid).include?(global_opts[:format])
225 $stderr.puts "#{$0}: --format must be one of json, yaml or uuid."
226 $stderr.puts "Use #{$0} --help for more information."
230 if global_opts[:short]
231 global_opts[:format] = 'uuid'
234 resource = ARGV.shift
235 if global_opts[:resources] or not resource_types.include?(resource)
236 help_resources(discovery_document, resource)
240 if not (discovery_document["resources"][resource.pluralize]["methods"].
242 help_methods(discovery_document, resource, method)
245 discovered_params = discovery_document\
246 ["resources"][resource.pluralize]\
247 ["methods"][method]["parameters"]
248 method_opts = Trollop::options do
249 discovered_params.each do |k,v|
251 opts[:type] = v["type"].to_sym if v.include?("type")
252 if [:datetime, :text, :object, :array].index opts[:type]
253 opts[:type] = :string # else trollop bork
255 opts[:default] = v["default"] if v.include?("default")
256 opts[:default] = v["default"].to_i if opts[:type] == :integer
257 opts[:default] = to_boolean(v["default"]) if opts[:type] == :boolean
258 opts[:required] = true if v.include?("required") and v["required"]
260 description = ' ' + v["description"] if v.include?("description")
261 opt k.to_sym, description, opts
263 body_object = discovery_document["resources"][resource.pluralize]["methods"][method]["request"]
264 if body_object and discovered_params[resource].nil?
266 if body_object["required"] == false
269 opt resource.to_sym, "#{resource} (request body)", {
270 required: is_required,
276 discovered_params.each do |k,v|
278 if ['object', 'array'].index(v["type"]) and method_opts.has_key? k
279 if method_opts[k].andand.match /^\//
280 method_opts[k] = File.open method_opts[k], 'rb' do |f| f.read end
284 return resource, method, method_opts, global_opts, ARGV
287 resource_schema, method, method_opts, global_opts, remaining_opts = parse_arguments(arvados.discovery_document)
288 controller = resource_schema.pluralize
290 api_method = 'arvados.' + controller + '.' + method
292 if global_opts[:dry_run]
293 if global_opts[:verbose]
294 $stderr.puts "#{api_method} #{method_opts.inspect}"
299 request_parameters = {}.merge(method_opts)
300 resource_body = request_parameters.delete(resource_schema.to_sym)
303 resource_schema => resource_body
311 'arvados.users.event_stream',
312 'arvados.jobs.log_stream',
313 'arvados.jobs.log_tail_follow'
315 # Special case for methods that respond with data streams rather
316 # than JSON (TODO: use the discovery document instead of a static
318 uri_s = eval(api_method).generate_uri(request_parameters)
319 Curl::Easy.perform(uri_s) do |curl|
320 curl.headers['Accept'] = 'text/plain'
321 curl.headers['Authorization'] = "OAuth2 #{ENV['ARVADOS_API_TOKEN']}"
322 if ENV['ARVADOS_API_HOST_INSECURE']
323 curl.ssl_verify_peer = false
324 curl.ssl_verify_host = false
326 if global_opts[:verbose]
327 curl.on_header { |data| $stderr.write data }
329 curl.on_body { |data| $stdout.write data }
333 request_body[:api_token] = ENV['ARVADOS_API_TOKEN']
334 request_body[:_profile] = true
335 result = client.execute(:api_method => eval(api_method),
336 :parameters => request_parameters,
337 :body => request_body,
338 :authenticated => false)
342 results = JSON.parse result.body
343 rescue JSON::ParserError => e
344 abort "Failed to parse server response:\n" + e.to_s
347 if results["errors"] then
348 abort "Error: #{results["errors"][0]}"
351 case global_opts[:format]
353 puts Oj.dump(results, :indent => 1)
357 if results["items"] and results["kind"].match /list$/i
358 results['items'].each do |i| puts i['uuid'] end
359 elsif results['uuid'].nil?
360 abort("Response did not include a uuid:\n" +
361 Oj.dump(results, :indent => 1) +