/
apply.go
260 lines (227 loc) · 7.95 KB
/
apply.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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
/*
* Copyright 2018- The Pixie 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.
*
* SPDX-License-Identifier: Apache-2.0
*/
package k8s
import (
"bytes"
"context"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"regexp"
"strings"
log "github.com/sirupsen/logrus"
k8serrors "k8s.io/apimachinery/pkg/api/errors"
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"
jsonserializer "k8s.io/apimachinery/pkg/runtime/serializer/json"
"k8s.io/apimachinery/pkg/util/yaml"
"k8s.io/client-go/dynamic"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/restmapper"
"k8s.io/klog/v2"
)
func init() {
// Suppress k8s log output.
klog.InitFlags(nil)
err := flag.Set("logtostderr", "false")
if err != nil {
log.WithError(err).Error("Failed to set flag")
}
err = flag.Set("v", "9")
if err != nil {
log.WithError(err).Error("Failed to set flag")
}
err = flag.Set("alsologtostderr", "false")
if err != nil {
log.WithError(err).Error("Failed to set flag")
}
// Suppress k8s log output.
klog.SetOutput(io.Discard)
}
// ConvertResourceToYAML converts the given object to a YAML which can be applied.
func ConvertResourceToYAML(obj runtime.Object) (string, error) {
buf := new(bytes.Buffer)
e := jsonserializer.NewYAMLSerializer(jsonserializer.DefaultMetaFactory, nil, nil)
err := e.Encode(obj, buf)
if err != nil {
return "", err
}
return buf.String(), nil
}
// ApplyYAML does the equivalent of a kubectl apply for the given yaml. If allowUpdate is true, then we update the resource
// if it already exists.
func ApplyYAML(clientset kubernetes.Interface, config *rest.Config, namespace string, yamlFile io.Reader, allowUpdate bool) error {
return ApplyYAMLForResourceTypes(clientset, config, namespace, yamlFile, []string{}, allowUpdate)
}
// KeyValueStringToMap converts a user-inputted label string (label1=value,label2=value2) into a string map.
// Supports values that contain commas, as long as they are surrounded by quotes.
// eg. (label1="valuea,valueb",label2=value2)
func KeyValueStringToMap(labels string) (map[string]string, error) {
labelMap := make(map[string]string)
if labels == "" {
return labelMap, nil
}
// Support values that contain commas by replacing all values that are in quotes with a placeholder, and then replacing the placeholder after splitting on commas.
quotedReplMap := make(map[string]string)
pattern, err := regexp.Compile(`"([^"]+)"`)
if err != nil {
return labelMap, err
}
quotedMatches := pattern.FindAllStringSubmatch(labels, -1)
for i, quotedMatch := range quotedMatches {
if len(quotedMatch) < 2 {
continue
}
match := quotedMatch[1]
repl := fmt.Sprintf("__val%d__", i)
quotedReplMap[repl] = match
labels = strings.Replace(labels, fmt.Sprintf(`"%s"`, match), repl, 1)
}
splitString := strings.Split(labels, ",")
for _, labelPair := range splitString {
splitLabel := strings.Split(labelPair, "=")
if len(splitLabel) != 2 || splitLabel[0] == "" || splitLabel[1] == "" {
return nil, errors.New("Label string is malformed")
}
if _, ok := quotedReplMap[splitLabel[0]]; ok {
return nil, errors.New("Can not have quoted key, only quoted values")
}
val := splitLabel[1]
if origVal, ok := quotedReplMap[splitLabel[1]]; ok {
val = origVal
}
labelMap[splitLabel[0]] = val
}
return labelMap, nil
}
// ApplyYAMLForResourceTypes only applies the specified types in the given YAML file.
func ApplyYAMLForResourceTypes(clientset kubernetes.Interface, config *rest.Config, namespace string, yamlFile io.Reader, allowedResources []string, allowUpdate bool) error {
resources, err := GetResourcesFromYAML(yamlFile)
if err != nil {
return err
}
return ApplyResources(clientset, config, resources, namespace, allowedResources, allowUpdate)
}
// Resource is an unstructured resource object with a group kind mapping.
type Resource struct {
Object *unstructured.Unstructured
GVK *schema.GroupVersionKind
}
// GetResourcesFromYAML parses the YAMLs into K8s resource objects that can be passed to the API.
func GetResourcesFromYAML(yamlFile io.Reader) ([]*Resource, error) {
resources := make([]*Resource, 0)
decodedYAML := yaml.NewYAMLOrJSONDecoder(yamlFile, 4096)
for {
ext := runtime.RawExtension{}
err := decodedYAML.Decode(&ext)
if err != nil && err == io.EOF {
break
} else if err != nil {
return nil, err
}
if ext.Raw == nil {
continue
}
_, gvk, err := unstructured.UnstructuredJSONScheme.Decode(ext.Raw, nil, nil)
if err != nil {
log.WithError(err).Fatalf(err.Error())
return nil, err
}
var unstructRes unstructured.Unstructured
unstructRes.Object = make(map[string]interface{})
var unstructBlob interface{}
err = json.Unmarshal(ext.Raw, &unstructBlob)
if err != nil {
return nil, err
}
unstructRes.Object = unstructBlob.(map[string]interface{})
resources = append(resources, &Resource{
Object: &unstructRes,
GVK: gvk,
})
}
return resources, nil
}
// ApplyResources applies the following resources to the give namespace/cluster.
func ApplyResources(clientset kubernetes.Interface, config *rest.Config, resources []*Resource, namespace string, allowedResources []string, allowUpdate bool) error {
discoveryClient := clientset.Discovery()
apiGroupResources, err := restmapper.GetAPIGroupResources(discoveryClient)
if err != nil {
return err
}
rm := restmapper.NewDiscoveryRESTMapper(apiGroupResources)
for _, resource := range resources {
mapping, err := rm.RESTMapping(resource.GVK.GroupKind(), resource.GVK.Version)
if err != nil {
return err
}
k8sRes := mapping.Resource.Resource
if len(allowedResources) != 0 {
validResource := false
for _, res := range allowedResources {
if res == k8sRes {
validResource = true
}
}
if !validResource {
continue // Don't apply this resource.
}
}
restconfig := config
restconfig.GroupVersion = &schema.GroupVersion{
Group: mapping.GroupVersionKind.Group,
Version: mapping.GroupVersionKind.Version,
}
dynamicClient, err := dynamic.NewForConfig(restconfig)
if err != nil {
return err
}
res := dynamicClient.Resource(mapping.Resource)
objNS := namespace
if objNS == "" { // If no namespace specified, use the namespace from the resource.
if nestedNS, ok, _ := unstructured.NestedString(resource.Object.Object, "metadata", "namespace"); ok {
objNS = nestedNS
}
}
nsRes := res.Namespace(objNS)
createRes := nsRes
if k8sRes == "validatingwebhookconfigurations" || k8sRes == "mutatingwebhookconfigurations" || k8sRes == "namespaces" || k8sRes == "configmap" || k8sRes == "clusterrolebindings" || k8sRes == "clusterroles" || k8sRes == "customresourcedefinitions" {
createRes = res
}
_, err = createRes.Create(context.Background(), resource.Object, metav1.CreateOptions{})
if err != nil {
if !k8serrors.IsAlreadyExists(err) {
return err
} else if (k8sRes == "clusterroles" || k8sRes == "cronjobs") || allowUpdate {
// TODO(michelle,vihang,philkuz) Update() fails on services and PVCs that are already running on the
// cluster. We will need to fix this before we can successfully update those resources. K8s is unhappy
// that we don't specify resourceVersion and clusterIP for services.
_, err = createRes.Update(context.Background(), resource.Object, metav1.UpdateOptions{})
if err != nil {
log.WithError(err).Info("Could not update K8s resource")
}
}
}
}
return nil
}