2015-07-27 15:17:44 +00:00
|
|
|
import os
|
|
|
|
import logging
|
|
|
|
import json
|
|
|
|
import base64
|
|
|
|
|
|
|
|
from requests import Request, Session
|
|
|
|
|
|
|
|
from util.config.provider.baseprovider import get_yaml, CannotWriteConfigException
|
|
|
|
from util.config.provider.fileprovider import FileConfigProvider
|
|
|
|
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
2015-11-13 22:05:14 +00:00
|
|
|
KUBERNETES_API_HOST = os.environ.get('KUBERNETES_SERVICE_HOST', '')
|
|
|
|
port = os.environ.get('KUBERNETES_SERVICE_PORT')
|
|
|
|
if port:
|
|
|
|
KUBERNETES_API_HOST += ':' + port
|
2015-07-27 15:17:44 +00:00
|
|
|
|
|
|
|
SERVICE_ACCOUNT_TOKEN_PATH = '/var/run/secrets/kubernetes.io/serviceaccount/token'
|
|
|
|
|
2015-10-23 16:18:11 +00:00
|
|
|
QE_NAMESPACE = os.environ.get('QE_K8S_NAMESPACE', 'quay-enterprise')
|
|
|
|
QE_CONFIG_SECRET = os.environ.get('QE_K8S_CONFIG_SECRET', 'quay-enterprise-config-secret')
|
2015-07-27 15:17:44 +00:00
|
|
|
|
|
|
|
class KubernetesConfigProvider(FileConfigProvider):
|
|
|
|
""" Implementation of the config provider that reads and writes configuration
|
|
|
|
data from a Kubernetes Secret. """
|
|
|
|
def __init__(self, config_volume, yaml_filename, py_filename):
|
|
|
|
super(KubernetesConfigProvider, self).__init__(config_volume, yaml_filename, py_filename)
|
|
|
|
|
|
|
|
self.yaml_filename = yaml_filename
|
|
|
|
|
|
|
|
# Load the service account token from the local store.
|
|
|
|
if not os.path.exists(SERVICE_ACCOUNT_TOKEN_PATH):
|
|
|
|
raise Exception('Cannot load Kubernetes service account token')
|
|
|
|
|
|
|
|
with open(SERVICE_ACCOUNT_TOKEN_PATH, 'r') as f:
|
|
|
|
self._service_token = f.read()
|
|
|
|
|
|
|
|
# Make sure the configuration volume exists.
|
|
|
|
if not self.volume_exists():
|
|
|
|
os.makedirs(config_volume)
|
|
|
|
|
|
|
|
@property
|
|
|
|
def provider_id(self):
|
|
|
|
return 'k8s'
|
|
|
|
|
|
|
|
def save_config(self, config_obj):
|
|
|
|
self._update_secret_file(self.yaml_filename, get_yaml(config_obj))
|
|
|
|
super(KubernetesConfigProvider, self).save_config(config_obj)
|
|
|
|
|
2015-12-08 20:00:50 +00:00
|
|
|
def write_volume_file(self, filename, contents):
|
|
|
|
super(KubernetesConfigProvider, self).write_volume_file(filename, contents)
|
|
|
|
|
|
|
|
try:
|
|
|
|
self._update_secret_file(filename, contents)
|
|
|
|
except IOError as ioe:
|
|
|
|
raise CannotWriteConfigException(str(ioe))
|
|
|
|
|
2016-12-09 22:37:26 +00:00
|
|
|
def remove_volume_file(self, filename):
|
|
|
|
super(KubernetesConfigProvider, self).remove_volume_file(filename)
|
2015-07-27 15:17:44 +00:00
|
|
|
|
|
|
|
try:
|
2016-12-09 22:37:26 +00:00
|
|
|
self._update_secret_file(filename, None)
|
2015-07-27 15:17:44 +00:00
|
|
|
except IOError as ioe:
|
|
|
|
raise CannotWriteConfigException(str(ioe))
|
|
|
|
|
2016-12-09 22:37:26 +00:00
|
|
|
def save_volume_file(self, filename, flask_file):
|
|
|
|
filepath = super(KubernetesConfigProvider, self).save_volume_file(filename, flask_file)
|
|
|
|
with open(filepath, 'r') as f:
|
|
|
|
self.write_volume_file(filename, f.read())
|
|
|
|
|
2015-07-27 15:17:44 +00:00
|
|
|
def _assert_success(self, response):
|
|
|
|
if response.status_code != 200:
|
2016-08-26 17:50:22 +00:00
|
|
|
logger.error('Kubernetes API call failed with response: %s => %s', response.status_code,
|
2015-07-27 15:17:44 +00:00
|
|
|
response.text)
|
2016-08-26 17:50:22 +00:00
|
|
|
raise CannotWriteConfigException('Kubernetes API call failed: %s' % response.text)
|
2015-07-27 15:17:44 +00:00
|
|
|
|
2016-12-09 22:37:26 +00:00
|
|
|
def _update_secret_file(self, filename, value=None):
|
2016-08-26 17:50:22 +00:00
|
|
|
# Check first that the namespace for Quay Enterprise exists. If it does not, report that
|
|
|
|
# as an error, as it seems to be a common issue.
|
|
|
|
namespace_url = 'namespaces/%s' % (QE_NAMESPACE)
|
|
|
|
response = self._execute_k8s_api('GET', namespace_url)
|
2016-12-09 23:31:02 +00:00
|
|
|
if response.status_code // 100 != 2:
|
2016-08-26 17:50:22 +00:00
|
|
|
msg = 'A Kubernetes namespace with name `%s` must be created to save config' % QE_NAMESPACE
|
|
|
|
raise CannotWriteConfigException(msg)
|
|
|
|
|
2016-12-09 22:37:26 +00:00
|
|
|
# Check if the secret exists. If not, then we create an empty secret and then update the file
|
|
|
|
# inside.
|
2015-10-23 16:18:11 +00:00
|
|
|
secret_url = 'namespaces/%s/secrets/%s' % (QE_NAMESPACE, QE_CONFIG_SECRET)
|
2015-07-27 15:17:44 +00:00
|
|
|
secret = self._lookup_secret()
|
2016-12-09 22:37:26 +00:00
|
|
|
if secret is None:
|
|
|
|
self._assert_success(self._execute_k8s_api('POST', secret_url, {
|
|
|
|
"kind": "Secret",
|
|
|
|
"apiVersion": "v1",
|
|
|
|
"metadata": {
|
|
|
|
"name": QE_CONFIG_SECRET
|
|
|
|
},
|
|
|
|
"data": {}
|
|
|
|
}))
|
|
|
|
|
|
|
|
# Update the secret to reflect the file change.
|
|
|
|
secret['data'] = secret.get('data', {})
|
|
|
|
|
|
|
|
if value is not None:
|
|
|
|
secret['data'][filename] = base64.b64encode(value)
|
|
|
|
else:
|
|
|
|
secret['data'].pop(filename)
|
2015-07-27 15:17:44 +00:00
|
|
|
|
|
|
|
self._assert_success(self._execute_k8s_api('PUT', secret_url, secret))
|
|
|
|
|
|
|
|
|
|
|
|
def _lookup_secret(self):
|
2015-10-23 16:18:11 +00:00
|
|
|
secret_url = 'namespaces/%s/secrets/%s' % (QE_NAMESPACE, QE_CONFIG_SECRET)
|
2015-07-27 15:17:44 +00:00
|
|
|
response = self._execute_k8s_api('GET', secret_url)
|
|
|
|
if response.status_code != 200:
|
|
|
|
return None
|
|
|
|
|
|
|
|
return json.loads(response.text)
|
|
|
|
|
|
|
|
def _execute_k8s_api(self, method, relative_url, data=None):
|
|
|
|
headers = {
|
|
|
|
'Authorization': 'Bearer ' + self._service_token
|
|
|
|
}
|
|
|
|
|
|
|
|
if data:
|
|
|
|
headers['Content-Type'] = 'application/json'
|
|
|
|
|
|
|
|
data = json.dumps(data) if data else None
|
|
|
|
session = Session()
|
|
|
|
url = 'https://%s/api/v1/%s' % (KUBERNETES_API_HOST, relative_url)
|
|
|
|
|
|
|
|
request = Request(method, url, data=data, headers=headers)
|
|
|
|
return session.send(request.prepare(), verify=False, timeout=2)
|