Class: K8sKit::Context

Inherits:
Object
  • Object
show all
Defined in:
lib/k8s_kit/context.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(namespace: nil) ⇒ Context

Returns a new instance of Context.



7
8
9
# File 'lib/k8s_kit/context.rb', line 7

def initialize(namespace: nil)
  @namespace = namespace
end

Instance Attribute Details

#namespaceObject (readonly)

Returns the value of attribute namespace.



5
6
7
# File 'lib/k8s_kit/context.rb', line 5

def namespace
  @namespace
end

Instance Method Details

#job(name) ⇒ Object



39
40
41
# File 'lib/k8s_kit/context.rb', line 39

def job(name)
  Job.new(self, name)
end

#kubectlObject



11
12
13
14
# File 'lib/k8s_kit/context.rb', line 11

def kubectl
  ns = namespace ? "-n #{namespace}" : ''
  "kubectl #{ns}"
end

#pod(name) ⇒ Object



35
36
37
# File 'lib/k8s_kit/context.rb', line 35

def pod(name)
  Pod.new(self, name)
end

#run(cmd, silent: true) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/k8s_kit/context.rb', line 16

def run(cmd, silent: true)
  cmd = "#{kubectl} #{cmd}"

  out = []
  Open3.popen2e(cmd) do |stdin, stdout_err, wait_thr|
    while line = stdout_err.gets
      puts line unless silent
      out << line
    end

    exit_status = wait_thr.value
    unless exit_status.success?
      abort "Failed: #{cmd}"
    end
  end

  out.join("\n").chomp
end

#wait_for_all_pods_ready(timeout: 300) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/k8s_kit/context.rb', line 43

def wait_for_all_pods_ready(timeout: 300)
  t0 = Time.now

  print 'Waiting for all pods to be ready...'
  loop do
    statuses = run('get pods -o jsonpath="{.items.*.status.containerStatuses[*].ready}"')
    if statuses.empty?
      puts ''
      raise StandardError, 'No pod could be found in the namespace'
    end

    return unless statuses.include?('false')

    if t0 + timeout < Time.now
      puts ''
      raise StandardError, 'Timeout while waiting for pods to become ready'
    end

    print '.'
    sleep 2
  end
end