-
Notifications
You must be signed in to change notification settings - Fork 24
/
utils.go
321 lines (276 loc) · 8.79 KB
/
utils.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
320
321
package installation
import (
"context"
"errors"
"fmt"
"net/http"
"strings"
"time"
"github.com/fluxninja/aperture/pkg/log"
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
"github.com/imdario/mergo"
"golang.org/x/exp/slices"
"helm.sh/helm/v3/pkg/chart"
"helm.sh/helm/v3/pkg/chart/loader"
"helm.sh/helm/v3/pkg/chartutil"
"helm.sh/helm/v3/pkg/engine"
"helm.sh/helm/v3/pkg/release"
"helm.sh/helm/v3/pkg/releaseutil"
batchv1 "k8s.io/api/batch/v1"
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/types"
"k8s.io/client-go/rest"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/yaml"
)
var (
valuesFile string
kubeConfig string
kubeRestConfig *rest.Config
version string
latestVersion string
namespace string
kubeClient client.Client
timeout int
)
const (
apertureLatestVersion = "latest"
defaultNS = "default"
controller = "controller"
apertureController = "aperture-controller"
agent = "agent"
apertureAgent = "aperture-agent"
istioConfig = "istioconfig"
istioConfigReleaseName = "aperture-envoy-filter"
)
// getTemplets loads CRDs, hooks and manifests from the Helm chart.
func getTemplets(chartName, releaseName string, order releaseutil.KindSortOrder) ([]chart.CRD, []*release.Hook, []releaseutil.Manifest, error) {
chartURL := fmt.Sprintf("https://fluxninja.github.io/aperture/%s-%s.tgz", chartName, version)
resp, err := http.Get(chartURL) //nolint
if err != nil {
return nil, nil, nil, fmt.Errorf("failed to download chart: %s", err)
}
defer resp.Body.Close()
ch, err := loader.LoadArchive(resp.Body)
if err != nil {
return nil, nil, nil, fmt.Errorf("failed to load chart: %s", err)
}
values := ch.Values
if valuesFile != "" {
values, err = chartutil.ReadValuesFile(valuesFile)
if err != nil {
return nil, nil, nil, fmt.Errorf("failed to read values: %s", err)
}
} else if releaseName == agent && slices.Compare(order, releaseutil.UninstallOrder) == 0 {
values = map[string]interface{}{
"agent": map[string]interface{}{
"config": map[string]interface{}{
"etcd": map[string]interface{}{
"endpoints": []string{"dummy"},
},
"prometheus": map[string]interface{}{
"address": "dummy",
},
},
},
}
}
renderedValues, err := chartutil.ToRenderValues(ch, values, chartutil.ReleaseOptions{Name: releaseName, Namespace: namespace}, chartutil.DefaultCapabilities)
if err != nil {
return nil, nil, nil, fmt.Errorf("failed to read values: %s", err)
}
files, err := engine.RenderWithClient(ch, renderedValues, kubeRestConfig)
if err != nil {
return nil, nil, nil, fmt.Errorf("failed to render chart: %s", err)
}
for k := range files {
if strings.HasSuffix(k, "NOTES.txt") {
delete(files, k)
}
}
hooks, manifests, err := releaseutil.SortManifests(files, chartutil.DefaultVersionSet, order)
return ch.CRDObjects(), hooks, manifests, err
}
// applyManifest creates/updates the generated manifest to Kubernetes.
func applyManifest(manifest string) error {
unstructuredObject, err := prepareUnstructuredObject(manifest)
if err != nil {
return err
}
log.Info().Msgf("Applying - %s/%s", unstructuredObject.GetKind(), unstructuredObject.GetName())
attempt := 0
for attempt < 5 {
attempt++
if err = applyObjectToKubernetes(unstructuredObject); err != nil && strings.Contains(err.Error(), "no matches for kind") {
time.Sleep(time.Second * time.Duration(attempt))
continue
}
break
}
if err != nil {
return fmt.Errorf("failed to apply - %s/%s, Error - '%s'", unstructuredObject.GetKind(), unstructuredObject.GetName(), err)
}
return nil
}
// applyObjectToKubernetes applies the given object to Kubernetes.
func applyObjectToKubernetes(unstructuredObject *unstructured.Unstructured) error {
key := types.NamespacedName{
Name: unstructuredObject.GetName(),
Namespace: unstructuredObject.GetNamespace(),
}
existing := unstructuredObject.DeepCopy()
err := kubeClient.Get(context.Background(), key, existing)
if err != nil && !apierrors.IsNotFound(err) {
return err
}
if !apierrors.IsNotFound(err) {
opts := cmpopts.IgnoreFields(
metav1.ObjectMeta{},
"Generation", "ResourceVersion", "SelfLink", "UID",
"CreationTimestamp", "DeletionTimestamp", "DeletionGracePeriodSeconds",
"OwnerReferences", "Finalizers",
)
// Check if there are any differences between the existing and the new object
if !cmp.Equal(unstructuredObject, existing, opts) {
err = mergo.Map(&unstructuredObject.Object, &existing.Object)
if err != nil {
return err
}
err = kubeClient.Patch(context.Background(), unstructuredObject, client.MergeFrom(existing))
}
} else {
err = kubeClient.Create(context.Background(), unstructuredObject)
}
return err
}
// deleteManifest deletes the generated manifest from Kubernetes.
func deleteManifest(manifest string) error {
unstructuredObject, err := prepareUnstructuredObject(manifest)
if err != nil {
return err
}
log.Info().Msgf("Deleting - %s/%s", unstructuredObject.GetKind(), unstructuredObject.GetName())
err = kubeClient.Delete(context.Background(), unstructuredObject)
if apierrors.IsNotFound(err) {
return nil
}
if err != nil {
return fmt.Errorf("failed to delete - %s/%s, Error - '%s'", unstructuredObject.GetKind(), unstructuredObject.GetName(), err)
}
return nil
}
// manageNamespace creates namespace if not present.
func manageNamespace() error {
ns := &corev1.Namespace{}
err := kubeClient.Get(context.Background(), types.NamespacedName{Name: namespace}, ns)
if apierrors.IsNotFound(err) {
ns.Name = namespace
if err = kubeClient.Create(context.Background(), ns); err != nil {
return err
}
}
return nil
}
// waitForHook waits for 1 successful execution of the hook.
func waitForHook(name string, ctx context.Context) error {
job := &batchv1.Job{}
for {
err := kubeClient.Get(ctx, types.NamespacedName{Namespace: namespace, Name: name}, job)
if err != nil || job.Status.Succeeded != 1 {
time.Sleep(3 * time.Second)
continue
}
break
}
return nil
}
// prepareUnstructuredObject prepares unstructured.Unstructured from given YAML string.
func prepareUnstructuredObject(manifest string) (*unstructured.Unstructured, error) {
content := map[string]interface{}{}
err := yaml.Unmarshal([]byte(manifest), &content)
if err != nil {
return nil, err
}
unstructuredObject := &unstructured.Unstructured{
Object: content,
}
if unstructuredObject.GetNamespace() == "" {
unstructuredObject.SetNamespace(namespace)
}
return unstructuredObject, nil
}
// handleInstall handles installation for given chart using given release name.
func handleInstall(chartName, releaseName string) error {
crds, _, manifests, err := getTemplets(chartName, releaseName, releaseutil.InstallOrder)
if err != nil {
return err
}
errs := []error{}
for _, crd := range crds {
if err = applyManifest(string(crd.File.Data)); err != nil {
errs = append(errs, err)
}
}
for _, manifest := range manifests {
if err = applyManifest(manifest.Content); err != nil {
errs = append(errs, err)
}
}
for _, err := range errs {
log.Error().Msg(err.Error())
}
if len(errs) != 0 {
return fmt.Errorf("failed to complete install successfully")
}
return nil
}
// handleUnInstall handles uninstallation for given chart using given release name.
func handleUnInstall(chartName, releaseName string) error {
crds, hooks, manifests, err := getTemplets(chartName, releaseName, releaseutil.UninstallOrder)
if err != nil {
return err
}
errs := []error{}
for _, hook := range hooks {
log.Info().Msgf("Executing hook - %s", hook.Name)
if err = applyManifest(hook.Manifest); err != nil {
return err
}
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(timeout)*time.Second)
defer cancel()
if err = waitForHook(hook.Name, ctx); err != nil {
if errors.Is(err, context.DeadlineExceeded) {
return fmt.Errorf("timed out waiting for pre-delete hook completion")
}
return err
}
if err = deleteManifest(hook.Manifest); err != nil {
errs = append(errs, err)
}
if err = kubeClient.DeleteAllOf(
context.Background(), &corev1.Pod{}, client.InNamespace(namespace), client.MatchingLabels{"job-name": hook.Name}); err != nil {
errs = append(errs, err)
}
}
for _, manifest := range manifests {
if err = deleteManifest(manifest.Content); err != nil {
errs = append(errs, err)
}
}
for _, crd := range crds {
if err = deleteManifest(string(crd.File.Data)); err != nil {
errs = append(errs, err)
}
}
for _, err := range errs {
log.Error().Msg(err.Error())
}
if len(errs) != 0 {
return fmt.Errorf("failed to complete uninstall successfully")
}
return nil
}