-
Notifications
You must be signed in to change notification settings - Fork 2
/
deploy.go
319 lines (284 loc) · 9.83 KB
/
deploy.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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
// Copyright Mia srl
// SPDX-License-Identifier: Apache-2.0
//
// 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 deploy
import (
"context"
"encoding/json"
"fmt"
"time"
"github.com/mia-platform/mlp/internal/utils"
"github.com/mia-platform/mlp/pkg/resourceutil"
corev1 "k8s.io/api/core/v1"
apierrors "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/client-go/discovery"
"k8s.io/client-go/dynamic"
)
const (
dependenciesChecksum = "dependencies-checksum"
deployAll = "deploy_all"
)
type k8sClients struct {
dynamic dynamic.Interface
discovery discovery.DiscoveryInterface
}
// Run execute the deploy command from cli
func Run(inputPaths []string, deployConfig utils.DeployConfig, opts *utils.Options) {
restConfig, err := opts.Config.ToRESTConfig()
utils.CheckError(err, "")
// The following two options manage client-side throttling to decrease pressure on api-server
// Kubectl sets 300 bursts 50.0 QPS:
// https://github.com/kubernetes/kubectl/blob/0862c57c87184432986c85674a237737dabc53fa/pkg/cmd/cmd.go#L92
restConfig.QPS = 500.0
restConfig.Burst = 500
clients := &k8sClients{
dynamic: dynamic.NewForConfigOrDie(restConfig),
discovery: discovery.NewDiscoveryClientForConfigOrDie(restConfig),
}
currentTime := time.Now()
err = doRun(clients, opts.Namespace, inputPaths, deployConfig, currentTime)
utils.CheckError(err, "")
}
func doRun(clients *k8sClients, namespace string, inputPaths []string, deployConfig utils.DeployConfig, currentTime time.Time) error {
filePaths, err := utils.ExtractYAMLFiles(inputPaths)
utils.CheckError(err, "Error extracting yaml files")
resources, err := resourceutil.MakeResources(filePaths, namespace)
if err != nil {
fmt.Printf("fails to make resources: %s\n", err)
return err
}
err = prepareResources(deployConfig.DeployType, resources, currentTime)
if err != nil {
fmt.Printf("fails to prepare resources: %s\n", err)
return err
}
err = deploy(clients, namespace, resources, deployConfig)
if err != nil {
fmt.Printf("fails to deploy: %s", err)
return err
}
return cleanup(clients, namespace, resources)
}
func prepareResources(deployType string, resources []resourceutil.Resource, currentTime time.Time) error {
configMapMap, secretMap, err := resourceutil.MapSecretAndConfigMap(resources)
utils.CheckError(err, "error preparing resources")
for _, res := range resources {
res := res
if res.GroupVersionKind.Kind != deploymentKind && res.GroupVersionKind.Kind != cronJobKind {
continue
}
if deployType == deployAll {
if err := ensureDeployAll(&res, currentTime); err != nil {
fmt.Printf("fails to ensure deploy all: %s\n", err)
return err
}
}
if err := insertDependencies(&res, configMapMap, secretMap); err != nil {
fmt.Printf("fails to insert dependencies: %s\n", err)
return err
}
}
return nil
}
func insertDependencies(res *resourceutil.Resource, configMapMap map[string]string, secretMap map[string]string) error {
var path []string
var err error
switch res.GroupVersionKind.Kind {
case deploymentKind:
path = []string{"spec", "template", "spec"}
case cronJobKind:
path = []string{"spec", "jobTemplate", "spec", "template", "spec"}
}
unstrPodSpec, _, err := unstructured.NestedMap(res.Object.Object, path...)
if err != nil {
fmt.Printf("fails to get unstructured pod spec %s: %s\n", res.Object.GetName(), err)
return err
}
var podSpec corev1.PodSpec
err = runtime.DefaultUnstructuredConverter.FromUnstructured(unstrPodSpec, &podSpec)
if err != nil {
fmt.Printf("fails to convert unstructured pod %s spec: %s\n", res.Object.GetName(), err)
return err
}
dependencies := resourceutil.GetPodsDependencies(podSpec)
// NOTE: ConfigMaps and Secrets that are used as dependency for the resource but do not exist
// in the resource files provided are ignored and no annotation is created for them.
var checksumMap = map[string]string{}
for _, configMapName := range dependencies[resourceutil.ConfigMap] {
if checksum, ok := configMapMap[configMapName]; ok {
checksumMap[fmt.Sprintf("%s-configmap", configMapName)] = checksum
}
}
for _, secretName := range dependencies[resourceutil.Secret] {
if checksum, ok := secretMap[secretName]; ok {
checksumMap[fmt.Sprintf("%s-secret", secretName)] = checksum
}
}
jsonCheckSumMap, err := json.Marshal(checksumMap)
if err != nil {
fmt.Printf("can not convert checksumMap to json: %s", err.Error())
}
switch res.GroupVersionKind.Kind {
case deploymentKind:
path = []string{"spec", "template", "metadata", "annotations"}
case cronJobKind:
path = []string{"spec", "jobTemplate", "spec", "template", "metadata", "annotations"}
}
currentAnnotations, found, err := unstructured.NestedStringMap(res.Object.Object,
path...)
if err != nil {
return err
}
if !found {
currentAnnotations = make(map[string]string)
}
currentAnnotations[resourceutil.GetMiaAnnotation(dependenciesChecksum)] = string(jsonCheckSumMap)
return unstructured.SetNestedStringMap(res.Object.Object,
currentAnnotations,
path...)
}
// cleanup removes the resources no longer deployed by `mlp` and updates
// the secret in the cluster with the updated set of resources
func cleanup(clients *k8sClients, namespace string, resources []resourceutil.Resource) error {
actual := makeResourceMap(resources)
old, err := getOldResourceMap(clients, namespace)
if err != nil {
return err
}
// Prune only if it is not the first release or after an empty release
if len(old) != 0 {
deleteMap := deletedResources(actual, old)
for _, resourceGroup := range deleteMap {
err = prune(clients, namespace, resourceGroup)
if err != nil {
return err
}
}
}
err = updateResourceSecret(clients.dynamic, namespace, actual)
return err
}
func updateResourceSecret(dynamic dynamic.Interface, namespace string, resources map[string]*ResourceList) error {
secretContent, err := json.Marshal(resources)
if err != nil {
return err
}
secret := &corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: resourceSecretName,
Namespace: namespace,
},
TypeMeta: metav1.TypeMeta{Kind: "Secret", APIVersion: "v1"},
Data: map[string][]byte{"resources": secretContent},
}
unstr, err := fromRuntimeObjtoUnstruct(secret, secret.GroupVersionKind())
if err != nil {
return err
}
if _, err = dynamic.Resource(gvrSecrets).
Namespace(unstr.GetNamespace()).
Create(context.Background(), unstr, metav1.CreateOptions{}); err != nil {
if apierrors.IsAlreadyExists(err) {
_, err = dynamic.Resource(gvrSecrets).
Namespace(unstr.GetNamespace()).
Update(context.Background(),
unstr,
metav1.UpdateOptions{})
if err != nil {
return err
}
} else {
return err
}
}
return nil
}
func prune(clients *k8sClients, namespace string, resourceGroup *ResourceList) error {
for _, res := range resourceGroup.Resources {
fmt.Printf("Deleting: %v %v\n", resourceGroup.Gvk.Kind, res)
gvr, err := resourceutil.FromGVKtoGVR(clients.discovery, *resourceGroup.Gvk)
if err != nil {
return err
}
onClusterObj, err := clients.dynamic.Resource(gvr).Namespace(namespace).
Get(context.Background(), res, metav1.GetOptions{})
if err != nil {
if apierrors.IsNotFound(err) {
fmt.Printf("already not present on cluster\n")
continue
}
return err
}
// delete the object only if the resource has the managed by MIA label
if onClusterObj.GetLabels()[resourceutil.ManagedByLabel] != resourceutil.ManagedByMia {
continue
}
err = clients.dynamic.Resource(gvr).Namespace(namespace).
Delete(context.Background(), res, metav1.DeleteOptions{})
if err != nil && !apierrors.IsNotFound(err) {
return err
}
}
return nil
}
func deploy(clients *k8sClients, namespace string, resources []resourceutil.Resource, deployConfig utils.DeployConfig) error {
// for each resource ensure namespace if a namespace is not passed to mlp ensure namespace in the resource, gives error
// on no namespace passed to mlp and no namespace in yaml
// The namespace given to mlp overrides yaml namespace
for _, res := range resources {
if namespace == "" {
resourceNamespace := res.Object.GetNamespace()
if resourceNamespace != "" && deployConfig.EnsureNamespace {
if err := ensureNamespaceExistence(clients, resourceNamespace); err != nil {
return err
}
} else if resourceNamespace == "" {
return fmt.Errorf("no namespace passed and no namespace in resource: %s %s", res.GroupVersionKind.Kind, res.Object.GetName())
}
} else {
res.Object.SetNamespace(namespace)
}
}
if namespace != "" && deployConfig.EnsureNamespace {
if err := ensureNamespaceExistence(clients, namespace); err != nil {
return err
}
}
// apply the resources
for _, res := range resources {
err := apply(clients, res, deployConfig)
if err != nil {
return err
}
}
return nil
}
func ensureNamespaceExistence(clients *k8sClients, namespace string) error {
ns := &unstructured.Unstructured{}
ns.SetUnstructuredContent(map[string]interface{}{
"apiVersion": "v1",
"kind": "Namespace",
"metadata": map[string]interface{}{
"name": namespace,
},
})
fmt.Printf("Creating namespace %s\n", namespace)
if _, err := clients.dynamic.Resource(gvrNamespaces).Create(context.Background(), ns, metav1.CreateOptions{}); err != nil && !apierrors.IsAlreadyExists(err) {
return err
}
return nil
}