forked from rancher/rancher
-
Notifications
You must be signed in to change notification settings - Fork 1
/
namespace_utils.go
117 lines (102 loc) · 2.45 KB
/
namespace_utils.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
package namespace
import (
"encoding/json"
"time"
"k8s.io/api/core/v1"
)
const (
statusAnn = "cattle.io/status"
GlobalNamespace = "cattle-global-data"
)
func SetNamespaceCondition(namespace *v1.Namespace, d time.Duration, conditionType string, conditionStatus bool, message string) error {
annotations := namespace.ObjectMeta.Annotations
if annotations == nil {
annotations = map[string]string{}
}
ann := annotations[statusAnn]
conditionStatusStr := "False"
if conditionStatus {
conditionStatusStr = "True"
}
bAnn, err := GenerateConditionAnnotation(ann, d, conditionType, conditionStatusStr, message)
if err != nil {
return err
}
annotations[statusAnn] = bAnn
namespace.ObjectMeta.Annotations = annotations
return nil
}
func GenerateConditionAnnotation(ann string, d time.Duration, conditionType string, conditionStatus string, message string) (string, error) {
status := &status{}
if ann != "" {
err := json.Unmarshal([]byte(ann), status)
if err != nil {
return "", err
}
}
if status.Conditions == nil {
status.Conditions = []condition{}
}
var idx int
found := false
for i, c := range status.Conditions {
if c.Type == conditionType {
idx = i
found = true
break
}
}
conditionMessage := ""
if conditionStatus != "True" {
conditionMessage = message
}
cond := condition{
Type: conditionType,
Status: conditionStatus,
Message: conditionMessage,
LastUpdateTime: time.Now().Add(d).Format(time.RFC3339),
}
if found {
status.Conditions[idx] = cond
} else {
status.Conditions = append(status.Conditions, cond)
}
bAnn, err := json.Marshal(status)
if err != nil {
return "", err
}
return string(bAnn), nil
}
func IsNamespaceConditionSet(namespace *v1.Namespace, conditionType string, conditionStatus bool) (bool, error) {
if namespace.ObjectMeta.Annotations == nil {
return false, nil
}
ann := namespace.ObjectMeta.Annotations[statusAnn]
if ann == "" {
return false, nil
}
status := &status{}
err := json.Unmarshal([]byte(ann), status)
if err != nil {
return false, err
}
conditionStatusStr := "False"
if conditionStatus {
conditionStatusStr = "True"
}
for _, c := range status.Conditions {
if c.Type == conditionType && c.Status == conditionStatusStr {
return true, nil
}
}
return false, nil
}
type status struct {
Conditions []condition
}
type condition struct {
Type string
Status string
Message string
LastUpdateTime string
}