This repository has been archived by the owner on Aug 20, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.go
259 lines (233 loc) · 6.16 KB
/
main.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
package main
import (
"bufio"
"errors"
"flag"
"fmt"
"github.com/gertd/go-pluralize"
"io"
"os"
"sort"
"strings"
"gopkg.in/yaml.v3"
)
type kindNameVersion struct {
apiVersion string
kind string
name string
}
type kindName struct {
kind string
name string
}
type flags struct {
fromFile string
toFile string
outputFile string
ignored string
}
func main() {
var args = flags{}
flag.StringVar(&args.fromFile, "from", "", "Path to manifests file before upgrade.")
flag.StringVar(&args.toFile, "to", "", "Path to manifests file of upgrade.")
flag.StringVar(&args.outputFile, "output", "", "Name of the cleanup script file to be generated.")
flag.StringVar(&args.ignored, "ignore", "", "List of resources to ignore."+
"\nUsage: -ignore kind1:name1,kind2:name2"+
"\nExample: -ignore service:foo,servicemonitors.monitoring.coreos.com:bar")
flag.Parse()
out := os.Stdout
if err := run(out, args); err != nil {
fmt.Fprintf(out, "Error: %v\n", err)
os.Exit(2)
}
}
func run(out io.Writer, f flags) error {
if len(f.fromFile) == 0 {
return errors.New("flag not specified: from")
}
if len(f.toFile) == 0 {
return errors.New("flag not specified: to")
}
from, err := parseManifest(out, f.fromFile)
if err != nil {
return err
}
to, err := parseManifest(out, f.toFile)
if err != nil {
return err
}
var ignored []kindName
if len(f.ignored) > 0 {
ignored, err = parseIgnoredManifests(f.ignored)
if err != nil {
return err
}
}
orphaned := compare(from, to)
if len(orphaned) == 0 {
fmt.Fprintf(out, "Manifests are equal\n")
return nil
}
orphaned = removeIgnored(orphaned, ignored)
printSummary(out, orphaned)
if len(f.outputFile) > 0 {
if err = generateDeletionScript(out, f.outputFile, orphaned); err != nil {
return err
}
}
return nil
}
func parseIgnoredManifests(ignored string) ([]kindName, error) {
manifestStrings := strings.Split(ignored, ",")
var ignoreManifests []kindName
for _, manifestString := range manifestStrings {
manifest := strings.Split(manifestString, ":")
if len(manifest) != 2 {
return nil, fmt.Errorf("invalid ignored manifest format: %v", manifestString)
}
ignoreManifests = append(ignoreManifests, kindName{
kind: manifest[0],
name: manifest[1],
})
}
return ignoreManifests, nil
}
func compare(left, right map[string]kindNameVersion) []kindNameVersion {
var orphaned []kindNameVersion
for k, v := range left {
if _, found := right[k]; !found {
orphaned = append(orphaned, v)
}
}
sort.Slice(orphaned, func(i, j int) bool {
var l, r = orphaned[i], orphaned[j]
if l.kind == r.kind {
return l.name < r.name
}
return l.kind < r.kind
})
return orphaned
}
func removeIgnored(knvs []kindNameVersion, ignored []kindName) []kindNameVersion {
var filtered []kindNameVersion
for _, knv := range knvs {
if len(ignored) > 0 && shouldIgnore(knv, ignored) {
continue
}
filtered = append(filtered, knv)
}
return filtered
}
func shouldIgnore(found kindNameVersion, ignored []kindName) bool {
for _, i := range ignored {
if i.kind == simpleKind(found) && i.name == found.name {
return true
}
}
return false
}
func parseManifest(out io.Writer, filePath string) (map[string]kindNameVersion, error) {
installManifestsYAML, err := os.ReadFile(filePath)
if err != nil {
return nil, fmt.Errorf("unable to read manifest file at '%v': %v", filePath, err)
}
manifestsSlice, err := unmarshal(out, string(installManifestsYAML))
if err != nil {
return nil, fmt.Errorf("unable to parse manifests: %v", err)
}
results := make(map[string]kindNameVersion)
for _, m := range manifestsSlice {
kind := getKind(m)
name := getName(m)
apiVersion := getAPIVersion(m)
results[getKind(m)+getName(m)] = kindNameVersion{
apiVersion: apiVersion,
kind: kind,
name: name,
}
}
return results, nil
}
func unmarshal(out io.Writer, manifests string) ([]map[string]interface{}, error) {
var results []map[string]interface{}
decoder := yaml.NewDecoder(strings.NewReader(manifests))
for {
manifestYaml := make(map[string]interface{})
err := decoder.Decode(&manifestYaml)
if manifestYaml == nil {
continue
}
if errors.Is(err, io.EOF) {
break
}
var typeError *yaml.TypeError
if errors.As(err, &typeError) {
fmt.Fprintf(out, "WARN - type error: %v\n", err)
continue
}
if err != nil {
return nil, fmt.Errorf("unable to decode manifest to yaml: %v", err)
}
results = append(results, manifestYaml)
}
return results, nil
}
func getAPIVersion(manifest map[string]interface{}) string {
return manifest["apiVersion"].(string)
}
func getKind(manifest map[string]interface{}) string {
return manifest["kind"].(string)
}
func getName(manifest map[string]interface{}) string {
return manifest["metadata"].(map[string]interface{})["name"].(string)
}
func generateDeletionScript(out io.Writer, withName string, from []kindNameVersion) error {
file, err := os.Create(withName)
if err != nil {
return fmt.Errorf("unable to crea te file: %v", err)
}
defer func(f *os.File) {
_ = f.Close()
}(file)
w := bufio.NewWriter(file)
_, err = w.WriteString("#!/usr/bin/env bash\n\n")
if err != nil {
return fmt.Errorf("error writing to file: %v", err)
}
pluralizer := pluralize.NewClient()
for _, m := range from {
m.kind = pluralizer.Plural(m.kind)
kind := simpleKind(m)
name := strings.ToLower(m.name)
deletionCmd := fmt.Sprintf("kubectl delete -n kyma-system %s %s\n", kind, name)
_, err = w.WriteString(deletionCmd)
if err != nil {
return fmt.Errorf("error writing to file: %v", err)
}
}
err = w.Flush()
if err != nil {
return fmt.Errorf("error writing to file - %v", err)
}
_, err = fmt.Fprintf(out, "Deletion script created: '%s'\n", withName)
if err != nil {
return err
}
return nil
}
func printSummary(out io.Writer, manifests []kindNameVersion) {
if len(manifests) == 0 {
return
}
fmt.Fprintf(out, "Resources to be deleted after upgrade:\n")
for _, m := range manifests {
fmt.Fprintf(out, "%+v\n", m)
}
}
func simpleKind(m kindNameVersion) string {
kind := strings.ToLower(m.kind)
if strings.Contains(m.apiVersion, "/") {
kind = fmt.Sprintf("%s.%s", kind, strings.ToLower(strings.Split(m.apiVersion, "/")[0]))
}
return kind
}