Class: GoodData::Rest::Connection

Inherits:
Object
  • Object
show all
Includes:
MonitorMixin
Defined in:
lib/gooddata/rest/connection.rb,
lib/gooddata/rest/phmap.rb

Overview

Wrapper of low-level HTTP/REST client/library

Constant Summary collapse

PH_MAP =

PH_MAP for wildcarding of URLs in reports

[
  ['/gdc/projects/{id}/execute', %r{/gdc/projects/[^\/]+/execute}],

  ['/gdc/dataload/projects/{id}/outputStage', %r{/gdc/dataload/projects/[^\/]+/outputStage}],

  ['/gdc/datawarehouse/instances/{id}', %r{/gdc/datawarehouse/instances/[^\/]+}],
  ['/gdc/datawarehouse/executions/{id}', %r{/gdc/datawarehouse/executions/[^\/]+}],

  # domain dataproducts' clients
  ['/gdc/domains/{id}/dataproducts/{data_product}/clients?segment={segment}',
   %r{\/gdc\/domains\/[^\/]+\/dataproducts\/[^\/]+\/clients\?.*segment=[^\/]+}],
  ['/gdc/domains/{id}/dataproducts/{data_product}/clients/{client}', %r{/gdc/domains/[^\/]+/dataproducts/[^\/]+/clients/[^\/]+}],
  ['/gdc/domains/{id}/dataproducts/{data_product}/clients', %r{/gdc/domains/[^\/]+/dataproducts/[^\/]+/clients}],

  # domain dataproducts' segments
  ['/gdc/domains/{id}/dataproducts/{data_product}/segments/{segment}/synchronizeClients/results/{result}/details?offset={offset}&limit={limit}',
   %r{/gdc/domains/[^\/]+/dataproducts/[^\/]+/segments/[^\/]+/synchronizeClients/results/[^\/]+/details\?offset=[\d]+&limit=[\d]+}],
  ['/gdc/domains/{id}/dataproducts/{data_product}/segments/{segment}/synchronizeClients/results/{result}',
   %r{/gdc/domains/[^\/]+/dataproducts/[^\/]+/segments/[^\/]+/synchronizeClients/results/[^\/]+}],
  ['/gdc/domains/{id}/dataproducts/{data_product}/segments/{segment}', %r{/gdc/domains/[^\/]+/dataproducts/[^\/]+/segments/[^\/]+}],
  ['/gdc/domains/{id}/dataproducts/{data_product}/segments', %r{/gdc/domains/[^\/]+/dataproducts/[^\/]+/segments}],

  # domain dataproducts' provision & update
  ['/gdc/domains/{id}/dataproducts/{data_product}/provisionClientProjects/results/{result}/details?offset={offset}&limit={limit}',
   %r{/gdc/domains/[^\/]+/dataproducts/[^\/]+/provisionClientProjects/results/[^\/]+/details\?offset=[\d]+&limit=[\d]+}],
  ['/gdc/domains/{id}/dataproducts/{data_product}/provisionClientProjects/results/{result}',
   %r{/gdc/domains/[^\/]+/dataproducts/[^\/]+/provisionClientProjects/results/[^\/]+}],
  ['/gdc/domains/{id}/dataproducts/{data_product}/provisionClientProjects',
   %r{/gdc/domains/[^\/]+/dataproducts/[^\/]+/provisionClientProjects}],
  ['/gdc/domains/{id}/dataproducts/{data_product}/updateClients?deleteExtraInSegments={segments}',
   %r{/gdc/domains/[^\/]+/dataproducts/[^\/]+/updateClients\?deleteExtraInSegments=[^\/]+}],
  ['/gdc/domains/{id}/dataproducts/{data_product}/updateClients',
   %r{/gdc/domains/[^\/]+/dataproducts/[^\/]+/updateClients}],

  # domain dataproduct
  ['/gdc/domains/{id}/dataproducts/{data_product}', %r{/gdc/domains/[^\/]+/dataproducts/[^\/]+}],
  ['/gdc/domains/{id}/dataproducts', %r{/gdc/domains/[^\/]+/dataproducts}],

  # domain segments
  ['/gdc/domains/{id}/segments/{segment}/synchronizeClients/results/{result}/details?offset={offset}&limit={limit}',
   %r{/gdc/domains/[^\/]+/segments/[^\/]+/synchronizeClients/results/[^\/]+/details\?offset=[\d]+&limit=[\d]+}],
  ['/gdc/domains/{id}/segments/{segment}/synchronizeClients/results/{result}',
   %r{/gdc/domains/[^\/]+/segments/[^\/]+/synchronizeClients/results/[^\/]+}],
  ['/gdc/domains/{id}/segments/{segment}/', %r{/gdc/domains/[^\/]+/segments/[^\/]+/}],
  ['/gdc/domains/{id}/segments/{segment}', %r{/gdc/domains/[^\/]+/segments/[^\/]+}],

  # domain clients
  ['/gdc/domains/{id}/clients?segment={segment}', %r{/gdc/domains/[^\/]+/clients\?segment=[^\/]+}],
  ['/gdc/domains/{id}/clients/{client_id}/settings/lcm.title', %r{/gdc/domains/[^\/]+/clients/[^\/]+/settings/lcm.title}],
  ['/gdc/domains/{id}/clients/{client_id}/settings/lcm.token', %r{/gdc/domains/[^\/]+/clients/[^\/]+/settings/lcm.token}],
  ['/gdc/domains/{id}/clients/{client_id}', %r{/gdc/domains/[^\/]+/clients/[^\/]+}],
  ['/gdc/domains/{id}/provisionClientProjects/results/{result}/details?offset={offset}&limit={limit}',
   %r{/gdc/domains/[^\/]+/provisionClientProjects/results/[^\/]+/details\?offset=[\d]+&limit=[\d]+}],
  ['/gdc/domains/{id}/provisionClientProjects/results/{result}', %r{/gdc/domains/[^\/]+/provisionClientProjects/results/[^\/]+}],
  ['/gdc/domains/{id}/provisionClientProjects', %r{/gdc/domains/[^\/]+/provisionClientProjects}],
  ['/gdc/domains/{id}/updateClients', %r{/gdc/domains/[^\/]+/updateClients}],
  ['/gdc/domains/{id}/', %r{/gdc/domains/[^\/]+/}],

  ['/gdc/exporter/result/{id}/{id}', %r{/gdc/exporter/result/[^\/]+/[^\/]+}],

  ['/gdc/internal/lcm/domains/{id}/dataproducts/{data_product}/segments/{segment}/syncProcesses/{process}',
   %r{/gdc/internal/lcm/domains/[^\/]+/dataproducts/[^\/]+/segments/[^\/]+/syncProcesses/[^\/]+}],
  ['/gdc/internal/lcm/domains/{id}/dataproducts/{data_product}/segments/{segment}/syncProcesses',
   %r{/gdc/internal/lcm/domains/[^\/]+/dataproducts/[^\/]+/segments/[^\/]+/syncProcesses}],

  ['/gdc/internal/projects/{id}/objects/setPermissions', %r{/gdc/internal/projects/[^\/]+/objects/setPermissions}],
  ['/gdc/internal/projects/{id}/roles', %r{/gdc/internal/projects/[^\/]+/roles}],
  ['/gdc/dataload/projects/{id}/modelMapping/datasets/bulk/upsert', %r{/gdc/dataload/projects/[^\/]+/modelMapping/datasets/bulk/upsert}],
  ['/gdc/dataload/internal/projects/{id}/ldmLayout', %r{/gdc/dataload/internal/projects/[^\/]+/ldmLayout}],
  ['/gdc/md/{id}/variables/item/{id}', %r{/gdc/md/[^\/]+/variables/item/[\d]+}],
  ['/gdc/md/{id}/validate/task/{id}', %r{/gdc/md/[^\/]+/validate/task/[^\/]+}],
  ['/gdc/md/{id}/using2/{id}/{id}', %r{/gdc/md/[^\/]+/using2/[\d]+/[\d]+}],
  ['/gdc/md/{id}/using2/{id}', %r{/gdc/md/[^\/]+/using2/[\d]+}],
  ['/gdc/md/{id}/userfilters?users={users}', %r{\/gdc\/md\/[^\/]+\/userfilters\?users=[\/\w+@.]+}],
  ['/gdc/md/{id}/userfilters?count={count}&offset={offset}', %r{/gdc/md/[^\/]+/userfilters\?count=[\d]+&offset=[\d]+}],
  ['/gdc/md/{id}/usedby2/{id}/{id}', %r{/gdc/md/[^\/]+/usedby2/[\d]+/[\d]+}],
  ['/gdc/md/{id}/usedby2/{id}', %r{/gdc/md/[^\/]+/usedby2/[\d]+}],
  ['/gdc/md/{id}/tasks/{id}/status', %r{/gdc/md/[^\/]+/tasks/[^\/]+/status}],
  ['/gdc/md/{id}/obj/{id}/validElements', %r{/gdc/md/[^\/]+/obj/[\d]+/validElements(/)?(\?.*)?}],
  ['/gdc/md/{id}/obj/{id}/elements', %r{/gdc/md/[^\/]+/obj/[\d]+/elements(/)?(\?.*)?}],
  ['/gdc/md/{id}/obj/{id}', %r{/gdc/md/[^\/]+/obj/[\d]+}],
  ['/gdc/md/{id}/etltask/{id}', %r{/gdc/md/[^\/]+/etltask/[^\/]+}],
  ['/gdc/md/{id}/dataResult/{id}', %r{/gdc/md/[^\/]+/dataResult/[\d]+}],
  ['/gdc/md/{id}', %r{/gdc/md/[^\/]+}],

  ['/gdc/projects/{id}/users/{id}/roles', %r{/gdc/projects/[^\/]+/users/[^\/]+/roles}],
  ['/gdc/projects/{id}/users/{id}/permissions', %r{/gdc/projects/[^\/]+/users/[^\/]+/permissions}],
  ['/gdc/projects/{id}/users', %r{/gdc/projects/[^\/]+/users}],
  ['/gdc/projects/{id}/schedules/{id}/executions/{id}', %r{/gdc/projects/[^\/]+/schedules/[^\/]+/executions/[^\/]+}],
  ['/gdc/projects/{id}/schedules/{id}', %r{/gdc/projects/[^\/]+/schedules/[^\/]+}],
  ['/gdc/projects/{id}/roles/{id}', %r{/gdc/projects/[^\/]+/roles/[\d]+}],
  ['/gdc/projects/{id}/model/view/{id}', %r{/gdc/projects/[^\/]+/model/view/[^\/]+}],
  ['/gdc/projects/{id}/model/view', %r{/gdc/projects/[^\/]+/model/view}],
  ['/gdc/projects/{id}/model/diff/{id}', %r{/gdc/projects/[^\/]+/model/diff/[^\/]+}],
  ['/gdc/projects/{id}/model/diff', %r{/gdc/projects/[^\/]+/model/diff}],
  ['/gdc/projects/{id}/dataload/metadata/{project}', %r{/gdc/projects/[^\/]+/dataload/metadata/[^\/]+}],
  ['/gdc/projects/{id}/dataload/processes/{id}/executions/{id}', %r{/gdc/projects/[^\/]+/dataload/processes/[^\/]+/executions/[^\/]+}],
  ['/gdc/projects/{id}/dataload/processes/{id}', %r{/gdc/projects/[^\/]+/dataload/processes/[^\/]+}],
  ['/gdc/projects/{id}/', %r{/gdc/projects/[^\/]+/}],
  ['/gdc/projects/{id}', %r{/gdc/projects/[^\/]+}],

  ['/gdc/userGroups/{id}', %r{/gdc/userGroups/[^\/]+}],

  ['/gdc/account/profile/{id}', %r{/gdc/account/profile/[^\/]+}],
  ['/gdc/account/login/{id}', %r{/gdc/account/login/[^\/]+}],
  ['/gdc/account/domains/{id}/users?login={login}', %r{/gdc/account/domains/[^\/]+/users\?login=[^&$]+}],
  ['/gdc/account/domains/{id}', %r{/gdc/account/domains/[^\/]+}]
]
HTTPS_PROTOCOL =
'https://'
HTTP_PROTOCOL =
'http://'
DEFAULT_URL =
'https://secure.gooddata.com'
LOGIN_PATH =
'/gdc/account/login'
TOKEN_PATH =
'/gdc/account/token'
KEYS_TO_SCRUB =
[:password, :verifyPassword, :authorizationToken]
API_LEVEL =
2
ID_LENGTH =
16
DEFAULT_HEADERS =
{
  :content_type => :json,
  :accept => [:json, :zip],
  :user_agent => GoodData.gem_version_string
}
DEFAULT_WEBDAV_HEADERS =
{
  :user_agent => GoodData.gem_version_string
}
CERTIFICATE_STORE =
OpenSSL::X509::Store.new.freeze
DEFAULT_LOGIN_PAYLOAD =
{
  :headers => DEFAULT_HEADERS,
  :verify_ssl => true,
  :ssl_cert_store => CERTIFICATE_STORE
}
RETRYABLE_ERRORS =
[
  Net::HTTPBadResponse,
  RestClient::InternalServerError,
  RestClient::Exceptions::OpenTimeout,
  RestClient::Exceptions::ReadTimeout,
  RestClient::RequestTimeout,
  RestClient::MethodNotAllowed,
  SystemCallError,
  Timeout::Error
]
RETRY_TIME_INITIAL_VALUE =
1
RETRY_TIME_COEFFICIENT =
2

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(opts) ⇒ Connection

Returns a new instance of Connection.



159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
# File 'lib/gooddata/rest/connection.rb', line 159

def initialize(opts)
  super()
  @stats = ThreadSafe::Hash.new
  @execution_id = opts[:execution_id]

  headers = opts[:headers] || {}
  @webdav_headers = DEFAULT_WEBDAV_HEADERS.merge(headers)

  @user = nil
  @server = nil
  @opts = opts
  @verify_ssl = @opts[:verify_ssl] == false || @opts[:verify_ssl] == OpenSSL::SSL::VERIFY_NONE ? OpenSSL::SSL::VERIFY_NONE : OpenSSL::SSL::VERIFY_PEER

  # Initialize headers
  reset_headers!

  @at_exit_handler_installed = nil
end

Instance Attribute Details

#request_paramsObject (readonly) Also known as: cookies, headers

Returns the value of attribute request_params.



149
150
151
# File 'lib/gooddata/rest/connection.rb', line 149

def request_params
  @request_params
end

#serverObject (readonly)

Returns the value of attribute server.



154
155
156
# File 'lib/gooddata/rest/connection.rb', line 154

def server
  @server
end

#statsObject (readonly)

Returns the value of attribute stats.



155
156
157
# File 'lib/gooddata/rest/connection.rb', line 155

def stats
  @stats
end

#userObject (readonly)

Returns the value of attribute user.



156
157
158
# File 'lib/gooddata/rest/connection.rb', line 156

def user
  @user
end

#verify_sslObject (readonly)

Returns the value of attribute verify_ssl.



157
158
159
# File 'lib/gooddata/rest/connection.rb', line 157

def verify_ssl
  @verify_ssl
end

Class Method Details

.construct_login_payload(username, password) ⇒ Object



76
77
78
79
80
81
82
83
84
85
86
# File 'lib/gooddata/rest/connection.rb', line 76

def (username, password)
  res = {
    'postUserLogin' => {
      'login' => username,
      'password' => password,
      'remember' => 1,
      'verify_level' => 2
    }
  }
  res
end

.generate_string(length = ID_LENGTH) ⇒ String

Generate random string with URL safe base64 encoding

Parameters:

  • length (String) (defaults to: ID_LENGTH)

    Length of random string to be generated

Returns:

  • (String)

    Generated random string



93
94
95
# File 'lib/gooddata/rest/connection.rb', line 93

def generate_string(length = ID_LENGTH)
  SecureRandom.urlsafe_base64(length)
end

.logging_retry_error(e, retry_time) ⇒ Object



142
143
144
145
146
# File 'lib/gooddata/rest/connection.rb', line 142

def logging_retry_error(e, retry_time)
  error_message =  "#{e.message}, retrying in #{retry_time} seconds"
  GoodData.logger.warn error_message
  GoodData.gd_logger.warn error_message
end

.map_placeholders(title) ⇒ Object



10
11
12
13
14
15
# File 'lib/gooddata/rest/phmap.rb', line 10

def self.map_placeholders(title)
  PH_MAP.each do |pm|
    break if title.gsub!(pm[1], pm[0])
  end
  title
end

.retryable(options = {}, &_block) ⇒ Object

Retry block if exception thrown



98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
# File 'lib/gooddata/rest/connection.rb', line 98

def retryable(options = {}, &_block)
  opts = { :tries => 14, :on => RETRYABLE_ERRORS }.merge(options)

  retry_exception = opts[:on]
  retries = opts[:tries]

  unless retry_exception.is_a?(Array)
    retry_exception = [retry_exception]
  end

  retry_time = RETRY_TIME_INITIAL_VALUE
  begin
    return yield
  rescue RestClient::Unauthorized, RestClient::Forbidden => e # , RestClient::Unauthorized => e
    raise e unless options[:refresh_token]
    raise e if options[:dont_reauth]

    logging_retry_error(e, retry_time)
    options[:refresh_token].call # (dont_reauth: true)
    if (retries -= 1) > 0
      retry
    else
      fail e
    end
  rescue RestClient::TooManyRequests, RestClient::ServiceUnavailable, *retry_exception => e
    logging_retry_error(e, retry_time)
    sleep retry_time
    if OpenSSL::SSL.const_defined?(:SSLErrorWaitReadable) && e.is_a?(OpenSSL::SSL::SSLErrorWaitReadable)
      GoodData.gd_logger.warn "Refresh token status=start retry_time=#{retry_time}. Error: #{e.message}"
      options[:refresh_token].call # (dont_reauth: true)
      GoodData.gd_logger.warn "Refresh token status=success retry_time=#{retry_time}. Error: #{e.message}"
    end

    # Total 10 retry requests with 1.5 coefficent should take ~ 2 mins to finish
    if (retries -= 1) > 0
      retry_time *= RETRY_TIME_COEFFICIENT
      retry
    else
      fail e
    end
  end
  yield
end

Instance Method Details

#connect(username, password, options = {}) ⇒ Object

Connect using username and password



179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
# File 'lib/gooddata/rest/connection.rb', line 179

def connect(username, password, options = {})
  server = options[:server] || Helpers::AuthHelper.read_server
  options = .merge(options)
  headers = options[:headers] || {}

  options = options.merge(headers)
  @server = RestClient::Resource.new fix_server_url(server), options

  # Install at_exit handler first
  unless @at_exit_handler_installed
    begin
      at_exit { disconnect if @user }
    rescue RestClient::Unauthorized
      GoodData.logger.info 'Already logged out'
    ensure
      @at_exit_handler_installed = true
    end
  end

  # Reset old cookies first
  if options[:sst_token]
    headers = {
      :x_gdc_authsst => options[:sst_token],
      :x_gdc_authtt => options[:tt_token]
    }
    merge_headers!(headers)
    get('/gdc/account/token', @request_params)

    @user = get('/gdc/account/profile/current')
    GoodData.logger.info("Connected using SST to server #{@server.url} to profile \"#{@user['accountSetting']['login']}\"")
    @auth = {}
    refresh_token :dont_reauth => true
  elsif  options[:headers][:x_gdc_authsst]
    @request_params = options[:headers]
    @user = get('/gdc/account/profile/current')
    GoodData.logger.info("Connected using SST to server #{@server.url} to profile \"#{@user['accountSetting']['login']}\"")
    @auth = {}
    refresh_token :dont_reauth => true
  else
    GoodData.logger.info("Connected using username \"#{username}\" to server #{@server.url}")
    credentials = Connection.(username, password)
    generate_session_id
    @auth = post(, credentials, :dont_reauth => true)['userLogin']

    refresh_token :dont_reauth => true
    @user = get(@auth['profile'])
  end
  GoodData.logger.info('Connection successful')
rescue RestClient::Unauthorized => e
  GoodData.logger.info('Bad Login or Password')
  GoodData.logger.info('Connection failed')
  raise e
rescue RestClient::Forbidden => e
  GoodData.logger.info('Connection failed')
  raise e
end

#delete(uri, options = {}) ⇒ Object

HTTP DELETE

Parameters:

  • uri (String)

    Target URI



344
345
346
# File 'lib/gooddata/rest/connection.rb', line 344

def delete(uri, options = {})
  request(:delete, uri, nil, options)
end

#disconnectObject

Disconnect



237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
# File 'lib/gooddata/rest/connection.rb', line 237

def disconnect
  # TODO: Wrap somehow
  url = @auth['state']

  begin
    clear_session_id
    delete(url, :x_gdc_authsst => sst_token, :tries => 0) if url
  rescue RestClient::Unauthorized
    begin
      refresh_token
      delete(url, :x_gdc_authsst => sst_token, :tries => 0) if url
    rescue RestClient::Unauthorized
      GoodData.logger.info 'Already disconnected'
    end
  end

  @auth = nil
  @server = nil
  @user = nil

  reset_headers!
end

#download(what, where, options = {}) ⇒ Object

Parameters:

  • what

    Address of the remote file.

  • where

    Full path to the target file.

  • [Bool] (Hash)

    a customizable set of options



263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
# File 'lib/gooddata/rest/connection.rb', line 263

def download(what, where, options = {})
  # handle the path (directory) given in what
  ilast_slash = what.rindex('/')
  if ilast_slash.nil?
    what_dir = ''
  else
    # take the directory from the path
    what_dir = what[0..ilast_slash - 1]
    # take the filename from the path
    what = what[ilast_slash + 1..-1]
  end

  option_dir = options[:directory] || ''
  option_dir = option_dir[0..-2] if option_dir[-1] == '/'

  # join the otion dir with the what_dir
  # [option dir empty, what dir empty] => the joined dir
  dir_hash = {
    [true, true] => '',
    [true, false] => what_dir,
    [false, true] => option_dir,
    [false, false] => "#{what_dir}/#{option_dir}"
  }
  dir = dir_hash[[option_dir.empty?, what_dir.empty?]]

  staging_uri = options[:staging_url].to_s

  base_url = dir.empty? ? staging_uri : URI.join("#{server}", staging_uri, "#{dir}/").to_s
  sanitized_what = options[:url_encode] == false ? what : CGI.escape(what)
  url = URI.join("#{server}", base_url, sanitized_what).to_s

  b = proc do |f|
    raw = {
      :headers => @webdav_headers.merge(:x_gdc_authtt => headers[:x_gdc_authtt]),
      :method => :get,
      :url => url,
      :verify_ssl => verify_ssl
    }
    RestClient::Request.execute(raw) do |chunk, _x, response|
      if response.code.to_s == '202'
        fail RestRetryError, 'Got 202, retry'
      elsif response.code.to_s != '200'
        fail ArgumentError, "Error downloading #{url}. Got response: #{response.code} #{response} #{response.body}"
      end
      f.write chunk
    end
  end

  GoodData::Rest::Connection.retryable(:tries => Helpers::GD_MAX_RETRY, :refresh_token => proc { refresh_token }, :on => RestRetryError) do
    if where.is_a?(IO) || where.is_a?(StringIO)
      b.call(where)
    else
      # Assume it is a string or file
      File.open(where, 'w') do |f|
        b.call(f)
      end
    end
  end
end

#enrich_error_message(exception) ⇒ Object



491
492
493
494
495
496
497
498
499
500
501
502
503
504
# File 'lib/gooddata/rest/connection.rb', line 491

def enrich_error_message(exception)
  begin
    return exception unless exception.response

    response = JSON.parse(exception.response.body, symbolize_names: true)
    return exception unless exception.message && response[:error] && response[:error][:message]

    request_id = exception.response.headers[:x_gdc_request] || 'unknown'

    exception.message = exception.message + ': ' + response[:error][:message] % response[:error][:parameters] + ' request_id: ' + request_id
  rescue JSON::ParserError # rubocop:disable Lint/HandleExceptions
  end
  exception
end

#generate_request_idObject



487
488
489
# File 'lib/gooddata/rest/connection.rb', line 487

def generate_request_id
  "#{@execution_id}:#{session_id}:#{call_id}"
end

#get(uri, options = {}, &user_block) ⇒ Object

HTTP GET

Parameters:

  • uri (String)

    Target URI



393
394
395
# File 'lib/gooddata/rest/connection.rb', line 393

def get(uri, options = {}, &user_block)
  request(:get, uri, nil, options, &user_block)
end

#log_error(e, uri, params, options = {}) ⇒ Object

Helper for logging error

Parameters:

  • e (RuntimeException)

    Exception to log

  • uri (String)

    Uri on which the request failed

  • params (Hash)

    Additional params



353
354
355
356
357
358
359
# File 'lib/gooddata/rest/connection.rb', line 353

def log_error(e, uri, params, options = {})
  return if e.response && e.response.code == 401 && !uri.include?('token') && !uri.include?('login')

  if options[:do_not_log].nil? || options[:do_not_log].index(e.class).nil?
    GoodData.logger.error(format_error(e, params))
  end
end

#post(uri, data = nil, options = {}) ⇒ Object

HTTP POST

Parameters:

  • uri (String)

    Target URI



407
408
409
# File 'lib/gooddata/rest/connection.rb', line 407

def post(uri, data = nil, options = {})
  request(:post, uri, data, options)
end

#put(uri, data, options = {}) ⇒ Object

HTTP PUT

Parameters:

  • uri (String)

    Target URI



400
401
402
# File 'lib/gooddata/rest/connection.rb', line 400

def put(uri, data, options = {})
  request(:put, uri, data, options)
end

#refresh_token(_options = {}) ⇒ Object



323
324
325
326
327
328
329
330
331
332
# File 'lib/gooddata/rest/connection.rb', line 323

def refresh_token(_options = {})
  begin # rubocop:disable Style/RedundantBegin
    # avoid infinite loop GET fails with 401
    response = get(TOKEN_PATH, :x_gdc_authsst => sst_token, :dont_reauth => true)
    # Remove when TT sent in headers. Currently we need to parse from body
    merge_headers!(:x_gdc_authtt => GoodData::Helpers.get_path(response, %w(userToken token)))
  rescue Exception => e # rubocop:disable Style/RescueException
    raise e
  end
end

#request(method, uri, data, options = {}, &user_block) ⇒ Object



361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
# File 'lib/gooddata/rest/connection.rb', line 361

def request(method, uri, data, options = {}, &user_block)
  request_id = options[:request_id] || generate_request_id
  log_info(options.merge(request_id: request_id))
  stats_on = options[:stats_on]

  payload = data.is_a?(Hash) ? data.to_json : data

  GoodData.rest_logger.info "#{method.to_s.upcase}: #{@server.url}#{uri}, #{scrub_params(data, KEYS_TO_SCRUB)}"
  profile method.to_s.upcase, uri, request_id, stats_on do
    b = proc do
      params = fresh_request_params(request_id).merge(options)

      params['X-GDC-VERSION'] = API_LEVEL

      case method
      when :get
        @server[uri].get(params, &user_block)
      when :put
        @server[uri].put(payload, params)
      when :delete
        @server[uri].delete(params)
      when :post
        @server[uri].post(payload, params)
      end
    end
    process_response(options, &b)
  end
end

#server_urlString

Returns server URI

Returns:

  • (String)

    server uri



337
338
339
# File 'lib/gooddata/rest/connection.rb', line 337

def server_url
  @server && @server.url
end

#sst_tokenObject

Reader method for SST token



414
415
416
# File 'lib/gooddata/rest/connection.rb', line 414

def sst_token
  request_params[:x_gdc_authsst]
end

#stats_table(values = stats) ⇒ Object



418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
# File 'lib/gooddata/rest/connection.rb', line 418

def stats_table(values = stats)
  sorted = values.sort_by { |_k, v| v[:avg] }
  Terminal::Table.new :headings => %w(title avg min max total calls) do |t|
    overall = {
      :avg => 0,
      :calls => 0,
      :total => 0
    }

    sorted.each do |l|
      avg = l[1][:avg]
      min = l[1][:min]
      max = l[1][:max]
      total = l[1][:total]
      calls = l[1][:calls]

      row = [
        l[0],
        sprintf('%.3f', avg),
        sprintf('%.3f', min),
        sprintf('%.3f', max),
        sprintf('%.3f', total),
        calls
      ]

      overall[:min] = min if overall[:min].nil? || min < overall[:min]
      overall[:max] = max if overall[:max].nil? || max > overall[:max]
      overall[:total] += total
      overall[:calls] += calls
      overall[:avg] += avg

      t.add_row row
    end

    overall[:avg] = overall[:avg] / sorted.length
    row = [
      'TOTAL',
      sprintf('%.3f', overall[:avg]),
      sprintf('%.3f', overall[:min]),
      sprintf('%.3f', overall[:max]),
      sprintf('%.3f', overall[:total]),
      overall[:calls]
    ]

    t.add_row :separator
    t.add_row row
  end
end

#tt_tokenObject

Reader method for TT token



470
471
472
# File 'lib/gooddata/rest/connection.rb', line 470

def tt_token
  request_params[:x_gdc_authtt]
end

#upload(file, options = {}) ⇒ Object

Uploads a file to GoodData server



476
477
478
479
480
481
482
483
484
485
# File 'lib/gooddata/rest/connection.rb', line 476

def upload(file, options = {})
  dir = options[:directory] || ''
  staging_uri = options[:staging_url].to_s
  url = dir.empty? ? staging_uri : URI.join("#{server}", staging_uri, "#{dir}/").to_s
  # Make a directory, if needed
  create_webdav_dir_if_needed url unless dir.empty?

  webdav_filename = options[:filename] || File.basename(file)
  do_stream_file URI.join("#{server}", url, CGI.escape(webdav_filename)), file
end