-
Notifications
You must be signed in to change notification settings - Fork 118
/
Copy pathoverride.go
238 lines (211 loc) · 8.37 KB
/
override.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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
/*
Copyright 2018 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 override supports the /override context command.
package override
import (
"context"
"fmt"
"regexp"
"strings"
"github.com/jenkins-x/go-scm/scm"
"github.com/jenkins-x/lighthouse/pkg/apis/lighthouse/v1alpha1"
lighthouseclient "github.com/jenkins-x/lighthouse/pkg/client/clientset/versioned/typed/lighthouse/v1alpha1"
"github.com/jenkins-x/lighthouse/pkg/config"
"github.com/jenkins-x/lighthouse/pkg/config/job"
"github.com/jenkins-x/lighthouse/pkg/jobutil"
"github.com/jenkins-x/lighthouse/pkg/plugins"
"github.com/jenkins-x/lighthouse/pkg/scmprovider"
"github.com/jenkins-x/lighthouse/pkg/util"
"github.com/sirupsen/logrus"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/sets"
)
const pluginName = "override"
var (
overrideRe = regexp.MustCompile(`(?mi)^/(?:lh-)?override( (.+?)\s*)?$`)
)
type scmProviderClient interface {
CreateComment(owner, repo string, number int, pr bool, comment string) error
CreateStatus(org, repo, ref string, s *scm.StatusInput) (*scm.Status, error)
GetPullRequest(org, repo string, number int) (*scm.PullRequest, error)
GetRef(org, repo, ref string) (string, error)
HasPermission(org, repo, user string, role ...string) (bool, error)
ListStatuses(org, repo, ref string) ([]*scm.Status, error)
ProviderType() string
PRRefFmt() string
IsOrgAdmin(string, string) (bool, error)
QuoteAuthorForComment(string) string
}
func createOverrideJob(lhClient lighthouseclient.LighthouseJobInterface, job *v1alpha1.LighthouseJob) (*v1alpha1.LighthouseJob, error) {
overrideStatus := job.Status
createdJob, err := lhClient.Create(context.TODO(), job, metav1.CreateOptions{})
if err != nil {
return nil, err
}
createdJob.Status = overrideStatus
return lhClient.UpdateStatus(context.TODO(), createdJob, metav1.UpdateOptions{})
}
func presubmitForContext(jc config.JobConfig, org, repo, context string) *job.Presubmit {
for _, p := range jc.AllPresubmits([]string{org + "/" + repo}) {
if p.Context == context {
return &p
}
}
return nil
}
var (
plugin = plugins.Plugin{
Description: "The override plugin allows repo admins to force a github status context to pass",
Commands: []plugins.Command{{
Name: "override",
Arg: &plugins.CommandArg{
Pattern: `[^\r\n]+`,
},
Description: "Forces a github status context to green (one per line).",
WhoCanUse: "Repo administrators",
Action: plugins.
Invoke(func(match plugins.CommandMatch, pc plugins.Agent, e scmprovider.GenericCommentEvent) error {
return handle(match.Arg, pc.SCMProviderClient, pc.LighthouseClient, pc.Config.JobConfig, pc.Logger, e)
}).
When(plugins.Action(scm.ActionCreate), plugins.IsPR(), plugins.IssueState("open")),
}},
}
)
func init() {
plugins.RegisterPlugin(pluginName, plugin)
}
func authorized(spc scmProviderClient, log *logrus.Entry, org, repo, user string) bool {
ok, err := spc.HasPermission(org, repo, user, scmprovider.RoleAdmin)
if err != nil {
log.WithError(err).Warnf("cannot determine whether %s is an admin of %s/%s", user, org, repo)
return false
}
if !ok && spc.ProviderType() == "stash" {
ok, err = spc.IsOrgAdmin(org, user)
if err != nil {
log.WithError(err).Warnf("cannot determine whether %s is an admin of %s/%s", user, org, repo)
return false
}
}
return ok
}
func description(user string) string {
return fmt.Sprintf("%s %s", util.OverriddenByPrefix, user)
}
func formatList(list []string) string {
var lines []string
for _, item := range list {
lines = append(lines, fmt.Sprintf(" - `%s`", item))
}
return strings.Join(lines, "\n")
}
func handle(context string, spc scmProviderClient, lhClient lighthouseclient.LighthouseJobInterface, jc config.JobConfig, log *logrus.Entry, e scmprovider.GenericCommentEvent) error {
org := e.Repo.Namespace
repo := e.Repo.Name
number := e.Number
user := e.Author.Login
overrides := sets.NewString()
if context == "" {
resp := "/override requires a failed status context to operate on, but none was given"
log.Debug(resp)
return spc.CreateComment(org, repo, number, e.IsPR, plugins.FormatResponseRaw(e.Body, e.Link, spc.QuoteAuthorForComment(user), resp))
}
overrides.Insert(context)
if !authorized(spc, log, org, repo, user) {
resp := fmt.Sprintf("%s unauthorized: /override is restricted to repo administrators", user)
log.Debug(resp)
return spc.CreateComment(org, repo, number, e.IsPR, plugins.FormatResponseRaw(e.Body, e.Link, spc.QuoteAuthorForComment(user), resp))
}
pr, err := spc.GetPullRequest(org, repo, number)
if err != nil {
resp := fmt.Sprintf("Cannot get PR #%d in %s/%s", number, org, repo)
log.WithError(err).Warn(resp)
return spc.CreateComment(org, repo, number, e.IsPR, plugins.FormatResponseRaw(e.Body, e.Link, spc.QuoteAuthorForComment(user), resp))
}
sha := pr.Head.Sha
statuses, err := spc.ListStatuses(org, repo, sha)
if err != nil {
resp := fmt.Sprintf("Cannot get commit statuses for PR #%d in %s/%s", number, org, repo)
log.WithError(err).Warn(resp)
return spc.CreateComment(org, repo, number, e.IsPR, plugins.FormatResponseRaw(e.Body, e.Link, spc.QuoteAuthorForComment(user), resp))
}
contexts := sets.NewString()
for _, status := range statuses {
if status.State == scm.StateSuccess {
continue
}
contexts.Insert(status.Label)
}
if unknown := overrides.Difference(contexts); unknown.Len() > 0 {
resp := fmt.Sprintf(`/override requires a failed status context to operate on.
The following unknown contexts were given:
%s
Only the following contexts were expected:
%s`, formatList(unknown.List()), formatList(contexts.List()))
log.Debug(resp)
return spc.CreateComment(org, repo, number, e.IsPR, plugins.FormatResponseRaw(e.Body, e.Link, spc.QuoteAuthorForComment(user), resp))
}
done := sets.String{}
defer func() {
if len(done) == 0 {
return
}
msg := fmt.Sprintf("Overrode contexts on behalf of %s: %s", user, strings.Join(done.List(), ", "))
log.Info(msg)
err := spc.CreateComment(org, repo, number, e.IsPR, plugins.FormatResponseRaw(e.Body, e.Link, spc.QuoteAuthorForComment(user), msg))
if err != nil {
log.WithError(err).Warn("Failed to create the comment")
}
}()
for _, status := range statuses {
if status.State == scm.StateSuccess || !overrides.Has(status.Label) {
continue
}
// First create the overridden prow result if necessary
if pre := presubmitForContext(jc, org, repo, status.Label); pre != nil {
baseSHA, err := spc.GetRef(org, repo, "heads/"+pr.Base.Ref)
if err != nil {
resp := fmt.Sprintf("Cannot get base ref of PR")
log.WithError(err).Warn(resp)
return spc.CreateComment(org, repo, number, e.IsPR, plugins.FormatResponseRaw(e.Body, e.Link, spc.QuoteAuthorForComment(user), resp))
}
pj, _ := jobutil.NewPresubmit(log, pr, baseSHA, *pre, e.GUID, spc.PRRefFmt())
now := metav1.Now()
pj.Status = v1alpha1.LighthouseJobStatus{
State: v1alpha1.SuccessState,
Description: description(user),
StartTime: now,
CompletionTime: &now,
}
log.WithFields(jobutil.LighthouseJobFields(&pj)).Info("Creating a new override LighthouseJob.")
if _, err := createOverrideJob(lhClient, &pj); err != nil {
resp := fmt.Sprintf("Failed to create override job for %s", status.Label)
log.WithError(err).Warn(resp)
return spc.CreateComment(org, repo, number, e.IsPR, plugins.FormatResponseRaw(e.Body, e.Link, spc.QuoteAuthorForComment(user), resp))
}
}
statusInput := &scm.StatusInput{
State: scm.StateSuccess,
Label: status.Label,
Target: status.Target,
Desc: description(user),
}
if _, err := spc.CreateStatus(org, repo, sha, statusInput); err != nil {
resp := fmt.Sprintf("Cannot update PR status for context %s", statusInput.Label)
log.WithError(err).Warn(resp)
return spc.CreateComment(org, repo, number, e.IsPR, plugins.FormatResponseRaw(e.Body, e.Link, spc.QuoteAuthorForComment(user), resp))
}
done.Insert(status.Label)
}
return nil
}