db-deployer/api.py
Chris Cowley 74ebf0521b Linting
2024-09-30 17:35:25 +02:00

121 lines
3.3 KiB
Python

import os
import random
from flask import (
Flask,
)
from flask_restful import (
Resource,
Api
)
from kubernetes import client as k8s_client
from kubernetes.client import api_client
from kubernetes import (
config,
dynamic
)
# from kubernetes.dynamic.exceptions import ResourceNotFoundError
app = Flask(__name__)
api = Api(app)
if "KUBERNETES_SERVICE_HOST" in os.environ:
config.load_incluster_config()
else:
config.load_kube_config()
v1 = k8s_client.CoreV1Api()
client = dynamic.DynamicClient(
api_client.ApiClient(configuration=config.load_kube_config())
)
custom_object_api = k8s_client.CustomObjectsApi()
first_names = ['Ada', 'Bela', 'Cade', 'Dax', 'Eva',
'Fynn', 'Gia', 'Hugo', 'Ivy', 'Jax']
last_names = ['Smith', 'Johnson', 'Williams', 'Jones', 'Brown', 'Davis',
'Miller', 'Wilson', 'Moore', 'Taylor']
def create_name():
first_name = random.choice(first_names)
last_name = random.choice(last_names)
return f"{first_name}{last_name}"
class DBCluster(Resource):
def get(self):
namespace = "test"
clusters = []
mariadb_resource = client.resources.get(
api_version='k8s.mariadb.com/v1alpha1',
kind='MariaDB'
)
mariadbs = mariadb_resource.get(namespace=namespace)
for mariadb in mariadbs.items:
name = mariadb.metadata.name
clusters.append({'name': name})
return clusters
def post(self):
namespace = "test"
name = random.choice(first_names).lower()
print(name)
mariadb = {
'apiVersion': 'k8s.mariadb.com/v1alpha1',
'kind': 'MariaDB',
'metadata': {
'name': name,
'namespace': namespace,
},
'spec': {
'rootPasswordSecretKeyRef': {
'name': 'mariadb-root',
'key': 'password',
'generate': True
},
'username': 'mariadb',
'passwordSecretKeyRef': {
'name': 'mariadb-password',
'key': 'password',
'generate': True
},
'port': 3306,
'storage': {
'size': '1Gi',
}
}
}
mariadb_instance = custom_object_api.create_namespaced_custom_object(
group='k8s.mariadb.com',
version='v1alpha1',
namespace=namespace,
plural='mariadbs',
body=mariadb
)
return mariadb_instance
class DBClusterDetails(Resource):
def get(self, name):
namespace = "test"
mariadb_resource = client.resources.get(
api_version='k8s.mariadb.com/v1alpha1',
kind='MariaDB'
)
mariadbs = mariadb_resource.get(namespace=namespace)
for mariadb in mariadbs.items:
if mariadb.metadata.name == name:
data = {
"name": mariadb.metadata.name,
"storage": mariadb.spec.storage.size,
}
return data
api.add_resource(DBCluster, '/clusters')
api.add_resource(DBClusterDetails, '/clusters/<string:name>')
if __name__ == '__main__':
app.run(host='0.0.0.0', debug=True)