-
Notifications
You must be signed in to change notification settings - Fork 0
/
owner.go
110 lines (89 loc) · 2.33 KB
/
owner.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
package pod
import (
"fmt"
"time"
"strings"
"github.com/rancher/norman/api/access"
"github.com/rancher/norman/types"
"github.com/rancher/norman/types/values"
"github.com/rancher/rancher/pkg/controllers/user/workload"
"github.com/rancher/rancher/pkg/ref"
"github.com/rancher/types/apis/project.cattle.io/v3/schema"
"github.com/sirupsen/logrus"
"k8s.io/apimachinery/pkg/util/cache"
)
var (
replicaSetOwnerCache = cache.NewLRUExpireCache(1000)
)
type key struct {
SubContext string
Namespace string
ReplicaSetName string
}
type value struct {
Kind string
Name string
}
func getReplicaSetOwner(apiContext *types.APIContext, namespace, name string) (string, string, error) {
subContext := apiContext.SubContext["/v3/schemas/project"]
if subContext == "" {
subContext = apiContext.SubContext["/v3/schemas/cluster"]
}
if subContext == "" {
logrus.Warnf("failed to find subcontext to lookup replicaSet owner")
return "", "", nil
}
key := key{
SubContext: subContext,
Namespace: namespace,
ReplicaSetName: name,
}
val, ok := replicaSetOwnerCache.Get(key)
if ok {
value, _ := val.(value)
return value.Kind, value.Name, nil
}
data := map[string]interface{}{}
if err := access.ByID(apiContext, &schema.Version, workload.ReplicaSetType, ref.FromStrings(namespace, name), &data); err != nil {
return "", "", err
}
kind, name := getOwner(data)
replicaSetOwnerCache.Add(key, value{
Kind: kind,
Name: name,
}, time.Hour)
return kind, name, nil
}
func getOwner(data map[string]interface{}) (string, string) {
ownerReferences, ok := values.GetSlice(data, "ownerReferences")
if !ok {
return "", ""
}
for _, ownerReference := range ownerReferences {
controller, _ := ownerReference["controller"].(bool)
if !controller {
continue
}
kind, _ := ownerReference["kind"].(string)
name, _ := ownerReference["name"].(string)
return kind, name
}
return "", ""
}
func resolveWorkloadID(apiContext *types.APIContext, data map[string]interface{}) string {
kind, name := getOwner(data)
if kind == "" {
return ""
}
namespace, _ := data["namespaceId"].(string)
if kind == "ReplicaSet" {
k, n, err := getReplicaSetOwner(apiContext, namespace, name)
if err != nil {
return ""
}
if k != "" {
kind, name = k, n
}
}
return strings.ToLower(fmt.Sprintf("%s:%s:%s", kind, namespace, name))
}