Class: Minfra::Cli::Kube

Inherits:
Object
  • Object
show all
Includes:
Common, Logging
Defined in:
lib/minfra/cli/commands/kube.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Logging

#debug, #deprecated, #error, #exit_error, #info, #warn

Methods included from Common

#run_cmd

Constructor Details

#initialize(options, config) ⇒ Kube

Returns a new instance of Kube.



12
13
14
15
16
# File 'lib/minfra/cli/commands/kube.rb', line 12

def initialize(options, config)
  @options = options
  @config = config
  @env_config = config.orch_env_config
end

Instance Attribute Details

#configObject (readonly)

Returns the value of attribute config.



10
11
12
# File 'lib/minfra/cli/commands/kube.rb', line 10

def config
  @config
end

#env_configObject (readonly)

Returns the value of attribute env_config.



10
11
12
# File 'lib/minfra/cli/commands/kube.rb', line 10

def env_config
  @env_config
end

#optionsObject (readonly)

Returns the value of attribute options.



10
11
12
# File 'lib/minfra/cli/commands/kube.rb', line 10

def options
  @options
end

Instance Method Details

#createObject



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# File 'lib/minfra/cli/commands/kube.rb', line 31

def create
  $stdout.sync

  network_mask = @config.project.kind.network.mask
  gateway_ip = @config.project.kind.network.gateway
  panel_ip = @config.project.kind.panel.ip

  info "step: creating network #{kind_name} #{network_mask} gw #{gateway_ip}"
  # run(%{docker network inspect kind | grep "Subnet"}, exit_on_error: false).success?
  run(%(docker network rm #{kind_name}), exit_on_error: false)

  run(%(docker network create --gateway #{gateway_ip} --subnet=#{network_mask} #{kind_name}), exit_on_error: true)

  info "step: creating '#{kind_name}' kind cluster (can take some minutes)"
  kind_kube_path = Runner.run('echo $KUBECONFIG').to_s.strip
  kind_config = Templater.read(config.base_path.join('config', 'kind.yaml.erb'), params: { config: })
  File.write(config.kind_config_path, kind_config)

  run(%(KIND_EXPERIMENTAL_DOCKER_NETWORK=#{kind_name} kind create cluster --name "#{kind_name}" --config #{@config.kind_config_path}))

  info 'step: configuring kind'
  
  set_kind_dns
  
  configs = [YAML.safe_load(File.read(kind_kube_path))]

  existing_config = YAML.safe_load(File.read(kube_config_path))

  existing_config['clusters'] = existing_config['clusters'].reject do |c|
    configs.map do |k|
      k['clusters']
    end.flatten.map { |n| n['name'] }.include?(c['name'])
  end.concat(configs.map do |k|
               k['clusters']
             end.flatten)
  existing_config['users'] = existing_config['users'].reject do |c|
                               configs.map do |k|
                                 k['users']
                               end.flatten.map { |n| n['name'] }.include?(c['name'])
                             end.concat(configs.map do |k|
                                          k['users']
                                        end.flatten).uniq { |k| k['name'] }
  existing_config['contexts'] = existing_config['contexts'].reject do |c|
    configs.map do |k|
      k['contexts']
    end.flatten.map { |n| n['name'] }.include?(c['name'])
  end.concat(configs.map do |k|
               k['contexts']
             end.flatten)
  File.write(@config.kube_config_path, YAML.dump(existing_config))

  info 'step: starting kind'
  run_kubectl %( config use-context kind-#{kind_name} )

  run_kubectl %(create clusterrolebinding default-admin --serviceaccount=kube-system:default --clusterrole=cluster-admin)

  #        info "step: attaching newly created kind cluster to its own docker network"
  #        info run(%{docker network connect #{kind_name} #{kind_name}-control-plane --ip #{panel_ip}})
end

#dashboard(stack_name, env, deployment, cluster) ⇒ Object



18
19
20
21
22
23
24
# File 'lib/minfra/cli/commands/kube.rb', line 18

def dashboard(stack_name, env, deployment, cluster)
  stack = init(stack_name, env, deployment, cluster)
  insecure_flag = l('infra::allow_insecure_k8s_connections') ? '--insecure-skip-tls-verify' : ''
  cmd = "k9s #{insecure_flag} --kubeconfig #{kube_config_path} --context #{stack.cluster_name} --namespace #{stack_name} --command pod"
  debug(cmd)
  exec(cmd)
end

#deploy(stack_name, _reason_message) ⇒ Object



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
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
# File 'lib/minfra/cli/commands/kube.rb', line 101

def deploy(stack_name, _reason_message)
  # TBD: options is global, avoid it!

  test = options[:test]
  stack = init(stack_name,
               options[:environment],
               options[:deployment],
               options[:cluster])
  cluster = stack.cluster_name

  method = options['install'] ? 'install' : 'upgrade'

  stack.release_path.mkpath

  File.open(stack.compose_path, 'w') do |f|
    Orchparty::App.new(cluster_name: cluster,
                       application_name: stack.name,
                       force_variable_definition: false,
                       file_name: stack.stack_rb_path.to_s,
                       status_dir: stack.release_path,
                       options:)
                  .print(method:, out_io: f)
  end
  # run_cmd(generate_cmd, :bash)
  bash_cmd = ["cd #{stack.release_path}"]
  run_cmd(bash_cmd, :bash)

  run_cmd(["cd #{stack.release_path}",
           "git --no-pager diff #{stack.release_path}"], :bash, silence: true)
  # run_cmd("helm diff upgrade --allow-unreleased ccs-integration-service state/stacks/development-staging-1/ccs-integration-service/helm -n ccs-integration-service", :bash, silence: true)

  errors = stack.check_plan
  unless errors.empty?
    if config['force_mem']
      exit_error(errors.join("\n"))
    else
      warn(errors.join("\n"))
    end
  end

  return if test

  exit_error('Deployment aborted!') if !(@config.dev? || options[:force] == true) && !Ask.boolean('Are the changes ok?')

  orch = Orchparty::App.new(cluster_name: cluster,
                            application_name: stack.name,
                            force_variable_definition: false,
                            file_name: stack.stack_rb_path.to_s,
                            status_dir: stack.release_path,
                            options:)
  orch.send(method)
end

#destroy(stack_name) ⇒ Object



174
175
176
177
178
179
180
181
182
183
# File 'lib/minfra/cli/commands/kube.rb', line 174

def destroy(stack_name)
  stack = init(stack_name,
               options[:environment],
               options[:deployment],
               options[:cluster])
  # Our convention is that our stack name is the namespace in helm.
  # Sometimes the helm release name can be the same as the stack name (usually in the normal stacks).
  # However, stacks that combine multiple helm charts have the release name different from the stack name, that's why we have to list them all in a sub-command.
  run_helm(%{uninstall --namespace #{stack_name} --kube-context #{stack.cluster_name} $(helm list --namespace #{stack_name} --kube-context #{stack.cluster_name} --short)})
end

#destroy_dev_clusterObject



95
96
97
98
99
# File 'lib/minfra/cli/commands/kube.rb', line 95

def destroy_dev_cluster
  run %(kind delete cluster --name #{kind_name})
  run(%(docker rm -f #{kind_name}-control-plane), exit_on_error: false)
  run(%(docker network rm #{kind_name}), exit_on_error: false)
end

#kubectl_command(args) ⇒ Object



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
# File 'lib/minfra/cli/commands/kube.rb', line 185

def kubectl_command(args)
  exit_error('You must specify a stack name (--stack).') unless options['stack']

  subcommand = args.shift

  if %w[exec logs port-forward].include?(subcommand)
    resource = nil
    implicit_resource = 'pod'
  else
    resource = args.shift
  end

  stack = init(options[:stack],
               options[:environment],
               options[:deployment],
               options[:cluster])

  cluster = stack.cluster_name
  if [resource,
      implicit_resource].include?('pod') && %w[delete describe exec logs port-forward].include?(subcommand)
    cmd_get_pods = "--kubeconfig #{kube_config_path} --context #{cluster} --namespace #{options[:stack]} get pod -o jsonpath='{range .items[*]}{.metadata.name}{\"\\n\"}'"

    pods_list = run_kubectl(cmd_get_pods).stdout_lines

    fuzzy_pod_name = args.shift

    matching_pods = pods_list.select { |p| p.include?(fuzzy_pod_name) }

    exit_error("Could not find any pods that have '#{fuzzy_pod_name}' in their name.") if matching_pods.empty?

    position = 0
    if options[:position]
      p = options[:position].to_i
      if p <= matching_pods.size
        position = p - 1
      else
        exit_error("You specified '--position #{options[:position]} but only #{matching_pods.size} pods matched the name.")
      end
    end

    pod_name = matching_pods[position]
  end

  extra_args = args.dup

  if subcommand == 'exec'
    subcommand = 'exec -ti'
    extra_args.unshift('--')
    extra_args << 'bash' if args.empty?
  end

  extra_args = extra_args.join(' ')

  cmd = "--kubeconfig #{kube_config_path} --context #{cluster} --namespace #{options[:stack]} #{subcommand} #{resource} #{pod_name} #{extra_args}"
  KubeCtlRunner.run(cmd, runner: :exec)
end

#listObject



170
171
172
# File 'lib/minfra/cli/commands/kube.rb', line 170

def list
  puts run_helm(%(list --all-namespaces))
end

#push(image) ⇒ Object



91
92
93
# File 'lib/minfra/cli/commands/kube.rb', line 91

def push(image)
  run %(kind load docker-image --name #{kind_name} #{image})
end

#restartObject



26
27
28
29
# File 'lib/minfra/cli/commands/kube.rb', line 26

def restart
  run %(docker start #{kind_name}-control-plane)
  set_kind_dns
end

#rollback(stack_name, env, deployment, cluster) ⇒ Object



154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
# File 'lib/minfra/cli/commands/kube.rb', line 154

def rollback(stack_name, env, deployment, cluster)
  stack = init(stack_name,
               env,
               deployment,
               cluster)

  cluster = stack.cluster_name

  extra_args = args.dup
  extra_args.delete('rollback')

  extra_args = extra_args.join(' ')

  run_helm("--kube-context #{cluster} rollback #{options[:stack]} #{extra_args}")
end