Adding `tag' command: initial commit.
[arvados.git] / sdk / cli / bin / arv
1 #!/usr/bin/env ruby
2
3 # Arvados cli client
4 #
5 # Ward Vandewege <ward@clinicalfuture.com>
6
7 if RUBY_VERSION < '1.9.3' then
8   abort <<-EOS
9 #{$0.gsub(/^\.\//,'')} requires Ruby version 1.9.3 or higher.
10   EOS
11 end
12
13 # read authentication data from ~/.arvados if present
14 lineno = 0
15 config_file = File.expand_path('~/.arvados')
16 if File.exist? config_file then
17   File.open(config_file, 'r').each do |line|
18     lineno = lineno + 1
19     # skip comments
20     if line.match('^\s*#') then
21       next
22     end
23     var, val = line.split('=', 2)
24     # allow environment settings to override config files.
25     if var and val
26       ENV[var] ||= val
27     else
28       warn "#{config_file}: #{lineno}: could not parse `#{line}'"
29     end
30   end
31 end
32
33 case ARGV[0]
34 when 'keep'
35   ARGV.shift
36   @sub = ARGV.shift
37   if ['get', 'put'].index @sub then
38     # Native Arvados
39     exec `which arv-#{@sub}`.strip, *ARGV
40   elsif ['ls', 'less', 'check'].index @sub then
41     # wh* shims
42     exec `which wh#{@sub}`.strip, *ARGV
43   else
44     puts "Usage: \n" +
45       "#{$0} keep ls\n" +
46       "#{$0} keep get\n" +
47       "#{$0} keep put\n" +
48       "#{$0} keep less\n" +
49       "#{$0} keep check\n"
50   end
51   abort
52 when 'pipeline'
53   ARGV.shift
54   @sub = ARGV.shift
55   if ['run'].index @sub then
56     exec `which arv-run-pipeline-instance`.strip, *ARGV
57   else
58     puts "Usage: \n" +
59       "#{$0} pipeline run [...]\n" +
60       "(see arv-run-pipeline-instance --help for details)\n"
61   end
62   abort
63 when 'tag'
64   ARGV.shift
65   @sub = ARGV.shift
66   if ['add', 'remove'].index @sub then
67     exec `which arv-tag`.strip, *ARGV
68   else
69     $stderr.puts "Usage: \n" +
70       "#{$0} tag add tag1 [tag2 ...] --objects object_uuid1 [object_uuid2...]\n" +
71       "#{$0} tag remove tag1 [tag2 ...] --objects object_uuid1 [object_uuid2...]\n" +
72       "#{$0} tag remove --all\n"
73   end
74 end
75
76 ENV['ARVADOS_API_VERSION'] ||= 'v1'
77
78 if not ENV.include?('ARVADOS_API_HOST') or not ENV.include?('ARVADOS_API_TOKEN') then
79   abort <<-EOS
80 ARVADOS_API_HOST and ARVADOS_API_TOKEN need to be defined as environment variables.
81   EOS
82 end
83
84 begin
85   require 'curb'
86   require 'rubygems'
87   require 'google/api_client'
88   require 'json'
89   require 'pp'
90   require 'trollop'
91   require 'andand'
92   require 'oj'
93   require 'active_support/inflector'
94   require 'yaml'
95 rescue LoadError
96   abort <<-EOS
97
98 Please install all required gems: 
99
100   gem install activesupport andand curb google-api-client json oj trollop
101
102   EOS
103 end
104
105 ActiveSupport::Inflector.inflections do |inflect|
106   inflect.irregular 'specimen', 'specimens'
107   inflect.irregular 'human', 'humans'
108 end
109
110 module Kernel
111   def suppress_warnings
112     original_verbosity = $VERBOSE
113     $VERBOSE = nil
114     result = yield
115     $VERBOSE = original_verbosity
116     return result
117   end
118 end
119
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 }
123 end
124
125 class Google::APIClient
126  def discovery_document(api, version)
127   api = api.to_s
128   return @discovery_documents["#{api}:#{version}"] ||= (begin
129     response = self.execute!(
130       :http_method => :get,
131       :uri => self.discovery_uri(api, version),
132       :authenticated => false
133     )
134     response.body.class == String ? JSON.parse(response.body) : response.body
135   end)
136  end
137 end
138
139 class ArvadosClient < Google::APIClient
140   def execute(*args)
141     if args.last.is_a? Hash
142       args.last[:headers] ||= {}
143       args.last[:headers]['Accept'] ||= 'application/json'
144     end
145     super(*args)
146   end
147 end
148
149 client = ArvadosClient.new(:host => ENV['ARVADOS_API_HOST'], :application_name => 'arvados-cli', :application_version => '1.0')
150 arvados = client.discovered_api('arvados', ENV['ARVADOS_API_VERSION'])
151
152 def to_boolean(s)
153   !!(s =~ /^(true|t|yes|y|1)$/i)
154 end
155
156 def help_methods(discovery_document, resource, method=nil)
157   banner = "\n"
158   banner += "The #{resource} resource type supports the following methods:"
159   banner += "\n\n"
160   discovery_document["resources"][resource.pluralize]["methods"].
161     each do |k,v|
162     description = ''
163     description = '  ' + v["description"] if v.include?("description")
164     banner += "   #{sprintf("%20s",k)}#{description}\n"
165   end
166   banner += "\n"
167   STDERR.puts banner
168   
169   if not method.nil? and method != '--help' then 
170     Trollop::die ("Unknown method #{method.inspect} " +
171                   "for resource #{resource.inspect}")
172   end
173   exit 255
174 end
175
176 def help_resources(discovery_document, resource)
177   banner = "\n"
178   banner += "This Arvados instance supports the following resource types:"
179   banner += "\n\n"
180   discovery_document["resources"].each do |k,v|
181     description = ''
182     if discovery_document["schemas"].include?(k.singularize.capitalize) and 
183         discovery_document["schemas"][k.singularize.capitalize].include?('description') then
184       description = '  ' + discovery_document["schemas"][k.singularize.capitalize]["description"]
185     end
186     banner += "   #{sprintf("%30s",k.singularize)}#{description}\n"
187   end
188   banner += "\n"
189   STDERR.puts banner
190
191   if not resource.nil? and resource != '--help' then 
192     Trollop::die "Unknown resource type #{resource.inspect}"
193   end
194   exit 255
195 end
196
197 def parse_arguments(discovery_document)
198   resource_types = Array.new()
199   resource_types << '--help'
200   discovery_document["resources"].each do |k,v|
201     resource_types << k.singularize
202   end
203
204   global_opts = Trollop::options do
205     banner "arvados cli client"
206     opt :dry_run, "Don't actually do anything", :short => "-n"
207     opt :verbose, "Print some things on stderr", :short => "-v"
208     opt :uuid, "Return the UUIDs of the objects in the response, one per line (default)", :short => nil
209     opt :json, "Return the entire response received from the API server, as a JSON object", :short => "-j"
210     opt :human, "Return the response received from the API server, as a JSON object with whitespace added for human consumption", :short => "-h"
211     opt :pretty, "Synonym of --human", :short => nil
212     opt :yaml, "Return the response received from the API server, in YAML format", :short => "-y"
213     stop_on resource_types
214   end
215   
216   resource = ARGV.shift
217   if resource == '--help' or not resource_types.include?(resource)
218     help_resources(discovery_document, resource)
219   end
220
221   method = ARGV.shift
222   if not (discovery_document["resources"][resource.pluralize]["methods"].
223           include?(method))
224     help_methods(discovery_document, resource, method)
225   end
226
227   discovered_params = discovery_document\
228     ["resources"][resource.pluralize]\
229     ["methods"][method]["parameters"]
230   method_opts = Trollop::options do
231     discovered_params.each do |k,v|
232       opts = Hash.new()
233       opts[:type] = v["type"].to_sym if v.include?("type")
234       if [:datetime, :text, :object, :array].index opts[:type]
235         opts[:type] = :string                       # else trollop bork
236       end
237       opts[:default] = v["default"] if v.include?("default")
238       opts[:default] = v["default"].to_i if opts[:type] == :integer
239       opts[:default] = to_boolean(v["default"]) if opts[:type] == :boolean
240       opts[:required] = true if v.include?("required") and v["required"]
241       description = ''
242       description = '  ' + v["description"] if v.include?("description")
243       opt k.to_sym, description, opts
244     end
245     body_object = discovery_document["resources"][resource.pluralize]["methods"][method]["request"]
246     if body_object and discovered_params[resource].nil?
247       is_required = true
248       if body_object["required"] == false
249         is_required = false
250       end
251       opt resource.to_sym, "#{resource} (request body)", {
252         required: is_required,
253         type: :string
254       }
255       discovered_params[resource.to_sym] = body_object
256     end
257   end
258
259   discovered_params.each do |k,v|
260     k = k.to_sym
261     if ['object', 'array'].index(v["type"]) and method_opts.has_key? k
262       if method_opts[k].match /^\//
263         method_opts[k] = File.open method_opts[k], 'rb' do |f| f.read end
264       end
265     end
266   end
267   return resource, method, method_opts, global_opts, ARGV
268 end
269
270 resource_schema, method, method_opts, global_opts, remaining_opts = parse_arguments(arvados.discovery_document)
271 controller = resource_schema.pluralize
272
273 api_method = 'arvados.' + controller + '.' + method
274
275 if global_opts[:dry_run]
276   if global_opts[:verbose]
277     $stderr.puts "#{api_method} #{method_opts.inspect}"
278   end
279   exit
280 end
281
282 request_parameters = {}.merge(method_opts)
283 resource_body = request_parameters.delete(resource_schema.to_sym)
284 if resource_body
285   request_body = {
286     resource_schema => JSON.parse(resource_body)
287   }
288 else
289   request_body = {}
290 end
291
292 case api_method
293 when
294   'arvados.users.event_stream',
295   'arvados.jobs.log_stream',
296   'arvados.jobs.log_tail_follow'
297
298   # Special case for methods that respond with data streams rather
299   # than JSON (TODO: use the discovery document instead of a static
300   # list of methods)
301   uri_s = eval(api_method).generate_uri(request_parameters)
302   Curl::Easy.perform(uri_s) do |curl|
303     curl.headers['Accept'] = 'text/plain'
304     curl.headers['Authorization'] = "OAuth2 #{ENV['ARVADOS_API_TOKEN']}"
305     if ENV['ARVADOS_API_HOST_INSECURE']
306       curl.ssl_verify_peer = false 
307       curl.ssl_verify_host = false
308     end
309     if global_opts[:verbose]
310       curl.on_header { |data| $stderr.write data }
311     end
312     curl.on_body { |data| $stdout.write data }
313   end
314   exit 0
315 else
316   request_body[:api_token] = ENV['ARVADOS_API_TOKEN']
317   result = client.execute(:api_method => eval(api_method),
318                           :parameters => request_parameters,
319                           :body => request_body,
320                           :authenticated => false)
321 end
322
323 begin
324   results = JSON.parse result.body
325 rescue JSON::ParserError => e
326   abort "Failed to parse server response:\n" + e.to_s
327 end
328
329 if results["errors"] then
330   abort "Error: #{results["errors"][0]}"
331 end
332
333 if global_opts[:human] or global_opts[:pretty] then
334   puts Oj.dump(results, :indent => 1)
335 elsif global_opts[:yaml] then
336   puts results.to_yaml
337 elsif global_opts[:json] then
338   puts Oj.dump(results)
339 elsif results["items"] and results["kind"].match /list$/i
340   results['items'].each do |i| puts i['uuid'] end
341 elsif results['uuid'].nil?
342   abort("Response did not include a uuid:\n" +
343         Oj.dump(results, :indent => 1) +
344         "\n")
345 else
346   puts results['uuid']
347 end