-
Notifications
You must be signed in to change notification settings - Fork 136
Expand file tree
/
Copy pathapp_interface.go
More file actions
370 lines (323 loc) · 12.4 KB
/
app_interface.go
File metadata and controls
370 lines (323 loc) · 12.4 KB
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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
package git
import (
"fmt"
"log"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"github.com/openshift/osdctl/cmd/promote/iexec"
"github.com/openshift/osdctl/cmd/promote/pathutil"
kyaml "sigs.k8s.io/kustomize/kyaml/yaml"
"gopkg.in/yaml.v3"
)
const (
canaryStr = "-prod-canary"
prodHiveStr = "hivep"
)
type Service struct {
Name string `yaml:"name"`
ResourceTemplates []struct {
Name string `yaml:"name"`
URL string `yaml:"url"`
PATH string `yaml:"path"` // Optional: path within the repo (used by dynatrace)
Targets []struct {
Name string
Namespace map[string]string `yaml:"namespace"`
Ref string `yaml:"ref"`
Parameters map[string]interface{} `yaml:"parameters"`
} `yaml:"targets"`
} `yaml:"resourceTemplates"`
}
type AppInterface struct {
GitDirectory string
GitExecutor iexec.IExec
}
// replaceTargetSha replaces sha for targets in file whose name matches a given substring
// returns updated yaml, error, and false if no targets were found.
func replaceTargetSha(fileContent string, targetSuffix string, promotionGitHash string) (string, error, bool) {
node, err := kyaml.Parse(fileContent)
if err != nil {
return "", fmt.Errorf("error parsing saas YAML: %v", err), false
}
targetFound := false
rts, err := kyaml.Lookup("resourceTemplates").Filter(node)
if err != nil {
return "", fmt.Errorf("error querying resource templates: %v", err), false
}
for i := range len(rts.Content()) {
targets, err := kyaml.Lookup("resourceTemplates", strconv.Itoa(i), "targets").Filter(node)
if err != nil {
return "", fmt.Errorf("error querying saas YAML: %v", err), false
}
err = targets.VisitElements(func(element *kyaml.RNode) error {
name, _ := element.GetString("name")
match, _ := regexp.MatchString("(.*)"+targetSuffix, name)
if match {
targetFound = true
fmt.Println("updating target: ", name)
_, err = element.Pipe(kyaml.SetField("ref", kyaml.NewStringRNode(promotionGitHash)))
if err != nil {
return fmt.Errorf("error setting ref: %v", err)
}
}
return nil
})
}
return node.MustString(), err, targetFound
}
func DefaultAppInterfaceDirectory() string {
return filepath.Join(os.Getenv("HOME"), "git", "app-interface")
}
func BootstrapOsdCtlForAppInterfaceAndServicePromotions(appInterfaceCheckoutDir string, gitExecutor iexec.Exec) AppInterface {
a := AppInterface{}
a.GitExecutor = gitExecutor
if appInterfaceCheckoutDir != "" {
a.GitDirectory = appInterfaceCheckoutDir
err := a.checkAppInterfaceCheckout()
if err != nil {
log.Fatalf("Provided directory %s is not an AppInterface directory: %v", a.GitDirectory, err)
}
return a
}
dir, err := GetBaseDir(gitExecutor)
if err == nil {
a.GitDirectory = dir
err = a.checkAppInterfaceCheckout()
if err == nil {
return a
}
}
log.Printf("Not running in AppInterface directory: %v - Trying %s next\n", err, DefaultAppInterfaceDirectory())
a.GitDirectory = DefaultAppInterfaceDirectory()
err = a.checkAppInterfaceCheckout()
if err != nil {
log.Fatalf("%s is not an AppInterface directory: %v", DefaultAppInterfaceDirectory(), err)
}
log.Printf("Found AppInterface in %s.\n", a.GitDirectory)
return a
}
// checkAppInterfaceCheckout checks if the script is running in the checkout of app-interface
func (a *AppInterface) checkAppInterfaceCheckout() error {
output, err := a.GitExecutor.Output(a.GitDirectory, "git", "remote", "-v")
if err != nil {
return fmt.Errorf("error executing 'git remote -v': %v", err)
}
outputString := output
// Check if the output contains the app-interface repository URL
if !strings.Contains(outputString, "gitlab.cee.redhat.com") && !strings.Contains(outputString, "app-interface") {
return fmt.Errorf("not running in checkout of app-interface")
}
return nil
}
func GetCurrentGitHashFromAppInterface(saarYamlFile []byte, serviceName string, namespaceRef string) (string, string, error) {
hash, repo, _, err := GetCurrentGitHashAndPathFromAppInterface(saarYamlFile, serviceName, namespaceRef)
return hash, repo, err
}
// GetCurrentGitHashAndPathFromAppInterface returns the current git hash, service repo, and service path
// This version also returns the PATH field from the resource template (used by dynatrace)
func GetCurrentGitHashAndPathFromAppInterface(saarYamlFile []byte, serviceName string, namespaceRef string) (string, string, string, error) {
var currentGitHash string
var serviceRepo string
var servicePath string
var service Service
err := yaml.Unmarshal(saarYamlFile, &service)
if err != nil {
log.Fatal(fmt.Errorf("cannot unmarshal yaml data of service %s: %v", serviceName, err))
}
if namespaceRef != "" {
for _, resourceTemplate := range service.ResourceTemplates {
for _, target := range resourceTemplate.Targets {
if strings.Contains(target.Namespace["$ref"], namespaceRef) {
currentGitHash = target.Ref
servicePath = resourceTemplate.PATH
break
}
}
}
} else if service.Name == "saas-configuration-anomaly-detection-db" {
for _, resourceTemplate := range service.ResourceTemplates {
for _, target := range resourceTemplate.Targets {
if strings.Contains(target.Namespace["$ref"], "app-sre-observability-production-int.yml") {
currentGitHash = target.Ref
servicePath = resourceTemplate.PATH
break
}
}
}
} else if strings.Contains(service.Name, "configuration-anomaly-detection") {
for _, resourceTemplate := range service.ResourceTemplates {
for _, target := range resourceTemplate.Targets {
if strings.Contains(target.Namespace["$ref"], "configuration-anomaly-detection-production") {
currentGitHash = target.Ref
servicePath = resourceTemplate.PATH
break
}
}
}
} else if strings.Contains(service.Name, "rhobs-rules-and-dashboards") {
for _, resourceTemplate := range service.ResourceTemplates {
for _, target := range resourceTemplate.Targets {
if strings.Contains(target.Namespace["$ref"], "production") {
currentGitHash = target.Ref
servicePath = resourceTemplate.PATH
break
}
}
}
} else if strings.Contains(service.Name, "saas-backplane-api") {
for _, resourceTemplate := range service.ResourceTemplates {
for _, target := range resourceTemplate.Targets {
if strings.Contains(target.Namespace["$ref"], "backplanep") {
currentGitHash = target.Ref
servicePath = resourceTemplate.PATH
break
}
}
}
} else {
for _, resourceTemplate := range service.ResourceTemplates {
if !strings.Contains(resourceTemplate.Name, "package") {
for _, target := range resourceTemplate.Targets {
if strings.Contains(target.Name, canaryStr) {
currentGitHash = target.Ref // get canary target ref
servicePath = resourceTemplate.PATH
break
}
}
if currentGitHash == "" { // canary targets not found
for _, target := range resourceTemplate.Targets {
if strings.Contains(target.Namespace["$ref"], prodHiveStr) {
currentGitHash = target.Ref
servicePath = resourceTemplate.PATH
break
}
}
}
}
}
}
if currentGitHash == "" {
return "", "", "", fmt.Errorf("production namespace not found for service %s", serviceName)
}
if len(service.ResourceTemplates) > 0 {
serviceRepo = service.ResourceTemplates[0].URL
}
if serviceRepo == "" {
return "", "", "", fmt.Errorf("service repo not found for service %s", serviceName)
}
return currentGitHash, serviceRepo, servicePath, nil
}
func GetCurrentPackageTagFromAppInterface(saasFile string) (string, error) {
saasData, err := os.ReadFile(saasFile)
if err != nil {
return "", fmt.Errorf("failed to read file '%s': %w", saasFile, err)
}
service := Service{}
err = yaml.Unmarshal(saasData, &service)
if err != nil {
return "", fmt.Errorf("failed to unmarshal service definition: %w", err)
}
var currentPackageTag string
if strings.Contains(service.Name, "configuration-anomaly-detection") {
return "", fmt.Errorf("cannot promote package for configuration-anomaly-detection")
}
if strings.Contains(service.Name, "rhobs-rules-and-dashboards") {
return "", fmt.Errorf("cannot promote package for rhobs-rules-and-dashboards")
}
for _, resourceTemplate := range service.ResourceTemplates {
if strings.Contains(resourceTemplate.Name, "package") {
for _, target := range resourceTemplate.Targets {
if strings.Contains(target.Namespace["$ref"], prodHiveStr) {
currentPackageTag = target.Parameters["PACKAGE_TAG"].(string)
}
}
}
}
return currentPackageTag, nil
}
func (a *AppInterface) UpdateAppInterface(_, saasFile, currentGitHash, promotionGitHash, branchName string, hotfix bool) error {
// Note: Caller should have already synced with origin/master before calling this function
// to ensure currentGitHash is accurate
if err := a.GitExecutor.Run(a.GitDirectory, "git", "branch", "-D", branchName); err != nil {
fmt.Printf("failed to cleanup branch %s: %v, continuing to create it.\n", branchName, err)
}
if err := a.GitExecutor.Run(a.GitDirectory, "git", "checkout", "-b", branchName, "master"); err != nil {
return fmt.Errorf("failed to create branch %s: %v, does it already exist? If so, please delete it with `git branch -D %s` first", branchName, err, branchName)
}
// Update the hash in the SAAS file
fileContent, err := os.ReadFile(saasFile)
if err != nil {
return fmt.Errorf("failed to read file %s: %v", saasFile, err)
}
var newContent string
var canaryTargetsSetUp bool
// If this is a hotfix, update all targets to bypass progressive delivery
if hotfix {
fmt.Println("hotfix mode: updating all targets to bypass progressive delivery")
newContent = strings.ReplaceAll(string(fileContent), currentGitHash, promotionGitHash)
} else {
// If canary targets are set up in saas, replace the hash only in canary targets in the file content
// Otherwise proceed to promoting to all prod hives.
newContent, err, canaryTargetsSetUp = replaceTargetSha(string(fileContent), canaryStr, promotionGitHash)
if err != nil {
return fmt.Errorf("error modifying YAML: %v", err)
}
if !canaryTargetsSetUp {
fmt.Println("canary targets not set, continuing to replace all occurrences of sha.")
newContent = strings.ReplaceAll(string(fileContent), currentGitHash, promotionGitHash)
}
}
err = os.WriteFile(saasFile, []byte(newContent), 0600)
if err != nil {
return fmt.Errorf("failed to write to file %s: %v", saasFile, err)
}
return nil
}
func (a *AppInterface) UpdatePackageTag(saasFile, oldTag, promotionTag, branchName string) error {
// Note: Caller should have already synced with origin/master before calling this function
// to ensure oldTag is accurate
if err := a.GitExecutor.Run(a.GitDirectory, "git", "branch", "-D", branchName); err != nil {
fmt.Printf("failed to cleanup branch %s: %v, continuing to create it.\n", branchName, err)
}
// Update the hash in the SAAS file
fileContent, err := os.ReadFile(saasFile)
if err != nil {
return fmt.Errorf("failed to read file %s: %v", saasFile, err)
}
// Replace the hash in the file content
newContent := strings.ReplaceAll(string(fileContent), oldTag, promotionTag)
err = os.WriteFile(saasFile, []byte(newContent), 0600)
if err != nil {
return fmt.Errorf("failed to write to file %s: %v", saasFile, err)
}
return nil
}
func (a *AppInterface) CommitSaasFile(saasFile, commitMessage string) error {
// Commit the change
if err := a.GitExecutor.Run(a.GitDirectory, "git", "add", saasFile); err != nil {
return fmt.Errorf("failed to add file %s: %v", saasFile, err)
}
if err := a.GitExecutor.Run(a.GitDirectory, "git", "commit", "-m", commitMessage); err != nil {
return fmt.Errorf("failed to commit changes: %v", err)
}
return nil
}
func (a *AppInterface) CommitSaasAndAppYmlFile(saasFile, serviceName, commitMessage string) error {
if err := a.GitExecutor.Run(a.GitDirectory, "git", "add", saasFile); err != nil {
return fmt.Errorf("failed to add file %s: %v", saasFile, err)
}
componentName := strings.TrimPrefix(serviceName, "saas-")
appYmlPath, err := pathutil.DeriveAppYmlPath(a.GitDirectory, saasFile, componentName)
if err != nil {
return fmt.Errorf("failed to derive app.yml path: %v", err)
}
if err := a.GitExecutor.Run(a.GitDirectory, "git", "add", appYmlPath); err != nil {
return fmt.Errorf("failed to add file %s: %v", appYmlPath, err)
}
if err := a.GitExecutor.Run(a.GitDirectory, "git", "commit", "-m", commitMessage); err != nil {
return fmt.Errorf("failed to commit changes: %v", err)
}
return nil
}