BlueGit

timfa bluegit

Files

bluegit / internal / server / events.go

events.go

fix: start een pipeline na commits vanuit de UI
timfa project_87923614_bot_3aff574f6f98414b945a8799374f9092 · pushed by timfa · 3 weeks ago
f576a3e4 History
events.go 8.8 KiB Download Raw
1package server
2
3import (
4 "bytes"
5 "context"
6 "io"
7 "net/http"
8 "net/url"
9 "os/exec"
10 "strings"
11 "time"
12
13 "gitlab.com/Timfa/bluegit/internal/access"
14 "gitlab.com/Timfa/bluegit/internal/ci"
15 "gitlab.com/Timfa/bluegit/internal/gitrepo"
16 "gitlab.com/Timfa/bluegit/internal/i18n"
17 "gitlab.com/Timfa/bluegit/internal/ssrf"
18 "gitlab.com/Timfa/bluegit/internal/store"
19 "gitlab.com/Timfa/bluegit/internal/webhook"
20)
21
22// postReceive is de enige route voor een ref-wijziging die BlueGit zelf maakt:
23// de Pipeline Editor, suggesties, een merge en een tag. mutate schrijft de refs.
24// Daarna geldt hetzelfde als na een git push: pipeline, webhook en activity.
25func (s *Server) postReceive(ctx context.Context, repo store.Repo, user store.User, dir string, mutate func() error) error {
26 before, err := gitrepo.Refs(ctx, s.Git, dir)
27 if err != nil {
28 before = map[string]string{}
29 }
30 if err := mutate(); err != nil {
31 return err
32 }
33 after, err := gitrepo.Refs(ctx, s.Git, dir)
34 if err != nil {
35 if s.Log != nil {
36 s.Log.Error("post-receive", "err", err)
37 }
38 return nil
39 }
40 s.AfterPush(repo, user, before, after)
41 return nil
42}
43
44// AfterPush behandelt elke nieuwe ref zoals een git push.
45// git http, SSH en postReceive zijn de enige aanroepers.
46func (s *Server) AfterPush(repo store.Repo, user store.User, before, after map[string]string) {
47 if after == nil {
48 return
49 }
50 actor := user.Username
51 for ref, sha := range after {
52 if before[ref] == sha || isZero(sha) {
53 continue
54 }
55 commit := s.peeled(repo, sha)
56 if strings.HasPrefix(ref, "refs/tags/") {
57 name := strings.TrimPrefix(ref, "refs/tags/")
58 s.startPipeline(context.Background(), repo, commit, ref, actor, "push", before[ref], nil)
59 s.recordContribution(user.ID, repo.ID, "tag", ref, time.Now().UTC())
60 s.pushHook(repo, actor, name, commit)
61 continue
62 }
63 branch, ok := gitrepo.BranchOfRef(ref)
64 if !ok {
65 continue
66 }
67 s.recordPushContributions(repo, user, map[string]string{ref: before[ref]}, map[string]string{ref: sha})
68 s.startPipeline(context.Background(), repo, commit, ref, actor, "push", before[ref], nil)
69 s.startMergeRequestPipelines(context.Background(), repo, commit, branch, actor, before[ref])
70 s.rerunMergeRequestsOnTarget(context.Background(), repo, branch, actor)
71 s.pushHook(repo, actor, branch, commit)
72 }
73}
74
75func (s *Server) pushHook(repo store.Repo, actor, branch, commit string) {
76 s.Dispatch(repo.ID, webhook.Event{
77 Type: webhook.EventPush,
78 Project: repo.FullPath(),
79 Branch: branch,
80 Commit: commit,
81 Summary: i18n.T(i18n.EN, "hook.push", actor, branch, repo.FullPath()),
82 URL: strings.TrimRight(s.Cfg.BaseURL, "/") + "/" + repo.FullPath(),
83 Actor: actor,
84 })
85}
86
87func (s *Server) peeled(repo store.Repo, sha string) string {
88 if s.StoragePath() == "" || sha == "" {
89 return sha
90 }
91 dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name)
92 if commit := gitOne(context.Background(), s.Git, dir, "rev-parse", "--verify", sha+"^{commit}"); commit != "" {
93 return commit
94 }
95 return sha
96}
97
98func isZero(sha string) bool {
99 return strings.Trim(sha, "0") == ""
100}
101
102func (s *Server) startPipeline(ctx context.Context, repo store.Repo, sha, ref, actor, source, before string, mr *ci.MRInfo) int64 {
103 if !s.Cfg.CI.Enabled || s.StoragePath() == "" {
104 return 0
105 }
106 title, jobs, broken := s.planPipeline(ctx, repo, sha, ref, source, before, mr)
107 if broken != nil {
108 id, err := s.Store.RecordConfigFailure(ctx, repo.ID, sha, ref, broken.Error())
109 if err != nil && s.Log != nil {
110 s.Log.Error("pipeline", "err", err)
111 }
112 if mr != nil && id != 0 {
113 _ = s.Store.AttachPipelineMR(ctx, id, mr.ID)
114 }
115 if id != 0 {
116 s.cancelOlder(ctx, repo.ID, ref, id)
117 }
118 return id
119 }
120 if len(jobs) == 0 {
121 return 0
122 }
123 id, err := s.Store.CreatePipeline(ctx, repo.ID, sha, ref, source, actor, title, jobs)
124 if err != nil {
125 if s.Log != nil {
126 s.Log.Error("pipeline", "err", err)
127 }
128 return 0
129 }
130 if mr != nil {
131 _ = s.Store.AttachPipelineMR(ctx, id, mr.ID)
132 }
133 s.cancelOlder(ctx, repo.ID, ref, id)
134 return id
135}
136
137func (s *Server) cancelOlder(ctx context.Context, repoID int64, ref string, keep int64) {
138 running, pipes, err := s.Store.CancelInterruptible(ctx, repoID, ref, keep)
139 if err != nil {
140 if s.Log != nil {
141 s.Log.Error("interruptible", "err", err)
142 }
143 return
144 }
145 if s.Runner != nil {
146 s.Runner.Interrupt(running)
147 }
148 for _, id := range pipes {
149 if _, err := s.Store.RefreshPipelineStatus(ctx, id); err != nil && s.Log != nil {
150 s.Log.Error("pipelinestatus", "err", err)
151 }
152 }
153}
154
155func gitOne(ctx context.Context, gitBin, dir string, args ...string) string {
156 out, err := exec.CommandContext(ctx, gitBin, append([]string{"-C", dir}, args...)...).Output()
157 if err != nil {
158 return ""
159 }
160 return strings.TrimSpace(string(out))
161}
162
163func gitLines(ctx context.Context, gitBin, dir string, args ...string) []string {
164 out := gitOne(ctx, gitBin, dir, args...)
165 if out == "" {
166 return []string{}
167 }
168 return strings.Split(out, "\n")
169}
170
171func changedFiles(ctx context.Context, gitBin, dir, sha, before string, all []string) []string {
172 if before == "" || strings.Trim(before, "0") == "" {
173 parent := gitOne(ctx, gitBin, dir, "rev-parse", "--verify", sha+"^")
174 if parent == "" {
175 return all
176 }
177 before = parent
178 }
179 out, err := exec.CommandContext(ctx, gitBin, "-C", dir, "diff", "--name-only", before, sha).Output()
180 if err != nil {
181 return nil
182 }
183 text := strings.TrimSpace(string(out))
184 if text == "" {
185 return []string{}
186 }
187 return strings.Split(text, "\n")
188}
189
190func pushEvent(repo store.Repo, kind, branch, commit, actor, summary, path string) webhook.Event {
191 return webhook.Event{
192 Type: kind, Project: repo.FullPath(), Branch: branch, Commit: commit,
193 Actor: actor, Summary: summary, URL: path,
194 }
195}
196
197func (s *Server) Dispatch(repoID int64, ev webhook.Event) {
198 ctx := context.Background()
199 repo, err := s.Store.RepoByID(ctx, repoID)
200 if err != nil {
201 return
202 }
203 if ev.Project == "" {
204 ev.Project = repo.FullPath()
205 }
206 if !strings.HasPrefix(ev.URL, "http") {
207 ev.URL = strings.TrimRight(s.Cfg.BaseURL, "/") + ev.URL
208 }
209 if repo.OwnerKind == "group" {
210 if g, err := s.Store.GroupByID(ctx, repo.OwnerID); err == nil {
211 ev.Group = g.Path
212 }
213 }
214 patterns, _ := s.Store.ProtectedPatterns(ctx, repo.ID)
215 protected := access.BranchProtected(patterns, ev.Branch)
216 s.deliver(ctx, "repo", repo.ID, ev, protected)
217 if repo.OwnerKind == "group" {
218 s.deliver(ctx, "group", repo.OwnerID, ev, protected)
219 }
220 if ev.Type == webhook.EventPipelineFailure {
221 s.queueFailureMail(repo, ev)
222 }
223}
224
225func (s *Server) deliver(ctx context.Context, kind string, scopeID int64, ev webhook.Event, refProtected bool) {
226 hooks, err := s.Store.ListWebhooks(ctx, kind, scopeID)
227 if err != nil {
228 return
229 }
230 secrets, err := s.Store.SecretValues(ctx, kind, scopeID, refProtected)
231 if err != nil {
232 s.Log.Error("geheimen voor webhook", "err", err)
233 return
234 }
235 client := ssrf.NewClient(10 * time.Second)
236 for _, h := range hooks {
237 if !h.Active {
238 continue
239 }
240 ok, err := webhook.Allows(webhook.Hook{Preset: h.Preset, Events: h.Events, BranchFilter: h.BranchFilter}, ev)
241 if err != nil {
242 _ = s.Store.AddDelivery(ctx, h.ID, ev.Type, 0, err.Error())
243 continue
244 }
245 if !ok {
246 continue
247 }
248 rawURL, err := webhook.Expand(h.URLTemplate, ev, secrets)
249 if err != nil {
250 _ = s.Store.AddDelivery(ctx, h.ID, ev.Type, 0, err.Error())
251 continue
252 }
253 target, err := urlParse(rawURL)
254 if err != nil {
255 _ = s.Store.AddDelivery(ctx, h.ID, ev.Type, 0, err.Error())
256 continue
257 }
258 if err := ssrf.ValidateURL(target); err != nil {
259 _ = s.Store.AddDelivery(ctx, h.ID, ev.Type, 0, err.Error())
260 continue
261 }
262 headers, err := webhook.RenderHeaders(h.Preset, h.Headers, ev, secrets)
263 if err != nil {
264 _ = s.Store.AddDelivery(ctx, h.ID, ev.Type, 0, err.Error())
265 continue
266 }
267 body, err := webhook.RenderBody(h.BodyTemplate, ev, secrets)
268 if err != nil {
269 _ = s.Store.AddDelivery(ctx, h.ID, ev.Type, 0, err.Error())
270 continue
271 }
272 method := h.Method
273 if method == "" {
274 method = http.MethodPost
275 }
276 req, err := http.NewRequestWithContext(ctx, method, rawURL, bytes.NewReader(body))
277 if err != nil {
278 _ = s.Store.AddDelivery(ctx, h.ID, ev.Type, 0, err.Error())
279 continue
280 }
281 for k, v := range headers {
282 if strings.ContainsAny(k, "\r\n") || strings.ContainsAny(v, "\r\n") {
283 continue
284 }
285 req.Header.Set(k, v)
286 }
287 res, err := client.Do(req)
288 if err != nil {
289 _ = s.Store.AddDelivery(ctx, h.ID, ev.Type, 0, err.Error())
290 continue
291 }
292 _, _ = io.Copy(io.Discard, io.LimitReader(res.Body, 1<<20))
293 res.Body.Close()
294 _ = s.Store.AddDelivery(ctx, h.ID, ev.Type, res.StatusCode, "")
295 }
296}
297
298func urlParse(raw string) (*url.URL, error) {
299 u, err := url.Parse(raw)
300 if err != nil {
301 return nil, i18n.E("err.whURL")
302 }
303 return u, nil
304}
305
306func gitSHA(r *http.Request, gitBin, dir, rev string) (string, error) {
307 out, err := exec.CommandContext(r.Context(), gitBin, "-C", dir, "rev-parse", "--verify", rev+"^{commit}").Output()
308 if err != nil {
309 return "", err
310 }
311 return strings.TrimSpace(string(out)), nil
312}