Class: K8s::Transport
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
-
#options ⇒ Object
readonly
Returns the value of attribute options.
-
#path_prefix ⇒ Object
readonly
Returns the value of attribute path_prefix.
-
#server ⇒ Object
readonly
Returns the value of attribute server.
Class Method Summary collapse
-
.config(config, server: nil, **overrides) ⇒ K8s::Transport
Construct transport from kubeconfig.
-
.in_cluster_config(**options) ⇒ K8s::Transport
In-cluster config within a kube pod, using the kubernetes service envs and serviceaccount secrets.
- .token_from_auth_provider_config(auth_provider_config) ⇒ String
- .token_from_exec(exec_conf) ⇒ String
Instance Method Summary collapse
- #build_excon ⇒ Excon::Connection
- #excon ⇒ Excon::Connection
- #format_request(options) ⇒ String
- #get(*path, **options) ⇒ Array<response_class, Hash, NilClass>
- #gets(*paths, **options) ⇒ Array<response_class, Hash, NilClass>
-
#initialize(server, auth_token: nil, auth_username: nil, auth_password: nil, **options) ⇒ Transport
constructor
A new instance of Transport.
-
#need_delete_body? ⇒ Boolean
True if delete options should be sent as bode of the DELETE request.
- #parse_response(response, request_options, response_class: nil) ⇒ response_class, Hash
- #path(*parts) ⇒ String
- #request(response_class: nil, **options) ⇒ response_class, Hash
- #request_options(request_object: nil, content_type: 'application/json', **options) ⇒ Hash
- #requests(*options, skip_missing: false, skip_forbidden: false, retry_errors: true, **common_options) ⇒ Array<response_class, Hash, NilClass>
- #version ⇒ K8s::API::Version
Methods included from Logging
Methods included from Logging::ModuleMethods
#debug!, #log_level, #log_level=, #quiet!, #verbose!
Constructor Details
#initialize(server, auth_token: nil, auth_username: nil, auth_password: nil, **options) ⇒ Transport
Returns a new instance of Transport.
161 162 163 164 165 166 167 168 169 170 171 |
# File 'lib/k8s/transport.rb', line 161 def initialize(server, auth_token: nil, auth_username: nil, auth_password: nil, **) uri = URI.parse(server) @server = "#{uri.scheme}://#{uri.host}:#{uri.port}" @path_prefix = File.join('/', uri.path, '/') # add leading and/or trailing slashes @auth_token = auth_token @auth_username = auth_username @auth_password = auth_password = logger! progname: @server end |
Instance Attribute Details
#options ⇒ Object (readonly)
Returns the value of attribute options.
154 155 156 |
# File 'lib/k8s/transport.rb', line 154 def end |
#path_prefix ⇒ Object (readonly)
Returns the value of attribute path_prefix.
154 155 156 |
# File 'lib/k8s/transport.rb', line 154 def path_prefix @path_prefix end |
#server ⇒ Object (readonly)
Returns the value of attribute server.
154 155 156 |
# File 'lib/k8s/transport.rb', line 154 def server @server end |
Class Method Details
.config(config, server: nil, **overrides) ⇒ K8s::Transport
Construct transport from kubeconfig
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 92 |
# File 'lib/k8s/transport.rb', line 34 def self.config(config, server: nil, **overrides) = {} server ||= config.cluster.server if config.cluster.insecure_skip_tls_verify logger.debug "Using config with .cluster.insecure_skip_tls_verify" [:ssl_verify_peer] = false end if path = config.cluster. logger.debug "Using config with .cluster.certificate_authority" [:ssl_ca_file] = path end if data = config.cluster. logger.debug "Using config with .cluster.certificate_authority_data" ssl_cert_store = [: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" [:client_cert] = cert [: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" [:client_cert_data] = Base64.decode64(cert_data) [:client_key_data] = Base64.decode64(key_data) end if token = config.user.token logger.debug "Using config with .user.token=..." [:auth_token] = token elsif config.user.auth_provider && auth_provider_config = config.user.auth_provider.config logger.debug "Using config with .user.auth-provider.name=#{config.user.auth_provider.name}" [:auth_token] = token_from_auth_provider_config(auth_provider_config) elsif exec_conf = config.user.exec logger.debug "Using config with .user.exec.command=#{exec_conf.command}" [:auth_token] = token_from_exec(exec_conf) elsif config.user.username && config.user.password logger.debug "Using config with .user.password=..." [:auth_username] = config.user.username [:auth_password] = config.user.password end logger.info "Using config with server=#{server}" new(server, **, **overrides) end |
.in_cluster_config(**options) ⇒ K8s::Transport
In-cluster config within a kube pod, using the kubernetes service envs and serviceaccount secrets
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 |
# File 'lib/k8s/transport.rb', line 132 def self.in_cluster_config(**) 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_PORT_HTTPS environment not set") if port.empty? host_with_ipv6_brackets_if_needed = if host.include? "::" "[#{host}]" else host end new( "https://#{host_with_ipv6_brackets_if_needed}:#{port}", ssl_verify_peer: .key?(:ssl_verify_peer) ? .delete(:ssl_verify_peer) : true, ssl_ca_file: .delete(:ssl_ca_file) || File.join((ENV['TELEPRESENCE_ROOT'] || '/'), 'var/run/secrets/kubernetes.io/serviceaccount/ca.crt'), auth_token: .delete(:auth_token) || File.read(File.join((ENV['TELEPRESENCE_ROOT'] || '/'), 'var/run/secrets/kubernetes.io/serviceaccount/token')), ** ) end |
.token_from_auth_provider_config(auth_provider_config) ⇒ String
96 97 98 99 100 101 102 103 104 105 106 107 |
# File 'lib/k8s/transport.rb', line 96 def self.token_from_auth_provider_config(auth_provider_config) return auth_provider_config['id-token'] if auth_provider_config['id-token'] auth_data = `#{auth_provider_config['cmd-path']} #{auth_provider_config['cmd-args']}`.strip if auth_provider_config['token-key'] json_path = JsonPath.new(auth_provider_config['token-key'][1...-1]) json_path.first(auth_data) else auth_data end end |
.token_from_exec(exec_conf) ⇒ String
111 112 113 114 115 116 117 118 119 120 121 122 123 124 |
# File 'lib/k8s/transport.rb', line 111 def self.token_from_exec(exec_conf) cmd = [exec_conf.command] cmd += exec_conf.args if exec_conf.args orig_env = ENV.to_h if envs = exec_conf.env envs.each do |env| ENV[env['name']] = env['value'] end end auth_json = `#{cmd.join(' ')}`.strip ENV.replace(orig_env) JSON.parse(auth_json).dig('status', 'token') end |
Instance Method Details
#build_excon ⇒ Excon::Connection
179 180 181 182 183 184 185 186 187 |
# File 'lib/k8s/transport.rb', line 179 def build_excon Excon.new( @server, persistent: true, middlewares: EXCON_MIDDLEWARES, headers: REQUEST_HEADERS, ** ) end |
#excon ⇒ Excon::Connection
174 175 176 |
# File 'lib/k8s/transport.rb', line 174 def excon @excon ||= build_excon end |
#format_request(options) ⇒ String
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 |
# File 'lib/k8s/transport.rb', line 219 def format_request() method = [:method] path = [:path] body = nil if [:query] path += Excon::Utils.query_string() end if obj = [:request_object] body = "<#{obj.class.name}>" end [method, path, body].compact.join " " end |
#get(*path, **options) ⇒ Array<response_class, Hash, NilClass>
371 372 373 374 |
# File 'lib/k8s/transport.rb', line 371 def get(*path, **) = .merge({ method: 'GET', path: self.path(*path) }) request(**) end |
#gets(*paths, **options) ⇒ Array<response_class, Hash, NilClass>
379 380 381 382 383 384 385 386 387 388 389 |
# File 'lib/k8s/transport.rb', line 379 def gets(*paths, **) requests( *paths.map do |path| { method: 'GET', path: self.path(path) } end, ** ) end |
#need_delete_body? ⇒ Boolean
Returns true if delete options should be sent as bode of the DELETE request.
364 365 366 |
# File 'lib/k8s/transport.rb', line 364 def need_delete_body? @need_delete_body ||= Gem::Version.new(version.gitVersion.match(/^v*((\d|\.)*)/)[1]) < DELETE_OPTS_BODY_VERSION_MIN end |
#parse_response(response, request_options, response_class: nil) ⇒ response_class, Hash
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 |
# File 'lib/k8s/transport.rb', line 241 def parse_response(response, , response_class: nil) method = [:method] path = [:path] content_type = response.headers['Content-Type']&.split(';', 2)&.first 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'].inspect}") 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(*parts) ⇒ String
191 192 193 194 |
# File 'lib/k8s/transport.rb', line 191 def path(*parts) joined_parts = File.join(*parts) joined_parts.start_with?(path_prefix) ? joined_parts : File.join(path_prefix, joined_parts) end |
#request(response_class: nil, **options) ⇒ response_class, Hash
284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 |
# File 'lib/k8s/transport.rb', line 284 def request(response_class: nil, **) if [:method] == 'DELETE' && need_delete_body? [:request_object] = .delete(:query) end = (**) start = Time.now excon_client = [:response_block] ? build_excon : excon response = excon_client.request(**) t = Time.now - start obj = [:response_block] ? {} : parse_response(response, , response_class: response_class) rescue K8s::Error::API => e logger.warn { "#{format_request(options)} => HTTP #{e.code} #{e.reason} in #{'%.3f' % t}s" } logger.debug { "Request: #{excon_options[:body]}" } if [: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 [:body] logger.debug { "Response: #{response.body}" } obj end |
#request_options(request_object: nil, content_type: 'application/json', **options) ⇒ Hash
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 |
# File 'lib/k8s/transport.rb', line 200 def (request_object: nil, content_type: 'application/json', **) [:headers] ||= {} if @auth_token [:headers]['Authorization'] = "Bearer #{@auth_token}" elsif @auth_username && @auth_password [:headers]['Authorization'] = "Basic #{Base64.strict_encode64("#{@auth_username}:#{@auth_password}")}" end if request_object [:headers]['Content-Type'] = content_type [:body] = request_object.to_json end end |
#requests(*options, skip_missing: false, skip_forbidden: false, retry_errors: true, **common_options) ⇒ Array<response_class, Hash, NilClass>
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 |
# File 'lib/k8s/transport.rb', line 315 def requests(*, skip_missing: false, skip_forbidden: false, retry_errors: true, **) return [] if .empty? # excon chokes start = Time.now responses = excon.requests( .map{ |opts| (**.merge(opts)) } ) t = Time.now - start objects = responses.zip().map{ |response, | response_class = [:response_class] || [:response_class] begin parse_response(response, , 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 => e raise unless retry_errors logger.warn { "Retry #{format_request(request_options)} => HTTP #{e.code} #{e.reason} in #{'%.3f' % t}s" } # only retry the failed request, not the entire pipeline request(response_class: response_class, **.merge()) end } rescue K8s::Error => e logger.warn { "[#{options.map{ |o| format_request(o) }.join ', '}] => HTTP #{e.code} #{e.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 |
#version ⇒ K8s::API::Version
356 357 358 359 360 361 |
# File 'lib/k8s/transport.rb', line 356 def version @version ||= get( '/version', response_class: K8s::API::Version ) end |