Skip to content

Commit

Permalink
added applicationset and daemonsets
Browse files Browse the repository at this point in the history
  • Loading branch information
pavelzag committed Jan 31, 2024
1 parent 06c9de1 commit e0354d4
Show file tree
Hide file tree
Showing 2 changed files with 149 additions and 11 deletions.
65 changes: 58 additions & 7 deletions app/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
import time
from distutils import util

from kubernetes import client
from kubernetes import client, dynamic

from k8s_client.api_client import K8sApiClient

Expand All @@ -25,6 +25,8 @@

POD = 'pod'
DEPLOYMENT = 'deployment'
DAEMONSET = 'daemonset'
APPLICATIONSET = 'applicationset'
SERVICE = 'service'
NAMESPACE = 'namespace'
EXPIRATION_TIME = 'expiration_time'
Expand All @@ -38,7 +40,7 @@ def has_time_passed(epoch_time: int) -> bool:
return False


def delete_object(object_type: str, namespace: str, object_name: str, apps_api, core_api) -> None:
def delete_object(object_type: str, namespace: str, object_name: str, apps_api, core_api, dyn_client) -> None:
try:
if object_type == DEPLOYMENT:

Expand All @@ -51,6 +53,14 @@ def delete_object(object_type: str, namespace: str, object_name: str, apps_api,
)
)
logging.info(f"Deployment {object_name} deleted")
elif object_type == APPLICATIONSET:
applicationset_resource = dyn_client.resources.get(api_version='argoproj.io/v1alpha1',
kind='ApplicationSet')
dyn_client.delete(resource=applicationset_resource, name=object_name, namespace=namespace)
logging.info(f"{object_type.capitalize()} {object_name} deleted")
elif object_type == DAEMONSET:
apps_api.delete_namespaced_daemon_set(name=object_name, namespace=namespace)
logging.info(f"Daemonset {object_name} deleted")
elif object_type == POD:
core_api.delete_namespaced_pod(name=object_name, namespace=namespace)
logging.info(f"Pod {object_name} deleted")
Expand All @@ -67,17 +77,21 @@ def delete_object(object_type: str, namespace: str, object_name: str, apps_api,
def main():
parser = argparse.ArgumentParser(description='Kubernetes object management script')
parser.add_argument('--all-objects', action='store', help='Delete all objects', default="true")
parser.add_argument('--delete-applicationset', action='store', help='Delete applicationsets', default="false")
parser.add_argument('--delete-daemonset', action='store', help='Delete daemonsets', default="false")
parser.add_argument('--delete-deployment', action='store', help='Delete deployments', default="false")
parser.add_argument('--delete-pod', action='store', help='Delete pods', default="false")
parser.add_argument('--delete-service', action='store', help='Delete services', default="false")
parser.add_argument('--delete-namespace', action='store', help='Delete namespaces', default="false")
parser.add_argument('--debug-mode', action='store', help='Debug Mode', default="true")
parser.add_argument('--in-cluster-mode', action='store', help='InCluster Mode', default="true")
parser.add_argument('--context-name', action='store', help='Cluster Name', default="default")
parser.add_argument('--context-name', action='store', help='Cluster Name', default="minikube")

args = parser.parse_args()
all_objects = bool(util.strtobool(args.all_objects))
delete_deployment = bool(util.strtobool(args.delete_deployment))
delete_daemonset = bool(util.strtobool(args.delete_daemonset))
delete_applicationset = bool(util.strtobool(args.delete_applicationset))
delete_pod = bool(util.strtobool(args.delete_pod))
delete_service = bool(util.strtobool(args.delete_service))
delete_namespace = bool(util.strtobool(args.delete_namespace))
Expand All @@ -90,7 +104,41 @@ def main():
api_client = k8s_api.fetch_api_client()
core_api = client.CoreV1Api(api_client=api_client)
apps_api = client.AppsV1Api(api_client=api_client)
dyn_client = dynamic.DynamicClient(api_client)

if delete_applicationset or all_objects:
logging.info("\nChecking labels for Applicationsets to delete:")
try:
api_resource = dyn_client.resources.get(api_version='argoproj.io/v1alpha1',
kind='ApplicationSet')
application_sets = api_resource.get()
for appset in application_sets.items:
if appset.metadata.labels is not None:
if EXPIRATION_TIME in appset.metadata.labels.to_dict():
if appset.metadata.labels['expiration_time'].isdigit():
if has_time_passed(epoch_time=int(appset.metadata.labels['expiration_time'])):
logging.info(f'Expiration time is up for {appset.metadata.name} {APPLICATIONSET}')
delete_object(object_type=APPLICATIONSET, object_name=appset.metadata.name,
namespace=appset.metadata.namespace, apps_api=apps_api, core_api=core_api,
dyn_client=dyn_client)
except client.exceptions.ApiException as e:
logging.error(f'Failed to fetch deployments due to {e}')

if delete_daemonset or all_objects:
logging.info("\nChecking labels for Daemonsets to delete:")
try:
daemonsets = apps_api.list_daemon_set_for_all_namespaces(watch=False)
for ds in daemonsets.items:
if ds.metadata.labels is not None:
if EXPIRATION_TIME in ds.metadata.labels:
if ds.metadata.labels['expiration_time'].isdigit():
if has_time_passed(epoch_time=int(ds.metadata.labels['expiration_time'])):
logging.info(f'Expiration time is up for {ds.metadata.name} {DAEMONSET}')
delete_object(object_type=DAEMONSET, object_name=ds.metadata.name,
namespace=ds.metadata.namespace, apps_api=apps_api, core_api=core_api,
dyn_client=dyn_client)
except client.exceptions.ApiException as e:
logging.error(f'Failed to fetch deployments due to {e}')
if delete_deployment or all_objects:
logging.info("\nChecking labels for Deployments to delete:")
try:
Expand All @@ -102,7 +150,8 @@ def main():
if has_time_passed(epoch_time=int(dep.metadata.labels['expiration_time'])):
logging.info(f'Expiration time is up for {dep.metadata.name} {DEPLOYMENT}')
delete_object(object_type=DEPLOYMENT, object_name=dep.metadata.name,
namespace=dep.metadata.namespace, apps_api=apps_api, core_api=core_api)
namespace=dep.metadata.namespace, apps_api=apps_api, core_api=core_api,
dyn_client=dyn_client)
except client.exceptions.ApiException as e:
logging.error(f'Failed to fetch deployments due to {e}')

Expand All @@ -118,7 +167,7 @@ def main():
logging.info(f'Expiration time is up for {pod.metadata.name} {POD}')
delete_object(object_type=POD, namespace=pod.metadata.namespace,
object_name=pod.metadata.name,
apps_api=apps_api, core_api=core_api)
apps_api=apps_api, core_api=core_api, dyn_client=dyn_client)
except client.exceptions.ApiException as e:
logging.error(f'Failed to fetch pods due to {e}')

Expand All @@ -133,7 +182,8 @@ def main():
if has_time_passed(epoch_time=int(svc.metadata.labels['expiration_time'])):
logging.info(f'Expiration time is up for {svc.metadata.name} {SERVICE}')
delete_object(object_type=SERVICE, namespace=svc.metadata.namespace,
object_name=svc.metadata.name, apps_api=apps_api, core_api=core_api)
object_name=svc.metadata.name, apps_api=apps_api, core_api=core_api,
dyn_client=dyn_client)
except client.exceptions.ApiException as e:
logging.error(f'Failed to fetch services due to {e}')

Expand All @@ -148,7 +198,8 @@ def main():
if has_time_passed(epoch_time=int(ns.metadata.labels['expiration_time'])):
logging.info(f'Expiration time is up for {ns.metadata.name} {NAMESPACE}')
delete_object(object_type=NAMESPACE, namespace=ns.metadata.name,
object_name=ns.metadata.name, apps_api=apps_api, core_api=core_api)
object_name=ns.metadata.name, apps_api=apps_api, core_api=core_api,
dyn_client=dyn_client)
except client.exceptions.ApiException as e:
logging.error(f'Failed to fetch namespaces due to {e}')

Expand Down
95 changes: 91 additions & 4 deletions deployment/test_deployment.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,10 @@ spec:
expiration_time: "1706263086"
spec:
containers:
- name: nginx
image: nginx:latest
ports:
- containerPort: 80
- name: nginx
image: nginx:latest
ports:
- containerPort: 80

---

Expand All @@ -48,3 +48,90 @@ spec:
port: 80
targetPort: 80
type: NodePort

---
apiVersion: apps/v1
kind: DaemonSet
metadata:

name: busybox-daemonset
labels:
expiration_time: "1706448655"
spec:
selector:
matchLabels:
name: busybox-pod
template:
metadata:
labels:
name: busybox-pod
expiration_time: "1706448655"
spec:
containers:
- name: busybox-container
image: busybox
args:
- "/bin/sh"
- "-c"
- "while true; do sleep 3600; done"

---
apiVersion: argoproj.io/v1alpha1
kind: ApplicationSet
metadata:
name: example-applicationset
labels:
expiration_time: "1706448655"
namespace: argocd
spec:
generators:
- list:
elements:
- cluster: in-cluster
url: https://kubernetes.default.svc
template:
metadata:
name: '{{cluster}}-guestbook'
spec:
project: default
source:
repoURL: https://github.com/argoproj/argocd-example-apps.git
targetRevision: HEAD
path: guestbook
destination:
server: '{{url}}'
namespace: guestbook
---
apiVersion: argoproj.io/v1alpha1
kind: ApplicationSet
metadata:
name: httpd-applicationset
namespace: argocd
labels:
expiration_time: "1706448655"
spec:
generators:
- list:
elements:
- cluster: development
url: https://development-cluster-api-url
- cluster: staging
url: https://staging-cluster-api-url
- cluster: production
url: https://production-cluster-api-url
template:
metadata:
name: '{{cluster}}-httpd'
spec:
project: default
source:
repoURL: 'https://your-git-repository-url.git'
targetRevision: HEAD
path: path/to/your/httpd/application
destination:
server: '{{url}}'
namespace: your-namespace
syncPolicy:
automated:
selfHeal: true
prune: true

0 comments on commit e0354d4

Please sign in to comment.