2018-11-16 19:37:17 -05:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2017-11-07 07:50:39 -05:00
|
|
|
module Gitlab
|
|
|
|
module Kubernetes
|
|
|
|
class Namespace
|
2020-01-17 01:08:39 -05:00
|
|
|
attr_accessor :name, :labels
|
2017-11-07 07:50:39 -05:00
|
|
|
|
2020-01-17 01:08:39 -05:00
|
|
|
def initialize(name, client, labels: nil)
|
2017-11-07 11:51:30 -05:00
|
|
|
@name = name
|
2017-11-07 07:50:39 -05:00
|
|
|
@client = client
|
2020-01-17 01:08:39 -05:00
|
|
|
@labels = labels
|
2017-11-07 07:50:39 -05:00
|
|
|
end
|
|
|
|
|
|
|
|
def exists?
|
|
|
|
@client.get_namespace(name)
|
2018-11-13 07:46:01 -05:00
|
|
|
rescue ::Kubeclient::ResourceNotFoundError
|
2017-11-07 07:50:39 -05:00
|
|
|
false
|
|
|
|
end
|
|
|
|
|
|
|
|
def create!
|
2020-01-17 01:08:39 -05:00
|
|
|
resource = ::Kubeclient::Resource.new(metadata: { name: name, labels: labels })
|
2017-11-07 07:50:39 -05:00
|
|
|
|
2019-04-10 02:38:27 -04:00
|
|
|
log_event(:begin_create)
|
2017-11-07 07:50:39 -05:00
|
|
|
@client.create_namespace(resource)
|
|
|
|
end
|
|
|
|
|
|
|
|
def ensure_exists!
|
|
|
|
exists? || create!
|
2019-04-10 02:38:27 -04:00
|
|
|
rescue ::Kubeclient::HttpError => error
|
|
|
|
log_create_failed(error)
|
|
|
|
raise
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def log_create_failed(error)
|
|
|
|
logger.error({
|
2020-02-19 01:09:21 -05:00
|
|
|
exception: {
|
|
|
|
class: error.class.name,
|
|
|
|
message: error.message
|
|
|
|
},
|
2019-04-10 02:38:27 -04:00
|
|
|
status_code: error.error_code,
|
|
|
|
namespace: name,
|
|
|
|
class_name: self.class.name,
|
2020-02-19 01:09:21 -05:00
|
|
|
event: :failed_to_create_namespace
|
2019-04-10 02:38:27 -04:00
|
|
|
})
|
|
|
|
end
|
|
|
|
|
|
|
|
def log_event(event)
|
|
|
|
logger.info(
|
|
|
|
namespace: name,
|
|
|
|
class_name: self.class.name,
|
|
|
|
event: event
|
|
|
|
)
|
|
|
|
end
|
|
|
|
|
|
|
|
def logger
|
|
|
|
@logger ||= Gitlab::Kubernetes::Logger.build
|
2017-11-07 07:50:39 -05:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|