forked from operator-framework/operator-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathk8sutil.go
201 lines (182 loc) · 5.83 KB
/
k8sutil.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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
// Copyright 2018 The Operator-SDK Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package k8sutil
import (
"encoding/json"
"fmt"
"os"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/runtime/serializer"
intstr "k8s.io/apimachinery/pkg/util/intstr"
cgoscheme "k8s.io/client-go/kubernetes/scheme"
)
var (
// scheme tracks the type registry for the sdk
// This scheme is used to decode json data into the correct Go type based on the object's GVK
// All types that the operator watches must be added to this scheme
scheme = runtime.NewScheme()
codecs = serializer.NewCodecFactory(scheme)
)
func init() {
// Add the standard kubernetes [GVK:Types] type registry
// e.g (v1,Pods):&v1.Pod{}
metav1.AddToGroupVersion(scheme, schema.GroupVersion{Version: "v1"})
cgoscheme.AddToScheme(scheme)
}
func decoder(gv schema.GroupVersion) runtime.Decoder {
codec := codecs.UniversalDecoder(gv)
return codec
}
type addToSchemeFunc func(*runtime.Scheme) error
// AddToSDKScheme allows CRDs to register their types with the sdk scheme
func AddToSDKScheme(addToScheme addToSchemeFunc) {
addToScheme(scheme)
}
// RuntimeObjectFromUnstructured converts an unstructured to a runtime object
func RuntimeObjectFromUnstructured(u *unstructured.Unstructured) runtime.Object {
gvk := u.GroupVersionKind()
decoder := decoder(gvk.GroupVersion())
b, err := u.MarshalJSON()
if err != nil {
panic(err)
}
ro, _, err := decoder.Decode(b, &gvk, nil)
if err != nil {
err = fmt.Errorf("failed to decode json data with gvk(%v): %v", gvk.String(), err)
panic(err)
}
return ro
}
// UnstructuredFromRuntimeObject converts a runtime object to an unstructured
func UnstructuredFromRuntimeObject(ro runtime.Object) *unstructured.Unstructured {
b, err := json.Marshal(ro)
if err != nil {
panic(err)
}
var u unstructured.Unstructured
if err := json.Unmarshal(b, &u.Object); err != nil {
panic(err)
}
return &u
}
// UnstructuredIntoRuntimeObject unmarshalls an unstructured into a given runtime object
// TODO: https://github.com/operator-framework/operator-sdk/issues/127
func UnstructuredIntoRuntimeObject(u *unstructured.Unstructured, into runtime.Object) error {
gvk := u.GroupVersionKind()
decoder := decoder(gvk.GroupVersion())
b, err := u.MarshalJSON()
if err != nil {
return err
}
_, _, err = decoder.Decode(b, &gvk, into)
if err != nil {
return fmt.Errorf("failed to decode json data with gvk(%v): %v", gvk.String(), err)
}
return nil
}
// RuntimeObjectIntoRuntimeObject unmarshalls an runtime.Object into a given runtime object
func RuntimeObjectIntoRuntimeObject(from runtime.Object, into runtime.Object) error {
b, err := json.Marshal(from)
if err != nil {
return err
}
gvk := from.GetObjectKind().GroupVersionKind()
decoder := decoder(gvk.GroupVersion())
_, _, err = decoder.Decode(b, &gvk, into)
if err != nil {
return fmt.Errorf("failed to decode json data with gvk(%v): %v", gvk.String(), err)
}
return nil
}
// GetNameAndNamespace extracts the name and namespace from the given runtime.Object
// and returns a error if any of those is missing.
func GetNameAndNamespace(object runtime.Object) (string, string, error) {
accessor := meta.NewAccessor()
name, err := accessor.Name(object)
if err != nil {
return "", "", fmt.Errorf("failed to get name for object: %v", err)
}
namespace, err := accessor.Namespace(object)
if err != nil {
return "", "", fmt.Errorf("failed to get namespace for object: %v", err)
}
return name, namespace, nil
}
func ObjectInfo(kind, name, namespace string) string {
return kind + ": " + namespace + "/" + name
}
// GetWatchNamespace returns the namespace the operator should be watching for changes
func GetWatchNamespace() (string, error) {
ns, found := os.LookupEnv(WatchNamespaceEnvVar)
if !found {
return "", fmt.Errorf("%s must be set", WatchNamespaceEnvVar)
}
if len(ns) == 0 {
return "", fmt.Errorf("%s must not be empty", WatchNamespaceEnvVar)
}
return ns, nil
}
// GetOperatorName return the operator name
func GetOperatorName() (string, error) {
operatorName, found := os.LookupEnv(OperatorNameEnvVar)
if !found {
return "", fmt.Errorf("%s must be set", OperatorNameEnvVar)
}
if len(operatorName) == 0 {
return "", fmt.Errorf("%s must not be empty", OperatorNameEnvVar)
}
return operatorName, nil
}
// InitOperatorService return the static service which expose operator metrics
func InitOperatorService() (*v1.Service, error) {
operatorName, err := GetOperatorName()
if err != nil {
return nil, err
}
namespace, err := GetWatchNamespace()
if err != nil {
return nil, err
}
service := &v1.Service{
ObjectMeta: metav1.ObjectMeta{
Name: operatorName,
Namespace: namespace,
Labels: map[string]string{"name": operatorName},
},
TypeMeta: metav1.TypeMeta{
Kind: "Service",
APIVersion: "v1",
},
Spec: v1.ServiceSpec{
Ports: []v1.ServicePort{
{
Port: PrometheusMetricsPort,
Protocol: v1.ProtocolTCP,
TargetPort: intstr.IntOrString{
Type: intstr.String,
StrVal: PrometheusMetricsPortName,
},
Name: PrometheusMetricsPortName,
},
},
Selector: map[string]string{"name": operatorName},
},
}
return service, nil
}