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 new tool: patch release cherry pick notification #2432

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
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
16 changes: 16 additions & 0 deletions cmd/patch-release-notify/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# Patch Release Notify

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.

## Install

The simplest way to install the `patch-release-notify` CLI is via `go get`:

```
$ go get k8s.io/release/cmd/patch-release-notify
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
$ go get k8s.io/release/cmd/patch-release-notify
$ go install k8s.io/release/cmd/patch-release-notify@latest

I think go get is deprecated for installing binaries.

```

This will install `patch-release-notify` to `$(go env GOPATH)/bin/patch-release-notify`.

Also if you have the `kubernetes/release` cloned you can run the `make release-tools` to build all the tools.
295 changes: 295 additions & 0 deletions cmd/patch-release-notify/cmd/root.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,295 @@
/*
Copyright 2022 The Kubernetes Authors.
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
Copyright 2022 The Kubernetes Authors.
Copyright 2023 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 cmd

import (
"bytes"
"embed"
"errors"
"fmt"
"html/template"
"io"
"math"
"net/http"
"os"
"path/filepath"
"strings"
"time"

"github.com/sirupsen/logrus"
"github.com/spf13/cobra"

"k8s.io/release/cmd/schedule-builder/model"
"k8s.io/release/pkg/mail"
"sigs.k8s.io/release-utils/env"
"sigs.k8s.io/release-utils/log"
"sigs.k8s.io/yaml"
)

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

// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
Use: "patch-release-notify --schedule-path /path/to/schedule.yaml",
Short: "patch-release-notify check the cherry pick deadline and send an email to notify",
Example: "patch-release-notify --schedule-path /path/to/schedule.yaml",
SilenceUsage: true,
SilenceErrors: true,
PersistentPreRunE: initLogging,
RunE: func(*cobra.Command, []string) error {
return run(opts)
},
}

type options struct {
sendgridAPIKey string
schedulePath string
dayToalert int
name string
email string
nomock bool
logLevel string
}

var opts = &options{}

const (
sendgridAPIKeyEnvKey = "SENDGRID_API_KEY" //nolint:gosec // this will be provided via env vars
layout = "2006-01-02"

schedulePathFlag = "schedule-path"
nameFlag = "name"
emailFlag = "email"
dayToalertFlag = "days-to-alert"
)

var requiredFlags = []string{
schedulePathFlag,
Copy link
Member

Choose a reason for hiding this comment

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

Could we point that to a default remote location without requiring the path to be locally available?

}

type Template struct {
Releases []TemplateRelease
}

type TemplateRelease struct {
Release string
CherryPickDeadline string
}

// Execute adds all child commands to the root command and sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
if err := rootCmd.Execute(); err != nil {
logrus.Fatal(err)
}
}

func init() {
opts.sendgridAPIKey = env.Default(sendgridAPIKeyEnvKey, "")

rootCmd.PersistentFlags().StringVar(
&opts.schedulePath,
schedulePathFlag,
"",
"path where can find the schedule.yaml file",
)

rootCmd.PersistentFlags().BoolVar(
&opts.nomock,
"nomock",
false,
"run the command to target the production environment",
)

rootCmd.PersistentFlags().StringVar(
&opts.logLevel,
"log-level",
"info",
fmt.Sprintf("the logging verbosity, either %s", log.LevelNames()),
)

rootCmd.PersistentFlags().StringVarP(
&opts.name,
nameFlag,
"n",
"",
"mail sender name",
)

rootCmd.PersistentFlags().IntVar(
&opts.dayToalert,
dayToalertFlag,
3,
"day to before the deadline to send the notification. Defaults to 3 days.",
Copy link
Member

Choose a reason for hiding this comment

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

Assuming the deadline is on Friday's, we probably wanna adjust the deadline to the previous Monday. So 4 days?

)

rootCmd.PersistentFlags().StringVarP(
&opts.email,
emailFlag,
"e",
"",
"email address",
)

for _, flag := range requiredFlags {
if err := rootCmd.MarkPersistentFlagRequired(flag); err != nil {
logrus.Fatal(err)
}
}
}

func initLogging(*cobra.Command, []string) error {
return log.SetupGlobalLogger(opts.logLevel)
}

func run(opts *options) error {
if err := opts.SetAndValidate(); err != nil {
return fmt.Errorf("validating schedule-path options: %w", err)
}

if opts.sendgridAPIKey == "" {
return fmt.Errorf(
"$%s is not set", sendgridAPIKeyEnvKey,
)
}

data, err := loadFileOrURL(opts.schedulePath)
if err != nil {
return fmt.Errorf("failed to read the file: %w", err)
}

patchSchedule := &model.PatchSchedule{}

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

if err := yaml.UnmarshalStrict(data, &patchSchedule); err != nil {
return fmt.Errorf("failed to decode the file: %w", err)
}

output := &Template{}

shouldSendEmail := false

for _, patch := range patchSchedule.Schedules {
t, err := time.Parse(layout, patch.CherryPickDeadline)
if err != nil {
return fmt.Errorf("parsing schedule time: %w", err)
}

currentTime := time.Now().UTC()
days := t.Sub(currentTime).Hours() / 24
intDay, _ := math.Modf(days)
if int(intDay) == opts.dayToalert {
output.Releases = append(output.Releases, TemplateRelease{
Release: patch.Release,
CherryPickDeadline: patch.CherryPickDeadline,
})
shouldSendEmail = true
}
}

tmpl, err := template.ParseFS(tpls, "templates/email.tmpl")
if err != nil {
return fmt.Errorf("parsing template: %w", err)
}

var tmplBytes bytes.Buffer
err = tmpl.Execute(&tmplBytes, output)
if err != nil {
return fmt.Errorf("parsing values to the template: %w", err)
}

if !shouldSendEmail {
logrus.Info("No email is needed to send")
return nil
}

if !opts.nomock {
logrus.Info("This is a mock only, will print out the email before sending to a test mailing list")
fmt.Println(tmplBytes.String())
}

logrus.Info("Preparing mail sender")
m := mail.NewSender(opts.sendgridAPIKey)

if opts.name != "" && opts.email != "" {
if err := m.SetSender(opts.name, opts.email); err != nil {
return fmt.Errorf("unable to set mail sender: %w", err)
}
} else {
logrus.Info("Retrieving default sender from sendgrid API")
if err := m.SetDefaultSender(); err != nil {
return fmt.Errorf("setting default sender: %w", err)
}
}

groups := []mail.GoogleGroup{mail.KubernetesAnnounceTestGoogleGroup}
if opts.nomock {
groups = []mail.GoogleGroup{
mail.KubernetesDevGoogleGroup,
}
}
logrus.Infof("Using Google Groups as announcement target: %v", groups)

if err := m.SetGoogleGroupRecipients(groups...); err != nil {
return fmt.Errorf("unable to set mail recipients: %w", err)
}

logrus.Info("Sending mail")
subject := "[Please Read] Patch Releases cherry-pick deadline"

if err := m.Send(tmplBytes.String(), subject); err != nil {
return fmt.Errorf("unable to send mail: %w", err)
}

return nil
}

// SetAndValidate sets some default options and verifies if options are valid
func (o *options) SetAndValidate() error {
logrus.Info("Validating schedule-path options...")

if o.schedulePath == "" {
return errors.New("need to set the schedule-path")
}

return nil
}

func loadFileOrURL(fileRef string) ([]byte, error) {
var raw []byte
var err error
if strings.HasPrefix(fileRef, "http://") || strings.HasPrefix(fileRef, "https://") {
// #nosec G107
resp, err := http.Get(fileRef)
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-notify/cmd/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}}
<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}}
<br>
<p>For PRs that you intend to land for the upcoming patch sets, please
ensure they have:</p>
<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>
</body>
</html>
23 changes: 23 additions & 0 deletions cmd/patch-release-notify/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
/*
Copyright 2022 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 "k8s.io/release/cmd/patch-release-notify/cmd"

func main() {
cmd.Execute()
}
Loading