Class: Katello::HttpResource

Inherits:
Object
  • Object
show all
Defined in:
app/lib/katello/http_resource.rb

Defined Under Namespace

Classes: NetworkException, RestClientException

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(json = {}) ⇒ HttpResource

Returns a new instance of HttpResource.



22
23
24
# File 'app/lib/katello/http_resource.rb', line 22

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

Instance Attribute Details

#jsonObject (readonly)

Returns the value of attribute json.



20
21
22
# File 'app/lib/katello/http_resource.rb', line 20

def json
  @json
end

Class Method Details

.create_thing(request_type) ⇒ Object



154
155
156
# File 'app/lib/katello/http_resource.rb', line 154

def create_thing(request_type)
  request_type.new
end

.delete(a_path = nil, headers = {}) ⇒ Object



121
122
123
124
125
126
127
128
129
130
131
132
133
# File 'app/lib/katello/http_resource.rb', line 121

def delete(a_path = nil, headers = {})
  logger.debug "Resource DELETE request: #{a_path}"
  print_debug_info(a_path, headers)
  a_path = URI.encode(a_path)
  client = rest_client(Net::HTTP::Delete, :delete, a_path)
  result = process_response(client.delete(headers))
  result
rescue RestClient::Exception => e
  raise_rest_client_exception e, a_path, "DELETE"
rescue Errno::ECONNREFUSED
  service = a_path.split("/").second
  raise Errors::ConnectionRefusedException, _("A backend service [ %s ] is unreachable") % service.capitalize
end

.get(a_path, headers = {}) ⇒ Object



79
80
81
82
83
84
85
86
87
88
89
90
91
# File 'app/lib/katello/http_resource.rb', line 79

def get(a_path, headers = {})
  logger.debug "Resource GET request: #{a_path}"
  print_debug_info(a_path, headers)
  a_path = URI.encode(a_path)
  client = rest_client(Net::HTTP::Get, :get, a_path)
  result = process_response(client.get(headers))
  result
rescue RestClient::Exception => e
  raise_rest_client_exception e, a_path, "GET"
rescue Errno::ECONNREFUSED
  service = a_path.split("/").second
  raise Errors::ConnectionRefusedException, _("A backend service [ %s ] is unreachable") % service.capitalize
end

.hash_to_query(query_parameters) ⇒ Object



196
197
198
199
200
201
# File 'app/lib/katello/http_resource.rb', line 196

def hash_to_query(query_parameters)
  query_parameters.inject("?") do |so_far, current|
    so_far << "&" unless so_far == "?"
    so_far << "#{current[0].to_s}=#{url_encode(current[1])}"
  end
end

.join_path(*args) ⇒ Object



147
148
149
150
151
152
# File 'app/lib/katello/http_resource.rb', line 147

def join_path(*args)
  args.inject("") do |so_far, current|
    so_far << '/' if (!so_far.empty? && so_far[so_far.length - 1].chr != '/') || current[0].chr != '/'
    so_far << current.strip
  end
end

.loggerObject

children must redefine



36
37
38
# File 'app/lib/katello/http_resource.rb', line 36

def logger
  fail NotImplementedError
end

.post(a_path, payload = {}, headers = {}) ⇒ Object



93
94
95
96
97
98
99
100
101
102
103
104
105
# File 'app/lib/katello/http_resource.rb', line 93

def post(a_path, payload = {}, headers = {})
  logger.debug "Resource POST request: #{a_path}, #{payload}"
  print_debug_info(a_path, headers, payload)
  a_path = URI.encode(a_path)
  client = rest_client(Net::HTTP::Post, :post, a_path)
  result = process_response(client.post(payload, headers))
  result
rescue RestClient::Exception => e
  raise_rest_client_exception e, a_path, "POST"
rescue Errno::ECONNREFUSED
  service = a_path.split("/").second
  raise Katello::Errors::ConnectionRefusedException, _("A backend service [ %s ] is unreachable") % service.capitalize
end


64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'app/lib/katello/http_resource.rb', line 64

def print_debug_info(_a_path, headers = {}, payload = {})
  logger.debug "Headers: #{headers.to_json}"
  # calling to_json on file has side-effects breaking manifest import.
  # this fix prevents this problem
  payload_to_print = payload.reduce({}) do |h, (k, v)|
    h[k] = case v
           when File then "{{file}}"
           else v
           end
  end
  logger.debug "Body: #{payload_to_print.to_json}"
rescue
  logger.debug "Unable to print debug information"
end

.process_response(resp) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'app/lib/katello/http_resource.rb', line 40

def process_response(resp)
  logger.debug "Processing response: #{resp.code}"
  logger.debug resp.body
  return resp unless resp.code.to_i >= 400
  parsed = {}
  message = "Rest exception while processing the call"
  service_code = ""
  status_code = resp.code.to_s
  begin
    parsed = JSON.parse resp.body
    message = parsed["displayMessage"] if parsed["displayMessage"]
    service_code = parsed["code"] if parsed["code"]
  rescue => error
    logger.error "Error parsing the body: " << error.backtrace.join("\n")
    if %w(404 500 502 503 504).member? resp.code.to_s
      logger.error "Remote server status code " << resp.code.to_s
      raise RestClientException, {:message => error.to_s, :service_code => service_code, :code => status_code}, caller
    else
      raise NetworkException, [resp.code.to_s, resp.body].reject { |s| s.nil? || s.empty? }.join(' ')
    end
  end
  fail RestClientException, {:message => message, :service_code => service_code, :code => status_code}, caller
end

.put(a_path, payload = {}, headers = {}) ⇒ Object



107
108
109
110
111
112
113
114
115
116
117
118
119
# File 'app/lib/katello/http_resource.rb', line 107

def put(a_path, payload = {}, headers = {})
  logger.debug "Resource PUT request: #{a_path}, #{payload}"
  print_debug_info(a_path, headers, payload)
  a_path = URI.encode(a_path)
  client = rest_client(Net::HTTP::Put, :put, a_path)
  result = process_response(client.put(payload, headers))
  result
rescue RestClient::Exception => e
  raise_rest_client_exception e, a_path, "PUT"
rescue Errno::ECONNREFUSED
  service = a_path.split("/").second
  raise Errors::ConnectionRefusedException, _("A backend service [ %s ] is unreachable") % service.capitalize
end

.raise_rest_client_exception(e, a_path, http_method) ⇒ Object

re-raise the same exception with nicer error message



136
137
138
139
140
141
142
143
144
145
# File 'app/lib/katello/http_resource.rb', line 136

def raise_rest_client_exception(e, a_path, http_method)
  # message method in rest-client is hardcoded - we need to override it
  msg = "#{name}: #{e.message} #{e.http_body} (#{http_method} #{a_path})"
  (class << e; self; end).instance_eval do
    define_method(:message) do
      msg
    end
  end
  fail e
end

.rest_client(http_type, method, path) ⇒ Object

Creates a RestClient::Resource class with a signed OAuth style Authentication header added to the request headers.



160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
# File 'app/lib/katello/http_resource.rb', line 160

def rest_client(http_type, method, path)
  # Need full path to properly generate the signature
  url = self.site + path
  params = { :site => self.site,
             :http_method => method,
             :request_token_path => "",
             :authorize_path => "",
             :access_token_path => ""}

  params[:ca_file] = self.ca_cert_file unless self.ca_cert_file.nil?
  # New OAuth consumer to setup signing the request
  consumer = OAuth::Consumer.new(self.consumer_key,
                      self.consumer_secret,
                      params)

  # The type is passed in, GET/POST/PUT/DELETE
  request = http_type.new(url)

  # Sign the request with OAuth
  consumer.sign!(request)
  # Extract the header and add it to the RestClient
  added_header = {'Authorization' => request['Authorization']}
  RestClient::Resource.new url,
    :headers => added_header,
    :open_timeout => SETTINGS[:katello][:rest_client_timeout],
    :timeout => SETTINGS[:katello][:rest_client_timeout]
end

.url_encode(element) ⇒ String

Encode url element if its not nil. This helper method is used mainly in resource path methods.

Parameters:

  • element (String)

    to encode

Returns:

  • (String)

    encoded element or nil



192
193
194
# File 'app/lib/katello/http_resource.rb', line 192

def url_encode(element)
  CGI.escape element.to_s unless element.nil?
end

Instance Method Details

#[](key) ⇒ Object



26
27
28
# File 'app/lib/katello/http_resource.rb', line 26

def [](key)
  @json[key]
end

#[]=(key, value) ⇒ Object



30
31
32
# File 'app/lib/katello/http_resource.rb', line 30

def []=(key, value)
  @json[key] = value
end