Skip to content
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

add aws lambda function to send patch cherry pick notification #3627

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
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
4 changes: 4 additions & 0 deletions cmd/patch-release-notification/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# Patch Release Notification

This simple tool has the objective to send an notification email when we are closer to
the patch release cycle to let people know that the cherry pick deadline is approaching.
318 changes: 318 additions & 0 deletions cmd/patch-release-notification/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,318 @@
/*
Copyright 2024 The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package main

import (
"bytes"
"context"
"embed"
"fmt"
"io"
"log"
"math"
"net/http"
"os"
"path/filepath"
"strings"
"text/template"
"time"

"gomodules.xyz/envconfig"
"gopkg.in/gomail.v2"
"gopkg.in/yaml.v3"

"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ses"
"github.com/sirupsen/logrus"

"k8s.io/release/cmd/schedule-builder/model"
)

//go:embed templates/email.tmpl
var tpls embed.FS

type Config struct {
FromEmail string `envconfig:"FROM_EMAIL" required:"true"`
ToEmail string `envconfig:"TO_EMAIL" required:"true"`
SchedulePath string `envconfig:"SCHEDULE_PATH" required:"true"`
DaysToAlert int `envconfig:"DAYS_TO_ALERT" required:"true"`

NoMock bool `default:"false" envconfig:"NO_MOCK" required:"true"`

AWSRegion string `envconfig:"AWS_REGION" required:"true"`
}

type Options struct {
AWSSess *session.Session
Config *Config
Context context.Context
}

const (
layout = "2006-01-02"
)

type Template struct {
Releases []TemplateRelease
}

type TemplateRelease struct {
Release string
CherryPickDeadline string
}

func main() {
lambda.Start(handler)
}

func getConfig() (*Config, error) {
var c Config
err := envconfig.Process("", &c)
if err != nil {
return nil, err
}
return &c, nil
}

func New(ctx context.Context) (*Options, error) {
cpanato marked this conversation as resolved.
Show resolved Hide resolved
config, err := getConfig()
if err != nil {
return nil, fmt.Errorf("failed to get config: %w", err)
}

// create new AWS session
sess, err := session.NewSession(&aws.Config{
Region: aws.String(config.AWSRegion),
})
if err != nil {
log.Println("Error occurred while creating aws session", err)
return nil, err
cpanato marked this conversation as resolved.
Show resolved Hide resolved
}

return &Options{
AWSSess: sess,
Config: config,
Context: ctx,
}, nil
}

func handler(ctx context.Context, request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) { //nolint: gocritic
o, err := New(ctx)
if err != nil {
return events.APIGatewayProxyResponse{
Body: `{"status": "nok"}`,
StatusCode: http.StatusInternalServerError,
}, err
}

cpanato marked this conversation as resolved.
Show resolved Hide resolved
data, err := loadFileOrURL(o.Config.SchedulePath)
if err != nil {
return events.APIGatewayProxyResponse{
Body: `{"status": "nok"}`,
StatusCode: http.StatusInternalServerError,
}, fmt.Errorf("failed to read the file: %w", err)
cpanato marked this conversation as resolved.
Show resolved Hide resolved
}

patchSchedule := &model.PatchSchedule{}

logrus.Info("Parsing the schedule...")

if err := yaml.Unmarshal(data, &patchSchedule); err != nil {
return events.APIGatewayProxyResponse{
Body: `{"status": "nok"}`,
StatusCode: http.StatusInternalServerError,
}, fmt.Errorf("failed to decode the file: %w", err)
cpanato marked this conversation as resolved.
Show resolved Hide resolved
}

output := &Template{}

shouldSendEmail := false

for _, patch := range patchSchedule.Schedules {
t, err := time.Parse(layout, patch.Next.CherryPickDeadline)
if err != nil {
return events.APIGatewayProxyResponse{
Body: `{"status": "nok"}`,
StatusCode: http.StatusInternalServerError,
}, fmt.Errorf("parsing schedule time: %w", err)
}

currentTime := time.Now().UTC()
days := t.Sub(currentTime).Hours() / 24
intDay, _ := math.Modf(days)
logrus.Infof("cherry pick deadline: %d, days to alert: %d", int(intDay), o.Config.DaysToAlert)
cpanato marked this conversation as resolved.
Show resolved Hide resolved
if int(intDay) == o.Config.DaysToAlert {
output.Releases = append(output.Releases, TemplateRelease{
Release: patch.Release,
CherryPickDeadline: patch.Next.CherryPickDeadline,
})
shouldSendEmail = true
}
}

tmpl, err := template.ParseFS(tpls, "templates/email.tmpl")
if err != nil {
return events.APIGatewayProxyResponse{
Body: `{"status": "nok"}`,
StatusCode: http.StatusInternalServerError,
}, fmt.Errorf("parsing template: %w", err)
}

var tmplBytes bytes.Buffer
err = tmpl.Execute(&tmplBytes, output)
if err != nil {
return events.APIGatewayProxyResponse{
Body: `{"status": "nok"}`,
StatusCode: http.StatusInternalServerError,
}, fmt.Errorf("parsing values to the template: %w", err)
cpanato marked this conversation as resolved.
Show resolved Hide resolved
}

if !shouldSendEmail {
logrus.Info("No email is needed to send")
return events.APIGatewayProxyResponse{
Body: `{"status": "ok"}`,
StatusCode: http.StatusOK,
}, nil
}
cpanato marked this conversation as resolved.
Show resolved Hide resolved

logrus.Info("Sending mail")
subject := "[Please Read] Patch Releases cherry-pick deadline"
cpanato marked this conversation as resolved.
Show resolved Hide resolved
fromEmail := o.Config.FromEmail

recipient := Recipient{
toEmails: []string{o.Config.ToEmail},
}

if !o.Config.NoMock {
logrus.Info("This is a mock only, will print out the email before sending to a test mailing list")
fmt.Println(tmplBytes.String())
// if is a mock we send the email to ourselves to test
recipient.toEmails = []string{o.Config.FromEmail}
xmudrii marked this conversation as resolved.
Show resolved Hide resolved
}

err = o.SendEmailRawSES(tmplBytes.String(), subject, fromEmail, recipient)
if err != nil {
return events.APIGatewayProxyResponse{
Body: `{"status": "nok"}`,
StatusCode: http.StatusInternalServerError,
}, fmt.Errorf("parsing values to the template: %w", err)
cpanato marked this conversation as resolved.
Show resolved Hide resolved
}

return events.APIGatewayProxyResponse{
Body: `{"status": "ok"}`,
StatusCode: 200,
}, nil
}

// Recipient struct to hold email IDs
type Recipient struct {
toEmails []string
ccEmails []string
bccEmails []string
}

// SendEmailSES sends email to specified email IDs
func (o *Options) SendEmailRawSES(messageBody, subject, fromEmail string, recipient Recipient) error {
// create raw message
msg := gomail.NewMessage()

// set to section
recipients := make([]*string, 0, len(recipient.toEmails))
for _, r := range recipient.toEmails {
recipient := r
recipients = append(recipients, &recipient)
}

// Set to emails
msg.SetHeader("To", recipient.toEmails...)

// cc mails mentioned
if len(recipient.ccEmails) != 0 {
// Need to add cc mail IDs also in recipient list
for _, r := range recipient.ccEmails {
recipient := r
recipients = append(recipients, &recipient)
}
msg.SetHeader("cc", recipient.ccEmails...)
}

// bcc mails mentioned
if len(recipient.bccEmails) != 0 {
// Need to add bcc mail IDs also in recipient list
for _, r := range recipient.bccEmails {
recipient := r
recipients = append(recipients, &recipient)
}
msg.SetHeader("bcc", recipient.bccEmails...)
}

// create an SES session.
svc := ses.New(o.AWSSess)

msg.SetAddressHeader("From", fromEmail, "Release Managers")
msg.SetHeader("To", recipient.toEmails...)
cpanato marked this conversation as resolved.
Show resolved Hide resolved
msg.SetHeader("Subject", subject)
msg.SetBody("text/html", messageBody)

// create a new buffer to add raw data
var emailRaw bytes.Buffer
_, err := msg.WriteTo(&emailRaw)
if err != nil {
log.Printf("failed to write mail: %v\n", err)
return err
cpanato marked this conversation as resolved.
Show resolved Hide resolved
}

// create new raw message
message := ses.RawMessage{Data: emailRaw.Bytes()}

input := &ses.SendRawEmailInput{Source: &fromEmail, Destinations: recipients, RawMessage: &message}

// send raw email
_, err = svc.SendRawEmail(input)
if err != nil {
log.Println("Error sending mail - ", err)
return err
cpanato marked this conversation as resolved.
Show resolved Hide resolved
}

log.Println("Email sent successfully to: ", recipient.toEmails)
cpanato marked this conversation as resolved.
Show resolved Hide resolved
return nil
}

func loadFileOrURL(fileRef string) ([]byte, error) {
var raw []byte
var err error
if strings.HasPrefix(fileRef, "http://") || strings.HasPrefix(fileRef, "https://") {
resp, err := http.Get(fileRef) //nolint:gosec // we are not using user input we set via env var
if err != nil {
return nil, err
}
defer resp.Body.Close()
raw, err = io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
} else {
raw, err = os.ReadFile(filepath.Clean(fileRef))
if err != nil {
return nil, err
}
}
return raw, nil
}
32 changes: 32 additions & 0 deletions cmd/patch-release-notification/templates/email.tmpl
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<!DOCTYPE html>
<html>
<body>
<p>Hello Kubernetes Community!</p>
{{range .Releases}}
<p>The cherry-pick deadline for the <b>{{ .Release }}</b> branches is <b>{{ .CherryPickDeadline }} EOD PT.</b></p>
{{end}}
Comment on lines +5 to +7
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we make this a single sentence instead of multiple lines? I think that might look better.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

that is like that becasue we might have a different date for a particular release, might not happen, but who knows :)

<br><p>Here are some quick links to search for cherry-pick PRs:</p>
{{range .Releases}}
<p> - release-{{ .Release }}: https://github.com/kubernetes/kubernetes/pulls?q=is%3Apr+is%3Aopen+base%3Arelease-{{ .Release }}+label%3Ado-not-merge%2Fcherry-pick-not-approved</p>
{{end}}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm wondering if we should also (or instead) have links that we use to search for cherry-pick PRs. That way, folks can double check that their PR is on the list to be reviewed (and we also avoid situations where folks think that their PR satisfies the criteria, but it doesn't).

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

did not follow your comment, that is a link or not?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What I thought is that we often use some queries to search for PRs to merge, such as https://github.com/kubernetes/kubernetes/pulls?q=is%3Apr+is%3Aopen+label%3Algtm+label%3Aapproved+milestone%3Av1.30+label%3Ado-not-merge%2Fcherry-pick-not-approved+-label%3Ado-not-merge%2Fhold+-label%3Ado-not-merge%2Fneeds-kind+-label%3Ado-not-merge%2Frelease-note-label-needed

The URL is a bit longer, but I was thinking if we should put it in the message somewhere. It could be very helpful because folks could use it check if their PR satisfies the criteria, i.e. if their PR will be reviewed. We often have some case where folks think that they did everything, but they actually missed something, and the PR gets missed -- this might help to avoid such cases.

However, this is something we can follow up on, I wouldn't block this PR on this.

<br>
<p>For PRs that you intend to land for the upcoming patch sets, please
ensure they have:</p>
cpanato marked this conversation as resolved.
Show resolved Hide resolved
<p> - a release note in the PR description</p>
<p> - /sig</p>
<p> - /kind</p>
<p> - /priority</p>
<p> - /lgtm</p>
<p> - /approve</p>
<p> - passing tests</p>
<br>
<p>Details on the cherry-pick process can be found here:</p>
<p>https://git.k8s.io/community/contributors/devel/sig-release/cherry-picks.md</p>
<p>We keep general info and up-to-date timelines for patch releases here:</p>
<p>https://kubernetes.io/releases/patch-releases/#upcoming-monthly-releases</p>
<p>If you have any questions for the Release Managers, please feel free to
reach out to us at #release-management (Kubernetes Slack) or [email protected]</p><br>
<p>We wish everyone a happy and safe week!</p>
<p>SIG-Release Team</p>
cpanato marked this conversation as resolved.
Show resolved Hide resolved
</body>
</html>
Loading
Loading