mirror of
https://github.com/jenkinsci/kubernetes-operator.git
synced 2026-10-05 15:41:10 +02:00
Refactor notifications package
This commit is contained in:
@@ -0,0 +1,87 @@
|
||||
package notifications
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/jenkinsci/kubernetes-operator/pkg/apis/jenkins/v1alpha2"
|
||||
|
||||
"github.com/mailgun/mailgun-go/v3"
|
||||
"github.com/pkg/errors"
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
"k8s.io/apimachinery/pkg/types"
|
||||
k8sclient "sigs.k8s.io/controller-runtime/pkg/client"
|
||||
)
|
||||
|
||||
const content = `
|
||||
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
|
||||
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
|
||||
<html>
|
||||
<head></head>
|
||||
<body>
|
||||
<h1 style="background-color: %s; color: white; padding: 3px 10px;">Jenkins Operator Reconciled</h1>
|
||||
<h3>Failed to do something</h3>
|
||||
<table>
|
||||
<tr>
|
||||
<td><b>CR name:</b></td>
|
||||
<td>%s</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><b>Configuration type:</b></td>
|
||||
<td>%s</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><b>Status:</b></td>
|
||||
<td><b style="color: %s;">%s</b></td>
|
||||
</tr>
|
||||
</table>
|
||||
<h6 style="font-size: 11px; color: grey; margin-top: 15px;">Powered by Jenkins Operator <3</h6>
|
||||
</body>
|
||||
</html>`
|
||||
|
||||
// MailGun is service for sending emails
|
||||
type MailGun struct {
|
||||
k8sClient k8sclient.Client
|
||||
}
|
||||
|
||||
func (m MailGun) getStatusColor(logLevel LoggingLevel) StatusColor {
|
||||
switch logLevel {
|
||||
case LogInfo:
|
||||
return "blue"
|
||||
case LogWarn:
|
||||
return "red"
|
||||
default:
|
||||
return "gray"
|
||||
}
|
||||
}
|
||||
|
||||
// Send is function for sending directly to API
|
||||
func (m MailGun) Send(event Event, config v1alpha2.Notification) error {
|
||||
secret := &corev1.Secret{}
|
||||
|
||||
selector := config.Mailgun.APIKeySecretKeySelector
|
||||
|
||||
err := m.k8sClient.Get(context.TODO(), types.NamespacedName{Name: selector.Name, Namespace: event.Jenkins.Namespace}, secret)
|
||||
if err != nil {
|
||||
return errors.WithStack(err)
|
||||
}
|
||||
|
||||
secretValue := string(secret.Data[selector.Key])
|
||||
if secretValue == "" {
|
||||
return errors.Errorf("Mailgun API is empty in secret '%s/%s[%s]", event.Jenkins.Namespace, selector.Name, selector.Key)
|
||||
}
|
||||
|
||||
mg := mailgun.NewMailgun(config.Mailgun.Domain, secretValue)
|
||||
|
||||
htmlMessage := fmt.Sprintf(content, m.getStatusColor(event.LogLevel), event.Jenkins.Name, event.ConfigurationType, m.getStatusColor(event.LogLevel), string(event.LogLevel))
|
||||
|
||||
msg := mg.NewMessage(fmt.Sprintf("Jenkins Operator Notifier <%s>", config.Mailgun.From), "Jenkins Operator Status", "", config.Mailgun.Recipient)
|
||||
msg.SetHtml(htmlMessage)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
|
||||
defer cancel()
|
||||
|
||||
_, _, err = mg.Send(ctx, msg)
|
||||
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
package notifications
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
|
||||
"github.com/jenkinsci/kubernetes-operator/pkg/apis/jenkins/v1alpha2"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
"k8s.io/apimachinery/pkg/types"
|
||||
k8sclient "sigs.k8s.io/controller-runtime/pkg/client"
|
||||
)
|
||||
|
||||
// Teams is Microsoft Teams Service
|
||||
type Teams struct {
|
||||
k8sClient k8sclient.Client
|
||||
}
|
||||
|
||||
// TeamsMessage is representation of json message structure
|
||||
type TeamsMessage struct {
|
||||
Type string `json:"@type"`
|
||||
Context string `json:"@context"`
|
||||
ThemeColor StatusColor `json:"themeColor"`
|
||||
Title string `json:"title"`
|
||||
Sections []TeamsSection `json:"sections"`
|
||||
}
|
||||
|
||||
// TeamsSection is MS Teams message section
|
||||
type TeamsSection struct {
|
||||
Facts []TeamsFact `json:"facts"`
|
||||
Text string `json:"text"`
|
||||
}
|
||||
|
||||
// TeamsFact is field where we can put content
|
||||
type TeamsFact struct {
|
||||
Name string `json:"name"`
|
||||
Value string `json:"value"`
|
||||
}
|
||||
|
||||
func (t Teams) getStatusColor(logLevel LoggingLevel) StatusColor {
|
||||
switch logLevel {
|
||||
case LogInfo:
|
||||
return "439FE0"
|
||||
case LogWarn:
|
||||
return "E81123"
|
||||
default:
|
||||
return "C8C8C8"
|
||||
}
|
||||
}
|
||||
|
||||
// Send is function for sending directly to API
|
||||
func (t Teams) Send(event Event, config v1alpha2.Notification) error {
|
||||
secret := &corev1.Secret{}
|
||||
|
||||
selector := config.Teams.URLSecretKeySelector
|
||||
|
||||
err := t.k8sClient.Get(context.TODO(), types.NamespacedName{Name: selector.Name, Namespace: event.Jenkins.Namespace}, secret)
|
||||
if err != nil {
|
||||
return errors.WithStack(err)
|
||||
}
|
||||
|
||||
secretValue := string(secret.Data[selector.Key])
|
||||
if secretValue == "" {
|
||||
return errors.Errorf("Microsoft Teams webhook URL is empty in secret '%s/%s[%s]", event.Jenkins.Namespace, selector.Name, selector.Key)
|
||||
}
|
||||
|
||||
msg, err := json.Marshal(TeamsMessage{
|
||||
Type: "MessageCard",
|
||||
Context: "https://schema.org/extensions",
|
||||
ThemeColor: t.getStatusColor(event.LogLevel),
|
||||
Title: titleText,
|
||||
Sections: []TeamsSection{
|
||||
{
|
||||
Facts: []TeamsFact{
|
||||
{
|
||||
Name: crNameFieldName,
|
||||
Value: event.Jenkins.Name,
|
||||
},
|
||||
{
|
||||
Name: configurationTypeFieldName,
|
||||
Value: event.ConfigurationType,
|
||||
},
|
||||
{
|
||||
Name: loggingLevelFieldName,
|
||||
Value: string(event.LogLevel),
|
||||
},
|
||||
{
|
||||
Name: namespaceFieldName,
|
||||
Value: event.Jenkins.Namespace,
|
||||
},
|
||||
},
|
||||
Text: event.Message,
|
||||
},
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
return errors.WithStack(err)
|
||||
}
|
||||
|
||||
request, err := http.NewRequest("POST", secretValue, bytes.NewBuffer(msg))
|
||||
if err != nil {
|
||||
return errors.WithStack(err)
|
||||
}
|
||||
|
||||
resp, err := client.Do(request)
|
||||
if err != nil {
|
||||
return errors.WithStack(err)
|
||||
}
|
||||
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package notifications
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/jenkinsci/kubernetes-operator/pkg/apis/jenkins/v1alpha2"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client/fake"
|
||||
)
|
||||
|
||||
func TestTeams_Send(t *testing.T) {
|
||||
fakeClient := fake.NewFakeClient()
|
||||
testURLSelectorKeyName := "test-url-selector"
|
||||
testSecretName := "test-secret"
|
||||
|
||||
event := Event{
|
||||
Jenkins: v1alpha2.Jenkins{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: testCrName,
|
||||
Namespace: testNamespace,
|
||||
},
|
||||
},
|
||||
ConfigurationType: testConfigurationType,
|
||||
Message: testMessage,
|
||||
MessageVerbose: testMessageVerbose,
|
||||
LogLevel: testLoggingLevel,
|
||||
}
|
||||
teams := Teams{k8sClient: fakeClient}
|
||||
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
var message TeamsMessage
|
||||
decoder := json.NewDecoder(r.Body)
|
||||
err := decoder.Decode(&message)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
assert.Equal(t, message.Title, titleText)
|
||||
assert.Equal(t, message.ThemeColor, teams.getStatusColor(event.LogLevel))
|
||||
|
||||
mainSection := message.Sections[0]
|
||||
|
||||
assert.Equal(t, mainSection.Text, event.Message)
|
||||
|
||||
for _, fact := range mainSection.Facts {
|
||||
switch fact.Name {
|
||||
case configurationTypeFieldName:
|
||||
assert.Equal(t, fact.Value, event.ConfigurationType)
|
||||
case crNameFieldName:
|
||||
assert.Equal(t, fact.Value, event.Jenkins.Name)
|
||||
case messageFieldName:
|
||||
assert.Equal(t, fact.Value, event.Message)
|
||||
case loggingLevelFieldName:
|
||||
assert.Equal(t, fact.Value, string(event.LogLevel))
|
||||
case namespaceFieldName:
|
||||
assert.Equal(t, fact.Value, event.Jenkins.Namespace)
|
||||
default:
|
||||
t.Errorf("Found unexpected '%+v' fact", fact)
|
||||
}
|
||||
}
|
||||
}))
|
||||
|
||||
defer server.Close()
|
||||
|
||||
secret := &corev1.Secret{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: testSecretName,
|
||||
Namespace: testNamespace,
|
||||
},
|
||||
|
||||
Data: map[string][]byte{
|
||||
testURLSelectorKeyName: []byte(server.URL),
|
||||
},
|
||||
}
|
||||
|
||||
err := fakeClient.Create(context.TODO(), secret)
|
||||
assert.NoError(t, err)
|
||||
|
||||
err = teams.Send(event, v1alpha2.Notification{
|
||||
Teams: v1alpha2.Teams{
|
||||
URLSecretKeySelector: v1alpha2.SecretKeySelector{
|
||||
LocalObjectReference: corev1.LocalObjectReference{
|
||||
Name: testSecretName,
|
||||
},
|
||||
Key: testURLSelectorKeyName,
|
||||
},
|
||||
},
|
||||
})
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package notifications
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/pkg/errors"
|
||||
"net/http"
|
||||
|
||||
"github.com/jenkinsci/kubernetes-operator/pkg/apis/jenkins/v1alpha2"
|
||||
"github.com/jenkinsci/kubernetes-operator/pkg/log"
|
||||
|
||||
k8sclient "sigs.k8s.io/controller-runtime/pkg/client"
|
||||
)
|
||||
|
||||
const (
|
||||
// LogWarn is warning log entry
|
||||
LogWarn LoggingLevel = "warn"
|
||||
|
||||
// LogInfo is info log entry
|
||||
LogInfo LoggingLevel = "info"
|
||||
|
||||
titleText = "Operator reconciled."
|
||||
messageFieldName = "Message"
|
||||
loggingLevelFieldName = "Logging Level"
|
||||
crNameFieldName = "CR Name"
|
||||
configurationTypeFieldName = "Configuration Type"
|
||||
namespaceFieldName = "Namespace"
|
||||
footerContent = "Powered by Jenkins Operator"
|
||||
)
|
||||
|
||||
var (
|
||||
testConfigurationType = "test-configuration"
|
||||
testCrName = "test-cr"
|
||||
testNamespace = "default"
|
||||
testMessage = "test-message"
|
||||
testMessageVerbose = "detail-test-message"
|
||||
testLoggingLevel = LogWarn
|
||||
|
||||
client = http.Client{}
|
||||
)
|
||||
|
||||
// StatusColor is useful for better UX
|
||||
type StatusColor string
|
||||
|
||||
// LoggingLevel is type for selecting different logging levels
|
||||
type LoggingLevel string
|
||||
|
||||
// Event contains event details which will be sent as a notification
|
||||
type Event struct {
|
||||
Jenkins v1alpha2.Jenkins
|
||||
ConfigurationType string
|
||||
LogLevel LoggingLevel
|
||||
Message string
|
||||
MessageVerbose string
|
||||
}
|
||||
|
||||
type service interface {
|
||||
Send(event Event, notificationConfig v1alpha2.Notification) error
|
||||
}
|
||||
|
||||
// Listen listens for incoming events and send it as notifications
|
||||
func Listen(events chan Event, k8sClient k8sclient.Client) {
|
||||
for event := range events {
|
||||
logger := log.Log.WithValues("cr", event.Jenkins.Name)
|
||||
for _, notificationConfig := range event.Jenkins.Spec.Notifications {
|
||||
var err error
|
||||
var svc service
|
||||
|
||||
if notificationConfig.Slack != (v1alpha2.Slack{}) {
|
||||
svc = Slack{k8sClient: k8sClient}
|
||||
} else if notificationConfig.Teams != (v1alpha2.Teams{}) {
|
||||
svc = Teams{k8sClient: k8sClient}
|
||||
} else if notificationConfig.Mailgun != (v1alpha2.Mailgun{}) {
|
||||
svc = MailGun{k8sClient: k8sClient}
|
||||
} else {
|
||||
logger.V(log.VWarn).Info(fmt.Sprintf("Unexpected notification `%+v`", notificationConfig))
|
||||
continue
|
||||
}
|
||||
|
||||
go func(notificationConfig v1alpha2.Notification) {
|
||||
err = notify(svc, event, notificationConfig)
|
||||
|
||||
if err != nil {
|
||||
if log.Debug {
|
||||
logger.Error(nil, fmt.Sprintf("%+v", errors.WithMessage(err, "failed to send notification")))
|
||||
} else {
|
||||
logger.Error(nil, fmt.Sprintf("%s", errors.WithMessage(err, "failed to send notification")))
|
||||
}
|
||||
}
|
||||
}(notificationConfig)
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
func notify(svc service, event Event, manifest v1alpha2.Notification) error {
|
||||
if event.LogLevel == LogInfo && string(manifest.LoggingLevel) == string(LogWarn) {
|
||||
return nil
|
||||
}
|
||||
|
||||
return svc.Send(event, manifest)
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
package notifications
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
|
||||
"github.com/jenkinsci/kubernetes-operator/pkg/apis/jenkins/v1alpha2"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
"k8s.io/apimachinery/pkg/types"
|
||||
k8sclient "sigs.k8s.io/controller-runtime/pkg/client"
|
||||
)
|
||||
|
||||
// Slack is messaging service
|
||||
type Slack struct {
|
||||
k8sClient k8sclient.Client
|
||||
}
|
||||
|
||||
// SlackMessage is representation of json message
|
||||
type SlackMessage struct {
|
||||
Text string `json:"text"`
|
||||
Attachments []SlackAttachment `json:"attachments"`
|
||||
}
|
||||
|
||||
// SlackAttachment is representation of json attachment
|
||||
type SlackAttachment struct {
|
||||
Fallback string `json:"fallback"`
|
||||
Color StatusColor `json:"color"`
|
||||
Pretext string `json:"pretext"`
|
||||
Title string `json:"title"`
|
||||
Text string `json:"text"`
|
||||
Fields []SlackField `json:"fields"`
|
||||
Footer string `json:"footer"`
|
||||
}
|
||||
|
||||
// SlackField is representation of json field.
|
||||
type SlackField struct {
|
||||
Title string `json:"title"`
|
||||
Value string `json:"value"`
|
||||
Short bool `json:"short"`
|
||||
}
|
||||
|
||||
func (s Slack) getStatusColor(logLevel LoggingLevel) StatusColor {
|
||||
switch logLevel {
|
||||
case LogInfo:
|
||||
return "#439FE0"
|
||||
case LogWarn:
|
||||
return "danger"
|
||||
default:
|
||||
return "#c8c8c8"
|
||||
}
|
||||
}
|
||||
|
||||
// Send is function for sending directly to API
|
||||
func (s Slack) Send(event Event, config v1alpha2.Notification) error {
|
||||
secret := &corev1.Secret{}
|
||||
selector := config.Slack.URLSecretKeySelector
|
||||
|
||||
err := s.k8sClient.Get(context.TODO(), types.NamespacedName{Name: selector.Name, Namespace: event.Jenkins.Namespace}, secret)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
slackMessage, err := json.Marshal(SlackMessage{
|
||||
Attachments: []SlackAttachment{
|
||||
{
|
||||
Fallback: "",
|
||||
Color: s.getStatusColor(event.LogLevel),
|
||||
Text: titleText,
|
||||
Fields: []SlackField{
|
||||
{
|
||||
Title: messageFieldName,
|
||||
Value: event.Message,
|
||||
Short: false,
|
||||
},
|
||||
{
|
||||
Title: crNameFieldName,
|
||||
Value: event.Jenkins.Name,
|
||||
Short: true,
|
||||
},
|
||||
{
|
||||
Title: configurationTypeFieldName,
|
||||
Value: event.ConfigurationType,
|
||||
Short: true,
|
||||
},
|
||||
{
|
||||
Title: loggingLevelFieldName,
|
||||
Value: string(event.LogLevel),
|
||||
Short: true,
|
||||
},
|
||||
{
|
||||
Title: namespaceFieldName,
|
||||
Value: event.Jenkins.Namespace,
|
||||
Short: true,
|
||||
},
|
||||
},
|
||||
Footer: footerContent,
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
secretValue := string(secret.Data[selector.Key])
|
||||
if secretValue == "" {
|
||||
return errors.Errorf("SecretValue %s is empty", selector.Name)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
request, err := http.NewRequest("POST", secretValue, bytes.NewBuffer(slackMessage))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
resp, err := client.Do(request)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package notifications
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/jenkinsci/kubernetes-operator/pkg/apis/jenkins/v1alpha2"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client/fake"
|
||||
)
|
||||
|
||||
func TestSlack_Send(t *testing.T) {
|
||||
fakeClient := fake.NewFakeClient()
|
||||
testURLSelectorKeyName := "test-url-selector"
|
||||
testSecretName := "test-secret"
|
||||
|
||||
event := Event{
|
||||
Jenkins: v1alpha2.Jenkins{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: testCrName,
|
||||
Namespace: testNamespace,
|
||||
},
|
||||
},
|
||||
ConfigurationType: testConfigurationType,
|
||||
Message: testMessage,
|
||||
MessageVerbose: testMessageVerbose,
|
||||
LogLevel: testLoggingLevel,
|
||||
}
|
||||
slack := Slack{k8sClient: fakeClient}
|
||||
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
var message SlackMessage
|
||||
decoder := json.NewDecoder(r.Body)
|
||||
err := decoder.Decode(&message)
|
||||
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
mainAttachment := message.Attachments[0]
|
||||
|
||||
assert.Equal(t, mainAttachment.Text, titleText)
|
||||
for _, field := range mainAttachment.Fields {
|
||||
switch field.Title {
|
||||
case configurationTypeFieldName:
|
||||
assert.Equal(t, field.Value, event.ConfigurationType)
|
||||
case crNameFieldName:
|
||||
assert.Equal(t, field.Value, event.Jenkins.Name)
|
||||
case messageFieldName:
|
||||
assert.Equal(t, field.Value, event.Message)
|
||||
case loggingLevelFieldName:
|
||||
assert.Equal(t, field.Value, string(event.LogLevel))
|
||||
case namespaceFieldName:
|
||||
assert.Equal(t, field.Value, event.Jenkins.Namespace)
|
||||
default:
|
||||
t.Fail()
|
||||
}
|
||||
}
|
||||
|
||||
assert.Equal(t, mainAttachment.Footer, footerContent)
|
||||
assert.Equal(t, mainAttachment.Color, slack.getStatusColor(event.LogLevel))
|
||||
}))
|
||||
|
||||
defer server.Close()
|
||||
|
||||
secret := &corev1.Secret{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: testSecretName,
|
||||
Namespace: testNamespace,
|
||||
},
|
||||
|
||||
Data: map[string][]byte{
|
||||
testURLSelectorKeyName: []byte(server.URL),
|
||||
},
|
||||
}
|
||||
|
||||
err := fakeClient.Create(context.TODO(), secret)
|
||||
assert.NoError(t, err)
|
||||
|
||||
err = slack.Send(event, v1alpha2.Notification{
|
||||
Slack: v1alpha2.Slack{
|
||||
URLSecretKeySelector: v1alpha2.SecretKeySelector{
|
||||
LocalObjectReference: corev1.LocalObjectReference{
|
||||
Name: testSecretName,
|
||||
},
|
||||
Key: testURLSelectorKeyName,
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
Reference in New Issue
Block a user