forked from Qovery/pleco
/
namespaces.go
101 lines (83 loc) · 2.68 KB
/
namespaces.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package k8s
import (
"context"
"fmt"
"github.com/MacLikorne/pleco/utils"
log "github.com/sirupsen/logrus"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"strconv"
"time"
)
type kubernetesNamespace struct {
Name string
NamespaceCreateTime time.Time
Status string
TTL int64
}
func listTaggedNamespaces(clientSet *kubernetes.Clientset, tagName string) ([]kubernetesNamespace, error) {
var taggedNamespaces []kubernetesNamespace
listOptions := metav1.ListOptions{
LabelSelector: tagName,
}
log.Debugf("Listing all Kubernetes namespaces with %s label", tagName)
namespaces, err := clientSet.CoreV1().Namespaces().List(context.TODO(), listOptions)
if err != nil {
return taggedNamespaces, err
}
if len(namespaces.Items) == 0 {
log.Debug("No Kubernetes namespaces with ttl were found")
return taggedNamespaces, nil
}
for _, namespace := range namespaces.Items {
for key, value := range namespace.ObjectMeta.Labels {
if key == tagName {
ttlValue, err := strconv.Atoi(value)
if err != nil {
log.Errorf("ttl value unrecognized for namespace %s", namespace.Name)
continue
}
taggedNamespaces = append(taggedNamespaces, kubernetesNamespace{
Name: namespace.Name,
NamespaceCreateTime: namespace.CreationTimestamp.Time,
Status: string(namespace.Status.Phase),
TTL: int64(ttlValue),
})
}
}
}
return taggedNamespaces, nil
}
func deleteNamespace(clientSet *kubernetes.Clientset, namespace kubernetesNamespace, dryRun bool) error {
deleteOptions := metav1.DeleteOptions{}
if namespace.Status == "Terminating" {
log.Infof("Namespace %s is already in Terminating state, skipping...", namespace.Name)
return nil
} else if namespace.Status != "Active" {
log.Warnf("Can't delete namespace %s because it is in %s state", namespace.Name, namespace.Status)
return nil
}
log.Infof("Deleting namespace %s, expired after %d seconds", namespace.Name, namespace.TTL)
if !dryRun {
err := clientSet.CoreV1().Namespaces().Delete(context.TODO(), namespace.Name, deleteOptions)
if err != nil {
return err
}
}
return nil
}
func DeleteExpiredNamespaces(clientSet *kubernetes.Clientset, tagName string, dryRun bool) error {
namespaces, err := listTaggedNamespaces(clientSet, tagName)
if err != nil {
return fmt.Errorf("can't list kubernetes namespaces: %s\n", err)
}
for _, namespace := range namespaces {
if utils.CheckIfExpired(namespace.NamespaceCreateTime, namespace.TTL, namespace.Name) {
err := deleteNamespace(clientSet, namespace, dryRun)
if err != nil {
log.Errorf("error while trying to delete namespace: %s", err)
}
}
}
return nil
}