Skip to content

Commit a242362

Browse files
authored
notification plugins: readability / dry refact, unnecessary pointers (#4166)
1 parent 17aa12f commit a242362

File tree

6 files changed

+97
-79
lines changed

6 files changed

+97
-79
lines changed

cmd/notification-dummy/main.go

Lines changed: 19 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -14,9 +14,9 @@ import (
1414
)
1515

1616
type PluginConfig struct {
17-
Name string `yaml:"name"`
18-
LogLevel *string `yaml:"log_level"`
19-
OutputFile *string `yaml:"output_file"`
17+
Name string `yaml:"name"`
18+
LogLevel string `yaml:"log_level"`
19+
OutputFile string `yaml:"output_file"`
2020
}
2121

2222
type DummyPlugin struct {
@@ -32,26 +32,30 @@ var logger hclog.Logger = hclog.New(&hclog.LoggerOptions{
3232
})
3333

3434
func (s *DummyPlugin) Notify(_ context.Context, notification *protobufs.Notification) (*protobufs.Empty, error) {
35-
if _, ok := s.PluginConfigByName[notification.GetName()]; !ok {
36-
return nil, fmt.Errorf("invalid plugin config name %s", notification.GetName())
37-
}
35+
name := notification.GetName()
36+
cfg, ok := s.PluginConfigByName[name]
3837

39-
cfg := s.PluginConfigByName[notification.GetName()]
38+
if !ok {
39+
return nil, fmt.Errorf("invalid plugin config name %s", name)
40+
}
4041

41-
if cfg.LogLevel != nil && *cfg.LogLevel != "" {
42-
logger.SetLevel(hclog.LevelFromString(*cfg.LogLevel))
42+
if cfg.LogLevel != "" {
43+
logger.SetLevel(hclog.LevelFromString(cfg.LogLevel))
4344
}
4445

45-
logger.Info(fmt.Sprintf("received signal for %s config", notification.GetName()))
46-
logger.Debug(notification.GetText())
46+
logger.Info(fmt.Sprintf("received signal for %s config", name))
47+
48+
text := notification.GetText()
49+
50+
logger.Debug(text)
4751

48-
if cfg.OutputFile != nil && *cfg.OutputFile != "" {
49-
f, err := os.OpenFile(*cfg.OutputFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644)
52+
if cfg.OutputFile != "" {
53+
f, err := os.OpenFile(cfg.OutputFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644)
5054
if err != nil {
5155
logger.Error(fmt.Sprintf("Cannot open notification file: %s", err))
5256
}
5357

54-
if _, err := f.WriteString(notification.GetText() + "\n"); err != nil {
58+
if _, err := f.WriteString(text + "\n"); err != nil {
5559
f.Close()
5660
logger.Error(fmt.Sprintf("Cannot write notification to file: %s", err))
5761
}
@@ -62,7 +66,7 @@ func (s *DummyPlugin) Notify(_ context.Context, notification *protobufs.Notifica
6266
}
6367
}
6468

65-
fmt.Fprintln(os.Stdout, notification.GetText())
69+
fmt.Fprintln(os.Stdout, text)
6670

6771
return &protobufs.Empty{}, nil
6872
}

cmd/notification-email/main.go

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -37,8 +37,8 @@ var EncryptionStringToType map[string]mail.Encryption = map[string]mail.Encrypti
3737
}
3838

3939
type PluginConfig struct {
40-
Name string `yaml:"name"`
41-
LogLevel *string `yaml:"log_level"`
40+
Name string `yaml:"name"`
41+
LogLevel string `yaml:"log_level"`
4242

4343
SMTPHost string `yaml:"smtp_host"`
4444
SMTPPort int `yaml:"smtp_port"`
@@ -94,16 +94,17 @@ func (n *EmailPlugin) Configure(_ context.Context, config *protobufs.Config) (*p
9494
}
9595

9696
func (n *EmailPlugin) Notify(_ context.Context, notification *protobufs.Notification) (*protobufs.Empty, error) {
97-
if _, ok := n.ConfigByName[notification.GetName()]; !ok {
98-
return nil, fmt.Errorf("invalid plugin config name %s", notification.GetName())
99-
}
97+
name := notification.GetName()
98+
cfg, ok := n.ConfigByName[name]
10099

101-
cfg := n.ConfigByName[notification.GetName()]
100+
if !ok {
101+
return nil, fmt.Errorf("invalid plugin config name %s", name)
102+
}
102103

103104
logger := baseLogger.Named(cfg.Name)
104105

105-
if cfg.LogLevel != nil && *cfg.LogLevel != "" {
106-
logger.SetLevel(hclog.LevelFromString(*cfg.LogLevel))
106+
if cfg.LogLevel != "" {
107+
logger.SetLevel(hclog.LevelFromString(cfg.LogLevel))
107108
}
108109

109110
logger.Debug("got notification")

cmd/notification-http/main.go

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ type PluginConfig struct {
2727
Headers map[string]string `yaml:"headers"`
2828
SkipTLSVerification bool `yaml:"skip_tls_verification"`
2929
Method string `yaml:"method"`
30-
LogLevel *string `yaml:"log_level"`
30+
LogLevel string `yaml:"log_level"`
3131
Client *http.Client `yaml:"-"`
3232
CertPath string `yaml:"cert_path"`
3333
KeyPath string `yaml:"key_path"`
@@ -117,19 +117,22 @@ func getTLSClient(c *PluginConfig) error {
117117
}
118118

119119
func (s *HTTPPlugin) Notify(ctx context.Context, notification *protobufs.Notification) (*protobufs.Empty, error) {
120-
if _, ok := s.PluginConfigByName[notification.GetName()]; !ok {
121-
return nil, fmt.Errorf("invalid plugin config name %s", notification.GetName())
122-
}
120+
name := notification.GetName()
121+
cfg, ok := s.PluginConfigByName[name]
123122

124-
cfg := s.PluginConfigByName[notification.GetName()]
123+
if !ok {
124+
return nil, fmt.Errorf("invalid plugin config name %s", name)
125+
}
125126

126-
if cfg.LogLevel != nil && *cfg.LogLevel != "" {
127-
logger.SetLevel(hclog.LevelFromString(*cfg.LogLevel))
127+
if cfg.LogLevel != "" {
128+
logger.SetLevel(hclog.LevelFromString(cfg.LogLevel))
128129
}
129130

130-
logger.Info(fmt.Sprintf("received signal for %s config", notification.GetName()))
131+
logger.Info(fmt.Sprintf("received signal for %s config", name))
132+
133+
text := notification.GetText()
131134

132-
request, err := http.NewRequestWithContext(ctx, cfg.Method, cfg.URL, bytes.NewReader([]byte(notification.GetText())))
135+
request, err := http.NewRequestWithContext(ctx, cfg.Method, cfg.URL, bytes.NewReader([]byte(text)))
133136
if err != nil {
134137
return nil, err
135138
}
@@ -139,7 +142,7 @@ func (s *HTTPPlugin) Notify(ctx context.Context, notification *protobufs.Notific
139142
request.Header.Add(headerName, headerValue)
140143
}
141144

142-
logger.Debug(fmt.Sprintf("making HTTP %s call to %s with body %s", cfg.Method, cfg.URL, notification.GetText()))
145+
logger.Debug(fmt.Sprintf("making HTTP %s call to %s with body %s", cfg.Method, cfg.URL, text))
143146

144147
resp, err := cfg.Client.Do(request.WithContext(ctx))
145148
if err != nil {

cmd/notification-sentinel/main.go

Lines changed: 24 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -20,11 +20,11 @@ import (
2020
)
2121

2222
type PluginConfig struct {
23-
Name string `yaml:"name"`
24-
CustomerID string `yaml:"customer_id"`
25-
SharedKey string `yaml:"shared_key"`
26-
LogType string `yaml:"log_type"`
27-
LogLevel *string `yaml:"log_level"`
23+
Name string `yaml:"name"`
24+
CustomerID string `yaml:"customer_id"`
25+
SharedKey string `yaml:"shared_key"`
26+
LogType string `yaml:"log_type"`
27+
LogLevel string `yaml:"log_level"`
2828
}
2929

3030
type SentinelPlugin struct {
@@ -39,43 +39,48 @@ var logger hclog.Logger = hclog.New(&hclog.LoggerOptions{
3939
JSONFormat: true,
4040
})
4141

42-
func (s *SentinelPlugin) getAuthorizationHeader(now string, length int, pluginName string) (string, error) {
42+
func (s *SentinelPlugin) getAuthorizationHeader(now string, length int, name string) (string, error) {
4343
xHeaders := "X-Ms-Date:" + now
4444

45+
cfg := s.PluginConfigByName[name]
46+
4547
stringToHash := fmt.Sprintf("POST\n%d\napplication/json\n%s\n/api/logs", length, xHeaders)
46-
decodedKey, _ := base64.StdEncoding.DecodeString(s.PluginConfigByName[pluginName].SharedKey)
48+
decodedKey, _ := base64.StdEncoding.DecodeString(cfg.SharedKey)
4749

4850
h := hmac.New(sha256.New, decodedKey)
4951
h.Write([]byte(stringToHash))
5052

5153
encodedHash := base64.StdEncoding.EncodeToString(h.Sum(nil))
52-
authorization := "SharedKey " + s.PluginConfigByName[pluginName].CustomerID + ":" + encodedHash
54+
authorization := "SharedKey " + cfg.CustomerID + ":" + encodedHash
5355

5456
logger.Trace("authorization header", "header", authorization)
5557

5658
return authorization, nil
5759
}
5860

5961
func (s *SentinelPlugin) Notify(ctx context.Context, notification *protobufs.Notification) (*protobufs.Empty, error) {
60-
if _, ok := s.PluginConfigByName[notification.GetName()]; !ok {
61-
return nil, fmt.Errorf("invalid plugin config name %s", notification.GetName())
62-
}
62+
name := notification.GetName()
63+
cfg, ok := s.PluginConfigByName[name]
6364

64-
cfg := s.PluginConfigByName[notification.GetName()]
65+
if !ok {
66+
return nil, fmt.Errorf("invalid plugin config name %s", name)
67+
}
6568

66-
if cfg.LogLevel != nil && *cfg.LogLevel != "" {
67-
logger.SetLevel(hclog.LevelFromString(*cfg.LogLevel))
69+
if cfg.LogLevel != "" {
70+
logger.SetLevel(hclog.LevelFromString(cfg.LogLevel))
6871
}
6972

70-
logger.Info("received notification for sentinel config", "name", notification.GetName())
73+
logger.Info("received notification for sentinel config", "name", name)
74+
75+
text := notification.GetText()
7176

72-
url := fmt.Sprintf("https://%s.ods.opinsights.azure.com/api/logs?api-version=2016-04-01", s.PluginConfigByName[notification.GetName()].CustomerID)
73-
body := strings.NewReader(notification.GetText())
77+
url := fmt.Sprintf("https://%s.ods.opinsights.azure.com/api/logs?api-version=2016-04-01", cfg.CustomerID)
78+
body := strings.NewReader(text)
7479

7580
// Cannot use time.RFC1123 as azure wants GMT, not UTC
7681
now := time.Now().UTC().Format("Mon, 02 Jan 2006 15:04:05 GMT")
7782

78-
authorization, err := s.getAuthorizationHeader(now, len(notification.GetText()), notification.GetName())
83+
authorization, err := s.getAuthorizationHeader(now, len(text), name)
7984
if err != nil {
8085
return &protobufs.Empty{}, err
8186
}
@@ -87,7 +92,7 @@ func (s *SentinelPlugin) Notify(ctx context.Context, notification *protobufs.Not
8792
}
8893

8994
req.Header.Set("Content-Type", "application/json")
90-
req.Header.Set("Log-Type", s.PluginConfigByName[notification.GetName()].LogType)
95+
req.Header.Set("Log-Type", cfg.LogType)
9196
req.Header.Set("Authorization", authorization)
9297
req.Header.Set("X-Ms-Date", now)
9398

cmd/notification-slack/main.go

Lines changed: 20 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -15,13 +15,13 @@ import (
1515
)
1616

1717
type PluginConfig struct {
18-
Name string `yaml:"name"`
19-
Webhook string `yaml:"webhook"`
20-
Channel string `yaml:"channel"`
21-
Username string `yaml:"username"`
22-
IconEmoji string `yaml:"icon_emoji"`
23-
IconURL string `yaml:"icon_url"`
24-
LogLevel *string `yaml:"log_level"`
18+
Name string `yaml:"name"`
19+
Webhook string `yaml:"webhook"`
20+
Channel string `yaml:"channel"`
21+
Username string `yaml:"username"`
22+
IconEmoji string `yaml:"icon_emoji"`
23+
IconURL string `yaml:"icon_url"`
24+
LogLevel string `yaml:"log_level"`
2525
}
2626
type Notify struct {
2727
protobufs.UnimplementedNotifierServer
@@ -36,21 +36,25 @@ var logger hclog.Logger = hclog.New(&hclog.LoggerOptions{
3636
})
3737

3838
func (n *Notify) Notify(ctx context.Context, notification *protobufs.Notification) (*protobufs.Empty, error) {
39-
if _, ok := n.ConfigByName[notification.GetName()]; !ok {
40-
return nil, fmt.Errorf("invalid plugin config name %s", notification.GetName())
41-
}
39+
name := notification.GetName()
40+
41+
cfg, ok := n.ConfigByName[name]
4242

43-
cfg := n.ConfigByName[notification.GetName()]
43+
if !ok {
44+
return nil, fmt.Errorf("invalid plugin config name %s", name)
45+
}
4446

45-
if cfg.LogLevel != nil && *cfg.LogLevel != "" {
46-
logger.SetLevel(hclog.LevelFromString(*cfg.LogLevel))
47+
if cfg.LogLevel != "" {
48+
logger.SetLevel(hclog.LevelFromString(cfg.LogLevel))
4749
}
4850

49-
logger.Info(fmt.Sprintf("found notify signal for %s config", notification.GetName()))
50-
logger.Debug(fmt.Sprintf("posting to %s webhook, message %s", cfg.Webhook, notification.GetText()))
51+
text := notification.GetText()
52+
53+
logger.Info(fmt.Sprintf("found notify signal for %s config", name))
54+
logger.Debug(fmt.Sprintf("posting to %s webhook, message %s", cfg.Webhook, text))
5155

5256
err := slack.PostWebhookContext(ctx, cfg.Webhook, &slack.WebhookMessage{
53-
Text: notification.GetText(),
57+
Text: text,
5458
Channel: cfg.Channel,
5559
Username: cfg.Username,
5660
IconEmoji: cfg.IconEmoji,

cmd/notification-splunk/main.go

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -26,10 +26,10 @@ var logger hclog.Logger = hclog.New(&hclog.LoggerOptions{
2626
})
2727

2828
type PluginConfig struct {
29-
Name string `yaml:"name"`
30-
URL string `yaml:"url"`
31-
Token string `yaml:"token"`
32-
LogLevel *string `yaml:"log_level"`
29+
Name string `yaml:"name"`
30+
URL string `yaml:"url"`
31+
Token string `yaml:"token"`
32+
LogLevel string `yaml:"log_level"`
3333
}
3434

3535
type Splunk struct {
@@ -43,17 +43,18 @@ type Payload struct {
4343
}
4444

4545
func (s *Splunk) Notify(ctx context.Context, notification *protobufs.Notification) (*protobufs.Empty, error) {
46-
if _, ok := s.PluginConfigByName[notification.GetName()]; !ok {
47-
return &protobufs.Empty{}, fmt.Errorf("splunk invalid config name %s", notification.GetName())
48-
}
46+
name := notification.GetName()
47+
cfg, ok := s.PluginConfigByName[name]
4948

50-
cfg := s.PluginConfigByName[notification.GetName()]
49+
if !ok {
50+
return &protobufs.Empty{}, fmt.Errorf("splunk invalid config name %s", name)
51+
}
5152

52-
if cfg.LogLevel != nil && *cfg.LogLevel != "" {
53-
logger.SetLevel(hclog.LevelFromString(*cfg.LogLevel))
53+
if cfg.LogLevel != "" {
54+
logger.SetLevel(hclog.LevelFromString(cfg.LogLevel))
5455
}
5556

56-
logger.Info(fmt.Sprintf("received notify signal for %s config", notification.GetName()))
57+
logger.Info(fmt.Sprintf("received notify signal for %s config", name))
5758

5859
p := Payload{Event: notification.GetText()}
5960

0 commit comments

Comments
 (0)