1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package object
17
18 import (
19 "fmt"
20 "strings"
21
22 rbacv1 "k8s.io/api/rbac/v1"
23 "k8s.io/apimachinery/pkg/api/meta"
24 "k8s.io/apimachinery/pkg/runtime"
25 "k8s.io/apimachinery/pkg/runtime/schema"
26 )
27
28 const (
29
30
31
32 fieldSeparator = "_"
33
34
35 colonTranscoded = "__"
36 )
37
38 var (
39 NilObjMetadata = ObjMetadata{}
40 )
41
42
43
44 var RBACGroupKind = map[schema.GroupKind]bool{
45 {Group: rbacv1.GroupName, Kind: "Role"}: true,
46 {Group: rbacv1.GroupName, Kind: "ClusterRole"}: true,
47 {Group: rbacv1.GroupName, Kind: "RoleBinding"}: true,
48 {Group: rbacv1.GroupName, Kind: "ClusterRoleBinding"}: true,
49 }
50
51
52
53
54 type ObjMetadata struct {
55 Namespace string
56 Name string
57 GroupKind schema.GroupKind
58 }
59
60
61
62
63
64
65
66
67
68
69
70 func ParseObjMetadata(s string) (ObjMetadata, error) {
71
72 index := strings.Index(s, fieldSeparator)
73 if index == -1 {
74 return NilObjMetadata, fmt.Errorf("unable to parse stored object metadata: %s", s)
75 }
76 namespace := s[:index]
77 s = s[index+1:]
78
79 index = strings.LastIndex(s, fieldSeparator)
80 if index == -1 {
81 return NilObjMetadata, fmt.Errorf("unable to parse stored object metadata: %s", s)
82 }
83 kind := s[index+1:]
84 s = s[:index]
85
86 index = strings.LastIndex(s, fieldSeparator)
87 if index == -1 {
88 return NilObjMetadata, fmt.Errorf("unable to parse stored object metadata: %s", s)
89 }
90 group := s[index+1:]
91
92 name := s[:index]
93 name = strings.ReplaceAll(name, colonTranscoded, ":")
94
95 if strings.Contains(name, fieldSeparator) {
96 return NilObjMetadata, fmt.Errorf("too many fields within: %s", s)
97 }
98
99 id := ObjMetadata{
100 Namespace: namespace,
101 Name: name,
102 GroupKind: schema.GroupKind{
103 Group: group,
104 Kind: kind,
105 },
106 }
107 return id, nil
108 }
109
110
111
112 func (o *ObjMetadata) Equals(other *ObjMetadata) bool {
113 if other == nil {
114 return false
115 }
116 return *o == *other
117 }
118
119
120
121
122 func (o ObjMetadata) String() string {
123 name := o.Name
124 if _, exists := RBACGroupKind[o.GroupKind]; exists {
125 name = strings.ReplaceAll(name, ":", colonTranscoded)
126 }
127 return fmt.Sprintf("%s%s%s%s%s%s%s",
128 o.Namespace, fieldSeparator,
129 name, fieldSeparator,
130 o.GroupKind.Group, fieldSeparator,
131 o.GroupKind.Kind)
132 }
133
134
135
136 func RuntimeToObjMeta(obj runtime.Object) (ObjMetadata, error) {
137 accessor, err := meta.Accessor(obj)
138 if err != nil {
139 return NilObjMetadata, err
140 }
141 id := ObjMetadata{
142 Namespace: accessor.GetNamespace(),
143 Name: accessor.GetName(),
144 GroupKind: obj.GetObjectKind().GroupVersionKind().GroupKind(),
145 }
146 return id, nil
147 }
148
View as plain text