Project

General

Profile

Download (6.82 KB) Statistics
| Branch: | Tag: | Revision:

runcible / lib / runcible / base.rb @ df1b6e2a

1
require 'rest_client'
2
require 'oauth'
3
require 'json'
4
require 'thread'
5

    
6
module Runcible
7
  class Base
8
    def initialize(config = {})
9
      @mutex = Mutex.new
10
      @config = config
11
    end
12

    
13
    def lazy_config=(a_block)
14
      @mutex.synchronize { @lazy_config = a_block }
15
    end
16

    
17
    def config
18
      @mutex.synchronize do
19
        @config = @lazy_config.call if defined?(@lazy_config)
20
        fail Runcible::ConfigurationUndefinedError, Runcible::ConfigurationUndefinedError.message unless @config
21
        @config
22
      end
23
    end
24

    
25
    def path(*args)
26
      self.class.path(*args)
27
    end
28

    
29
    # rubocop:disable Metrics/AbcSize:
30
    def call(method, path, options = {})
31
      clone_config = self.config.clone
32
      #on occation path will already have prefix (sync cancel)
33
      path = clone_config[:api_path] + path unless path.start_with?(clone_config[:api_path])
34

    
35
      RestClient.log = []
36
      headers = clone_config[:headers].clone
37

    
38
      get_params = options[:params] if options[:params]
39
      path = combine_get_params(path, get_params) if get_params
40

    
41
      client_options = {}
42
      client_options[:timeout] = clone_config[:timeout] if clone_config[:timeout]
43
      client_options[:open_timeout] = clone_config[:open_timeout] if clone_config[:open_timeout]
44
      client_options[:verify_ssl] = clone_config[:verify_ssl] unless clone_config[:verify_ssl].nil?
45

    
46
      if clone_config[:oauth]
47
        self.logger.warn('[DEPRECATION] Pulp oauth is deprecated.  Please use cert_auth instead.')
48
        headers = add_oauth_header(method, path, headers)
49
        headers['pulp-user'] = clone_config[:user]
50
      elsif clone_config[:cert_auth]
51
        if !clone_config[:cert_auth][:ssl_client_cert] || !clone_config[:cert_auth][:ssl_client_key]
52
          fail Runcible::ConfigurationUndefinedError, "Missing SSL certificate or key configuration."
53
        end
54
        client_options[:ssl_client_cert] = clone_config[:cert_auth][:ssl_client_cert]
55
        client_options[:ssl_client_key] = clone_config[:cert_auth][:ssl_client_key]
56
      else
57
        client_options[:user] = clone_config[:user]
58
        client_options[:password] = config[:http_auth][:password]
59
      end
60

    
61
      client_options[:ssl_ca_file] = config[:ca_cert_file] unless config[:ca_cert_file].nil?
62
      client = RestClient::Resource.new(clone_config[:url], client_options)
63

    
64
      args = [method]
65
      args << generate_payload(options) if [:post, :put].include?(method)
66
      args << headers
67

    
68
      response = get_response(client, path, *args)
69
      process_response(response)
70

    
71
    rescue RestClient::ResourceNotFound => e
72
      log_info
73
      raise e
74
    rescue => e
75
      log_exception
76
      raise e
77
    end
78

    
79
    def get_response(client, path, *args)
80
      client[path].send(*args) do |response, _request, _result, &_block|
81
        resp = response.return!
82
        log_debug
83
        return resp
84
      end
85
    end
86

    
87
    def combine_get_params(path, params)
88
      query_string = params.map do |k, v|
89
        if v.is_a? Array
90
          v.map { |y| "#{k}=#{y}" }.join('&')
91
        else
92
          "#{k}=#{v}"
93
        end
94
      end
95
      query_string = query_string.flatten.join('&')
96
      path + "?#{query_string}"
97
    end
98

    
99
    def generate_payload(options)
100
      if options[:payload].is_a?(String)
101
        return options[:payload]
102
      elsif options[:payload].is_a?(Hash)
103
        format_payload_json(options[:payload])
104
      end
105
    end
106

    
107
    def format_payload_json(payload_hash)
108
      if payload_hash
109
        if payload_hash[:optional]
110
          payload = if payload_hash[:required]
111
                      payload_hash[:required].merge(payload_hash[:optional])
112
                    else
113
                      payload_hash[:optional]
114
                    end
115
        elsif payload_hash[:delta]
116
          payload = payload_hash
117
        else
118
          payload = payload_hash[:required]
119
        end
120
      else
121
        payload = {}
122
      end
123

    
124
      return payload.to_json
125
    end
126

    
127
    def process_response(response)
128
      begin
129
        body = response.body == "null" ? nil : JSON.parse(response.body)
130
        if body.respond_to? :with_indifferent_access
131
          body = body.with_indifferent_access
132
        elsif body.is_a? Array
133
          body = body.map do |i|
134
            i.respond_to?(:with_indifferent_access) ? i.with_indifferent_access : i
135
          end
136
        end
137
        response = Runcible::Response.new(body, response)
138
      rescue JSON::ParserError
139
        log_exception
140
      end
141

    
142
      return response
143
    end
144

    
145
    def required_params(local_names, binding, keys_to_remove = [])
146
      local_names = local_names.each_with_object({}) do |v, acc|
147
        value = binding.eval(v.to_s) unless v == :_
148
        acc[v] = value unless value.nil?
149
        acc
150
      end
151

    
152
      #The double delete is to support 1.8.7 and 1.9.3
153
      local_names.delete(:payload)
154
      local_names.delete(:optional)
155
      local_names.delete('payload')
156
      local_names.delete('optional')
157
      keys_to_remove.each do |key|
158
        local_names.delete(key)
159
        local_names.delete(key.to_sym)
160
      end
161

    
162
      return local_names
163
    end
164

    
165
    def add_http_auth_header
166
      return {:user => config[:user], :password => config[:http_auth][:password]}
167
    end
168

    
169
    def add_oauth_header(method, path, headers)
170
      default_options = { :site               => config[:url],
171
                          :http_method        => method,
172
                          :request_token_path => '',
173
                          :authorize_path     => '',
174
                          :access_token_path  => '' }
175

    
176
      consumer = OAuth::Consumer.new(config[:oauth][:oauth_key], config[:oauth][:oauth_secret], default_options)
177

    
178
      method_to_http_request = { :get    => Net::HTTP::Get,
179
                                 :post   => Net::HTTP::Post,
180
                                 :put    => Net::HTTP::Put,
181
                                 :delete => Net::HTTP::Delete }
182

    
183
      http_request = method_to_http_request[method].new(path)
184
      consumer.sign!(http_request)
185

    
186
      headers['Authorization'] = http_request['Authorization']
187
      return headers
188
    end
189

    
190
    def log_debug
191
      if self.config[:logging][:debug]
192
        log_message = generate_log_message
193
        self.config[:logging][:logger].debug(log_message)
194
      end
195
    end
196

    
197
    def log_exception
198
      if self.config[:logging][:exception]
199
        log_message = generate_log_message
200
        self.config[:logging][:logger].error(log_message)
201
      end
202
    end
203

    
204
    def log_info
205
      if self.config[:logging][:info]
206
        log_message = generate_log_message
207
        self.config[:logging][:logger].info(log_message)
208
      end
209
    end
210

    
211
    def generate_log_message
212
      RestClient.log.join('\n')
213
    end
214

    
215
    def logger
216
      self.config[:logging][:logger]
217
    end
218
  end
219

    
220
  class ConfigurationUndefinedError < StandardError
221
    def self.message
222
      # override me to change the error message
223
      'Configuration not set. Runcible::Base.config= must be called before Runcible::Base.config.'
224
    end
225
  end
226
end