Class: Wavefront::ApiCaller

Inherits:
Object
  • Object
show all
Includes:
Mixins
Defined in:
lib/wavefront-sdk/core/api_caller.rb

Overview

Constructs and makes API calls to Wavefront.

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Mixins

#log, #parse_relative_time, #parse_time, #relative_time, #time_multiplier, #valid_relative_time?

Constructor Details

#initialize(calling_class, creds = {}, opts = {}) ⇒ Nil

Parameters:

  • calling_class

    [

  • creds (Hash) (defaults to: {})

    Wavefront credentials

  • opts (Hash) (defaults to: {})


25
26
27
28
29
30
# File 'lib/wavefront-sdk/core/api_caller.rb', line 25

def initialize(calling_class, creds = {}, opts = {})
  @calling_class = calling_class
  @opts          = opts
  setup_class_vars(opts)
  setup_endpoint(creds)
end

Instance Attribute Details

#calling_classObject (readonly)

Returns the value of attribute calling_class.



18
19
20
# File 'lib/wavefront-sdk/core/api_caller.rb', line 18

def calling_class
  @calling_class
end

#debugObject (readonly)

Returns the value of attribute debug.



18
19
20
# File 'lib/wavefront-sdk/core/api_caller.rb', line 18

def debug
  @debug
end

#loggerObject (readonly)

Returns the value of attribute logger.



18
19
20
# File 'lib/wavefront-sdk/core/api_caller.rb', line 18

def logger
  @logger
end

#netObject (readonly)

Returns the value of attribute net.



18
19
20
# File 'lib/wavefront-sdk/core/api_caller.rb', line 18

def net
  @net
end

#noopObject (readonly)

Returns the value of attribute noop.



18
19
20
# File 'lib/wavefront-sdk/core/api_caller.rb', line 18

def noop
  @noop
end

#optsObject (readonly)

Returns the value of attribute opts.



18
19
20
# File 'lib/wavefront-sdk/core/api_caller.rb', line 18

def opts
  @opts
end

#verboseObject (readonly)

Returns the value of attribute verbose.



18
19
20
# File 'lib/wavefront-sdk/core/api_caller.rb', line 18

def verbose
  @verbose
end

Instance Method Details

#delete(path) ⇒ Hash

Make a DELETE call to the Wavefront API and return the result as a Ruby hash.

Parameters:

  • path (String)

    path to be appended to the #net path.

Returns:

  • (Hash)

    API response



163
164
165
# File 'lib/wavefront-sdk/core/api_caller.rb', line 163

def delete(path)
  make_call(mk_conn(path), :delete)
end

#end_time(opts) ⇒ Object



120
121
122
# File 'lib/wavefront-sdk/core/api_caller.rb', line 120

def end_time(opts)
  Time.right_now + opts[:timeout] if opts[:timeout]&.positive?
end

#get(path, query = {}) ⇒ Hash

Make a GET call to the Wavefront API and return the result as a Ruby hash.

Parameters:

  • path (String)

    path to be appended to the #net path.

  • query (Hash) (defaults to: {})

    optional key-value pairs with will be made into a query string

  • request_opts (Hash)

    parameters to pass through to Faraday

Returns:

  • (Hash)

    API response



70
71
72
# File 'lib/wavefront-sdk/core/api_caller.rb', line 70

def get(path, query = {})
  make_call(mk_conn(path, {}), :get, nil, query)
end

#get_flat_params(path, query = {}) ⇒ Object

Had to introduce this for the Wavefront::Dashboard#acls method, which uses a query string of multiple id=s. By default Faraday only uses the last one. You must set the ‘params_encoder`. Rather than convolute the existing logic, it was cleaner to add this method. Parameters are same as #get.



80
81
82
# File 'lib/wavefront-sdk/core/api_caller.rb', line 80

def get_flat_params(path, query = {})
  make_call(flat_param_conn(path, query), :get)
end

#get_stream(path, query = {}, opts = {}) ⇒ Object

This is used by the Wavefront::Unstable::Spy methods to stream data. It prints to standard out.

Parameters:

  • path (String)

    path to be appended to the net path.

  • query (Hash) (defaults to: {})

    optional key-value pairs with will be made into a query string

  • opts (Hash) (defaults to: {})

    keys: timestamp_chunks – prints a timestamp before each chunk of streamed

    data
    

    timeout – after approximately this many seconds, return. It will be

    the first chunk *after* the given time
    

Returns:



96
97
98
99
100
101
102
103
104
# File 'lib/wavefront-sdk/core/api_caller.rb', line 96

def get_stream(path, query = {}, opts = {})
  conn = flat_param_conn(path, query)
  verbosity(conn, :get, query)
  stream_connection(conn, query, opts)
rescue Faraday::TimeoutError
  raise Wavefront::Exception::NetworkTimeout
rescue StopIteration
  nil
end

#mk_conn(path, headers = {}, opts = {}) ⇒ URI::HTTPS

Create a Faraday connection object. The server comes from the endpoint passed to the initializer in the ‘creds’ hash; the root of the URI is dynamically derived by the #setup_endpoint method.

Parameters:

  • path (String)

    uri path

  • headers (Hash) (defaults to: {})

    additional headers

  • request_opts (Hash)

    Faraday request parameters

Returns:

  • (URI::HTTPS)


49
50
51
52
53
54
55
56
57
# File 'lib/wavefront-sdk/core/api_caller.rb', line 49

def mk_conn(path, headers = {}, opts = {})
  url = format('%<scheme>s://%<endpoint>s%<path>s',
               scheme: net[:scheme],
               endpoint: net[:endpoint],
               path: [net[:api_base], path].uri_concat)
  set_opts = { url: Addressable::URI.encode(url),
               headers: net[:headers].merge(headers) }
  Faraday.new(set_opts.merge(opts))
end

#post(path, body = nil, ctype = 'text/plain') ⇒ Hash

Make a POST call to the Wavefront API and return the result as a Ruby hash.

Parameters:

  • path (String)

    path to be appended to the #net path.

  • body (String, Object) (defaults to: nil)

    optional body text to post. Objects will be converted to JSON

  • ctype (String) (defaults to: 'text/plain')

    the content type to use when posting

Returns:

  • (Hash)

    API response



134
135
136
137
138
139
# File 'lib/wavefront-sdk/core/api_caller.rb', line 134

def post(path, body = nil, ctype = 'text/plain')
  body = body.to_json unless body.is_a?(String)
  make_call(mk_conn(path,  'Content-Type': ctype,
                           Accept: 'application/json'),
            :post, nil, body)
end

#put(path, body = nil, ctype = 'application/json') ⇒ Hash

Make a PUT call to the Wavefront API and return the result as a Ruby hash.

Parameters:

  • path (String)

    path to be appended to the #net path.

  • body (String) (defaults to: nil)

    optional body text to post

  • ctype (String) (defaults to: 'application/json')

    the content type to use when putting

Returns:

  • (Hash)

    API response



150
151
152
153
154
# File 'lib/wavefront-sdk/core/api_caller.rb', line 150

def put(path, body = nil, ctype = 'application/json')
  make_call(mk_conn(path,  'Content-Type': ctype,
                           Accept: 'application/json'),
            :put, nil, body.to_json)
end

#respond(resp) ⇒ String

If we need to massage a raw response to fit what the Wavefront::Response class expects (I’m looking at you, ‘User’), a class can provide a #response_shim method.

Parameters:

  • resp (Faraday::Response)

Returns:

  • (String)

    body of response (JSON)



173
174
175
176
177
178
179
180
181
182
183
# File 'lib/wavefront-sdk/core/api_caller.rb', line 173

def respond(resp)
  body = if calling_class.respond_to?(:response_shim)
           calling_class.response_shim(resp.body, resp.status)
         else
           resp.body
         end

  return body if opts[:raw_response]

  Wavefront::Response.new(body, resp.status, opts)
end

#setup_class_vars(opts) ⇒ Object



32
33
34
35
36
37
# File 'lib/wavefront-sdk/core/api_caller.rb', line 32

def setup_class_vars(opts)
  @logger    = Wavefront::Logger.new(opts)
  @noop      = opts[:noop] || false
  @verbose   = opts[:verbose] || false
  @debug     = opts[:debug] || false
end

#stream_connection(conn, query, opts) ⇒ Object



106
107
108
109
110
111
112
113
114
115
116
117
118
# File 'lib/wavefront-sdk/core/api_caller.rb', line 106

def stream_connection(conn, query, opts)
  t_end = end_time(opts)

  conn.get do |req|
    req.params = query
    req.options.on_data = proc do |chunk, _size|
      raise StopIteration if t_end && Time.right_now >= t_end

      puts Time.now if opts[:timestamp_chunks]
      puts chunk
    end
  end
end

#verbosity(conn, method, *args) ⇒ Object

Try to describe the actual HTTP calls we make. There’s a bit of clumsy guesswork here



188
189
190
191
192
193
194
195
196
197
198
# File 'lib/wavefront-sdk/core/api_caller.rb', line 188

def verbosity(conn, method, *args)
  return unless noop || verbose

  log format('uri: %<method>s %<path>s',
             method: method.upcase,
             path: conn.url_prefix)

  return unless args.last && !args.last.empty?

  log method == :get ? "params: #{args.last}" : "body: #{args.last}"
end