Class: SolusVM::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/solusvm/base.rb

Overview

SolusVM::Base is the main class for mapping API resources as subclasses.

Direct Known Subclasses

Client, General, Node, Reseller, Server

Constant Summary

VALID_SERVER_TYPES =
["openvz", "xen", "xen hvm"]

Instance Attribute Summary (collapse)

Instance Method Summary (collapse)

Constructor Details

- (Base) initialize(config = {})

Returns a new instance of Base



8
9
10
# File 'lib/solusvm/base.rb', line 8

def initialize(config = {})
  @config = config
end

Instance Attribute Details

- (Object) returned_parameters (readonly)

Returns the value of attribute returned_parameters



6
7
8
# File 'lib/solusvm/base.rb', line 6

def returned_parameters
  @returned_parameters
end

Instance Method Details

- (Object) api_endpoint

Returns the API endpoint set in the instance configuration. Otherwise, it returns the default configuration.

Returns:

  • a String



123
124
125
# File 'lib/solusvm/base.rb', line 123

def api_endpoint
  @config.fetch(:url)
end

- (Object) api_id

Returns the API id set in the instance configuration. Otherwise, it returns the default configuration.

Returns:

  • a String



131
132
133
# File 'lib/solusvm/base.rb', line 131

def api_id
  @config.fetch(:api_id)
end

- (Object) api_key

Returns the API key set in the instance configuration. Otherwise, it returns the default configuration.

Returns:

  • a String.



139
140
141
# File 'lib/solusvm/base.rb', line 139

def api_key
  @config.fetch(:api_key)
end

- (Object) api_login

API login information.

Returns:

  • a Hash.



157
158
159
# File 'lib/solusvm/base.rb', line 157

def 
  { id: api_id, key: api_key }
end

- (Object) api_options(option)

API options

Parameters:

  • option

    Key to fetch

Returns:

  • the given option.



148
149
150
151
152
# File 'lib/solusvm/base.rb', line 148

def api_options(option)
  if options = @config[:options]
    options[option.to_sym]
  end
end

- (Object) conn

Creates a Faraday connection.

Returns:

  • a Faraday::Connection.



44
45
46
47
48
49
# File 'lib/solusvm/base.rb', line 44

def conn
  @conn ||= Faraday.new(ssl: ssl_option) do |c|
    c.request :retry if @config.fetch(:retry_request, false)
    c.adapter :net_http
  end
end

- (void) log_messages(options)

This method returns an undefined value.

Logs API actions to the configured logger.

Parameters:

  • options

    A Hash of options

Options Hash (options):

  • :action (Object)

    the API action



167
168
169
170
171
172
173
174
175
176
177
# File 'lib/solusvm/base.rb', line 167

def log_messages(options)
  logger, logger_method = api_options(:logger), api_options(:logger_method)

  if logger && logger.respond_to?(logger_method)
    logger.send(logger_method, "[Start] => #{options[:action]}")
    returned_parameters.each do |k,v|
      logger.send(logger_method, "   #{k} => #{v}")
    end
    logger.send(logger_method, "[End] => #{options[:action]}")
  end
end

- (Object) parse_error(status, body)

Parses error responses.

Parameters:

  • status

    HTTP status code

  • body

    Raw body

Returns:

  • a Hash or nil.

Raises:

  • SolusVM::AuthenticationError if there is an error authenticating with the API. This can happen if the request IP is not authorized, or if an invalid API key/id was provided.



92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
# File 'lib/solusvm/base.rb', line 92

def parse_error(status, body)
  if (200..299).include?(status)
    # Checks for application errors
    case body.downcase
    when /invalid ipaddress/i
      raise AuthenticationError, "This IP is not authorized to use the API"
    when /Invalid id or key/i
      raise AuthenticationError, "Invalid ID or key"
    when /Node not found/i
      { "status" => "error", "statusmsg" => "Node does not exist" }
    end
  else
    { "status" => "error", "statusmsg" => "Bad HTTP Status: #{status}" }
  end
end

- (Object) parse_response(status, body)

Converts the XML response to a Hash.

Parameters:

  • status

    Faraday::Response#status

  • body

    Faraday::Response#body

Returns:

  • a Hash.



67
68
69
# File 'lib/solusvm/base.rb', line 67

def parse_response(status, body)
  parse_error(status, body) || JSON.parse(body)
end

- (Object) parse_returned_params_as_list(attribute)

Parses a returned_parameters value as a list, if present.

Parameters:

  • attribute

    The attribute to check

Returns:

  • an Array or nil.



76
77
78
79
80
# File 'lib/solusvm/base.rb', line 76

def parse_returned_params_as_list(attribute)
  if returned_parameters[attribute] && !returned_parameters[attribute].empty?
    returned_parameters[attribute].to_s.split(",")
  end
end

- (Object) perform_request(options = {})

Prepares and sends the API request to the URL specified in `@config`.

Examples:

class MyClass < Base
  def create_server(name)
    perform_request(:action => "name", :id => 1)
  end
end

Parameters:

  • options (defaults to: {})

    A Hash of options. Any options not listed below are converted to HTTP query arguments and are passed along to the API.

Options Hash (options):

  • :action (Object)

    Specifies which API method to execute

Returns:

  • true if the request was successful.



28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/solusvm/base.rb', line 28

def perform_request(options = {})
  options.reject! { |_, v| v.nil? }

  # Force JSON responses
  options[:rdtype] = "json"

  response = conn.get api_endpoint, options.merge()

  @returned_parameters = parse_response(response.status, response.body)
  log_messages(options)
  successful?
end

- (Object) ssl_option

SSL options used when creating a Faraday connection.

Returns:

  • a Hash.



54
55
56
57
58
59
# File 'lib/solusvm/base.rb', line 54

def ssl_option
  {
    verify: true,
    ca_file: File.expand_path("../../cacert.pem", __FILE__)
  }
end

- (Object) statusmsg

API response message

Returns:

  • a String.



182
183
184
# File 'lib/solusvm/base.rb', line 182

def statusmsg
  returned_parameters["statusmsg"]
end

- (Boolean) successful?

Check if the request was successful.

my_class = MyClass.new
my_class.create_server("example.com")
my_class.successful? # => true

Returns:

  • (Boolean)

    true if the request was successful.



115
116
117
# File 'lib/solusvm/base.rb', line 115

def successful?
  returned_parameters["status"].nil? || returned_parameters["status"] == "success"
end

- (Object) validate_server_type(type) { ... }

Validates the server type.

Parameters:

  • type

    The server type to check

Yields:

  • Yields a required block if given server type is valid.

Returns:

  • the result of the block, or false if the server type is invalid.



193
194
195
196
197
198
199
200
201
202
203
204
205
206
# File 'lib/solusvm/base.rb', line 193

def validate_server_type(type, &block)
  type = type.strip

  if VALID_SERVER_TYPES.include?(type)
    yield
  else
    @returned_parameters = {
      "status"    => "error",
      "statusmsg" => "Invalid Virtual Server type: #{type}"
    }

    false
  end
end