Class: Nomad::Client
- Inherits:
-
Object
- Object
- Nomad::Client
- Includes:
- Configurable
- Defined in:
- lib/nomad/client.rb,
lib/nomad/api/job.rb,
lib/nomad/api/node.rb,
lib/nomad/api/agent.rb,
lib/nomad/api/region.rb,
lib/nomad/api/status.rb,
lib/nomad/api/system.rb,
lib/nomad/api/operator.rb,
lib/nomad/api/validate.rb,
lib/nomad/api/allocation.rb,
lib/nomad/api/evaluation.rb
Constant Summary collapse
- USER_AGENT =
The user agent for this client.
"NomadRuby/#{Nomad::VERSION} (+github.com/hashicorp/nomad-ruby)".freeze
- LOCATION_HEADER =
The name of the header used for redirection.
"location".freeze
- DEFAULT_HEADERS =
The default headers that are sent with every request.
{ "Content-Type" => "application/json", "Accept" => "application/json", "Accept-Encoding" => "gzip", "User-Agent" => USER_AGENT, }.freeze
- JSON_PARSE_OPTIONS =
The default list of options to use when parsing JSON.
{ max_nesting: false, create_additions: false, symbolize_names: true, }.freeze
- RESCUED_EXCEPTIONS =
[].tap do |a| # Failure to even open the socket (usually permissions) a << SocketError # Failed to reach the server (aka bad URL) a << Errno::ECONNREFUSED # Failed to read body or no response body given a << EOFError a << Timeout::Error a << Net::ReadTimeout a << Net::OpenTimeout end.freeze
Instance Attribute Summary collapse
-
#connection ⇒ Object
readonly
Returns the value of attribute connection.
Instance Method Summary collapse
-
#agent ⇒ Agent
A proxy to the Agent methods.
-
#allocation ⇒ Allocation
A proxy to the Allocation methods.
-
#build_uri(verb, path, params = {}) ⇒ URI
Construct a URL from the given verb and path.
-
#class_for_request(verb) ⇒ Class
Helper method to get the corresponding Net::HTTP class from the given HTTP verb.
-
#delete(path, params = {}, headers = {}) ⇒ Object
Perform a DELETE request.
-
#error(response) ⇒ Object
Raise a response error, extracting as much information from the server’s response as possible.
-
#evaluation ⇒ Evaluation
A proxy to the Evaluation methods.
-
#get(path, params = {}, headers = {}) ⇒ Object
Perform a GET request.
-
#initialize(options = {}) ⇒ Nomad::Client
constructor
Create a new Client with the given options.
-
#job ⇒ Job
A proxy to the Job methods.
-
#node ⇒ Node
A proxy to the Node methods.
-
#operator ⇒ Operator
A proxy to the Operator methods.
-
#patch(path, data, headers = {}) ⇒ Object
Perform a PATCH request.
-
#post(path, data = {}, headers = {}) ⇒ Object
Perform a POST request.
-
#put(path, data, headers = {}) ⇒ Object
Perform a PUT request.
-
#region ⇒ Region
A proxy to the Region methods.
-
#request(verb, path, data = {}, headers = {}) ⇒ String, Hash
Make an HTTP request with the given verb, data, params, and headers.
-
#same_options?(opts) ⇒ true, false
Determine if the given options are the same as ours.
- #setup_connection ⇒ Object
-
#status ⇒ Status
A proxy to the Status methods.
-
#success(response) ⇒ String, Hash
Parse the response object and manipulate the result based on the given
Content-Typeheader. -
#system ⇒ System
A proxy to the System methods.
-
#to_query_string(hash) ⇒ String?
Convert the given hash to a list of query string parameters.
-
#validate ⇒ Validate
A proxy to the Validate methods.
-
#with_retries(*rescued, &block) ⇒ Object
Execute the given block with retries and exponential backoff.
Methods included from Configurable
Constructor Details
#initialize(options = {}) ⇒ Nomad::Client
Create a new Client with the given options. Any options given take precedence over the default options.
55 56 57 58 59 60 61 62 63 |
# File 'lib/nomad/client.rb', line 55 def initialize( = {}) # Use any options given, but fall back to the defaults set on the module Nomad::Configurable.keys.each do |key| value = .key?(key) ? [key] : Defaults.public_send(key) instance_variable_set(:"@#{key}", value) end @connection = setup_connection end |
Instance Attribute Details
#connection ⇒ Object (readonly)
Returns the value of attribute connection.
65 66 67 |
# File 'lib/nomad/client.rb', line 65 def connection @connection end |
Instance Method Details
#agent ⇒ Agent
A proxy to the Agent methods.
9 10 11 |
# File 'lib/nomad/api/agent.rb', line 9 def agent @agent ||= Agent.new(self) end |
#allocation ⇒ Allocation
A proxy to the Allocation methods.
10 11 12 |
# File 'lib/nomad/api/allocation.rb', line 10 def allocation @allocation ||= Allocation.new(self) end |
#build_uri(verb, path, params = {}) ⇒ URI
Construct a URL from the given verb and path. If the request is a GET or DELETE request, the params are assumed to be query params are are converted as such using #to_query_string.
If the path is relative, it is merged with the Defaults.address attribute. If the path is absolute, it is converted to a URI object and returned.
256 257 258 259 260 261 262 263 264 265 266 267 |
# File 'lib/nomad/client.rb', line 256 def build_uri(verb, path, params = {}) # Add any query string parameters if [:delete, :get].include?(verb) path = [path, to_query_string(params)].compact.join("?") end # Ensure leading slash path = "/" << path if path && path[0] != "/" # Parse the URI return path end |
#class_for_request(verb) ⇒ Class
Helper method to get the corresponding Net::HTTP class from the given HTTP verb.
276 277 278 |
# File 'lib/nomad/client.rb', line 276 def class_for_request(verb) Net::HTTP.const_get(verb.to_s.capitalize) end |
#delete(path, params = {}, headers = {}) ⇒ Object
Perform a DELETE request.
99 100 101 |
# File 'lib/nomad/client.rb', line 99 def delete(path, params = {}, headers = {}) request(:delete, path, params, headers) end |
#error(response) ⇒ Object
Raise a response error, extracting as much information from the server’s response as possible.
318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 |
# File 'lib/nomad/client.rb', line 318 def error(response) # Use the correct exception class case response when Net::HTTPClientError klass = HTTPClientError when Net::HTTPServerError klass = HTTPServerError else klass = HTTPError end if (response.content_type || '').include?("json") # Attempt to parse the error as JSON begin json = JSON.parse(response.body, JSON_PARSE_OPTIONS) if json[:errors] raise klass.new(address, response, json[:errors]) end rescue JSON::ParserError; end end raise klass.new(address, response, [response.body]) end |
#evaluation ⇒ Evaluation
A proxy to the Evaluation methods.
10 11 12 |
# File 'lib/nomad/api/evaluation.rb', line 10 def evaluation @evaluation ||= Evaluation.new(self) end |
#get(path, params = {}, headers = {}) ⇒ Object
Perform a GET request.
75 76 77 |
# File 'lib/nomad/client.rb', line 75 def get(path, params = {}, headers = {}) request(:get, path, params, headers) end |
#job ⇒ Job
A proxy to the Job methods.
8 9 10 |
# File 'lib/nomad/api/job.rb', line 8 def job @job ||= Job.new(self) end |
#node ⇒ Node
A proxy to the Node methods.
8 9 10 |
# File 'lib/nomad/api/node.rb', line 8 def node @node ||= Node.new(self) end |
#operator ⇒ Operator
A proxy to the Operator methods.
8 9 10 |
# File 'lib/nomad/api/operator.rb', line 8 def operator @operator ||= Operator.new(self) end |
#patch(path, data, headers = {}) ⇒ Object
Perform a PATCH request.
93 94 95 |
# File 'lib/nomad/client.rb', line 93 def patch(path, data, headers = {}) request(:patch, path, data, headers) end |
#post(path, data = {}, headers = {}) ⇒ Object
Perform a POST request.
81 82 83 |
# File 'lib/nomad/client.rb', line 81 def post(path, data = {}, headers = {}) request(:post, path, data, headers) end |
#put(path, data, headers = {}) ⇒ Object
Perform a PUT request.
87 88 89 |
# File 'lib/nomad/client.rb', line 87 def put(path, data, headers = {}) request(:put, path, data, headers) end |
#region ⇒ Region
A proxy to the Region methods.
8 9 10 |
# File 'lib/nomad/api/region.rb', line 8 def region @region ||= Region.new(self) end |
#request(verb, path, data = {}, headers = {}) ⇒ String, Hash
Make an HTTP request with the given verb, data, params, and headers. If the response has a return type of JSON, the JSON is automatically parsed and returned as a hash; otherwise it is returned as a string.
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 |
# File 'lib/nomad/client.rb', line 122 def request(verb, path, data = {}, headers = {}) uri = URI.parse(path) if uri.absolute? new_path, uri.path, uri.fragment = uri.path, "", nil client = self.class.new(.merge( address: uri.to_s, )) return client.request(verb, new_path, data, headers) end # Build the URI and request object from the given information path = build_uri(verb, path, data) req = class_for_request(verb).new(path) # Get a list of headers headers = DEFAULT_HEADERS.merge(headers) # Add headers headers.each do |key, value| req.add_field(key, value) end # Setup PATCH/POST/PUT if [:patch, :post, :put].include?(verb) if data.respond_to?(:read) req.content_length = data.size req.body_stream = data elsif data.is_a?(Hash) req.form_data = data else req.body = data end end begin response = connection.request(req) case response when Net::HTTPRedirection # On a redirect of a GET or HEAD request, the URL already contains # the data as query string parameters. if [:head, :get].include?(verb) data = {} end request(verb, response[LOCATION_HEADER], data, headers) when Net::HTTPSuccess success(response) else error(response) end rescue *RESCUED_EXCEPTIONS => e raise HTTPConnectionError.new(address, e) end end |
#same_options?(opts) ⇒ true, false
Determine if the given options are the same as ours.
69 70 71 |
# File 'lib/nomad/client.rb', line 69 def (opts) .hash == opts.hash end |
#setup_connection ⇒ Object
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 |
# File 'lib/nomad/client.rb', line 176 def setup_connection # Create the HTTP connection object - since the proxy information defaults # to +nil+, we can just pass it to the initializer method instead of doing # crazy strange conditionals. uri = URI.parse(address) connection = Net::HTTP.new(uri.host, uri.port, proxy_address, proxy_port, proxy_username, proxy_password) # Use a custom open timeout if open_timeout || timeout connection.open_timeout = (open_timeout || timeout).to_i end # Use a custom read timeout if read_timeout || timeout connection.read_timeout = (read_timeout || timeout).to_i end # Also verify peer (this is the default). connection.verify_mode = OpenSSL::SSL::VERIFY_PEER # Apply SSL, if applicable if uri.scheme == "https" # Turn on SSL connection.use_ssl = true # Nomad requires TLS1.2 connection.ssl_version = "TLSv1_2" # Only use secure ciphers connection.ciphers = ssl_ciphers # Custom pem files, no problem! pem = ssl_pem_contents || ssl_pem_file ? File.read(ssl_pem_file) : nil if pem connection.cert = OpenSSL::X509::Certificate.new(pem) connection.key = OpenSSL::PKey::RSA.new(pem, ssl_pem_passphrase) end # Use custom CA cert for verification if ssl_ca_cert connection.ca_file = ssl_ca_cert end # Use custom CA path that contains CA certs if ssl_ca_path connection.ca_path = ssl_ca_path end # Naughty, naughty, naughty! Don't blame me when someone hops in # and executes a MITM attack! if !ssl_verify connection.verify_mode = OpenSSL::SSL::VERIFY_NONE end # Use custom timeout for connecting and verifying via SSL if ssl_timeout || timeout connection.ssl_timeout = (ssl_timeout || timeout).to_i end end return connection end |
#status ⇒ Status
A proxy to the Status methods.
8 9 10 |
# File 'lib/nomad/api/status.rb', line 8 def status @status ||= Status.new(self) end |
#success(response) ⇒ String, Hash
Parse the response object and manipulate the result based on the given Content-Type header. For now, this method only parses JSON, but it could be expanded in the future to accept other content types.
303 304 305 306 307 308 309 |
# File 'lib/nomad/client.rb', line 303 def success(response) if response.body && (response.content_type || '').include?("json") JSON.parse(response.body, JSON_PARSE_OPTIONS) else response.body end end |
#system ⇒ System
A proxy to the System methods.
8 9 10 |
# File 'lib/nomad/api/system.rb', line 8 def system @system ||= System.new(self) end |
#to_query_string(hash) ⇒ String?
Convert the given hash to a list of query string parameters. Each key and value in the hash is URI-escaped for safety.
288 289 290 291 292 |
# File 'lib/nomad/client.rb', line 288 def to_query_string(hash) hash.map do |key, value| "#{CGI.escape(key.to_s)}=#{CGI.escape(value.to_s)}" end.join('&')[/.+/] end |
#validate ⇒ Validate
A proxy to the Validate methods.
8 9 10 |
# File 'lib/nomad/api/validate.rb', line 8 def validate @validate ||= Validate.new(self) end |
#with_retries(*rescued, &block) ⇒ Object
Execute the given block with retries and exponential backoff.
347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 |
# File 'lib/nomad/client.rb', line 347 def with_retries(*rescued, &block) = rescued.last.is_a?(Hash) ? rescued.pop : {} exception = nil retries = 0 max_attempts = [:attempts] || Defaults::RETRY_ATTEMPTS backoff_base = [:base] || Defaults::RETRY_BASE backoff_max = [:max_wait] || Defaults::RETRY_MAX_WAIT begin return yield retries, exception rescue *rescued => e exception = e retries += 1 raise if retries > max_attempts # Calculate the exponential backoff combined with an element of # randomness. backoff = [backoff_base * (2 ** (retries - 1)), backoff_max].min backoff = backoff * (0.5 * (1 + Kernel.rand)) # Ensure we are sleeping at least the minimum interval. backoff = [backoff_base, backoff].max # Exponential backoff. Kernel.sleep(backoff) # Now retry retry end end |