Class: Fluent::Plugin::KubernetesMetadataFilter
Constant Summary
collapse
- K8_POD_CA_CERT =
'ca.crt'
- K8_POD_TOKEN =
'token'
- REGEX_VAR_LOG_PODS =
'(var\.log\.pods)\.(?<namespace>[^_]+)_(?<pod_name>[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*)_(?<pod_uuid>[a-z0-9-]*)\.(?<container_name>.+)\..*\.log$'
- REGEX_VAR_LOG_CONTAINERS =
'(var\.log\.containers)\.(?<pod_name>[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*)_(?<namespace>[^_]+)_(?<container_name>.+)-(?<docker_id>[a-z0-9]{64})\.log$'
Instance Method Summary
collapse
#get_pods_and_start_watcher, #process_pod_watcher_notices, #reset_pod_watch_retry_stats, #set_up_pod_thread, #start_pod_watch
#match_annotations, #parse_namespace_metadata, #parse_pod_metadata, #syms_to_strs
#get_namespaces_and_start_watcher, #process_namespace_watcher_notices, #reset_namespace_watch_retry_stats, #set_up_namespace_thread, #start_namespace_watch
#get_pod_metadata
Constructor Details
Returns a new instance of KubernetesMetadataFilter.
170
171
172
173
174
175
|
# File 'lib/fluent/plugin/filter_kubernetes_metadata.rb', line 170
def initialize
super
@prev_time = Time.now
@ssl_options = {}
@auth_options = {}
end
|
Instance Method Details
177
178
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
235
236
237
238
239
240
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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
|
# File 'lib/fluent/plugin/filter_kubernetes_metadata.rb', line 177
def configure(conf)
super
require 'kubeclient'
require 'lru_redux'
@stats = KubernetesMetadata::Stats.new
if @stats_interval <= 0
@stats = KubernetesMetadata::NoOpStats.new
self.define_singleton_method(:dump_stats) {}
end
if @cache_ttl < 0
log.info 'Setting the cache TTL to :none because it was <= 0'
@cache_ttl = :none
end
@id_cache = LruRedux::TTL::ThreadSafeCache.new(@cache_size, @cache_ttl)
@cache = LruRedux::TTL::ThreadSafeCache.new(@cache_size, @cache_ttl)
@namespace_cache = LruRedux::TTL::ThreadSafeCache.new(@cache_size, @cache_ttl)
@tag_to_kubernetes_name_regexp_compiled = Regexp.compile(@tag_to_kubernetes_name_regexp)
if @kubernetes_url.nil?
log.debug 'Kubernetes URL is not set - inspecting environ'
env_host = ENV['KUBERNETES_SERVICE_HOST']
env_port = ENV['KUBERNETES_SERVICE_PORT']
if present?(env_host) && present?(env_port)
if env_host =~ Resolv::IPv6::Regex
env_host = "[#{env_host}]"
end
@kubernetes_url = "https://#{env_host}:#{env_port}/api"
log.debug "Kubernetes URL is now '#{@kubernetes_url}'"
else
log.debug 'No Kubernetes URL could be found in config or environ'
end
end
if Dir.exist?(@secret_dir)
log.debug "Found directory with secrets: #{@secret_dir}"
ca_cert = File.join(@secret_dir, K8_POD_CA_CERT)
pod_token = File.join(@secret_dir, K8_POD_TOKEN)
if !present?(@ca_file) && File.exist?(ca_cert)
log.debug "Found CA certificate: #{ca_cert}"
@ca_file = ca_cert
end
if !present?(@bearer_token_file) && File.exist?(pod_token)
log.debug "Found pod token: #{pod_token}"
@bearer_token_file = pod_token
end
end
if present?(@kubernetes_url)
@ssl_options = {
client_cert: present?(@client_cert) ? OpenSSL::X509::Certificate.new(File.read(@client_cert)) : nil,
client_key: present?(@client_key) ? OpenSSL::PKey::RSA.new(File.read(@client_key)) : nil,
ca_file: @ca_file,
verify_ssl: @verify_ssl ? OpenSSL::SSL::VERIFY_PEER : OpenSSL::SSL::VERIFY_NONE
}
if @ssl_partial_chain
require 'openssl'
ssl_store = OpenSSL::X509::Store.new
ssl_store.set_default_paths
flagval = if defined? OpenSSL::X509::V_FLAG_PARTIAL_CHAIN
OpenSSL::X509::V_FLAG_PARTIAL_CHAIN
else
0x80000
end
ssl_store.flags = OpenSSL::X509::V_FLAG_CRL_CHECK_ALL | flagval
@ssl_options[:cert_store] = ssl_store
end
if present?(@bearer_token_file)
@auth_options[:bearer_token_file] = @bearer_token_file
end
create_client()
if @test_api_adapter
log.info "Extending client with test api adaper #{@test_api_adapter}"
require_relative @test_api_adapter.underscore
@client.extend(eval(@test_api_adapter))
end
begin
@client.api_valid?
rescue KubeException => e
raise Fluent::ConfigError, "Invalid Kubernetes API #{@apiVersion} endpoint #{@kubernetes_url}: #{e.message}"
end
if @watch
if ENV['K8S_NODE_NAME'].nil? || ENV['K8S_NODE_NAME'].strip.empty?
log.warn("!! The environment variable 'K8S_NODE_NAME' is not set to the node name which can affect the API server and watch efficiency !!")
end
pod_thread = Thread.new(self, &:set_up_pod_thread)
pod_thread.abort_on_exception = true
namespace_thread = Thread.new(self, &:set_up_namespace_thread)
namespace_thread.abort_on_exception = true
end
end
@annotations_regexps = []
@annotation_match.each do |regexp|
@annotations_regexps << Regexp.compile(regexp)
rescue RegexpError => e
log.error "Error: invalid regular expression in annotation_match: #{e}"
end
end
|
#create_client ⇒ Object
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
|
# File 'lib/fluent/plugin/filter_kubernetes_metadata.rb', line 302
def create_client()
log.debug 'Creating K8S client'
@client = nil
@client = Kubeclient::Client.new(
@kubernetes_url,
@apiVersion,
ssl_options: @ssl_options,
auth_options: @auth_options,
timeouts: {
open: @open_timeout,
read: @read_timeout
},
as: :parsed_symbolized
)
end
|
#dump_stats ⇒ Object
128
129
130
131
132
133
134
135
136
137
138
139
140
141
|
# File 'lib/fluent/plugin/filter_kubernetes_metadata.rb', line 128
def dump_stats
@curr_time = Time.now
return if @curr_time.to_i - @prev_time.to_i < @stats_interval
@prev_time = @curr_time
@stats.set(:pod_cache_size, @cache.count)
@stats.set(:namespace_cache_size, @namespace_cache.count) if @namespace_cache
log.info(@stats)
if log.level == Fluent::Log::LEVEL_TRACE
log.trace(" id cache: #{@id_cache.to_a}")
log.trace(" pod cache: #{@cache.to_a}")
log.trace("namespace cache: #{@namespace_cache.to_a}")
end
end
|
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
|
# File 'lib/fluent/plugin/filter_kubernetes_metadata.rb', line 143
def fetch_namespace_metadata(namespace_name)
log.trace("fetching namespace metadata: #{namespace_name}")
options = {
resource_version: '0' }
namespace_object = @client.get_namespace(namespace_name, nil, options)
log.trace("raw metadata for #{namespace_name}: #{namespace_object}")
metadata = parse_namespace_metadata(namespace_object)
@stats.bump(:namespace_cache_api_updates)
log.trace("parsed metadata for #{namespace_name}: #{metadata}")
@namespace_cache[metadata['namespace_id']] = metadata
rescue KubeException => e
if e.error_code == 401
log.info("Encountered '401 Unauthorized' exception, recreating client to refresh token")
create_client()
else
log.error "Exception '#{e}' encountered fetching namespace metadata from Kubernetes API #{@apiVersion} endpoint #{@kubernetes_url}"
@stats.bump(:namespace_cache_api_nil_error)
end
{}
rescue StandardError => e
@stats.bump(:namespace_cache_api_nil_error)
log.error "Exception '#{e}' encountered fetching namespace metadata from Kubernetes API #{@apiVersion} endpoint #{@kubernetes_url}"
{}
end
|
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
|
# File 'lib/fluent/plugin/filter_kubernetes_metadata.rb', line 98
def fetch_pod_metadata(namespace_name, pod_name)
log.trace("fetching pod metadata: #{namespace_name}/#{pod_name}")
options = {
resource_version: '0' }
pod_object = @client.get_pod(pod_name, namespace_name, options)
log.trace("raw metadata for #{namespace_name}/#{pod_name}: #{pod_object}")
metadata = parse_pod_metadata(pod_object)
@stats.bump(:pod_cache_api_updates)
log.trace("parsed metadata for #{namespace_name}/#{pod_name}: #{metadata}")
@cache[metadata['pod_id']] = metadata
rescue KubeException => e
if e.error_code == 401
log.info("Encountered '401 Unauthorized' exception, recreating client to refresh token")
create_client()
elsif e.error_code == 404
log.debug "Encountered '404 Not Found' exception, pod not found"
@stats.bump(:pod_cache_api_nil_error)
else
log.error "Exception '#{e}' encountered fetching pod metadata from Kubernetes API #{@apiVersion} endpoint #{@kubernetes_url}"
@stats.bump(:pod_cache_api_nil_error)
end
{}
rescue StandardError => e
@stats.bump(:pod_cache_api_nil_error)
log.error "Exception '#{e}' encountered fetching pod metadata from Kubernetes API #{@apiVersion} endpoint #{@kubernetes_url}"
{}
end
|
#filter(tag, time, record) ⇒ Object
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
|
# File 'lib/fluent/plugin/filter_kubernetes_metadata.rb', line 349
def filter(tag, time, record)
tag_match_data = tag.match(@tag_to_kubernetes_name_regexp_compiled)
batch_miss_cache = {}
if tag_match_data
cache_key = if tag_match_data.names.include?('pod_uuid') && !tag_match_data['pod_uuid'].nil?
tag_match_data['pod_uuid']
else
tag_match_data['docker_id']
end
docker_id = tag_match_data.names.include?('docker_id') ? tag_match_data['docker_id'] : nil
metadata = get_metadata_for_record(tag_match_data['namespace'], tag_match_data['pod_name'], tag_match_data['container_name'],
cache_key, time, batch_miss_cache, docker_id)
end
if @lookup_from_k8s_field && record.key?('kubernetes') && record.key?('docker') &&
record['kubernetes'].respond_to?(:has_key?) && record['docker'].respond_to?(:has_key?) &&
record['kubernetes'].key?('namespace_name') &&
record['kubernetes'].key?('pod_name') &&
record['kubernetes'].key?('container_name') &&
record['docker'].key?('container_id') &&
(k_metadata = get_metadata_for_record(record['kubernetes']['namespace_name'], record['kubernetes']['pod_name'],
record['kubernetes']['container_name'], record['docker']['container_id'],
time, batch_miss_cache, record['docker']['container_id']))
metadata = k_metadata
end
dump_stats
metadata ? record.merge(metadata) : record
end
|
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
|
# File 'lib/fluent/plugin/filter_kubernetes_metadata.rb', line 318
def get_metadata_for_record(namespace_name, pod_name, container_name, cache_key, create_time, batch_miss_cache, docker_id)
metadata = {
'docker' => { 'container_id' => "" },
'kubernetes' => {
'container_name' => container_name,
'namespace_name' => namespace_name,
'pod_name' => pod_name
}
}
metadata['docker']['container_id'] = docker_id unless docker_id.nil?
container_cache_key = container_name
if present?(@kubernetes_url)
pod_metadata = get_pod_metadata(cache_key, namespace_name, pod_name, create_time, batch_miss_cache)
if (pod_metadata.include? 'containers') && (pod_metadata['containers'].include? container_cache_key) && !@skip_container_metadata
metadata['kubernetes']['container_image'] = pod_metadata['containers'][container_cache_key]['image']
metadata['kubernetes']['container_image_id'] = pod_metadata['containers'][container_cache_key]['image_id'] unless pod_metadata['containers'][container_cache_key]['image_id'].empty?
metadata['docker']['container_id'] = pod_metadata['containers'][container_cache_key]['containerID'] unless pod_metadata['containers'][container_cache_key]['containerID'].empty?
end
metadata['kubernetes'].merge!(pod_metadata) if pod_metadata
metadata['kubernetes'].delete('containers')
end
metadata['kubernetes'].tap do |kube|
kube.each_pair do |k,v|
kube[k.dup] = v.dup
end
end
metadata.delete('docker') if metadata['docker'] && (metadata['docker']['container_id'].nil? || metadata['docker']['container_id'].empty?)
metadata
end
|
#present?(object) ⇒ Boolean
copied from activesupport
378
379
380
|
# File 'lib/fluent/plugin/filter_kubernetes_metadata.rb', line 378
def present?(object)
object.respond_to?(:empty?) ? !object.empty? : !!object
end
|