unip-controller/controller/src/basic_resources/deployments.py
2025-04-15 20:56:15 +03:00

64 lines
No EOL
2.6 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# ============================================================
# Система: Единая библиотека, Центр ИИ НИУ ВШЭ
# Модуль: Управления базовыми объектами Kubernetes
# Авторы: Полежаев В.А., Хританков А.С.
# Дата создания: 2025 г.
# ============================================================
from datetime import datetime, timezone
from kubernetes.client import ApiClient, CoreV1Api, ApiException, AppsV1Api
def delete_deployment_if_exists(api_client: ApiClient, namespace: str, deployment_name: str, logger):
apps_v1_api: AppsV1Api = AppsV1Api(api_client)
try:
apps_v1_api.delete_namespaced_deployment(name=deployment_name, namespace=namespace)
except ApiException as exc:
if exc.status == 404:
logger.info(f"Deployment {deployment_name} doesnt exist, do nothing")
return
raise exc
logger.info(f"Deployment {deployment_name} is deleted")
def create_deployment(api_client: ApiClient, namespace, manifest):
apps_v1_api: AppsV1Api = AppsV1Api(api_client)
apps_v1_api.create_namespaced_deployment(namespace=namespace, body=manifest)
def create_or_update_deployment(api_client: ApiClient, name: str, namespace: str, manifest, logger):
apps_v1_api: AppsV1Api = AppsV1Api(api_client)
try:
apps_v1_api.create_namespaced_deployment(namespace=namespace, body=manifest)
logger.info(f"Deployment {name} is created")
except ApiException as exc:
if exc.status == 409:
logger.warning(f'Deployment {name} already exists, will be replaced')
apps_v1_api.replace_namespaced_deployment(name=name, namespace=namespace, body=manifest)
logger.info(f"Deployment {name} is replaced")
def restart_deployment_if_exists(api_client: ApiClient, name: str, namespace: str, logger):
apps_v1_api: AppsV1Api = AppsV1Api(api_client)
now = datetime.now(timezone.utc).replace(tzinfo=None)
now = now.isoformat("T") + "Z"
patch = {
'spec': {
'template': {
'metadata': {
'annotations': {
'kubectl.kubernetes.io/restartedAt': now
}
}
}
}
}
try:
apps_v1_api.patch_namespaced_deployment(name, namespace, patch)
except ApiException as exc:
if exc.status == 404:
logger.warn(f"Deployment {namespace}.{name} doesnt exist, do nothing")
return
raise exc
logger.info(f"Deployment {namespace}.{name} scheduled for restart")