Class: K8s::Transport

Inherits:
Object
  • Object
show all
Includes:
Logging
Defined in:
lib/k8s/transport.rb

Overview

Excon-based HTTP transport handling request/response body JSON encoding

Constant Summary collapse

EXCON_MIDDLEWARES =

Excon middlewares for requests

[
  # XXX: necessary? redirected requests omit authz headers?
  Excon::Middleware::RedirectFollower
]
REQUEST_HEADERS =

Default request headers

{
  'Accept' => 'application/json'
}.freeze
DELETE_OPTS_BODY_VERSION_MIN =

Min version of Kube API for which delete options need to be sent as request body

Gem::Version.new('1.11')

Constants included from Logging

Logging::LOG_LEVEL, Logging::LOG_TARGET

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Logging

included, #logger, #logger!

Methods included from Logging::ModuleMethods

#debug!, #log_level, #log_level=, #quiet!, #verbose!

Constructor Details

#initialize(server, auth_token: nil, **options) ⇒ Transport

Returns a new instance of Transport.

Parameters:

  • server (String)

    URL with protocol://host:port - any /path is ignored

  • auth_token (String) (defaults to: nil)

    optional Authorization: Bearer token

  • options (Hash)

    @see Excon.new



120
121
122
123
124
125
126
# File 'lib/k8s/transport.rb', line 120

def initialize(server, auth_token: nil, **options)
  @server = server
  @auth_token = auth_token
  @options = options

  logger! progname: @server
end

Instance Attribute Details

#optionsObject (readonly)

Returns the value of attribute options.



115
116
117
# File 'lib/k8s/transport.rb', line 115

def options
  @options
end

#serverObject (readonly)

Returns the value of attribute server.



115
116
117
# File 'lib/k8s/transport.rb', line 115

def server
  @server
end

Class Method Details

.config(config, server: nil, **overrides) ⇒ K8s::Transport

Construct transport from kubeconfig

Parameters:

  • config (K8s::Config)
  • server (String) (defaults to: nil)

    override cluster.server from config

  • overrides

    @see #initialize

Returns:



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
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
# File 'lib/k8s/transport.rb', line 34

def self.config(config, server: nil, **overrides)
  options = {}

  server ||= config.cluster.server

  if config.cluster.insecure_skip_tls_verify
    logger.debug "Using config with .cluster.insecure_skip_tls_verify"

    options[:ssl_verify_peer] = false
  end

  if path = config.cluster.certificate_authority
    logger.debug "Using config with .cluster.certificate_authority"

    options[:ssl_ca_file] = path
  end

  if data = config.cluster.certificate_authority_data
    logger.debug "Using config with .cluster.certificate_authority_data"

    ssl_cert_store = options[:ssl_cert_store] = OpenSSL::X509::Store.new
    ssl_cert_store.add_cert(OpenSSL::X509::Certificate.new(Base64.decode64(data)))
  end

  if (cert = config.user.client_certificate) && (key = config.user.client_key)
    logger.debug "Using config with .user.client_certificate/client_key"

    options[:client_cert] = cert
    options[:client_key] = key
  end

  if (cert_data = config.user.client_certificate_data) && (key_data = config.user.client_key_data)
    logger.debug "Using config with .user.client_certificate_data/client_key_data"

    options[:client_cert_data] = Base64.decode64(cert_data)
    options[:client_key_data] = Base64.decode64(key_data)
  end

  if token = config.user.token
    logger.debug "Using config with .user.token=..."

    options[:auth_token] = token
  elsif config.user.auth_provider && auth_provider = config.user.auth_provider.config
    logger.debug "Using config with .user.auth-provider.name=#{config.user.auth_provider.name}"

    auth_data = `#{auth_provider['cmd-path']} #{auth_provider['cmd-args']}`.strip
    if auth_provider['token-key']
      json_path = JsonPath.new(auth_provider['token-key'][1...-1])
      options[:auth_token] = json_path.first(auth_data)
    else
      options[:auth_token] = auth_data
    end
  end

  logger.info "Using config with server=#{server}"

  new(server, **options, **overrides)
end

.in_cluster_config(**options) ⇒ K8s::Transport

In-cluster config within a kube pod, using the kubernetes service envs and serviceaccount secrets

Parameters:

  • options (Hash)

    see #new

Returns:

Raises:

  • (K8s::Error::Config)

    when the environment variables KUBERNETES_SEVICE_HOST and KUBERNETES_SERVICE_PORT_HTTPS are not set

  • (Errno::ENOENT, Errno::EACCES)

    when /var/run/secrets/kubernetes.io/serviceaccount/ca.crt or /var/run/secrets/kubernetes.io/serviceaccount/token can not be read



99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
# File 'lib/k8s/transport.rb', line 99

def self.in_cluster_config(**options)
  host = ENV['KUBERNETES_SERVICE_HOST'].to_s
  raise(K8s::Error::Configuration, "in_cluster_config failed: KUBERNETES_SERVICE_HOST environment not set") if host.empty?

  port = ENV['KUBERNETES_SERVICE_PORT_HTTPS'].to_s
  raise(K8s::Error::Configuration, "in_cluster_config failed: KUBERNETES_SERVICE_HOST environment not set") if port.empty?

  new(
    "https://#{host}:#{port}",
    ssl_verify_peer: options.key?(:ssl_verify_peer) ? options.delete(:ssl_verify_peer) : true,
    ssl_ca_file: options.delete(:ssl_ca_file) || File.join((ENV['TELEPRESENCE_ROOT'] || '/'), 'var/run/secrets/kubernetes.io/serviceaccount/ca.crt'),
    auth_token: options.delete(:auth_token) || File.read(File.join((ENV['TELEPRESENCE_ROOT'] || '/'), 'var/run/secrets/kubernetes.io/serviceaccount/token')),
    **options
  )
end

Instance Method Details

#exconExcon::Connection

Returns:

  • (Excon::Connection)


129
130
131
132
133
134
135
136
137
# File 'lib/k8s/transport.rb', line 129

def excon
  @excon ||= Excon.new(
    @server,
    persistent: true,
    middlewares: EXCON_MIDDLEWARES,
    headers: REQUEST_HEADERS,
    **@options
  )
end

#format_request(options) ⇒ String

Parameters:

  • options (Hash)

    as passed to Excon#request

Returns:

  • (String)


166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
# File 'lib/k8s/transport.rb', line 166

def format_request(options)
  method = options[:method]
  path = options[:path]
  body = nil

  if options[:query]
    path += Excon::Utils.query_string(options)
  end

  if obj = options[:request_object]
    body = "<#{obj.class.name}>"
  end

  [method, path, body].compact.join " "
end

#get(*path, **options) ⇒ Array<response_class, Hash, NilClass>

Parameters:

  • path (Array<String>)

    @see #path

  • options (Hash)

    @see #request

Returns:

  • (Array<response_class, Hash, NilClass>)


317
318
319
320
321
322
323
# File 'lib/k8s/transport.rb', line 317

def get(*path, **options)
  request(
    method: 'GET',
    path: self.path(*path),
    **options
  )
end

#gets(*paths, **options) ⇒ Array<response_class, Hash, NilClass>

Parameters:

  • paths (Array<String>)
  • options (Hash)

    @see #request

Returns:

  • (Array<response_class, Hash, NilClass>)


328
329
330
331
332
333
334
335
336
337
338
# File 'lib/k8s/transport.rb', line 328

def gets(*paths, **options)
  requests(
    *paths.map do |path|
      {
        method: 'GET',
        path: self.path(path)
      }
    end,
    **options
  )
end

#need_delete_body?Boolean

Returns true if delete options should be sent as bode of the DELETE request.

Returns:

  • (Boolean)

    true if delete options should be sent as bode of the DELETE request



310
311
312
# File 'lib/k8s/transport.rb', line 310

def need_delete_body?
  @need_delete_body ||= Gem::Version.new(version.gitVersion.match(/v*(.*)/)[1]) < DELETE_OPTS_BODY_VERSION_MIN
end

#parse_response(response, request_options, response_class: nil) ⇒ response_class, Hash

Parameters:

  • response (Hash)

    as returned by Excon#request

  • request_options (Hash)

    as passed to Excon#request

  • response_class (Class) (defaults to: nil)

    coerce into response body using #new

Returns:

  • (response_class, Hash)

Raises:



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
# File 'lib/k8s/transport.rb', line 188

def parse_response(response, request_options, response_class: nil)
  method = request_options[:method]
  path = request_options[:path]
  content_type, = response.headers['Content-Type'].split(';')

  case content_type
  when 'application/json'
    response_data = Yajl::Parser.parse(response.body)

  when 'text/plain'
    response_data = response.body # XXX: broken if status 2xx
  else
    raise K8s::Error::API.new(method, path, response.status, "Invalid response Content-Type: #{response.headers['Content-Type']}")
  end

  if response.status.between? 200, 299
    return response_data if content_type == 'text/plain'

    unless response_data.is_a? Hash
      raise K8s::Error::API.new(method, path, response.status, "Invalid JSON response: #{response_data.inspect}")
    end

    return response_data unless response_class

    response_class.new(response_data)
  else
    error_class = K8s::Error::HTTP_STATUS_ERRORS[response.status] || K8s::Error::API

    if response_data.is_a?(Hash) && response_data['kind'] == 'Status'
      status = K8s::API::MetaV1::Status.new(response_data)

      raise error_class.new(method, path, response.status, response.reason_phrase, status)
    elsif response_data
      raise error_class.new(method, path, response.status, "#{response.reason_phrase}: #{response_data}")
    else
      raise error_class.new(method, path, response.status, response.reason_phrase)
    end
  end
end

#path(*path) ⇒ String

Parameters:

  • path (Array<String>)

    join path parts together to build the full URL

Returns:

  • (String)


141
142
143
# File 'lib/k8s/transport.rb', line 141

def path(*path)
  File.join('/', *path)
end

#request(response_class: nil, **options) ⇒ response_class, Hash

Parameters:

  • response_class (Class) (defaults to: nil)

    coerce into response class using #new

  • options (Hash)

    @see Excon#request

Returns:

  • (response_class, Hash)


231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
# File 'lib/k8s/transport.rb', line 231

def request(response_class: nil, **options)
  if options[:method] == 'DELETE' && need_delete_body?
    options[:request_object] = options.delete(:query)
  end

  excon_options = request_options(**options)

  start = Time.now
  response = excon.request(**excon_options)
  t = Time.now - start

  obj = options[:response_block] ? {} : parse_response(response, options, response_class: response_class)
rescue K8s::Error::API => exc
  logger.warn { "#{format_request(options)} => HTTP #{exc.code} #{exc.reason} in #{'%.3f' % t}s" }
  logger.debug { "Request: #{excon_options[:body]}" } if excon_options[:body]
  logger.debug { "Response: #{response.body}" }
  raise
else
  logger.info { "#{format_request(options)} => HTTP #{response.status}: <#{obj.class}> in #{'%.3f' % t}s" }
  logger.debug { "Request: #{excon_options[:body]}" } if excon_options[:body]
  logger.debug { "Response: #{response.body}" }
  obj
end

#request_options(request_object: nil, content_type: 'application/json', **options) ⇒ Hash

Parameters:

  • request_object (Object) (defaults to: nil)

    include request body using to_json

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

    request body content-type

  • options (Hash)

    @see Excon#request

Returns:

  • (Hash)


149
150
151
152
153
154
155
156
157
158
159
160
161
162
# File 'lib/k8s/transport.rb', line 149

def request_options(request_object: nil, content_type: 'application/json', **options)
  options[:headers] ||= {}

  if @auth_token
    options[:headers]['Authorization'] = "Bearer #{@auth_token}"
  end

  if request_object
    options[:headers]['Content-Type'] = content_type
    options[:body] = request_object.to_json
  end

  options
end

#requests(*options, skip_missing: false, skip_forbidden: false, retry_errors: true, **common_options) ⇒ Array<response_class, Hash, NilClass>

Parameters:

  • options (Array<Hash>)

    @see #request

  • skip_missing (Boolean) (defaults to: false)

    return nil for HTTP 404 responses

  • skip_forbidden (Boolean) (defaults to: false)

    return nil for HTTP 403 responses

  • retry_errors (Boolean) (defaults to: true)

    retry with non-pipelined request for HTTP 503 responses

  • common_options (Hash)

    @see #request, merged with the per-request options

Returns:

  • (Array<response_class, Hash, NilClass>)


261
262
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
# File 'lib/k8s/transport.rb', line 261

def requests(*options, skip_missing: false, skip_forbidden: false, retry_errors: true, **common_options)
  return [] if options.empty? # excon chokes

  start = Time.now
  responses = excon.requests(
    options.map{ |opts| request_options(**common_options.merge(opts)) }
  )
  t = Time.now - start

  objects = responses.zip(options).map{ |response, request_options|
    response_class = request_options[:response_class] || common_options[:response_class]

    begin
      parse_response(response, request_options,
                     response_class: response_class)
    rescue K8s::Error::NotFound
      raise unless skip_missing

      nil
    rescue K8s::Error::Forbidden
      raise unless skip_forbidden

      nil
    rescue K8s::Error::ServiceUnavailable => exc
      raise unless retry_errors

      logger.warn { "Retry #{format_request(request_options)} => HTTP #{exc.code} #{exc.reason} in #{'%.3f' % t}s" }

      # only retry the failed request, not the entire pipeline
      request(response_class: response_class, **common_options.merge(request_options))
    end
  }
rescue K8s::Error => exc
  logger.warn { "[#{options.map{ |o| format_request(o) }.join ', '}] => HTTP #{exc.code} #{exc.reason} in #{'%.3f' % t}s" }
  raise
else
  logger.info { "[#{options.map{ |o| format_request(o) }.join ', '}] => HTTP [#{responses.map(&:status).join ', '}] in #{'%.3f' % t}s" }
  objects
end

#versionK8s::API::Version

Returns:



302
303
304
305
306
307
# File 'lib/k8s/transport.rb', line 302

def version
  @version ||= get(
    '/version',
    response_class: K8s::API::Version
  )
end