class OvirtSDK4::Connection

This class is responsible for managing an HTTP connection to the engine server. It is intended as the entry point for the SDK, and it provides access to the `system` service and, from there, to the rest of the services provided by the API.

Public Class Methods

new(opts = {}) click to toggle source

Creates a new connection to the API server.

source,ruby

connection = ::new(

url: 'https://engine.example.com/ovirt-engine/api',
username: 'admin@internal',
password: '...',
ca_file:'/etc/pki/ovirt-engine/ca.pem'

)


@param opts [Hash] The options used to create the connection.

@option opts [String] :url A string containing the base URL of the server, usually something like

`\https://server.example.com/ovirt-engine/api`.

@option opts [String] :username The name of the user, something like `admin@internal`.

@option opts [String] :password The password of the user.

@option opts [String] :token The token used to authenticate. Optionally the caller can explicitly provide

the token, instead of the user name and password. If the token isn't provided then it will be automatically
created.

@option opts [Boolean] :insecure (false) A boolean flag that indicates if the server TLS certificate and host

name should be checked.

@option opts [String] :ca_file The name of a PEM file containing the trusted CA certificates. The certificate

presented by the server will be verified using these CA certificates. If not set then the system wide CA
certificates store is used.

@option opts [Boolean] :debug (false) A boolean flag indicating if debug output should be generated. If the

values is `true` and the `log` parameter isn't `nil` then the data sent to and received from the server will be
written to the log. Be aware that user names and passwords will also be written, so handle with care.

@option opts [Logger] :log The logger where the log messages will be written.

@option opts [Boolean] :kerberos (false) A boolean flag indicating if Kerberos authentication should be used

instead of user name and password to obtain the OAuth token.

@option opts [Integer] :timeout (0) The maximun total time to wait for the response, in seconds. A value of zero

(the default) means wait for ever. If the timeout expires before the response is received an exception will be
raised.

@option opts [Boolean] :compress (true) A boolean flag indicating if the SDK should ask the server to send

compressed responses. Note that this is a hint for the server, and that it may return uncompressed data even
when this parameter is set to `true`. Also, compression will be automatically disabled when the `debug`
parameter is set to `true`, as otherwise the debug output will be compressed as well, and then it isn't
useful.

@option opts [String] :proxy_url A string containing the protocol, address and port number of the proxy server

to use to connect to the server. For example, in order to use the HTTP proxy `proxy.example.com` that is
listening on port `3128` the value should be `http://proxy.example.com:3128`. This is optional, and if not
given the connection will go directly to the server specified in the `url` parameter.

@option opts [String] :proxy_username The name of the user to authenticate to the proxy server.

@option opts [String] :proxy_password The password of the user to authenticate to the proxy server.

# File lib/ovirtsdk4/connection.rb, line 88
def initialize(opts = {})
  # Get the values of the parameters and assign default values:
  @url = opts[:url]
  @username = opts[:username]
  @password = opts[:password]
  @token = opts[:token]
  @insecure = opts[:insecure] || false
  @ca_file = opts[:ca_file]
  @debug = opts[:debug] || false
  @log = opts[:log]
  @kerberos = opts[:kerberos] || false
  @timeout = opts[:timeout] || 0
  @compress = opts[:compress] || true
  @proxy_url = opts[:proxy_url]
  @proxy_username = opts[:proxy_username]
  @proxy_password = opts[:proxy_password]

  # Automatically disable compression when debug is enabled, as otherwise the debug output generated by
  # libcurl is also compressed, and that isn't useful for debugging:
  @compress = false if @debug

  # Create the HTTP client:
  @client = HttpClient.new(
    insecure: @insecure,
    ca_file: @ca_file,
    debug: @debug,
    log: @log,
    timeout: @timeout,
    compress: @compress,
    proxy_url: @proxy_url,
    proxy_username: @proxy_username,
    proxy_password: @proxy_password
  )
end

Public Instance Methods

authenticate() click to toggle source

Performs the authentication process and returns the authentication token. Usually there is no need to call this method, as authentication is performed automatically when needed. But in some situations it may be useful to perform authentication explicitly, and then use the obtained token to create other connections, using the `token` parameter of the constructor instead of the user name and password.

@return [String]

# File lib/ovirtsdk4/connection.rb, line 345
def authenticate
  @token ||= create_access_token
end
build_sso_auth_request() click to toggle source

Builds a the URL and parameters to acquire the access token from SSO.

@return [Array] An array containing two elements, the first is the URL of the SSO service and the second is a hash

containing the parameters required to perform authentication.

@api private

# File lib/ovirtsdk4/connection.rb, line 271
def build_sso_auth_request
  # Compute the entry point and the parameters:
  parameters = {
    scope: 'ovirt-app-api'
  }
  if @kerberos
    entry_point = 'token-http-auth'
    parameters[:grant_type] = 'urn:ovirt:params:oauth:grant-type:http'
  else
    entry_point = 'token'
    parameters.merge!(
      grant_type: 'password',
      username: @username,
      password: @password
    )
  end

  # Compute the URL:
  url = URI(@url.to_s)
  url.path = "/ovirt-engine/sso/oauth/#{entry_point}"
  url = url.to_s

  # Return the pair containing the URL and the parameters:
  [url, parameters]
end
build_sso_revoke_request() click to toggle source

Builds a the URL and parameters to revoke the SSO access token

@return [Array] An array containing two elements, the first is the URL of the SSO service and the second is a hash

containing the parameters required to perform the revoke.

@api private

# File lib/ovirtsdk4/connection.rb, line 305
def build_sso_revoke_request
  # Compute the parameters:
  parameters = {
    scope: '',
    token: @token
  }

  # Compute the URL:
  url = URI(@url.to_s)
  url.path = '/ovirt-engine/services/sso-logout'
  url = url.to_s

  # Return the pair containing the URL and the parameters:
  [url, parameters]
end
close() click to toggle source

Releases the resources used by this connection.

# File lib/ovirtsdk4/connection.rb, line 402
def close
  # Revoke the SSO access token:
  revoke_access_token if @token

  # Close the HTTP client:
  @client.close if @client
end
create_access_token() click to toggle source

Obtains the access token from SSO to be used for bearer authentication.

@return [String] The access token.

@api private

# File lib/ovirtsdk4/connection.rb, line 194
def create_access_token
  # Build the URL and parameters required for the request:
  url, parameters = build_sso_auth_request

  # Send the request and wait for the request:
  response = get_sso_response(url, parameters)
  response = response[0] if response.is_a?(Array)

  # Check the response and raise an error if it contains an error code:
  code = response['error_code']
  error = response['error']
  raise Error, "Error during SSO authentication: #{code}: #{error}" if error

  response['access_token']
end
get_sso_response(url, parameters) click to toggle source

Execute a get request to the SSO server and return the response.

@param url [String] The URL of the SSO server.

@param parameters [Hash] The parameters to send to the SSO server.

@return [Hash] The JSON response.

@api private

# File lib/ovirtsdk4/connection.rb, line 240
def get_sso_response(url, parameters)
  # Create the request:
  request = HttpRequest.new(
    method: :POST,
    url: url,
    headers: {
      'User-Agent' => "RubySDK/#{VERSION}",
      'Content-Type' => 'application/x-www-form-urlencoded',
      'Accept' => 'application/json'
    },
    body: URI.encode_www_form(parameters)
  )

  # Create an empty response:
  response = HttpResponse.new

  # Send the request and wait for the response:
  @client.send(request, response)

  # Parse and return the JSON response:
  JSON.parse(response.body)
end
revoke_access_token() click to toggle source

Revoke the SSO access token.

@api private

# File lib/ovirtsdk4/connection.rb, line 215
def revoke_access_token
  # Build the URL and parameters required for the request:
  url, parameters = build_sso_revoke_request

  # Send the request and wait for the response:
  response = get_sso_response(url, parameters)
  response = response[0] if response.is_a?(Array)

  # Check the response and raise an error if it contains an error code:
  code = response['error_code']
  error = response['error']
  raise Error, "Error during SSO revoke: #{code}: #{error}" if error
end
send(request) click to toggle source

Sends an HTTP request and waits for the response.

@param request [HttpRequest] The request object containing the details of the HTTP request to send. @return [Response] A request object containing the details of the HTTP response received.

@api private

# File lib/ovirtsdk4/connection.rb, line 153
def send(request)
  # Add the base URL to the request:
  request.url = request.url.nil? ? request.url = @url : "#{@url}#{request.url}"

  # Set the headers common to all requests:
  request.headers.merge!(
    'User-Agent'   => "RubySDK/#{VERSION}",
    'Version'      => '4',
    'Content-Type' => 'application/xml',
    'Accept'       => 'application/xml'
  )

  # Older versions of the engine (before 4.1) required the 'all_content' as an HTTP header instead of a query
  # parameter. In order to better support those older versions of the engine we need to check if this parameter is
  # included in the request, and add the corresponding header.
  unless request.query.nil?
    all_content = request.query['all_content']
    request.headers['All-Content'] = all_content unless all_content.nil?
  end

  # Set the authentication token:
  @token ||= create_access_token
  request.token = @token

  # Create an empty response:
  response = HttpResponse.new

  # Send the request and wait for the response:
  @client.send(request, response)

  # Return the response:
  response
end
service(path) click to toggle source

Returns a reference to the service corresponding to the given path. For example, if the `path` parameter is `vms/123/diskattachments` then it will return a reference to the service that manages the disk attachments for the virtual machine with identifier `123`.

@param path [String] The path of the service, for example `vms/123/diskattachments`. @return [Service] @raise [Error] If there is no service corresponding to the given path.

# File lib/ovirtsdk4/connection.rb, line 141
def service(path)
  system_service.service(path)
end
system_service() click to toggle source

Returns a reference to the root of the services tree.

@return [SystemService]

# File lib/ovirtsdk4/connection.rb, line 128
def system_service
  @system_service ||= SystemService.new(self, '')
end
test(raise_exception = false) click to toggle source

Tests the connectivity with the server. If connectivity works correctly it returns `true`. If there is any connectivity problem it will either return `false` or raise an exception if the `raise_exception` parameter is `true`.

@param raise_exception [Boolean] @return [Boolean]

# File lib/ovirtsdk4/connection.rb, line 329
def test(raise_exception = false)
  system_service.get
  true
rescue StandardError
  raise if raise_exception
  false
end