Class: EY::API

Inherits:
Object show all
Defined in:
lib/engineyard/api.rb

Direct Known Subclasses

CLI::API

Defined Under Namespace

Classes: InvalidCredentials, RequestFailed

Constant Summary collapse

USER_AGENT_STRING =
"EngineYardCLI/#{VERSION}"

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(token = nil) ⇒ API

Returns a new instance of API.

Raises:

  • (ArgumentError)


9
10
11
12
13
# File 'lib/engineyard/api.rb', line 9

def initialize(token = nil)
  @token ||= token
  @token ||= self.class.read_token
  raise ArgumentError, "EY Cloud API token required" unless @token
end

Instance Attribute Details

#tokenObject (readonly)

Returns the value of attribute token.



5
6
7
# File 'lib/engineyard/api.rb', line 5

def token
  @token
end

Class Method Details

.fetch_token(email, password) ⇒ Object



103
104
105
106
107
108
# File 'lib/engineyard/api.rb', line 103

def self.fetch_token(email, password)
  api_token = request("/authenticate", :method => "post",
    :params => { :email => email, :password => password })["api_token"]
  save_token(api_token)
  api_token
end

.read_token(file = nil) ⇒ Object



110
111
112
113
114
115
116
117
118
119
120
121
122
# File 'lib/engineyard/api.rb', line 110

def self.read_token(file = nil)
  file ||= ENV['EYRC'] || File.expand_path("~/.eyrc")
  return false unless File.exists?(file)

  require 'yaml'

  data = YAML.load_file(file)
  if EY.config.default_endpoint?
    data["api_token"]
  else
    (data[EY.config.endpoint.to_s] || {})["api_token"]
  end
end

.request(path, opts = {}) ⇒ Object



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
# File 'lib/engineyard/api.rb', line 51

def self.request(path, opts={})
  require 'rest_client'
  require 'engineyard/rest_client_ext'
  require 'json'

  url = EY.config.endpoint + "api/v2#{path}"
  method = (opts.delete(:method) || 'get').to_s.downcase.to_sym
  params = opts.delete(:params) || {}
  headers = opts.delete(:headers) || {}
  headers["Accept"] ||= "application/json"
  headers["User-Agent"] = USER_AGENT_STRING

  begin
    EY.ui.debug("Request", "#{method.to_s.upcase} #{url}")
    case method
    when :get, :delete, :head
      url.query = RestClient::Payload::UrlEncoded.new(params).to_s
      resp = RestClient.send(method, url.to_s, headers)
    else
      resp = RestClient.send(method, url.to_s, params, headers)
    end
  rescue RestClient::Unauthorized
    raise InvalidCredentials
  rescue Errno::ECONNREFUSED
    raise RequestFailed, "Could not reach the cloud API"
  rescue RestClient::ResourceNotFound
    raise RequestFailed, "The requested resource could not be found"
  rescue RestClient::BadGateway
    raise RequestFailed, "AppCloud API is temporarily unavailable. Please try again soon."
  rescue RestClient::RequestFailed => e
    raise RequestFailed, "#{e.message} #{e.response}"
  rescue OpenSSL::SSL::SSLError
    raise RequestFailed, "SSL is misconfigured on your cloud"
  end

  if resp.body.empty?
    data = ''
  elsif resp.headers[:content_type] =~ /application\/json/
    begin
      data = JSON.parse(resp.body)
      EY.ui.debug("Response", data)
    rescue JSON::ParserError
      EY.ui.debug("Raw response", resp.body)
      raise RequestFailed, "Response was not valid JSON."
    end
  else
    data = resp.body
  end

  data
end

.save_token(token, file = nil) ⇒ Object



124
125
126
127
128
129
130
131
132
133
134
135
136
137
# File 'lib/engineyard/api.rb', line 124

def self.save_token(token, file = nil)
  file ||= ENV['EYRC'] || File.expand_path("~/.eyrc")
  require 'yaml'

  data = File.exists?(file) ? YAML.load_file(file) : {}
  if EY.config.default_endpoint?
    data.merge!("api_token" => token)
  else
    data.merge!(EY.config.endpoint.to_s => {"api_token" => token})
  end

  File.open(file, "w"){|f| YAML.dump(data, f) }
  true
end

Instance Method Details

#==(other) ⇒ Object

Raises:

  • (ArgumentError)


15
16
17
18
# File 'lib/engineyard/api.rb', line 15

def ==(other)
  raise ArgumentError unless other.is_a?(self.class)
  self.token == other.token
end

#appsObject



31
32
33
# File 'lib/engineyard/api.rb', line 31

def apps
  @apps ||= EY::Model::App.from_array(request('/apps')["apps"], :api => self)
end

#apps_for_repo(repo) ⇒ Object



39
40
41
42
# File 'lib/engineyard/api.rb', line 39

def apps_for_repo(repo)
  repo.fail_on_no_remotes!
  apps.find_all {|a| repo.has_remote?(a.repository_uri) }
end

#environmentsObject



27
28
29
# File 'lib/engineyard/api.rb', line 27

def environments
  @environments ||= EY::Model::Environment.from_array(request('/environments')["environments"], :api => self)
end

#request(url, opts = {}) ⇒ Object



20
21
22
23
24
25
# File 'lib/engineyard/api.rb', line 20

def request(url, opts={})
  opts[:headers] ||= {}
  opts[:headers]["X-EY-Cloud-Token"] = token
  EY.ui.debug("Token", token)
  self.class.request(url, opts)
end

#resolverObject



35
36
37
# File 'lib/engineyard/api.rb', line 35

def resolver
  @resolver ||= Resolver.new(self)
end

#userObject



44
45
46
# File 'lib/engineyard/api.rb', line 44

def user
  EY::Model::User.from_hash(request('/current_user')['user'])
end