Skip to content

Commit

Permalink
support email lists for admins (#865)
Browse files Browse the repository at this point in the history
  • Loading branch information
MatousJobanek authored Sep 20, 2023
1 parent cef9ffb commit c68ff26
Show file tree
Hide file tree
Showing 4 changed files with 117 additions and 159 deletions.
15 changes: 0 additions & 15 deletions controllers/toolchainstatus/toolchainstatus_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import (
"io"
"net/http"
"net/url"
"regexp"
"text/template"
"time"

Expand Down Expand Up @@ -104,8 +103,6 @@ const (
{{end}}`
)

var emailRegex = regexp.MustCompile("^[a-zA-Z0-9.!#$%&'*+\\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$")

// SetupWithManager sets up the controller with the Manager.
func (r *Reconciler) SetupWithManager(mgr manager.Manager) error {
return ctrl.NewControllerManagedBy(mgr).
Expand Down Expand Up @@ -490,11 +487,6 @@ func (r *Reconciler) sendToolchainStatusNotification(logger logr.Logger,
return errs.Wrapf(err, "unable to get ToolchainConfig")
}

if !isValidEmailAddress(config.Notifications().AdminEmail()) {
return errs.New(fmt.Sprintf("cannot create notification due to configuration error - admin.email [%s] is invalid or not set",
config.Notifications().AdminEmail()))
}

tsValue := time.Now().Format("20060102150405")
contentString := ""
subjectString := ""
Expand Down Expand Up @@ -948,10 +940,3 @@ func (s *regServiceSubstatusHandler) addRegistrationServiceHealthAndRevisionChec
// if we get here it means that component health is ok
return true
}

func isValidEmailAddress(email string) bool {
if len(email) < 3 && len(email) > 254 {
return false
}
return emailRegex.MatchString(email)
}
220 changes: 114 additions & 106 deletions controllers/toolchainstatus/toolchainstatus_controller_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1106,33 +1106,36 @@ func TestToolchainStatusNotifications(t *testing.T) {

os.Setenv("WATCH_NAMESPACE", test.HostOperatorNs)

toolchainConfig := commonconfig.NewToolchainConfigObjWithReset(t, testconfig.Notifications().AdminEmail("[email protected]"))

reconciler, req, fakeClient := prepareReconcile(t, requestName, newResponseGood(), mockLastGitHubAPICall, defaultGitHubClient, []string{"member-1", "member-2"},
hostOperatorDeployment, memberStatus, registrationServiceDeployment, toolchainStatus, toolchainConfig, proxyRoute())
t.Run("no notificaion created", func(t *testing.T) {
// given
toolchainConfig := commonconfig.NewToolchainConfigObjWithReset(t, testconfig.Notifications().AdminEmail("[email protected]"))
reconciler, req, fakeClient := prepareReconcile(t, requestName, newResponseGood(), mockLastGitHubAPICall, defaultGitHubClient, []string{"member-1", "member-2"},
hostOperatorDeployment, memberStatus, registrationServiceDeployment, toolchainStatus, toolchainConfig, proxyRoute())

// when
res, err := reconciler.Reconcile(context.TODO(), req)
// when
res, err := reconciler.Reconcile(context.TODO(), req)

// then
require.NoError(t, err)
assert.Equal(t, requeueResult, res)
// then
require.NoError(t, err)
assert.Equal(t, requeueResult, res)

AssertThatToolchainStatus(t, req.Namespace, requestName, fakeClient).
HasConditions(componentsReady(), unreadyNotificationNotCreated()).
HasHostOperatorStatus(hostOperatorStatusReady()).
HasMemberClusterStatus(memberCluster("member-1", ready()), memberCluster("member-2", ready())).
HasRegistrationServiceStatus(registrationServiceReady(conditionReady(toolchainv1alpha1.ToolchainStatusRegServiceReadyReason), conditionReadyWithMessage(toolchainv1alpha1.ToolchainStatusDeploymentRevisionCheckDisabledReason, "access token key is not provided"))).
HasHostRoutesStatus("https://api-toolchain-host-operator.host-cluster", hostRoutesAvailable())
AssertThatToolchainStatus(t, req.Namespace, requestName, fakeClient).
HasConditions(componentsReady(), unreadyNotificationNotCreated()).
HasHostOperatorStatus(hostOperatorStatusReady()).
HasMemberClusterStatus(memberCluster("member-1", ready()), memberCluster("member-2", ready())).
HasRegistrationServiceStatus(registrationServiceReady(conditionReady(toolchainv1alpha1.ToolchainStatusRegServiceReadyReason), conditionReadyWithMessage(toolchainv1alpha1.ToolchainStatusDeploymentRevisionCheckDisabledReason, "access token key is not provided"))).
HasHostRoutesStatus("https://api-toolchain-host-operator.host-cluster", hostRoutesAvailable())

// Confirm there is no notification
assertToolchainStatusNotificationNotCreated(t, fakeClient, unreadyStatusNotification)
assertToolchainStatusNotificationNotCreated(t, fakeClient, restoredStatusNotification)
// Confirm there is no notification
assertToolchainStatusNotificationNotCreated(t, fakeClient, unreadyStatusNotification)
assertToolchainStatusNotificationNotCreated(t, fakeClient, restoredStatusNotification)
})

t.Run("Notification not created when host operator deployment not ready within threshold", func(t *testing.T) {
// given
hostOperatorDeployment := newDeploymentWithConditions(defaultHostOperatorDeploymentName,
status.DeploymentNotAvailableCondition(), status.DeploymentProgressingCondition())
toolchainConfig := commonconfig.NewToolchainConfigObjWithReset(t, testconfig.Notifications().AdminEmail("[email protected]"))

reconciler, req, fakeClient := prepareReconcile(t, requestName, newResponseGood(), mockLastGitHubAPICall, defaultGitHubClient, []string{"member-1", "member-2"},
hostOperatorDeployment, memberStatus, registrationServiceDeployment, toolchainStatus, toolchainConfig, proxyRoute())
Expand Down Expand Up @@ -1172,9 +1175,7 @@ func TestToolchainStatusNotifications(t *testing.T) {

// then
require.Error(t, err)
require.Equal(t, fmt.Sprintf("Failed to create toolchain status unready notification: cannot create notification "+
"due to configuration error - admin.email [%s] is invalid or not set", email),
err.Error())
require.True(t, strings.HasPrefix(err.Error(), fmt.Sprintf("Failed to create toolchain status unready notification: The specified recipient [%s] is not a valid email address", email)))
assert.Equal(t, requeueResult, res)

// Confirm there is no notification
Expand All @@ -1198,106 +1199,113 @@ func TestToolchainStatusNotifications(t *testing.T) {

overrideLastTransitionTime(t, toolchainStatus, metav1.Time{Time: time.Now().Add(-time.Duration(24) * time.Hour)})

reconciler, req, fakeClient := prepareReconcile(t, requestName, newResponseGood(), mockLastGitHubAPICall, defaultGitHubClient, []string{"member-1", "member-2"},
hostOperatorDeployment, memberStatus, registrationServiceDeployment, toolchainStatus, toolchainConfig, proxyRoute())

// when
res, err := reconciler.Reconcile(context.TODO(), req)

// then
require.NoError(t, err)
assert.Equal(t, requeueResult, res)
// confirm restored notification has not been created
assertToolchainStatusNotificationNotCreated(t, fakeClient, restoredStatusNotification)
// Confirm the unready notification has been created
notification := assertToolchainStatusNotificationCreated(t, fakeClient)
require.True(t, strings.HasPrefix(notification.ObjectMeta.Name, "toolchainstatus-unready-"))

require.NotNil(t, notification)
require.Equal(t, notification.Spec.Subject, "ToolchainStatus has been in an unready status for an extended period")
require.Equal(t, notification.Spec.Recipient, "[email protected]")

t.Run("Toolchain status now ok again, notification should be removed", func(t *testing.T) {
hostOperatorDeployment := newDeploymentWithConditions(defaultHostOperatorDeploymentName,
status.DeploymentAvailableCondition())

// Reload the toolchain status
require.NoError(t, fakeClient.Get(context.Background(), test.NamespacedName(test.HostOperatorNs,
toolchainStatus.Name), toolchainStatus))

reconciler, req, fakeClient := prepareReconcile(t, requestName, newResponseGood(), mockLastGitHubAPICall, defaultGitHubClient, []string{"member-1", "member-2"},
hostOperatorDeployment, memberStatus, registrationServiceDeployment, toolchainStatus, proxyRoute())

// when
res, err := reconciler.Reconcile(context.TODO(), req)

// then
require.NoError(t, err)
assert.Equal(t, requeueResult, res)
for _, email := range []string{"[email protected]", "[email protected], [email protected]"} {
t.Run("for email "+email, func(t *testing.T) {
toolchainConfig := commonconfig.NewToolchainConfigObjWithReset(t, testconfig.Notifications().AdminEmail(email))

// Confirm there is no unready notification
assertToolchainStatusNotificationNotCreated(t, fakeClient, unreadyStatusNotification)

// Confirm restored notification has been created
notification := assertToolchainStatusNotificationCreated(t, fakeClient)
require.True(t, strings.HasPrefix(notification.ObjectMeta.Name, "toolchainstatus-restored-"))

require.NotNil(t, notification)
require.Equal(t, notification.Spec.Subject, "ToolchainStatus has now been restored to ready status")
require.Equal(t, notification.Spec.Recipient, "[email protected]")

t.Run("Toolchain status not ready again for extended period, notification is created", func(t *testing.T) {
// given
hostOperatorDeployment := newDeploymentWithConditions(defaultHostOperatorDeploymentName,
status.DeploymentNotAvailableCondition(), status.DeploymentProgressingCondition())

// Reload the toolchain status
require.NoError(t, fakeClient.Get(context.Background(), test.NamespacedName(test.HostOperatorNs,
toolchainStatus.Name), toolchainStatus))

// Reconcile in order to update the ready status to false
reconciler, req, fakeClient := prepareReconcile(t, requestName, newResponseGood(), mockLastGitHubAPICall, defaultGitHubClient, []string{"member-1", "member-2"},
hostOperatorDeployment, memberStatus, registrationServiceDeployment, toolchainStatus, toolchainConfig, proxyRoute())

// when
_, err := reconciler.Reconcile(context.TODO(), req)

require.NoError(t, err)
// Confirm there is no notification
assertToolchainStatusNotificationNotCreated(t, fakeClient, unreadyStatusNotification)
assertToolchainStatusNotificationNotCreated(t, fakeClient, restoredStatusNotification)

// Reload the toolchain status
require.NoError(t, fakeClient.Get(context.Background(), test.NamespacedName(test.HostOperatorNs,
toolchainStatus.Name), toolchainStatus))

// Now override the last transition time again
overrideLastTransitionTime(t, toolchainStatus, metav1.Time{Time: time.Now().Add(-time.Duration(24) * time.Hour)})

// Reconcile once more
reconciler, req, fakeClient = prepareReconcile(t, requestName, newResponseGood(), mockLastGitHubAPICall, defaultGitHubClient, []string{"member-1", "member-2"},
hostOperatorDeployment, memberStatus, registrationServiceDeployment, toolchainStatus, toolchainConfig, proxyRoute())

// when
res, err = reconciler.Reconcile(context.TODO(), req)
res, err := reconciler.Reconcile(context.TODO(), req)

// then
require.NoError(t, err)
assert.Equal(t, requeueResult, res)
// Confirm restored notification is not created
// confirm restored notification has not been created
assertToolchainStatusNotificationNotCreated(t, fakeClient, restoredStatusNotification)
// Confirm the unready notification has been created
notification := assertToolchainStatusNotificationCreated(t, fakeClient)
require.True(t, strings.HasPrefix(notification.ObjectMeta.Name, "toolchainstatus-unready-"))
require.Len(t, notification.ObjectMeta.Name, 38)

require.NotNil(t, notification)
assert.Equal(t, notification.Spec.Subject, "ToolchainStatus has been in an unready status for an extended period")
assert.Equal(t, notification.Spec.Recipient, "[email protected]")
assert.True(t, strings.HasPrefix(notification.Spec.Content, "<h3>The following issues"))
assert.True(t, strings.HasSuffix(strings.TrimSpace(notification.Spec.Content), "</div>"))
assert.NotContains(t, notification.Spec.Content, "managedFields")
require.Equal(t, notification.Spec.Subject, "ToolchainStatus has been in an unready status for an extended period")
require.Equal(t, notification.Spec.Recipient, email)

t.Run("Toolchain status now ok again, notification should be removed", func(t *testing.T) {
hostOperatorDeployment := newDeploymentWithConditions(defaultHostOperatorDeploymentName,
status.DeploymentAvailableCondition())

// Reload the toolchain status
require.NoError(t, fakeClient.Get(context.Background(), test.NamespacedName(test.HostOperatorNs,
toolchainStatus.Name), toolchainStatus))

reconciler, req, fakeClient := prepareReconcile(t, requestName, newResponseGood(), mockLastGitHubAPICall, defaultGitHubClient, []string{"member-1", "member-2"},
hostOperatorDeployment, memberStatus, registrationServiceDeployment, toolchainStatus, proxyRoute())

// when
res, err := reconciler.Reconcile(context.TODO(), req)

// then
require.NoError(t, err)
assert.Equal(t, requeueResult, res)

// Confirm there is no unready notification
assertToolchainStatusNotificationNotCreated(t, fakeClient, unreadyStatusNotification)

// Confirm restored notification has been created
notification := assertToolchainStatusNotificationCreated(t, fakeClient)
require.True(t, strings.HasPrefix(notification.ObjectMeta.Name, "toolchainstatus-restored-"))

fmt.Println(notification)
require.NotNil(t, notification)
require.Equal(t, "ToolchainStatus has now been restored to ready status", notification.Spec.Subject)
require.Equal(t, email, notification.Spec.Recipient)

t.Run("Toolchain status not ready again for extended period, notification is created", func(t *testing.T) {
// given
hostOperatorDeployment := newDeploymentWithConditions(defaultHostOperatorDeploymentName,
status.DeploymentNotAvailableCondition(), status.DeploymentProgressingCondition())

// Reload the toolchain status
require.NoError(t, fakeClient.Get(context.Background(), test.NamespacedName(test.HostOperatorNs,
toolchainStatus.Name), toolchainStatus))

// Reconcile in order to update the ready status to false
reconciler, req, fakeClient := prepareReconcile(t, requestName, newResponseGood(), mockLastGitHubAPICall, defaultGitHubClient, []string{"member-1", "member-2"},
hostOperatorDeployment, memberStatus, registrationServiceDeployment, toolchainStatus, toolchainConfig, proxyRoute())

// when
_, err := reconciler.Reconcile(context.TODO(), req)

require.NoError(t, err)
// Confirm there is no notification
assertToolchainStatusNotificationNotCreated(t, fakeClient, unreadyStatusNotification)
assertToolchainStatusNotificationNotCreated(t, fakeClient, restoredStatusNotification)

// Reload the toolchain status
require.NoError(t, fakeClient.Get(context.Background(), test.NamespacedName(test.HostOperatorNs,
toolchainStatus.Name), toolchainStatus))

// Now override the last transition time again
overrideLastTransitionTime(t, toolchainStatus, metav1.Time{Time: time.Now().Add(-time.Duration(24) * time.Hour)})

// Reconcile once more
reconciler, req, fakeClient = prepareReconcile(t, requestName, newResponseGood(), mockLastGitHubAPICall, defaultGitHubClient, []string{"member-1", "member-2"},
hostOperatorDeployment, memberStatus, registrationServiceDeployment, toolchainStatus, toolchainConfig, proxyRoute())

// when
res, err = reconciler.Reconcile(context.TODO(), req)

// then
require.NoError(t, err)
assert.Equal(t, requeueResult, res)
// Confirm restored notification is not created
assertToolchainStatusNotificationNotCreated(t, fakeClient, restoredStatusNotification)
// Confirm the unready notification has been created
notification := assertToolchainStatusNotificationCreated(t, fakeClient)
require.True(t, strings.HasPrefix(notification.ObjectMeta.Name, "toolchainstatus-unready-"))
require.Len(t, notification.ObjectMeta.Name, 38)
require.NotNil(t, notification)
assert.Equal(t, "ToolchainStatus has been in an unready status for an extended period", notification.Spec.Subject)
assert.Equal(t, email, notification.Spec.Recipient)
assert.True(t, strings.HasPrefix(notification.Spec.Content, "<h3>The following issues"))
assert.True(t, strings.HasSuffix(strings.TrimSpace(notification.Spec.Content), "</div>"))
assert.NotContains(t, notification.Spec.Content, "managedFields")
})
})
})
})
}
})
})
})
Expand Down
13 changes: 1 addition & 12 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ module github.com/codeready-toolchain/host-operator

require (
github.com/codeready-toolchain/api v0.0.0-20230912073725-4ae0201b4630
github.com/codeready-toolchain/toolchain-common v0.0.0-20230919021542-5a14033d7b7c
github.com/codeready-toolchain/toolchain-common v0.0.0-20230920120310-0f59f17bca92
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/ghodss/yaml v1.0.0
github.com/go-bindata/go-bindata v3.1.2+incompatible
Expand Down Expand Up @@ -55,13 +55,11 @@ require (
github.com/emicklei/go-restful/v3 v3.8.0 // indirect
github.com/evanphx/json-patch v5.6.0+incompatible // indirect
github.com/evanphx/json-patch/v5 v5.6.0 // indirect
github.com/fatih/color v1.12.0 // indirect
github.com/fsnotify/fsnotify v1.5.4 // indirect
github.com/go-logr/zapr v1.2.3 // indirect
github.com/go-openapi/jsonpointer v0.19.5 // indirect
github.com/go-openapi/jsonreference v0.19.5 // indirect
github.com/go-openapi/swag v0.19.14 // indirect
github.com/gobuffalo/flect v0.2.5 // indirect
github.com/gogo/protobuf v1.3.2 // indirect
github.com/golang-jwt/jwt/v4 v4.2.0 // indirect
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect
Expand All @@ -75,12 +73,9 @@ require (
github.com/h2non/parth v0.0.0-20190131123155-b4df798d6542 // indirect
github.com/huandu/xstrings v1.3.1 // indirect
github.com/imdario/mergo v0.3.12 // indirect
github.com/inconshreveable/mousetrap v1.0.0 // indirect
github.com/josharian/intern v1.0.0 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/mailru/easyjson v0.7.6 // indirect
github.com/mattn/go-colorable v0.1.8 // indirect
github.com/mattn/go-isatty v0.0.12 // indirect
github.com/matttproud/golang_protobuf_extensions v1.0.2-0.20181231171920-c182affec369 // indirect
github.com/migueleliasweb/go-github-mock v0.0.18 // indirect
github.com/mitchellh/copystructure v1.0.0 // indirect
Expand All @@ -94,31 +89,25 @@ require (
github.com/prometheus/procfs v0.7.3 // indirect
github.com/segmentio/backo-go v1.0.0 // indirect
github.com/shopspring/decimal v1.2.0 // indirect
github.com/spf13/cobra v1.4.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
go.uber.org/atomic v1.7.0 // indirect
go.uber.org/multierr v1.6.0 // indirect
golang.org/x/crypto v0.9.0 // indirect
golang.org/x/mod v0.8.0 // indirect
golang.org/x/net v0.10.0 // indirect
golang.org/x/oauth2 v0.7.0 // indirect
golang.org/x/sys v0.8.0 // indirect
golang.org/x/term v0.8.0 // indirect
golang.org/x/text v0.9.0 // indirect
golang.org/x/time v0.3.0 // indirect
golang.org/x/tools v0.6.0 // indirect
gomodules.xyz/jsonpatch/v2 v2.2.0 // indirect
google.golang.org/appengine v1.6.7 // indirect
google.golang.org/protobuf v1.28.0 // indirect
gopkg.in/inf.v0 v0.9.1 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
k8s.io/code-generator v0.25.0 // indirect
k8s.io/component-base v0.25.0 // indirect
k8s.io/gengo v0.0.0-20211129171323-c02415ce4185 // indirect
k8s.io/kube-openapi v0.0.0-20220803162953-67bda5d908f1 // indirect
k8s.io/kubectl v0.24.0 // indirect
k8s.io/utils v0.0.0-20220728103510-ee6ede2d64ed // indirect
sigs.k8s.io/controller-tools v0.10.0 // indirect
sigs.k8s.io/json v0.0.0-20220713155537-f223a00ba0e2 // indirect
sigs.k8s.io/structured-merge-diff/v4 v4.2.3 // indirect
sigs.k8s.io/yaml v1.3.0 // indirect
Expand Down
Loading

0 comments on commit c68ff26

Please sign in to comment.