08ff8d0244d18a874dc78fa103cc772e4a2b9307
[arvados.git] / sdk / cli / 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 ENV['ARVADOS_API_VERSION'] ||= 'v1'
14
15 if not ENV.include?('ARVADOS_API_HOST') or not ENV.include?('ARVADOS_API_TOKEN') then
16   abort <<-EOS
17 ARVADOS_API_HOST and ARVADOS_API_TOKEN need to be defined as environment variables.
18   EOS
19 end
20
21 begin
22   require 'rubygems'
23   require 'google/api_client'
24   require 'json'
25   require 'pp'
26   require 'trollop'
27   require 'andand'
28   require 'oj'
29 rescue LoadError
30   abort <<-EOS
31
32 Please install all required gems: 
33
34   google-api-client
35   json
36   trollop
37   andand
38   oj
39
40   EOS
41 end
42
43 module Kernel
44   def suppress_warnings
45     original_verbosity = $VERBOSE
46     $VERBOSE = nil
47     result = yield
48     $VERBOSE = original_verbosity
49     return result
50   end
51 end
52
53 # do this if you're testing with a dev server and you don't care about SSL certificate checks:
54 if ENV['ARVADOS_API_HOST_INSECURE']
55   suppress_warnings { OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE }
56 end
57
58 class Google::APIClient
59  def discovery_document(api, version)
60   api = api.to_s
61   return @discovery_documents["#{api}:#{version}"] ||= (begin
62     response = self.execute!(
63       :http_method => :get,
64       :uri => self.discovery_uri(api, version),
65       :authenticated => false
66     )
67     response.body.class == String ? JSON.parse(response.body) : response.body
68   end)
69  end
70 end
71
72 client = Google::APIClient.new(:host => ENV['ARVADOS_API_HOST'], :application_name => 'arvados-cli', :application_version => '1.0')
73 arvados = client.discovered_api('arvados', ENV['ARVADOS_API_VERSION'])
74
75 def to_boolean(s)
76   !!(s =~ /^(true|t|yes|y|1)$/i)
77 end
78
79 def parse_arguments(discovery_document)
80   resource_types = Array.new()
81   resource_types << '--help'
82   discovery_document["resources"].each do |k,v|
83     resource_types << k.singularize
84   end
85
86   global_opts = Trollop::options do
87     banner "arvados cli client"
88     opt :dry_run, "Don't actually do anything", :short => "-n"
89     opt :verbose, "Print some things on stderr", :short => "-v"
90     opt :uuid, "Return the UUIDs of the objects in the response, one per line (default)", :short => nil
91     opt :json, "Return the entire response received from the API server, as a JSON object", :short => "-j"
92     opt :human, "Return the response received from the API server, as a JSON object with whitespace added for human consumption", :short => "-h"
93     opt :pretty, "Synonym of --human", :short => nil
94     stop_on resource_types
95   end
96   
97   # get the subcommand
98   resource_arg = ARGV.shift
99   if resource_types.include?(resource_arg) and resource_arg != '--help' then
100     # subcommand exists
101     # Now see if the method supplied exists
102     method = ARGV.shift
103     if discovery_document["resources"][resource_arg.pluralize]["methods"].include?(method) then
104       # method exists. Collect arguments.
105       discovered_params = discovery_document["resources"][resource_arg.pluralize]["methods"][method]["parameters"]
106       method_opts = Trollop::options do
107         discovered_params.each do |k,v|
108           opts = Hash.new()
109           opts[:type] = v["type"].to_sym if v.include?("type")
110           if [:datetime, :text, :object].index opts[:type]
111             opts[:type] = :string                       # else trollop bork
112           end
113           opts[:default] = v["default"] if v.include?("default")
114           opts[:default] = v["default"].to_i if opts[:type] == :integer
115           opts[:default] = to_boolean(v["default"]) if opts[:type] == :boolean
116           opts[:required] = true if v.include?("required") and v["required"]
117           description = ''
118           description = '  ' + v["description"] if v.include?("description")
119           opt k.to_sym, description, opts
120         end
121       end
122       discovered_params.each do |k,v|
123         if v["type"] == "object" and method_opts.has_key? k
124           method_opts[k] = JSON.parse method_opts[k]
125         end
126       end
127     else
128       banner = "\nThis resource type supports the following methods:\n\n"
129       discovery_document["resources"][resource_arg.pluralize]["methods"].each do |k,v|
130         description = ''
131         description = '  ' + v["description"] if v.include?("description")
132         banner += "   #{sprintf("%20s",k)}#{description}\n"
133       end
134       banner += "\n"
135
136       STDERR.puts banner
137   
138       if not method.nil? and method != '--help' then 
139         Trollop::die "Unknown method #{method.to_s} for command #{resource_arg.to_s}"
140       else
141         exit 255
142       end
143
144     end
145     
146   else
147     banner = "\nThis Arvados instance supports the following resource types:\n\n"
148     discovery_document["resources"].each do |k,v|
149       description = ''
150       if discovery_document["schemas"].include?(k.singularize.capitalize) and 
151          discovery_document["schemas"][k.singularize.capitalize].include?('description') then
152         description = '  ' + discovery_document["schemas"][k.singularize.capitalize]["description"]
153       end
154       banner += "   #{sprintf("%30s",k.singularize)}#{description}\n"
155     end
156     banner += "\n"
157
158     STDERR.puts banner
159
160     if not resource_arg.nil? and resource_arg != '--help' then 
161       Trollop::die "Unknown resource type #{resource_arg.inspect}"
162     else
163       exit 255
164     end
165   end
166
167   return resource_arg.pluralize, method, method_opts, global_opts, ARGV
168 end
169
170 controller, method, method_opts, global_opts, remaining_opts = parse_arguments(arvados.discovery_document)
171
172 api_method = 'arvados.' + controller + '.' + method
173
174 if global_opts[:dry_run]
175   if global_opts[:verbose]
176     $stderr.puts "#{api_method} #{method_opts.inspect}"
177   end
178   exit
179 end
180
181 result = client.execute :api_method => eval(api_method), :parameters => { :api_token => ENV['ARVADOS_API_TOKEN'] }.merge(method_opts), :authenticated => false
182 results = JSON.parse result.body
183
184 if results["errors"] then
185   abort "Error: #{results["errors"][0]}"
186 end
187
188 if global_opts[:human] or global_opts[:pretty] then
189   puts Oj.dump(results, :indent => 1)
190 elsif global_opts[:json] then
191   puts Oj.dump(results)
192 elsif results["items"] and results["kind"].match /list$/i
193   results['items'].each do |i| puts i['uuid'] end
194 else
195   puts results['uuid']
196 end