Class: Kubes::CLI::Exec

Inherits:
Base
  • Object
show all
Extended by:
Memoist
Includes:
Logging, Util::Sh
Defined in:
lib/kubes/cli/exec.rb

Instance Method Summary collapse

Methods included from Util::Sh

#sh, #sh_capture

Methods included from Logging

#logger

Methods inherited from Base

#compile, #initialize, #pod_name

Constructor Details

This class inherits a constructor from Kubes::CLI::Base

Instance Method Details

#default_execObject



27
28
29
# File 'lib/kubes/cli/exec.rb', line 27

def default_exec
  ENV['KUBES_DEFAULT_EXEC'] || "sh"
end

#deployment_podObject



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/kubes/cli/exec.rb', line 45

def deployment_pod
  return unless 
  labels = ['labels'].map { |k,v| "#{k}=#{v}" }.join(',')
  ns = ['namespace']

  resp = sh_capture("kubectl get pod -l #{labels} -n #{ns} -o json")
  data = JSON.load(resp)
  pod = latest_pod(data['items'])

  unless pod
    logger.error "ERROR: Unable to find a running pod".color(:red)
    exit 1
  end

  pod['metadata']['name']
end

#find_podObject



31
32
33
# File 'lib/kubes/cli/exec.rb', line 31

def find_pod
  pod_name || deployment_pod
end

#latest_pod(items) ⇒ Object

get latest running pod



63
64
65
66
67
# File 'lib/kubes/cli/exec.rb', line 63

def latest_pod(items)
  running = items.select { |i| i['status']['phase'] == 'Running' }
  sorted = running.sort_by { |i| i['metadata']['creationTimestamp'] || 0 }
  sorted.last
end

#metadataObject



39
40
41
42
# File 'lib/kubes/cli/exec.rb', line 39

def 
  deployment = Kubes::Kubectl::Fetch::Deployment.new(@options)
  deployment. if deployment.found
end

#nsObject



35
36
37
# File 'lib/kubes/cli/exec.rb', line 35

def ns
  "-n #{['namespace']}" if 
end

#runObject



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/kubes/cli/exec.rb', line 7

def run
  compile
  pod = find_pod

  unless pod
    logger.info <<~EOL
      Unable to find a pod to exec into. This means there was no deployment found.
      You can also try using the -p option and specifying enough of the pod name. Example:

          kubes exec -p web

    EOL
    exit 1
  end

  container = " -c #{@options[:container]}" unless @options[:container].nil?
  cmd = @options[:cmd].empty? ? default_exec : @options[:cmd].join(' ')
  sh("kubectl exec #{ns} -ti #{pod}#{container} -- #{cmd}")
end