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 collapse

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(config = {}) ⇒ Base



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

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

Instance Attribute Details

#returned_parametersObject (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

#api_endpointObject

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

Returns a String



126
127
128
# File 'lib/solusvm/base.rb', line 126

def api_endpoint
  @config.fetch(:url)
end

#api_idObject

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

Returns a String



134
135
136
# File 'lib/solusvm/base.rb', line 134

def api_id
  @config.fetch(:api_id)
end

#api_keyObject

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

Returns a String.



142
143
144
# File 'lib/solusvm/base.rb', line 142

def api_key
  @config.fetch(:api_key)
end

#api_loginObject

Public: API login information.

Returns a Hash.



160
161
162
# File 'lib/solusvm/base.rb', line 160

def 
  { id: api_id, key: api_key }
end

#api_options(option) ⇒ Object

Public: API options

option - Key to fetch

Returns the given option.



151
152
153
154
155
# File 'lib/solusvm/base.rb', line 151

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

#connObject

Public: Creates a Faraday connection.

Returns a Faraday::Connection.



44
45
46
47
48
49
50
# 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
    c.options[:timeout] = 60
  end
end

#log_messages(options) ⇒ Object

Public: Logs API actions to the configured logger.

options - A Hash of options

:action - the API action

Returns nothing.



170
171
172
173
174
175
176
177
178
179
180
# File 'lib/solusvm/base.rb', line 170

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

#parse_error(status, body) ⇒ Object

Public: Parses error responses.

status - HTTP status code body - Raw body

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.

Returns a Hash or nil.



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

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" }
    when /Virtual server not found/i
      { "status" => "error", "statusmsg" => "Virtual server does not exist" }
    end
  else
    { "status" => "error", "statusmsg" => "Bad HTTP Status: #{status}" }
  end
end

#parse_response(status, body) ⇒ Object

Public: Converts the XML response to a Hash.

status - Faraday::Response#status body - Faraday::Response#body

Returns a Hash.



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

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

#parse_returned_params_as_list(attribute) ⇒ Object

Public: Parses a returned_parameters value as a list, if present.

attribute - The attribute to check

Returns an Array or nil.



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

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

#perform_request(options = {}) ⇒ Object

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

options - A Hash of options. Any options not listed below are converted

to HTTP query arguments and are passed along to the API.
:action - Specifies which API method to execute

Example

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

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

#ssl_optionObject

Public: SSL options used when creating a Faraday connection.

Returns a Hash.



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

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

#statusmsgObject

Public: API response message

Returns a String.



185
186
187
# File 'lib/solusvm/base.rb', line 185

def statusmsg
  returned_parameters["statusmsg"]
end

#successful?Boolean

Public: Check if the request was successful.

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

Returns true if the request was successful.



118
119
120
# File 'lib/solusvm/base.rb', line 118

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

#validate_server_type(type, &block) ⇒ Object

Public: Validates the server type.

type - The server type to check

Yields a required block if given server type is valid.

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



196
197
198
199
200
201
202
203
204
205
206
207
208
209
# File 'lib/solusvm/base.rb', line 196

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