-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
185 lines (156 loc) · 4.79 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
package main
import (
"encoding/json"
"flag"
"fmt"
"net/http"
"os"
"regexp"
"strconv"
"time"
"github.com/sirupsen/logrus"
"k8s.io/test-infra/pkg/flagutil"
"k8s.io/test-infra/prow/config"
"k8s.io/test-infra/prow/config/secret"
prowflagutil "k8s.io/test-infra/prow/flagutil"
"k8s.io/test-infra/prow/github"
"k8s.io/test-infra/prow/interrupts"
"k8s.io/test-infra/prow/pjutil"
"k8s.io/test-infra/prow/pluginhelp"
"k8s.io/test-infra/prow/pluginhelp/externalplugins"
"k8s.io/test-infra/prow/plugins"
)
const pluginName = "pingpong"
var (
pingpongRe = regexp.MustCompile(`(?mi)^/ping\s*$`)
)
type options struct {
port int
dryRun bool
github prowflagutil.GitHubOptions
webhookSecretFile string
}
func (o *options) Validate() error {
for _, group := range []flagutil.OptionGroup{&o.github} {
if err := group.Validate(o.dryRun); err != nil {
return err
}
}
return nil
}
func gatherOptions() options {
o := options{}
fs := flag.NewFlagSet(os.Args[0], flag.ExitOnError)
fs.IntVar(&o.port, "port", 8888, "Port to listen on.")
fs.BoolVar(&o.dryRun, "dry-run", true, "Dry run for testing. Uses API tokens but does not mutate.")
fs.StringVar(&o.webhookSecretFile, "hmac-secret-file", "/etc/webhook/hmac", "Path to the file containing the GitHub HMAC secret.")
for _, group := range []flagutil.OptionGroup{&o.github} {
group.AddFlags(fs)
}
fs.Parse(os.Args[1:])
return o
}
func helpProvider(enabledRepos []string) (*pluginhelp.PluginHelp, error) {
pluginHelp := &pluginhelp.PluginHelp{
Description: `This is a Prow external-plugin sample. if you commented "/ping" on Github, Prow bot reply "pong".`,
}
pluginHelp.AddCommand(pluginhelp.Command{
Usage: "/ping",
Description: "Response pong.",
WhoCanUse: "Anyone",
Examples: []string{"/ping"},
})
return pluginHelp, nil
}
func main() {
o := gatherOptions()
if err := o.Validate(); err != nil {
logrus.Fatalf("Invalid options: %v", err)
}
logrus.SetFormatter(&logrus.JSONFormatter{})
// TODO: Use global option from the prow config.
logrus.SetLevel(logrus.DebugLevel)
log := logrus.StandardLogger().WithField("plugin", pluginName)
secretAgent := &secret.Agent{}
if err := secretAgent.Start([]string{o.github.TokenPath, o.webhookSecretFile}); err != nil {
logrus.WithError(err).Fatal("Error starting secrets agent.")
}
githubClient, err := o.github.GitHubClient(secretAgent, o.dryRun)
if err != nil {
logrus.WithError(err).Fatal("Error getting GitHub client.")
}
serv := &server{
tokenGenerator: secretAgent.GetTokenGenerator(o.webhookSecretFile),
ghc: githubClient,
log: log,
}
health := pjutil.NewHealth()
log.Info("Complete serve setting")
mux := http.NewServeMux()
mux.Handle("/", serv)
externalplugins.ServeExternalPluginHelp(mux, log, helpProvider)
httpServer := &http.Server{Addr: ":" + strconv.Itoa(o.port), Handler: mux}
health.ServeReady()
defer interrupts.WaitForGracefulShutdown()
interrupts.ListenAndServe(httpServer, 5*time.Second)
}
type server struct {
tokenGenerator func() []byte
prowURL string
configAgent *config.Agent
ghc github.Client
log *logrus.Entry
}
func (s *server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
eventType, eventGUID, payload, ok, _ := github.ValidateWebhook(w, r, s.tokenGenerator())
if !ok {
return
}
fmt.Fprint(w, "Event received. Have a nice day.")
if err := s.handleEvent(eventType, eventGUID, payload); err != nil {
logrus.WithError(err).Error("Error parsing event.")
}
}
func (s *server) handleEvent(eventType, eventGUID string, payload []byte) error {
l := s.log.WithFields(logrus.Fields{
"event-type": eventType,
github.EventGUID: eventGUID,
})
switch eventType {
case "issue_comment":
var ic github.IssueCommentEvent
if err := json.Unmarshal(payload, &ic); err != nil {
return err
}
go func() {
if err := s.handleIssueComment(l, ic); err != nil {
s.log.WithError(err).WithFields(l.Data).Info("Refreshing github statuses failed.")
}
}()
default:
logrus.Debugf("skipping event of type %q", eventType)
}
return nil
}
func (s *server) handleIssueComment(l *logrus.Entry, ic github.IssueCommentEvent) error {
l = s.log.WithFields(logrus.Fields{
"body": ic.Comment.Body,
})
l.Info("handleIssueComment called")
if !ic.Issue.IsPullRequest() || ic.Action != github.IssueCommentActionCreated || ic.Issue.State == "closed" {
return nil
}
org := ic.Repo.Owner.Login
repo := ic.Repo.Name
num := ic.Issue.Number
l = l.WithFields(logrus.Fields{
github.OrgLogField: org,
github.RepoLogField: repo,
github.PrLogField: num,
})
if !pingpongRe.MatchString(ic.Comment.Body) {
return nil
}
l.Infof("Commenting with \"%s\".", "pong")
return s.ghc.CreateComment(org, repo, num, plugins.FormatICResponse(ic.Comment, "pong"))
}