Class: Fluent::KubernetesMetadataFilter

Inherits:
Filter
  • Object
show all
Defined in:
lib/fluent/plugin/filter_kubernetes_metadata.rb

Constant Summary collapse

K8_POD_CA_CERT =
'ca.crt'
K8_POD_TOKEN =
'token'

Instance Method Summary collapse

Constructor Details

#initializeKubernetesMetadataFilter

Returns a new instance of KubernetesMetadataFilter.



98
99
100
# File 'lib/fluent/plugin/filter_kubernetes_metadata.rb', line 98

def initialize
  super
end

Instance Method Details

#configure(conf) ⇒ Object



106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
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
175
176
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
# File 'lib/fluent/plugin/filter_kubernetes_metadata.rb', line 106

def configure(conf)
  super

  require 'kubeclient'
  require 'active_support/core_ext/object/blank'
  require 'lru_redux'

  if @de_dot && (@de_dot_separator =~ /\./).present?
    raise Fluent::ConfigError, "Invalid de_dot_separator: cannot be or contain '.'"
  end

  if @cache_ttl < 0
    @cache_ttl = :none
  end
  @cache = LruRedux::TTL::ThreadSafeCache.new(@cache_size, @cache_ttl)
  if @include_namespace_id
    @namespace_cache = LruRedux::TTL::ThreadSafeCache.new(@cache_size, @cache_ttl)
  end
  @tag_to_kubernetes_name_regexp_compiled = Regexp.compile(@tag_to_kubernetes_name_regexp)
  @container_name_to_kubernetes_regexp_compiled = Regexp.compile(@container_name_to_kubernetes_regexp)

  # Use Kubernetes default service account if we're in a pod.
  if @kubernetes_url.nil?
    env_host = ENV['KUBERNETES_SERVICE_HOST']
    env_port = ENV['KUBERNETES_SERVICE_PORT']
    if env_host.present? && env_port.present?
      @kubernetes_url = "https://#{env_host}:#{env_port}/api"
    end
  end

  # Use SSL certificate and bearer token from Kubernetes service account.
  if Dir.exist?(@secret_dir)
    ca_cert = File.join(@secret_dir, K8_POD_CA_CERT)
    pod_token = File.join(@secret_dir, K8_POD_TOKEN)

    if !@ca_file.present? and File.exist?(ca_cert)
      @ca_file = ca_cert
    end

    if !@bearer_token_file.present? and File.exist?(pod_token)
      @bearer_token_file = pod_token
    end
  end

  if @kubernetes_url.present?

    ssl_options = {
        client_cert: @client_cert.present? ? OpenSSL::X509::Certificate.new(File.read(@client_cert)) : nil,
        client_key:  @client_key.present? ? 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
    }

    auth_options = {}

    if @bearer_token_file.present?
      bearer_token = File.read(@bearer_token_file)
      auth_options[:bearer_token] = bearer_token
    end

    @client = Kubeclient::Client.new @kubernetes_url, @apiVersion,
                                     ssl_options: ssl_options,
                                     auth_options: auth_options

    begin
      @client.api_valid?
    rescue KubeException => kube_error
      raise Fluent::ConfigError, "Invalid Kubernetes API #{@apiVersion} endpoint #{@kubernetes_url}: #{kube_error.message}"
    end

    if @watch
      thread = Thread.new(self) { |this| this.start_watch }
      thread.abort_on_exception = true
      if @include_namespace_id
        namespace_thread = Thread.new(self) { |this| this.start_namespace_watch }
        namespace_thread.abort_on_exception = true
      end
    end
  end
  if @use_journal
    @merge_json_log_key = 'MESSAGE'
    self.class.class_eval { alias_method :filter_stream, :filter_stream_from_journal }
  else
    @merge_json_log_key = 'log'
    self.class.class_eval { alias_method :filter_stream, :filter_stream_from_files }
  end

  @annotations_regexps = []
  @annotation_match.each do |regexp|
    begin
      @annotations_regexps << Regexp.compile(regexp)
    rescue RegexpError => e
      log.error "Error: invalid regular expression in annotation_match: #{e}"
    end
  end

end

#de_dot!(h) ⇒ Object



336
337
338
339
340
341
342
343
344
# File 'lib/fluent/plugin/filter_kubernetes_metadata.rb', line 336

def de_dot!(h)
  h.keys.each do |ref|
    if h[ref] && ref =~ /\./
      v = h.delete(ref)
      newref = ref.to_s.gsub('.', @de_dot_separator)
      h[newref] = v
    end
  end
end

#filter(tag, time, record) ⇒ Object



102
103
104
# File 'lib/fluent/plugin/filter_kubernetes_metadata.rb', line 102

def filter(tag, time, record)
  record
end

#filter_stream_from_files(tag, es) ⇒ Object



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
# File 'lib/fluent/plugin/filter_kubernetes_metadata.rb', line 204

def filter_stream_from_files(tag, es)
  new_es = MultiEventStream.new

  match_data = tag.match(@tag_to_kubernetes_name_regexp_compiled)

  if match_data
     = {
      'docker' => {
        'container_id' => match_data['docker_id']
      },
      'kubernetes' => {
        'namespace_name' => match_data['namespace'],
        'pod_name'       => match_data['pod_name'],
        'container_name' => match_data['container_name']
      }
    }

    if @kubernetes_url.present?
      cache_key = "#{['kubernetes']['namespace_name']}_#{['kubernetes']['pod_name']}_#{['kubernetes']['container_name']}"

      this     = self
       = @cache.getset(cache_key) {
        if 
           = this.(
            ['kubernetes']['namespace_name'],
            ['kubernetes']['pod_name'],
            ['kubernetes']['container_name']
          )
          ['kubernetes'] =  if 
          
        end
      }
      if @include_namespace_id
        namespace_name = ['kubernetes']['namespace_name']
        namespace_id = @namespace_cache.getset(namespace_name) {
          namespace = @client.get_namespace(namespace_name)
          namespace['metadata']['uid'] if namespace
        }
        ['kubernetes']['namespace_id'] = namespace_id if namespace_id
      end
    end
  end

  es.each { |time, record|
    record = merge_json_log(record) if @merge_json_log

    record = record.merge() if 

    new_es.add(time, record)
  }

  new_es
end

#filter_stream_from_journal(tag, es) ⇒ Object



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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
# File 'lib/fluent/plugin/filter_kubernetes_metadata.rb', line 258

def filter_stream_from_journal(tag, es)
  new_es = MultiEventStream.new

  es.each { |time, record|
    record = merge_json_log(record) if @merge_json_log

     = nil
    if record.has_key?('CONTAINER_NAME') && record.has_key?('CONTAINER_ID_FULL')
       = record['CONTAINER_NAME'].match(@container_name_to_kubernetes_regexp_compiled) do |match_data|
         = {
          'docker' => {
            'container_id' => record['CONTAINER_ID_FULL']
          },
          'kubernetes' => {
            'namespace_name' => match_data['namespace'],
            'pod_name'       => match_data['pod_name'],
            'container_name' => match_data['container_name']
          }
        }
        if @kubernetes_url.present?
          cache_key = "#{['kubernetes']['namespace_name']}_#{['kubernetes']['pod_name']}_#{['kubernetes']['container_name']}"

          this     = self
           = @cache.getset(cache_key) {
            if 
               = this.(
                ['kubernetes']['namespace_name'],
                ['kubernetes']['pod_name'],
                ['kubernetes']['container_name']
              )
              ['kubernetes'] =  if 
              
            end
          }
          if @include_namespace_id
            namespace_name = ['kubernetes']['namespace_name']
            namespace_id = @namespace_cache.getset(namespace_name) {
              namespace = @client.get_namespace(namespace_name)
              namespace['metadata']['uid'] if namespace
            }
            ['kubernetes']['namespace_id'] = namespace_id if namespace_id
          end
        end
        
      end
      unless 
        log.debug "Error: could not match CONTAINER_NAME from record #{record}"
      end
    elsif record.has_key?('CONTAINER_NAME') && record['CONTAINER_NAME'].start_with?('k8s_')
      log.debug "Error: no container name and id in record #{record}"
    end

    if 
      record = record.merge()
    end

    new_es.add(time, record)
  }

  new_es
end

#get_metadata(namespace_name, pod_name, container_name) ⇒ Object



74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
# File 'lib/fluent/plugin/filter_kubernetes_metadata.rb', line 74

def (namespace_name, pod_name, container_name)
  begin
     = @client.get_pod(pod_name, namespace_name)
    return if !
    labels = syms_to_strs(['metadata']['labels'].to_h)
    annotations = match_annotations(syms_to_strs(['metadata']['annotations'].to_h))
    if @de_dot
      self.de_dot!(labels)
    end
     = {
        'namespace_name' => namespace_name,
        'pod_id'         => ['metadata']['uid'],
        'pod_name'       => pod_name,
        'container_name' => container_name,
        'labels'         => labels,
        'host'           => ['spec']['nodeName']
    }
    ['annotations'] = annotations unless annotations.empty?
    return 
  rescue KubeException
    nil
  end
end

#match_annotations(annotations) ⇒ Object



346
347
348
349
350
351
352
353
354
355
356
# File 'lib/fluent/plugin/filter_kubernetes_metadata.rb', line 346

def match_annotations(annotations)
  result = {}
  @annotations_regexps.each do |regexp|
    annotations.each do |key, value|
      if ::Fluent::StringUtil.match_regexp(regexp, key.to_s)
        result[key] = value
      end
    end
  end
  result
end

#merge_json_log(record) ⇒ Object



320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
# File 'lib/fluent/plugin/filter_kubernetes_metadata.rb', line 320

def merge_json_log(record)
  if record.has_key?(@merge_json_log_key)
    log = record[@merge_json_log_key].strip
    if log[0].eql?('{') && log[-1].eql?('}')
      begin
        record = JSON.parse(log).merge(record)
        unless @preserve_json_log
          record.delete(@merge_json_log_key)
        end
      rescue JSON::ParserError
      end
    end
  end
  record
end

#start_namespace_watchObject



402
403
404
405
406
407
408
409
410
411
412
413
414
415
# File 'lib/fluent/plugin/filter_kubernetes_metadata.rb', line 402

def start_namespace_watch
  resource_version = @client.get_namespaces.resourceVersion
  watcher          = @client.watch_namespaces(resource_version)
  watcher.each do |notice|
    puts notice
    case notice.type
      when 'DELETED'
        @namespace_cache.delete(notice.object['metadata']['name'])
      else
        # We only care about each namespace's name and UID, neither of which
        # is modifiable, so we only have to care about deletions.
    end
  end
end

#start_watchObject



358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
# File 'lib/fluent/plugin/filter_kubernetes_metadata.rb', line 358

def start_watch
  begin
    resource_version = @client.get_pods.resourceVersion
    watcher          = @client.watch_pods(resource_version)
  rescue Exception => e
    raise Fluent::ConfigError, "Exception encountered fetching metadata from Kubernetes API endpoint: #{e.message}"
  end

  watcher.each do |notice|
    case notice.type
      when 'MODIFIED'
        if notice.object.status.containerStatuses
          pod_cache_key = "#{notice.object['metadata']['namespace']}_#{notice.object['metadata']['name']}"
          notice.object.status.containerStatuses.each { |container_status|
            cache_key = "#{pod_cache_key}_#{container_status['name']}"
            cached    = @cache[cache_key]
            if cached
              # Only thing that can be modified is labels and (possibly) annotations
              labels = syms_to_strs(notice.object..labels.to_h)
              annotations = match_annotations(syms_to_strs(notice.object..annotations.to_h))
              if @de_dot
                self.de_dot!(labels)
              end
              cached['kubernetes']['labels'] = labels
              cached['kubernetes']['annotations'] = annotations unless annotations.empty?
              @cache[cache_key] = cached
            end
          }
        end
      when 'DELETED'
        if notice.object.status.containerStatuses
          pod_cache_key = "#{notice.object['metadata']['namespace']}_#{notice.object['metadata']['name']}"
          notice.object.status.containerStatuses.each { |container_status|
            cache_key = "#{pod_cache_key}_#{container_status['name']}"
            @cache.delete(cache_key)
          }
        end
      else
        # Don't pay attention to creations, since the created pod may not
        # end up on this node.
    end
  end
end

#syms_to_strs(hsh) ⇒ Object



59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/fluent/plugin/filter_kubernetes_metadata.rb', line 59

def syms_to_strs(hsh)
  newhsh = {}
  hsh.each_pair do |kk,vv|
    if vv.is_a?(Hash)
      vv = syms_to_strs(vv)
    end
    if kk.is_a?(Symbol)
      newhsh[kk.to_s] = vv
    else
      newhsh[kk] = vv
    end
  end
  newhsh
end