From 0eedd22c0cddb84b0f5819c748138fa9f67453ad Mon Sep 17 00:00:00 2001 From: Sebas Risco Date: Fri, 11 Sep 2020 13:54:18 +0200 Subject: [PATCH] Delete associated jobs when deleting a service --- pkg/backends/k8s.go | 26 ++++++++++++++++++++++++++ pkg/backends/openfaas.go | 5 +++++ 2 files changed, 31 insertions(+) diff --git a/pkg/backends/k8s.go b/pkg/backends/k8s.go index 525064d2..a7950e9c 100644 --- a/pkg/backends/k8s.go +++ b/pkg/backends/k8s.go @@ -191,6 +191,11 @@ func (k *KubeBackend) DeleteService(name string) error { log.Println(delErr.Error()) } + // Delete all the service's jobs + if err := deleteServiceJobs(name, k.namespace, k.kubeClientset); err != nil { + log.Printf("Error deleting associated jobs for service \"%s\": %v\n", name, err) + } + return nil } @@ -291,3 +296,24 @@ func deleteServiceConfigMap(name string, namespace string, kubeClientset *kubern return nil } + +func deleteServiceJobs(name string, namespace string, kubeClientset *kubernetes.Clientset) error { + // ListOptions to select all the associated jobs with the specified service + listOpts := metav1.ListOptions{ + LabelSelector: fmt.Sprintf("%s=%s", types.ServiceLabel, name), + } + + // Create DeleteOptions and configure PropagationPolicy for deleting associated pods in background + background := metav1.DeletePropagationBackground + delOpts := metav1.DeleteOptions{ + PropagationPolicy: &background, + } + + // Delete jobs + err := kubeClientset.BatchV1().Jobs(namespace).DeleteCollection(context.TODO(), delOpts, listOpts) + if err != nil { + return err + } + + return nil +} diff --git a/pkg/backends/openfaas.go b/pkg/backends/openfaas.go index a3d9a733..064c1aa0 100644 --- a/pkg/backends/openfaas.go +++ b/pkg/backends/openfaas.go @@ -291,6 +291,11 @@ func (of *OpenfaasBackend) DeleteService(name string) error { log.Println(delErr.Error()) } + // Delete all the service's jobs + if err := deleteServiceJobs(name, of.namespace, of.kubeClientset); err != nil { + log.Printf("Error deleting associated jobs for service \"%s\": %v\n", name, err) + } + return nil }