debian-mirror-gitlab/lib/quality/kubernetes_client.rb

85 lines
2.3 KiB
Ruby
Raw Normal View History

2018-12-05 23:21:45 +05:30
# frozen_string_literal: true
require_relative '../gitlab/popen' unless defined?(Gitlab::Popen)
module Quality
class KubernetesClient
2020-01-01 13:55:28 +05:30
RESOURCE_LIST = 'ingress,svc,pdb,hpa,deploy,statefulset,job,pod,secret,configmap,pvc,secret,clusterrole,clusterrolebinding,role,rolebinding,sa,crd'
2018-12-13 13:39:08 +05:30
CommandFailedError = Class.new(StandardError)
2018-12-05 23:21:45 +05:30
attr_reader :namespace
2018-12-13 13:39:08 +05:30
def initialize(namespace:)
2018-12-05 23:21:45 +05:30
@namespace = namespace
end
2019-12-26 22:10:19 +05:30
def cleanup(release_name:, wait: true)
2020-01-01 13:55:28 +05:30
delete_by_selector(release_name: release_name, wait: wait)
delete_by_matching_name(release_name: release_name)
end
private
def delete_by_selector(release_name:, wait:)
2019-12-26 22:10:19 +05:30
selector = case release_name
when String
%(-l release="#{release_name}")
when Array
%(-l 'release in (#{release_name.join(', ')})')
else
raise ArgumentError, 'release_name must be a string or an array'
end
2018-12-13 13:39:08 +05:30
command = [
'delete',
2020-01-01 13:55:28 +05:30
RESOURCE_LIST,
%(--namespace "#{namespace}"),
2018-12-13 13:39:08 +05:30
'--now',
2019-07-31 22:56:46 +05:30
'--ignore-not-found',
'--include-uninitialized',
2019-12-26 22:10:19 +05:30
%(--wait=#{wait}),
selector
2018-12-13 13:39:08 +05:30
]
2018-12-05 23:21:45 +05:30
run_command(command)
end
2020-01-01 13:55:28 +05:30
def delete_by_matching_name(release_name:)
resource_names = raw_resource_names
command = [
'delete',
%(--namespace "#{namespace}")
]
Array(release_name).each do |release|
resource_names
.select { |resource_name| resource_name.include?(release) }
.each { |matching_resource| run_command(command + [matching_resource]) }
end
end
def raw_resource_names
command = [
'get',
RESOURCE_LIST,
%(--namespace "#{namespace}"),
'-o custom-columns=NAME:.metadata.name'
]
run_command(command).lines.map(&:strip)
end
2018-12-05 23:21:45 +05:30
def run_command(command)
2018-12-13 13:39:08 +05:30
final_command = ['kubectl', *command].join(' ')
puts "Running command: `#{final_command}`" # rubocop:disable Rails/Output
result = Gitlab::Popen.popen_with_detail([final_command])
2018-12-05 23:21:45 +05:30
2018-12-13 13:39:08 +05:30
if result.status.success?
result.stdout.chomp.freeze
else
raise CommandFailedError, "The `#{final_command}` command failed (status: #{result.status}) with the following error:\n#{result.stderr}"
end
2018-12-05 23:21:45 +05:30
end
end
end