-
Notifications
You must be signed in to change notification settings - Fork 136
Expand file tree
/
Copy pathutils.go
More file actions
373 lines (312 loc) · 13.2 KB
/
utils.go
File metadata and controls
373 lines (312 loc) · 13.2 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
371
372
373
package saas
import (
"fmt"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"github.com/openshift/osdctl/cmd/promote/git"
"github.com/openshift/osdctl/cmd/promote/iexec"
"github.com/openshift/osdctl/cmd/promote/pathutil"
kyaml "sigs.k8s.io/kustomize/kyaml/yaml"
)
const (
OSDSaasDir = "data/services/osd-operators/cicd/saas"
BPSaasDir = "data/services/backplane/cicd/saas"
CADSaasDir = "data/services/configuration-anomaly-detection/cicd"
)
var (
ServicesSlice []string
ServicesFilesMap = map[string]string{}
)
func listServiceNames(appInterface git.AppInterface) error {
_, err := GetServiceNames(appInterface, OSDSaasDir, BPSaasDir, CADSaasDir)
if err != nil {
return err
}
sort.Strings(ServicesSlice)
fmt.Println("### Available service names ###")
for _, service := range ServicesSlice {
fmt.Println(service)
}
return nil
}
// discoverPipelineNamespace reads the SaaS file to find the actual pipeline namespace.
// The namespace may differ from the operator name due to abbreviations or inconsistencies.
//
// For example:
// - Operator: managed-cluster-validating-webhooks
// - Namespace: mcvw-pipelines (abbreviated)
//
// This function extracts the namespace from the pipelinesProvider.$ref field in the SaaS YAML.
func discoverPipelineNamespace(appInterface git.AppInterface, serviceName string) (string, error) {
// Get the SaaS file path from the services map
saasFilePath, ok := ServicesFilesMap[serviceName]
if !ok {
return "", fmt.Errorf("saas file not found for service %s", serviceName)
}
// Read the SaaS YAML file
fileContent, err := os.ReadFile(saasFilePath)
if err != nil {
return "", fmt.Errorf("failed to read SaaS file: %w", err)
}
// Parse YAML to get the pipelinesProvider reference
node, err := kyaml.Parse(string(fileContent))
if err != nil {
return "", fmt.Errorf("failed to parse SaaS YAML: %w", err)
}
// Extract pipelinesProvider.$ref path
// Example: "/services/osd-operators/managed-cluster-validating-webhooks/pipelines/tekton-mcvw-pipelines.appsrep09ue1.yaml"
pipelineRef, err := node.GetString("pipelinesProvider.$ref")
if err != nil {
return "", fmt.Errorf("failed to get pipelinesProvider.$ref: %w", err)
}
// Extract namespace from the pipeline provider filename
// Format: "tekton-{namespace}.appsrep09ue1.yaml" or "tekton.{namespace}.appsrep09ue1.yaml"
filename := filepath.Base(pipelineRef)
// Remove "tekton-" or "tekton." prefix
namespace := strings.TrimPrefix(filename, "tekton-")
namespace = strings.TrimPrefix(namespace, "tekton.")
// Remove cluster-specific suffix (e.g ".appsrep09ue1.yaml")
// Pattern: .{cluster-name}.yaml where cluster-name starts with "apps", "hive", etc.
if idx := strings.Index(namespace, "."); idx > 0 {
namespace = namespace[:idx]
}
if namespace == "" {
return "", fmt.Errorf("could not extract namespace from pipelinesProvider: %s", pipelineRef)
}
fmt.Printf("Discovered pipeline namespace: %s\n", namespace)
return namespace, nil
}
// generatePipelineLogsURL creates a Tekton console URL for viewing pipeline logs
// for the given operator. The URL points directly to the PipelineRuns list page
// in the operator's pipeline namespace on the appsrep09ue1 cluster.
//
// This function discovers the actual namespace from the SaaS file's pipelinesProvider
// reference to handle cases where the namespace name differs from the operator name
// (e.g mcvw-pipelines vs mc-validating-webhooks-pipelines).
//
// This provides immediate access to pipeline execution logs without dependency on
// log forwarding to external systems. Users can view all recent PipelineRuns and
// filter by environment, timestamp, or status directly in the Tekton console.
//
// Note: The env parameter is no longer used in URL construction since both INT
// and STAGE PipelineRuns are visible in the same namespace. It's kept for backward
// compatibility and may be removed in future versions.
func generatePipelineLogsURL(appInterface git.AppInterface, serviceName, operatorName, gitHash string, env string) string {
// Tekton console base URL for the appsrep09ue1 cluster where pipelines run
consoleBaseURL := "https://console-openshift-console.apps.rosa.appsrep09ue1.03r5.p3.openshiftapps.com"
// Try to discover the actual namespace from the SaaS file
namespace, err := discoverPipelineNamespace(appInterface, serviceName)
if err != nil {
// Fallback to constructing namespace from operator name
namespace = fmt.Sprintf("%s-pipelines", operatorName)
fmt.Printf("Warning: Could not discover namespace for %s (error: %v)\n", serviceName, err)
fmt.Printf("Falling back to standard convention: %s\n", namespace)
}
// Build URL to PipelineRuns list page for this operator's namespace
// Format: /k8s/ns/{namespace}/tekton.dev~v1~PipelineRun
url := fmt.Sprintf("%s/k8s/ns/%s/tekton.dev~v1~PipelineRun",
consoleBaseURL,
namespace)
return url
}
func servicePromotion(appInterface git.AppInterface, serviceName, gitHash string, namespaceRef string, osd, hcp, hotfix bool) error {
_, err := GetServiceNames(appInterface, OSDSaasDir, BPSaasDir, CADSaasDir)
if err != nil {
return err
}
serviceName, err = ValidateServiceName(ServicesSlice, serviceName)
if err != nil {
return err
}
saasDir, err := GetSaasDir(serviceName, osd, hcp)
if err != nil {
return err
}
fmt.Printf("SAAS Directory: %v\n", saasDir)
serviceData, err := os.ReadFile(saasDir)
if err != nil {
return fmt.Errorf("failed to read SAAS file: %v", err)
}
currentGitHash, serviceRepo, err := git.GetCurrentGitHashFromAppInterface(serviceData, serviceName, namespaceRef)
if err != nil {
return fmt.Errorf("failed to get current git hash or service repo: %v", err)
}
fmt.Printf("Current Git Hash: %v\nGit Repo: %v\n\n", currentGitHash, serviceRepo)
promotionGitHash, commitLog, err := git.CheckoutAndCompareGitHash(appInterface.GitExecutor, serviceRepo, gitHash, currentGitHash, "")
if err != nil {
return fmt.Errorf("failed to checkout and compare git hash: %v", err)
} else if promotionGitHash == "" {
fmt.Printf("Unable to find a git hash to promote. Exiting.\n")
os.Exit(6)
}
fmt.Printf("Service: %s will be promoted to %s\n", serviceName, promotionGitHash)
branchName := fmt.Sprintf("promote-%s-%s", serviceName, promotionGitHash)
err = appInterface.UpdateAppInterface(serviceName, saasDir, currentGitHash, promotionGitHash, branchName, hotfix)
if err != nil {
fmt.Printf("FAILURE: %v\n", err)
}
if hotfix {
err = updateAppYmlWithHotfix(appInterface, serviceName, saasDir, promotionGitHash)
if err != nil {
return fmt.Errorf("failed to update app.yml with hotfix: %v", err)
}
}
prefix := "saas-"
operatorName := strings.TrimPrefix(serviceName, prefix)
// Generate pipeline logs URLs for INT and STAGE validation
intPipelineLogsURL := generatePipelineLogsURL(appInterface, serviceName, operatorName, promotionGitHash, "int")
stagePipelineLogsURL := generatePipelineLogsURL(appInterface, serviceName, operatorName, promotionGitHash, "stage")
// Build GitLab Markdown formatted commit message
var commitMessage string
if hotfix {
commitMessage = fmt.Sprintf("Promote %s to %s (HOTFIX; bypass progressive delivery)\n\n", serviceName, promotionGitHash)
} else {
commitMessage = fmt.Sprintf("Promote %s to %s\n\n", serviceName, promotionGitHash)
}
// Add monitoring and validation links section
commitMessage += "## Monitoring and Validation\n\n"
commitMessage += fmt.Sprintf("- 📊 [Monitor rollout status](https://inscope.corp.redhat.com/catalog/default/component/%s/rollout)\n", operatorName)
// Note: INT runs dedicated E2E test pipelines, while STAGE typically runs deployment pipelines.
// Both links point to the same namespace, but the labels reflect the primary pipeline type for each environment.
commitMessage += fmt.Sprintf("- 🧪 [View INT e2e test logs](%s)\n", intPipelineLogsURL)
commitMessage += fmt.Sprintf("- 📦 [View STAGE deployment logs](%s)\n", stagePipelineLogsURL)
commitMessage += "- 🚨 [View Platform SRE Int/Stage incident activity](https://redhat.pagerduty.com/analytics/insights/incident-activity-report/9wMMqHHHSuvd8jMF1sByzA)\n"
commitMessage += "- 📈 [View Int/Stage PagerDuty Dashboard](https://redhat.pagerduty.com/analytics/overview-dashboard/sSWGx0MIdgVckAwpwbix8A)\n\n"
// Add changes section
commitMessage += "## Changes\n\n"
commitMessage += fmt.Sprintf("[Compare changes on GitHub](%s/compare/%s...%s)\n\n", serviceRepo, currentGitHash, promotionGitHash)
// Add commit log in code block for better formatting
commitMessage += "### Commit Log\n\n```\n"
commitMessage += commitLog
commitMessage += "\n```"
fmt.Printf("commitMessage: %s\n", commitMessage)
// ovverriding appInterface.GitExecuter to iexec.Exec{}
appInterface.GitExecutor = iexec.Exec{}
if hotfix {
err = appInterface.CommitSaasAndAppYmlFile(saasDir, serviceName, commitMessage)
} else {
err = appInterface.CommitSaasFile(saasDir, commitMessage)
}
if err != nil {
return fmt.Errorf("failed to commit changes to app-interface; manual commit may still succeed: %w", err)
}
fmt.Printf("The branch %s is ready to be pushed\n", branchName)
fmt.Println("")
fmt.Println("service:", serviceName)
fmt.Println("from:", currentGitHash)
fmt.Println("to:", promotionGitHash)
fmt.Println("READY TO PUSH,", serviceName, "promotion commit is ready locally")
return nil
}
func GetServiceNames(appInterface git.AppInterface, saaDirs ...string) ([]string, error) {
baseDir := appInterface.GitDirectory
for _, dir := range saaDirs {
dirGlob := filepath.Join(baseDir, dir, "saas-*")
filepaths, err := filepath.Glob(dirGlob)
if err != nil {
return nil, err
}
for _, filepath := range filepaths {
filename := strings.TrimPrefix(filepath, baseDir+"/"+dir+"/")
filename = strings.TrimSuffix(filename, ".yaml")
ServicesSlice = append(ServicesSlice, filename)
ServicesFilesMap[filename] = filepath
}
}
return ServicesSlice, nil
}
func ValidateServiceName(serviceSlice []string, serviceName string) (string, error) {
fmt.Printf("### Checking if service %s exists ###\n", serviceName)
for _, service := range serviceSlice {
if service == serviceName {
fmt.Printf("Service %s found\n", serviceName)
return serviceName, nil
}
if service == "saas-"+serviceName {
fmt.Printf("Service %s found\n", serviceName)
return "saas-" + serviceName, nil
}
}
return serviceName, fmt.Errorf("service %s not found", serviceName)
}
func GetSaasDir(serviceName string, osd bool, hcp bool) (string, error) {
if saasDir, ok := ServicesFilesMap[serviceName]; ok {
if strings.Contains(saasDir, ".yaml") && osd {
return saasDir, nil
}
// This is a hack while we migrate the rest of the operators unto Progressive Delivery
if osd {
saasDir = saasDir + "/deploy.yaml"
return saasDir, nil
} else if hcp {
saasDir = saasDir + "/hypershift-deploy.yaml"
return saasDir, nil
}
}
return "", fmt.Errorf("saas directory for service %s not found", serviceName)
}
// sets the hotfix git sha in app.yml, adding hotfixVersions to codeComponents if it does not exist, and otherwise overwriting the existing sha value
func setHotfixVersion(fileContent string, componentName string, gitHash string) (string, error, bool) {
node, err := kyaml.Parse(fileContent)
if err != nil {
return "", fmt.Errorf("error parsing app.yml: %v", err), false
}
componentFound := false
codeComponents, err := kyaml.Lookup("codeComponents").Filter(node)
if err != nil {
return "", fmt.Errorf("error querying codeComponents: %v", err), false
}
for i := range len(codeComponents.Content()) {
component, err := kyaml.Lookup("codeComponents", strconv.Itoa(i)).Filter(node)
if err != nil {
return "", fmt.Errorf("error querying component %d: %v", i, err), false
}
name, _ := component.GetString("name")
if name == componentName {
componentFound = true
fmt.Printf("Found component: %s\n", name)
fmt.Printf("Set hotfixVersions to [%s]\n", gitHash)
listYaml := fmt.Sprintf("- %s\n", gitHash)
listNode, err := kyaml.Parse(listYaml)
if err != nil {
return "", fmt.Errorf("failed to create hotfixVerions list: %v", err), false
}
_, err = component.Pipe(kyaml.SetField("hotfixVersions", listNode))
if err != nil {
return "", fmt.Errorf("error setting hotfixVersions: %v", err), false
}
break
}
}
return node.MustString(), err, componentFound
}
// locates the corresponding app.yml file, and updates the file with the hotfix sha
func updateAppYmlWithHotfix(appInterface git.AppInterface, serviceName, saasDir, gitHash string) error {
componentName := strings.TrimPrefix(serviceName, "saas-")
appYmlPath, err := pathutil.DeriveAppYmlPath(appInterface.GitDirectory, saasDir, componentName)
if err != nil {
return fmt.Errorf("failed to derive app.yml path: %v", err)
}
if _, err := os.Stat(appYmlPath); os.IsNotExist(err) {
return fmt.Errorf("app.yml file not found at %s", appYmlPath)
}
fileContent, err := os.ReadFile(appYmlPath)
if err != nil {
return fmt.Errorf("failed to read app.yml file: %v", err)
}
newContent, err, found := setHotfixVersion(string(fileContent), componentName, gitHash)
if err != nil {
return fmt.Errorf("error modifying app.yml: %v", err)
}
if !found {
return fmt.Errorf("component %s not found in app.yml", componentName)
}
err = os.WriteFile(appYmlPath, []byte(newContent), 0600)
if err != nil {
return fmt.Errorf("failed to write updated app.yml: %v", err)
}
return nil
}