8000 feat(coderd/notifications): group workspace build failure report by DanielleMaywood · Pull Request #17306 · coder/coder · GitHub
[go: up one dir, main page]

Skip to content

feat(coderd/notifications): group workspace build failure report #17306

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Apr 10, 2025
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
feat(notifications): group workspace build failure report
Instead of sending X many reports to a single template admin, we instead
send only 1.
  • Loading branch information
DanielleMaywood committed Apr 9, 2025
commit 3a2ebee9fbfe4d89a9ad6efd7873043a0cbc3b88
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
UPDATE notification_templates
SET
name = 'Report: Workspace Builds Failed',
title_template = 'Failed workspace builds report',
body_template =
E'The following templates have had build failures over the last {{.Data.report_frequency}}:
{{range $template := .Data.templates}}
- **{{$template.display_name}}** failed to build {{$template.failed_builds}}/{{$template.total_builds}} times
{{end}}

**Report:**
{{range $template := .Data.templates}}
{{range $version := $template.versions}}
**{{$template.display_name}}**@**{{$version.template_version_name}}** failed {{$version.failed_count}} time{{if gt $version.failed_count 1.0}}s{{end}}:
{{range $build := $version.failed_builds}}
* [{{$build.workspace_owner_username}} / {{$build.workspace_name}} / #{{$build.build_number}}]({{base_url}}/@{{$build.workspace_owner_username}}/{{$build.workspace_name}}/builds/{{$build.build_number}})
{{end}}
{{end}}
{{end}}

We recommend reviewing these issues to ensure future builds are successful.'
WHERE id = '34a20db2-e9cc-4a93-b0e4-8569699d7a00';
102 changes: 75 additions & 27 deletions coderd/notifications/notifications_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -978,45 +978,93 @@ func TestNotificationTemplates_Golden(t *testing.T) {
UserName: "Bobby",
UserEmail: "bobby@coder.com",
UserUsername: "bobby",
Labels: map[string]string{
"template_name": "bobby-first-template",
"template_display_name": "Bobby First Template",
},
Labels: map[string]string{},
// We need to use floats as `json.Unmarshal` unmarshal numbers in `map[string]any` to floats.
Data: map[string]any{
"failed_builds": 4.0,
"total_builds": 55.0,
"report_frequency": "week",
"template_versions": []map[string]any{
"templates": []map[string]any{
{
"template_version_name": "bobby-template-version-1",
"failed_count": 3.0,
"failed_builds": []map[string]any{
"name": "bobby-first-template",
"display_name": "Bobby First Template",
"failed_builds": 4.0,
"total_builds": 55.0,
"versions": []map[string]any{
{
"workspace_owner_username": "mtojek",
"workspace_name": "workspace-1",
"build_number": 1234.0,
"template_version_name": "bobby-template-version-1",
"failed_count": 3.0,
"failed_builds": []map[string]any{
{
"workspace_owner_username": "mtojek",
"workspace_name": "workspace-1",
"build_number": 1234.0,
},
{
"workspace_owner_username": "johndoe",
"workspace_name": "my-workspace-3",
"build_number": 5678.0,
},
{
"workspace_owner_username": "jack",
"workspace_name": "workwork",
"build_number": 774.0,
},
},
},
{
"workspace_owner_username": "johndoe",
"workspace_name": "my-workspace-3",
"build_number": 5678.0,
},
{
"workspace_owner_username": "jack",
"workspace_name": "workwork",
"build_number": 774.0,
"template_version_count": "bobby-template-version-2",
"failed_count": 1.0,
"failed_builds": []map[string]any{
{
"workspace_owner_username": "ben",
"workspace_name": "cool-workspace",
"build_number": 8888.0,
},
},
},
},
},
{
"template_version_name": "bobby-template-version-2",
"failed_count": 1.0,
"failed_builds": []map[string]any{
"name": "bobby-second-template",
"display_name": "Bobby Second Template",
"failed_builds": 5.0,
"total_builds": 50.0,
"versions": []map[string]any{
{
"template_version_name": "bobby-template-version-1",
"failed_count": 3.0,
"failed_builds": []map[string]any{
{
"workspace_owner_username": "daniellemaywood",
"workspace_name": "workspace-9",
"build_number": 9234.0,
},
{
"workspace_owner_username": "johndoe",
"workspace_name": "my-workspace-7",
"build_number": 8678.0,
},
{
"workspace_owner_username": "jack",
"workspace_name": "workworkwork",
"build_number": 374.0,
},
},
},
{
"workspace_owner_username": "ben",
"workspace_name": "cool-workspace",
"build_number": 8888.0,
"template_version_count": "bobby-template-version-2",
"failed_count": 2.0,
"failed_builds": []map[string]any{
{
"workspace_owner_username": "ben",
"workspace_name": "more-cool-workspace",
"build_number": 8878.0,
},
{
"workspace_owner_username": "ben",
"workspace_name": "less-cool-workspace",
"build_number": 8848.0,
},
},
},
},
},
Expand Down
158 changes: 94 additions & 64 deletions coderd/notifications/reports/generator.go
6D40
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import (
"github.com/coder/coder/v2/coderd/database/dbauthz"
"github.com/coder/coder/v2/coderd/database/dbtime"
"github.com/coder/coder/v2/coderd/notifications"
"github.com/coder/coder/v2/coderd/util/slice"
"github.com/coder/coder/v2/codersdk"
)

Expand Down Expand Up @@ -102,6 +103,11 @@ const (
failedWorkspaceBuildsReportFrequencyLabel = "week"
)

type adminReport struct {
stats database.GetWorkspaceBuildStatsByTemplatesRow
failedBuilds []database.GetFailedWorkspaceBuildsByTemplateIDRow
}

func reportFailedWorkspaceBuilds(ctx context.Context, logger slog.Logger, db database.Store, enqueuer notifications.Enqueuer, clk quartz.Clock) error {
now := clk.Now()
since := now.Add(-failedWorkspaceBuildsReportFrequency)
Expand Down Expand Up @@ -136,6 +142,8 @@ func reportFailedWorkspaceBuilds(ctx context.Context, logger slog.Logger, db dat
return xerrors.Errorf("unable to fetch failed workspace builds: %w", err)
}

reports := make(map[uuid.UUID][]adminReport)

for _, stats := range templateStatsRows {
select {
case <-ctx.Done():
Expand Down Expand Up @@ -165,33 +173,40 @@ func reportFailedWorkspaceBuilds(ctx context.Context, logger slog.Logger, db dat
logger.Error(ctx, "unable to fetch failed workspace builds", slog.F("template_id", stats.TemplateID), slog.Error(err))
continue
}
reportData := buildDataForReportFailedWorkspaceBuilds(stats, failedBuilds)

// Send reports to template admins
templateDisplayName := stats.TemplateDisplayName
if templateDisplayName == "" {
templateDisplayName = stats.TemplateName
for _, templateAdmin := range templateAdmins {
adminReports := reports[templateAdmin.ID]
adminReports = append(adminReports, adminReport{
failedBuilds: failedBuilds,
stats: stats,
})

reports[templateAdmin.ID] = adminReports
}
}

for _, templateAdmin := range templateAdmins {
select {
case <-ctx.Done():
logger.Debug(ctx, "context is canceled, quitting", slog.Error(ctx.Err()))
break
default:
}
for templateAdmin, reports := range reports {
select {
case <-ctx.Done():
logger.Debug(ctx, "context is canceled, quitting", slog.Error(ctx.Err()))
break
default:
}

if _, err := enqueuer.EnqueueWithData(ctx, templateAdmin.ID, notifications.TemplateWorkspaceBuildsFailedReport,
map[string]string{
"template_name": stats.TemplateName,
"template_display_name": templateDisplayName,
},
reportData,
"report_generator",
stats.TemplateID, stats.TemplateOrganizationID,
); err != nil {
logger.Warn(ctx, "failed to send a report with failed workspace builds", slog.Error(err))
}
reportData := buildDataForReportFailedWorkspaceBuilds(reports)

targets := []uuid.UUID{}
for _, report := range reports {
targets = append(targets, report.stats.TemplateID, report.stats.TemplateOrganizationID)
}

if _, err := enqueuer.EnqueueWithData(ctx, templateAdmin, notifications.TemplateWorkspaceBuildsFailedReport,
map[string]string{},
reportData,
"report_generator",
slice.Unique(targets)...,
); err != nil {
logger.Warn(ctx, "failed to send a report with failed workspace builds", slog.Error(err))
}
}

Expand All @@ -213,54 +228,69 @@ func reportFailedWorkspaceBuilds(ctx context.Context, logger slog.Logger, db dat

const workspaceBuildsLimitPerTemplateVersion = 10

func buildDataForReportFailedWorkspaceBuilds(stats database.GetWorkspaceBuildStatsByTemplatesRow, failedBuilds []database.GetFailedWorkspaceBuildsByTemplateIDRow) map[string]any {
// Build notification model for template versions and failed workspace builds.
//
// Failed builds are sorted by template version ascending, workspace build number descending.
// Review builds, group them by template versions, and assign to builds to template versions.
// The map requires `[]map[string]any{}` to be compatible with data passed to `NotificationEnqueuer`.
templateVersions := []map[string]any{}
for _, failedBuild := range failedBuilds {
c := len(templateVersions)

if c == 0 || templateVersions[c-1]["template_version_name"] != failedBuild.TemplateVersionName {
templateVersions = append(templateVersions, map[string]any{
"template_version_name": failedBuild.TemplateVersionName,
"failed_count": 1,
"failed_builds": []map[string]any{
{
"workspace_owner_username": failedBuild.WorkspaceOwnerUsername,
"workspace_name": failedBuild.WorkspaceName,
"build_number": failedBuild.WorkspaceBuildNumber,
func buildDataForReportFailedWorkspaceBuilds(reports []adminReport) map[string]any {
templates := []map[string]any{}

for _, report := range reports {
// Build notification model for template versions and failed workspace builds.
//
// Failed builds are sorted by template version ascending, workspace build number descending.
// Review builds, group them by template versions, and assign to builds to template versions.
// The map requires `[]map[string]any{}` to be compatible with data passed to `NotificationEnqueuer`.
templateVersions := []map[string]any{}
for _, failedBuild := range report.failedBuilds {
c := len(templateVersions)

if c == 0 || templateVersions[c-1]["template_version_name"] != failedBuild.TemplateVersionName {
templateVersions = append(templateVersions, map[string]any{
"template_version_name": failedBuild.TemplateVersionName,
"failed_count": 1,
"failed_builds": []map[string]any{
{
"workspace_owner_username": failedBuild.WorkspaceOwnerUsername,
"workspace_name": failedBuild.WorkspaceName,
"build_number": failedBuild.WorkspaceBuildNumber,
},
},
},
})
continue
})
continue
}

tv := templateVersions[c-1]
//nolint:errorlint,forcetypeassert // only this function prepares the notification model
tv["failed_count"] = tv["failed_count"].(int) + 1

//nolint:errorlint,forcetypeassert // only this function prepares the notification model
builds := tv["failed_builds"].([]map[string]any)
if len(builds) < workspaceBuildsLimitPerTemplateVersion {
// return N last builds to prevent long email reports
builds = append(builds, map[string]any{
"workspace_owner_username": failedBuild.WorkspaceOwnerUsername,
"workspace_name": failedBuild.WorkspaceName,
"build_number": failedBuild.WorkspaceBuildNumber,
})
tv["failed_builds"] = builds
}
templateVersions[c-1] = tv
}

tv := templateVersions[c-1]
//nolint:errorlint,forcetypeassert // only this function prepares the notification model
tv["failed_count"] = tv["failed_count"].(int) + 1

//nolint:errorlint,forcetypeassert // only this function prepares the notification model
builds := tv["failed_builds"].([]map[string]any)
if len(builds) < workspaceBuildsLimitPerTemplateVersion {
// return N last builds to prevent long email reports
builds = append(builds, map[string]any{
"workspace_owner_username": failedBuild.WorkspaceOwnerUsername,
"workspace_name": failedBuild.WorkspaceName,
"build_number": failedBuild.WorkspaceBuildNumber,
})
tv["failed_builds"] = builds
templateDisplayName := report.stats.TemplateDisplayName
if templateDisplayName == "" {
templateDisplayName = report.stats.TemplateName
}
templateVersions[c-1] = tv

templates = append(templates, map[string]any{
"failed_builds": report.stats.FailedBuilds,
"total_builds": report.stats.TotalBuilds,
"versions": templateVersions,
"name": report.stats.TemplateName,
"display_name": templateDisplayName,
})
}

return map[string]any{
"failed_builds": stats.FailedBuilds,
"total_builds": stats.TotalBuilds,
"report_frequency": failedWorkspaceBuildsReportFrequencyLabel,
"template_versions": templateVersions,
"report_frequency": failedWorkspaceBuildsReportFrequencyLabel,
"templates": templates,
}
}

Expand Down
Loading
Loading
< 10 /body> 0