Skip to content

Commit 19c3286

Browse files
Merge pull request #79 from drpaneas/mm
OSD-6004 - Allow generic var replacement for any usecase
2 parents 1cb7f12 + b92900e commit 19c3286

File tree

3 files changed

+76
-32
lines changed

3 files changed

+76
-32
lines changed

cmd/post.go

Lines changed: 59 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -19,36 +19,38 @@ import (
1919
)
2020

2121
var (
22-
template, clusterUUID, caseID string
23-
isURL bool
24-
HTMLBody []byte
25-
Message servicelog.Message
26-
GoodReply servicelog.GoodReply
27-
BadReply servicelog.BadReply
22+
template string
23+
isURL bool
24+
HTMLBody []byte
25+
Message servicelog.Message
26+
GoodReply servicelog.GoodReply
27+
BadReply servicelog.BadReply
28+
templateParams, userParameterNames, userParameterValues []string
2829
)
2930

3031
const (
31-
defaultTemplate = ""
32-
defaultClusterUUID = ""
33-
defaultCaseID = ""
34-
targetAPIPath = "/api/service_logs/v1/cluster_logs" // https://api.openshift.com/?urls.primaryName=Service%20logs#/default/post_api_service_logs_v1_cluster_logs
35-
modifiedJSON = "modified-template.json"
36-
clusterParameter = "${CLUSTER_UUID}"
37-
caseIDParameter = "${CASE_ID}"
38-
clusterUUIDLongName = "cluster-external-id"
39-
caseIDLongName = "support-case-id"
40-
clusterUUIDShorthand = "c"
41-
caseIDShorthand = "i"
32+
defaultTemplate = ""
33+
targetAPIPath = "/api/service_logs/v1/cluster_logs" // https://api.openshift.com/?urls.primaryName=Service%20logs#/default/post_api_service_logs_v1_cluster_logs
34+
modifiedJSON = "modified-template.json"
4235
)
4336

4437
// postCmd represents the post command
4538
var postCmd = &cobra.Command{
4639
Use: "post",
4740
Short: "Send a servicelog message to a given cluster",
4841
Run: func(cmd *cobra.Command, args []string) {
49-
readTemplate() // verify and parse
50-
replaceFlags(clusterUUID, defaultClusterUUID, clusterParameter, clusterUUIDLongName, clusterUUIDShorthand)
51-
replaceFlags(caseID, defaultCaseID, caseIDParameter, caseIDLongName, caseIDShorthand)
42+
43+
parseUserParameters() // parse all the '-p' user flags
44+
45+
readTemplate() // parse the given JSON template provided via '-t' flag
46+
47+
// For every '-p' flag, replace its related placeholder in the template
48+
for k, v := range templateParams {
49+
replaceFlags(userParameterValues[k], "", userParameterNames[k], userParameterNames[k], "p", v)
50+
}
51+
52+
// Check if there are any remaining placeholders in the template that are not replaced by a parameter
53+
checkLeftovers()
5254

5355
dir := tempDir()
5456
defer cleanup(dir)
@@ -75,8 +77,23 @@ var postCmd = &cobra.Command{
7577
func init() {
7678
// define required flags
7779
postCmd.Flags().StringVarP(&template, "template", "t", defaultTemplate, "Message template file or URL")
78-
postCmd.Flags().StringVarP(&clusterUUID, clusterUUIDLongName, clusterUUIDShorthand, defaultClusterUUID, "Target cluster UUID")
79-
postCmd.Flags().StringVarP(&caseID, caseIDLongName, caseIDShorthand, defaultCaseID, "Related ticket (RedHat Support Case ID)")
80+
postCmd.Flags().StringArrayVarP(&templateParams, "param", "p", templateParams, "Specify a key-value pair (eg. -p FOO=BAR) to set/override a parameter value in the template.")
81+
}
82+
83+
// parseUserParameters parse all the '-p FOO=BAR' parameters and checks for syntax errors
84+
func parseUserParameters() {
85+
for k, v := range templateParams {
86+
if !strings.Contains(v, "=") {
87+
log.Fatalf("Wrong syntax of '-p' flag. Please use it like this: '-p FOO=BAR'")
88+
}
89+
90+
userParameterNames = append(userParameterNames, fmt.Sprintf("${%v}", strings.Split(v, "=")[0]))
91+
userParameterValues = append(userParameterValues, strings.Split(v, "=")[1])
92+
93+
if userParameterValues[k] == "" {
94+
log.Fatalf("Wrong syntax of '-p' flag. Please use it like this: '-p FOO=BAR'")
95+
}
96+
}
8097
}
8198

8299
// accessTemplate checks if the provided template is currently accessible and returns an error
@@ -146,16 +163,31 @@ func readTemplate() {
146163
}
147164
}
148165

149-
func replaceFlags(flagName, flagDefaultValue, flagParameter, flagLongName, flagShorthand string) {
166+
func checkLeftovers() {
167+
unusedParameters, found := Message.FindLeftovers()
168+
if found {
169+
for _, v := range unusedParameters {
170+
regex := strings.NewReplacer("${", "", "}", "")
171+
log.Errorf("The selected template is using '%s' parameter, but '--%s' flag is not set for this one. Use '-%s %v=\"FOOBAR\"' to fix this.", v, "param", "p", regex.Replace(v))
172+
}
173+
if numberOfMissingParameters := len(unusedParameters); numberOfMissingParameters == 1 {
174+
log.Fatal("Please define this missing parameter properly.")
175+
} else {
176+
log.Fatalf("Please define all %v missing parameters properly.", numberOfMissingParameters)
177+
}
178+
}
179+
}
180+
181+
func replaceFlags(flagName, flagDefaultValue, flagParameter, flagLongName, flagShorthand, parameter string) {
150182
if err := strings.Compare(flagName, flagDefaultValue); err == 0 {
151183
// The user didn't set the flag. Check if the template is using the flag.
152184
if found := Message.SearchFlag(flagParameter); found == true {
153-
log.Fatalf("The selected template is using '%s' parameter, but '%s' flag is not set. Use '-%s' to fix this.", flagParameter, flagLongName, flagShorthand)
185+
log.Fatalf("The selected template is using '%s' parameter, but '%s' flag was not set. Use '-%s' to fix this.", flagParameter, flagLongName, flagShorthand)
154186
}
155187
} else {
156188
// The user set the flag. Check if the template is using the flag.
157189
if found := Message.SearchFlag(flagParameter); found == false {
158-
log.Fatalf("The selected template is not using '%s' parameter, but '%s' flag is set. Do not use '-%s' to fix this.", flagParameter, flagLongName, flagShorthand)
190+
log.Fatalf("The selected template is not using '%s' parameter, but '--%s' flag was set. Do not use '-%s %s' to fix this.", flagParameter, "param", flagShorthand, parameter)
159191
}
160192
Message.ReplaceWithFlag(flagParameter, flagName)
161193
}
@@ -261,8 +293,8 @@ func validateGoodResponse(body []byte) {
261293
log.Fatalf("Message sent, but wrong service_name information was passed (wanted %q, got %q)", Message.ServiceName, serviceName)
262294
}
263295
clusteruuid := GoodReply.ClusterUUID
264-
if clusterUUID != clusteruuid {
265-
log.Fatalf("Message sent, but to different cluster (wanted %q, got %q)", clusterUUID, clusteruuid)
296+
if clusteruuid != Message.ClusterUUID {
297+
log.Fatalf("Message sent, but to different cluster (wanted %q, got %q)", Message.ClusterUUID, clusteruuid)
266298
}
267299
summary := GoodReply.Summary
268300
if summary != Message.Summary {

docs/command/osdctl_servicelog_post.md

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,10 +13,9 @@ osdctl servicelog post [flags]
1313
### Options
1414

1515
```
16-
-c, --cluster-external-id string Target cluster UUID
17-
-h, --help help for post
18-
-i, --support-case-id string Related ticket (RedHat Support Case ID)
19-
-t, --template string Message template file or URL
16+
-h, --help help for post
17+
-p, --param stringArray Specify a key-value pair (eg. -p FOO=BAR) to set/override a parameter value in the template.
18+
-t, --template string Message template file or URL
2019
```
2120

2221
### Options inherited from parent commands

internal/servicelog/template.go

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
package servicelog
22

3-
import "strings"
3+
import (
4+
"regexp"
5+
"strings"
6+
)
47

58
// Message is the base template structure
69
type Message struct {
@@ -62,3 +65,13 @@ func (m *Message) SearchFlag(placeholder string) (found bool) {
6265
}
6366
return false
6467
}
68+
69+
func (m *Message) FindLeftovers() (matches []string, found bool) {
70+
r := regexp.MustCompile(`\${[^{}]*}`)
71+
str := m.Severity + m.ServiceName + m.ClusterUUID + m.Summary + m.Description
72+
matches = r.FindAllString(str, -1)
73+
if len(matches) > 0 {
74+
found = true
75+
}
76+
return matches, found
77+
}

0 commit comments

Comments
 (0)