Class: Kubetailrb::Reader::K8sPodReader

Inherits:
Object
  • Object
show all
Includes:
WithK8sClient, Validated
Defined in:
lib/kubetailrb/reader/k8s_pod_reader.rb

Overview

Read Kubernetes pod logs.

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from WithK8sClient

#create_k8s_client, #k8s_client

Methods included from Validated

#raise_if_blank, #raise_if_nil, #validate_boolean, #validate_last_nb_lines

Constructor Details

#initialize(pod_name:, container_name:, opts:, k8s_client: nil) ⇒ K8sPodReader

Returns a new instance of K8sPodReader.



19
20
21
22
23
24
25
26
27
28
# File 'lib/kubetailrb/reader/k8s_pod_reader.rb', line 19

def initialize(pod_name:, container_name:, opts:, k8s_client: nil)
  validate(pod_name, container_name, opts)

  @k8s_client = k8s_client
  @pod_name = pod_name
  @container_name = container_name
  @formatter = create_formatter(opts, pod_name, container_name)
  @filter = Kubetailrb::Filter::LogFilter.create(opts.excludes)
  @opts = opts
end

Instance Attribute Details

#optsObject (readonly)

Returns the value of attribute opts.



17
18
19
# File 'lib/kubetailrb/reader/k8s_pod_reader.rb', line 17

def opts
  @opts
end

#pod_nameObject (readonly)

Returns the value of attribute pod_name.



17
18
19
# File 'lib/kubetailrb/reader/k8s_pod_reader.rb', line 17

def pod_name
  @pod_name
end

Instance Method Details

#readObject



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/kubetailrb/reader/k8s_pod_reader.rb', line 30

def read
  pod_logs = read_pod_logs
  unless @opts.follow?
    print_logs pod_logs
    return
  end

  # NOTE: The watch method from kubeclient does not accept `tail_lines`
  # argument, so I had to resort to some hack... by using the first log to
  # print out. Not ideal, since it's not really the N last nb lines, and
  # assume every logs are different, which may not be true.
  # But it does the job for most cases.
  first_log_to_display = pod_logs.to_s.split("\n").first
  should_print_logs = false

  k8s_client.watch_pod_log(@pod_name, @opts.namespace, container: @container_name) do |line|
    # NOTE: Is it good practice to update a variable that is outside of a
    # block? Can we do better?
    should_print_logs = true if line == first_log_to_display

    print_logs(line) if should_print_logs
  end
end