Module: Croesus

Extended by:
Utils::ClassMethods
Includes:
IdentityMap, Querying, Utils
Defined in:
lib/croesus.rb,
lib/croesus/coerce.rb,
lib/croesus/dsl/dsl.rb,
lib/croesus/version.rb,
lib/croesus/querying.rb,
lib/croesus/attribute.rb,
lib/croesus/attributes.rb,
lib/croesus/validations.rb,
lib/croesus/identity_map.rb,
lib/croesus/dsl/route_dsl.rb,
lib/croesus/dsl/resource_dsl.rb,
lib/croesus/web_client/web_client.rb,
lib/croesus/web_client/web_request.rb,
lib/croesus/web_client/web_response.rb

Overview

Author: Stefano Harding <[email protected]>

Copyright © 2014 Stefano Harding

Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Defined Under Namespace

Modules: AnonoMod, Associations, BasicMethods, ClassMethods, Coercions, DSLHelpers, IdentityMap, InstanceMethods, ModFactory, Querying, Utils, Validations, Validator, Version Classes: Attribute, Attributes, Base, Coercer, Coercion, DSL, ResourceDSL, RouteDSL, WebClient, WebRequest, WebResponse

Constant Summary collapse

NotFound =
Class.new StandardError
APIError =
Class.new StandardError
CoercionError =
Class.new StandardError
ValidationError =
Class.new StandardError
ConfigurationError =
Class.new StandardError
InvalidStateError =
Class.new StandardError
InvalidMethodError =
Class.new StandardError
InvalidArgumentCount =
Class.new StandardError
API_ENDPOINT =

API_VERSION = { type: ‘APIVersion’, major: 1, minor: 3, micro: 2 }

'/resources/json/delphix'
HTTP_HEADERS =
{
  'Accept'           =>  'application/json; charset=UTF-8',
  'Content-Type'     =>  'application/json; charset=UTF-8',
  'User-Agent'       =>  "Croesus/#{Croesus::VERSION} " \
                         "(#{RUBY_ENGINE}/#{RUBY_PLATFORM} " \
                         "#{RUBY_VERSION}-p#{RUBY_PATCHLEVEL})"
}
Undefined =

Represents an undefined parameter used by auto-generated option methods

Object.new.freeze
VERSION =
Croesus::Version.string
@@timeout =
10
@@default_headers =
{}
@@validators =
[]

Class Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Utils::ClassMethods

callable, caller_name, camelize, class_name, classify, demodulize, pluralize, request_id, singularize, twenty_four_hours_ago, underscore, utc_httpdate, verify_options

Methods included from Utils

#callable, #caller_name, #camelize, #class_name, #classify, #command_in_path?, #demodulize, #pluralize, #request_id, #retrier, #singularize, #terminal_dimensions, #twenty_four_hours_ago, #underscore, #utc_httpdate, #verify_options

Methods included from IdentityMap

#add_to_identity_map, clear, #delete, enabled, enabled=, enabled?, include?, #remove_from_identity_map, repository, #save, use, without

Class Attribute Details

.api_passwdString

Returns password for authentication.

Returns:

  • (String)

    password for authentication



138
139
140
# File 'lib/croesus.rb', line 138

def api_passwd
  @api_passwd
end

.api_userString

Returns username to authenticate with.

Returns:

  • (String)

    username to authenticate with



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

def api_user
  @api_user
end

.api_versionObject

Returns the value of attribute api_version.



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

def api_version
  @api_version
end

.last_requestHash

Returns retruns the last request.

Returns:

  • (Hash)

    retruns the last request



113
114
115
# File 'lib/croesus.rb', line 113

def last_request
  @last_request
end

.last_responseHash

Returns retruns the last response.

Returns:

  • (Hash)

    retruns the last response



117
118
119
# File 'lib/croesus.rb', line 117

def last_response
  @last_response
end

.serverString

Returns Delphix server address.

Returns:

  • (String)

    Delphix server address



130
131
132
# File 'lib/croesus.rb', line 130

def server
  @server
end

.sessionHash, ...

Returns:

  • (Hash)

    retruns current session state

  • (#code)

    the response code from Delphix engine

  • (#headers)

    beautified with symbols and underscores

  • (#body)

    parsed response body

  • (#raw_body)

    un-parsed response body



125
126
127
# File 'lib/croesus.rb', line 125

def session
  @session
end

.verboseNothing

Returns enables verbosity.

Returns:

  • (Nothing)

    enables verbosity



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

def verbose
  @verbose
end

Class Method Details

.api_url(resource = nil) ⇒ URL

Returns the API endpoint for a given resource namespace by combining the server address with the appropriate HTTP headers.

Parameters:

  • resource (Resource) (defaults to: nil)

    namespace

Returns:

  • (URL)

    return the URL for the API endpoint



156
157
158
# File 'lib/croesus.rb', line 156

def self.api_url(resource = nil)
  'http://' + @server + resource
end

.append_validator(validator) ⇒ Object



52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/croesus/validations.rb', line 52

def self.append_validator(validator)
  unless validator.is_a?(Croesus::Validator::Base)
    raise ValidationError.new(
      'Validators inherit from Croesus::Validator::Base'
    )
  end

  if @@validators.detect { |v| v.name == validator.name }
    raise ValidationError.new('Validators must have unique names.')
  end

  @@validators << validator
end

.clear_default_headersObject



78
79
80
# File 'lib/croesus/web_client/web_client.rb', line 78

def self.clear_default_headers
  @@default_headers = {}
end

.cookiesHash

Establish a session with the Delphix engine and return an identifier through browser cookies. This session will be reused in subsequent calls, the same session credentials and state are preserved without requiring a re-authentication call. Sessions do not persisit between incovations.

Returns:

  • (Hash)

    cookies containing the new session cookies



174
175
176
177
178
# File 'lib/croesus.rb', line 174

def self.cookies
  @resp ||= Croesus.post session_url,
    { type: 'APISession', version: @api_version }
  @resp.cookies
end

.default_header(name, value) ⇒ Object



74
75
76
# File 'lib/croesus/web_client/web_client.rb', line 74

def self.default_header(name, value)
  @@default_headers[name] = value
end

.login(user = @api_user, passwd = @api_passwd) ⇒ Fixnum, ...

Authenticates the session so that API calls can be made. Only supports basic password authentication.

Parameters:

  • user (String) (defaults to: @api_user)

    user name to authenticate with

  • passwd (String) (defaults to: @api_passwd)

    password to authenticate with

Returns:

  • (Fixnum, #code)

    the response code from Delphix engine

  • (Hash, #headers)

    headers, beautified with symbols and underscores

  • (Hash, #body)

    body parsed response body where applicable (JSON responses are parsed to Objects/Associative Arrays)

  • (Hash, #raw_body)

    raw_body un-parsed response body



199
200
201
202
# File 'lib/croesus.rb', line 199

def self.(user = @api_user, passwd = @api_passwd)
  Croesus.post ,
    { type: 'LoginRequest', username: user, password: passwd }
end

.many(validation) ⇒ Object



224
225
226
# File 'lib/croesus.rb', line 224

def self.many(validation)
  Validations::Many.new(validation)
end

.optional(validation) ⇒ Object



220
221
222
# File 'lib/croesus.rb', line 220

def self.optional(validation)
  Validations::Optional.new(validation)
end

.timeout(seconds) ⇒ Object



82
83
84
# File 'lib/croesus/web_client/web_client.rb', line 82

def self.timeout(seconds)
  @@timeout = seconds
end

.validate(*args) ⇒ Object



216
217
218
# File 'lib/croesus.rb', line 216

def self.validate(*args)
  Base.validate(*args)
end

.validator_for(item) ⇒ Object



66
67
68
69
# File 'lib/croesus/validations.rb', line 66

def self.validator_for(item)
  @@validators.detect { |v| v.should_validate?(item) } ||
    raise(ValidationError.new("Could not find valid validator for: #{item}"))
end

Instance Method Details

#descendantsObject

From where forth do ye descend!



248
249
250
# File 'lib/croesus.rb', line 248

def descendants
  ObjectSpace.each_object(::Class).select {|klass| klass < self }
end

#methodFixnum, ...

Define the #get, #post, and #delete helper methods for sending HTTP requests to the Delphix engine. You shouldn’t need to use these methods directly, but they can be useful for debugging.

The following HTTP methods are supported by the Delphix Appliance:

 GET - Retrieve data from the server where complex input is not needed.
       All GET requests are guaranteed to be read-only, but not all
       read-only requests are required to use GET. Simple input
       (strings, number, boolean values) can be passed as query
       parameters.
POST - Issue a read/write operation, or make a read-only call that
       requires complex input. The optional body of the call is
       expressed as JSON.

DELETE - Delete an object on the system. For languages that don’t provide

a native wrapper for DELETE, or for delete operations with
optional input, all delete operations can also be invoked as POST
to the same URL with /delete appended to it.

Each method returns a hash that responds to #code, #headers, #body and #raw_body obtained from parsing the JSON object in the response body.

API request responses are parsed to Objects/Associative Arrays)

Parameters:

  • url (String<URL>)

    url the url of where to send the request

  • parameters (Hash{Symbol => String})

    key-value data of the HTTP

  • block (Block)

    block to execute when the request returns

Returns:

  • (Fixnum, #code)

    the response code from Delphix engine

  • (Hash, #headers)

    headers, beautified with symbols and underscores

  • (Hash, #body)

    body parsed response body where applicable (JSON

  • (Hash, #raw_body)

    raw_body un-parsed response body



119
120
121
122
123
124
# File 'lib/croesus/web_client/web_client.rb', line 119

[:get, :post, :delete].each do |method|
  define_singleton_method(method) do |url, parameters = {}, &callback|
    WebClient.request(method.to_sym, url, @@default_headers,
      parameters.to_json, @@timeout, &callback)
  end
end

#nameURL

Provides a wraper around getting the URL for the resource by using the resource_url shorthand.

Returns:

  • (URL)

    return the API URL for the given resource.



210
211
212
213
214
# File 'lib/croesus.rb', line 210

[:session, :login, :environment, :alert, :database, :source].each do |name|
  define_singleton_method(name.to_s + '_url') do
    api_url( '/resources/json/delphix/' + name.to_s)
  end
end