forked from rancher/rancher
/
owner.go
75 lines (61 loc) · 1.76 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
package workload
import (
"fmt"
"strings"
"github.com/rancher/norman/api/access"
"github.com/rancher/norman/types"
"github.com/rancher/norman/types/definition"
"github.com/rancher/norman/types/values"
"github.com/rancher/types/apis/project.cattle.io/v3/schema"
"github.com/rancher/types/client/project/v3"
)
func OwnerMap(context *types.APIContext) (map[string]string, error) {
result := map[string]string{}
var workloads []client.Workload
if err := access.List(context, &schema.Version, client.WorkloadType, &types.QueryOptions{
Options: map[string]string{
"hidden": "true",
},
}, &workloads); err != nil {
return nil, err
}
for _, workload := range workloads {
for _, owner := range workload.OwnerReferences {
if owner.Controller != nil && *owner.Controller {
id := key(definition.GetShortTypeFromFull(workload.Type), workload.Name)
result[id] = key(owner.Kind, owner.Name)
}
}
}
return result, nil
}
func ResolveWorkloadID(data map[string]interface{}, owners map[string]string) string {
workloadID := ""
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)
parent := key(kind, name)
workloadID = ""
for parent != "" {
workloadID = parent
parent = owners[workloadID]
}
}
if workloadID == "" {
return ""
}
parts := strings.SplitN(workloadID, "/", 2)
namespace, _ := data["namespaceId"].(string)
return fmt.Sprintf("%s:%s:%s", parts[0], namespace, parts[1])
}
func key(kind, name string) string {
return strings.ToLower(fmt.Sprintf("%s/%s", kind, name))
}