Class: K8s::Transport
- Inherits:
-
Object
show all
- Includes:
- Logging
- Defined in:
- lib/k8s/transport.rb
Constant Summary
collapse
- EXCON_MIDDLEWARES =
[
Excon::Middleware::RedirectFollower,
]
{
'Accept' => 'application/json',
}
Constants included
from Logging
Logging::LOG_LEVEL, Logging::LOG_TARGET
Instance Attribute Summary collapse
Class Method Summary
collapse
Instance Method Summary
collapse
-
#excon ⇒ Excon::Connection
-
#format_request(options) ⇒ Object
-
#get(*path, **options) ⇒ Object
-
#gets(*paths, response_class: nil, **options) ⇒ Object
-
#initialize(server, auth_token: nil, **options) ⇒ Transport
constructor
A new instance of Transport.
-
#parse_response(response, request_options, response_class: nil) ⇒ response_class, Hash
-
#path(*path) ⇒ String
-
#request(response_class: nil, **options) ⇒ Object
-
#request_options(request_object: nil, **options) ⇒ Hash
-
#requests(*options, response_class: nil, skip_missing: false) ⇒ Array<response_class, Hash, nil>
Methods included from Logging
included, #logger, #logger!
#debug!, #log_level, #log_level=, #quiet!, #verbose!
Constructor Details
#initialize(server, auth_token: nil, **options) ⇒ Transport
Returns a new instance of Transport.
81
82
83
84
85
86
87
|
# File 'lib/k8s/transport.rb', line 81
def initialize(server, auth_token: nil, **options)
@server = server
@auth_token = auth_token
@options = options
logger! progname: @server
end
|
Instance Attribute Details
#options ⇒ Object
Returns the value of attribute options.
78
79
80
|
# File 'lib/k8s/transport.rb', line 78
def options
@options
end
|
#server ⇒ Object
Returns the value of attribute server.
78
79
80
|
# File 'lib/k8s/transport.rb', line 78
def server
@server
end
|
Class Method Details
Construct transport from kubeconfig
23
24
25
26
27
28
29
30
31
32
33
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
|
# File 'lib/k8s/transport.rb', line 23
def self.config(config)
options = {}
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
logger.info "Using config with server=#{config.cluster.server}"
new(config.cluster.server, **options)
end
|
In-cluster config within a kube pod, using the kubernetes service envs and serviceaccount secrets
67
68
69
70
71
72
73
74
75
76
|
# File 'lib/k8s/transport.rb', line 67
def self.in_cluster_config
host = ENV['KUBERNETES_SERVICE_HOST']
port = ENV['KUBERNETES_SERVICE_PORT_HTTPS']
new("https://#{host}:#{port}",
ssl_verify_peer: true,
ssl_ca_file: '/var/run/secrets/kubernetes.io/serviceaccount/ca.crt',
auth_token: File.read('/var/run/secrets/kubernetes.io/serviceaccount/token'),
)
end
|
Instance Method Details
#excon ⇒ Excon::Connection
90
91
92
93
94
95
96
97
|
# File 'lib/k8s/transport.rb', line 90
def excon
@excon ||= Excon.new(@server,
persistent: true,
middlewares: EXCON_MIDDLEWARES,
headers: REQUEST_HEADERS,
**@options
)
end
|
120
121
122
123
124
125
126
127
128
129
130
131
132
133
|
# File 'lib/k8s/transport.rb', line 120
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) ⇒ Object
232
233
234
235
236
237
238
|
# File 'lib/k8s/transport.rb', line 232
def get(*path, **options)
request(
method: 'GET',
path: self.path(*path),
**options,
)
end
|
#gets(*paths, response_class: nil, **options) ⇒ Object
241
242
243
244
245
246
247
248
249
|
# File 'lib/k8s/transport.rb', line 241
def gets(*paths, response_class: nil, **options)
requests(*paths.map{|path| {
method: 'GET',
path: self.path(path),
**options,
} },
response_class: response_class,
)
end
|
#parse_response(response, request_options, response_class: nil) ⇒ response_class, Hash
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
|
# File 'lib/k8s/transport.rb', line 138
def parse_response(response, request_options, response_class: nil)
method = request_options[:method]
path = request_options[:path]
content_type, = response.['Content-Type'].split(';')
case content_type
when 'application/json'
response_data = JSON.parse(response.body)
when 'text/plain'
response_data = response.body else
raise K8s::Error::API.new(method, path, response.status, "Invalid response Content-Type: #{response.['Content-Type']}")
end
if response.status.between? 200, 299
unless response_data.is_a? Hash
raise K8s::Error::API.new(method, path, response.status, "Invalid JSON response: #{response_data.inspect}")
end
if response_class
return response_class.from_json(response_data)
else
return response_data end
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)
else
raise error_class.new(method, path, response.status, response.reason_phrase)
end
end
end
|
#path(*path) ⇒ String
100
101
102
|
# File 'lib/k8s/transport.rb', line 100
def path(*path)
File.join('/', *path)
end
|
#request(response_class: nil, **options) ⇒ Object
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
|
# File 'lib/k8s/transport.rb', line 176
def request(response_class: nil, **options)
excon_options = request_options(**options)
start = Time.now
response = excon.request(**excon_options)
t = Time.now - start
obj = 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}"}
return obj
end
|
#request_options(request_object: nil, **options) ⇒ Hash
105
106
107
108
109
110
111
112
113
114
115
116
117
118
|
# File 'lib/k8s/transport.rb', line 105
def request_options(request_object: nil, **options)
options[:headers] ||= {}
if @auth_token
options[:headers]['Authorization'] = "Bearer #{@auth_token}"
end
if request_object
options[:headers]['Content-Type'] = 'application/json'
options[:body] = request_object.to_json
end
options
end
|
#requests(*options, response_class: nil, skip_missing: false) ⇒ Array<response_class, Hash, nil>
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
|
# File 'lib/k8s/transport.rb', line 201
def requests(*options, response_class: nil, skip_missing: false)
return [] if options.empty?
start = Time.now
responses = excon.requests(
options.map{|options| request_options(**options)}
)
t = Time.now - start
objects = responses.zip(options).map{|response, request_options|
begin
parse_response(response, request_options,
response_class: request_options[:response_class] || response_class,
)
rescue K8s::Error::NotFound
if skip_missing
nil
else
raise
end
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{|r| r.status}.join ', '}] in #{'%.3f' % t}s" }
return objects
end
|