BlueGit

timfa bluegit

Files

bluegit / internal / server / events.go

events.go

feat: breid rules en de ingebouwde runner uit
timfa project_87923614_bot_3aff574f6f98414b945a8799374f9092 · pushed by timfa · 3 weeks ago
5fec96f0 History
events.go 7.4 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
22func (s *Server) AfterPush(repo store.Repo, user store.User, before, after map[string]string) {
23 if after == nil {
24 return
25 }
26 actor := user.Username
27 for ref, sha := range after {
28 if before[ref] == sha {
29 continue
30 }
31 if isZero(sha) {
32 continue
33 }
34 if strings.HasPrefix(ref, "refs/tags/") {
35 s.startPipeline(context.Background(), repo, sha, ref, actor, "push", before[ref], nil)
36 continue
37 }
38 branch, ok := gitrepo.BranchOfRef(ref)
39 if !ok {
40 continue
41 }
42 s.recordPushContributions(repo, user, map[string]string{ref: before[ref]}, map[string]string{ref: sha})
43 s.startPipeline(context.Background(), repo, sha, ref, actor, "push", before[ref], nil)
44 s.startMergeRequestPipelines(context.Background(), repo, sha, branch, actor, before[ref])
45 s.rerunMergeRequestsOnTarget(context.Background(), repo, branch, actor)
46 web := strings.TrimRight(s.Cfg.BaseURL, "/") + "/" + repo.FullPath()
47 s.Dispatch(repo.ID, webhook.Event{
48 Type: webhook.EventPush,
49 Project: repo.FullPath(),
50 Branch: branch,
51 Commit: sha,
52 Summary: i18n.T(i18n.EN, "hook.push", actor, branch, repo.FullPath()),
53 URL: web,
54 Actor: actor,
55 })
56 }
57}
58
59func isZero(sha string) bool {
60 return strings.Trim(sha, "0") == ""
61}
62
63func (s *Server) startPipeline(ctx context.Context, repo store.Repo, sha, ref, actor, source, before string, mr *ci.MRInfo) int64 {
64 if !s.Cfg.CI.Enabled || s.StoragePath() == "" {
65 return 0
66 }
67 title, jobs, broken := s.planPipeline(ctx, repo, sha, ref, source, before, mr)
68 if broken != nil {
69 id, err := s.Store.RecordConfigFailure(ctx, repo.ID, sha, ref, broken.Error())
70 if err != nil && s.Log != nil {
71 s.Log.Error("pipeline", "err", err)
72 }
73 if mr != nil && id != 0 {
74 _ = s.Store.AttachPipelineMR(ctx, id, mr.ID)
75 }
76 if id != 0 {
77 s.cancelOlder(ctx, repo.ID, ref, id)
78 }
79 return id
80 }
81 if len(jobs) == 0 {
82 return 0
83 }
84 id, err := s.Store.CreatePipeline(ctx, repo.ID, sha, ref, source, actor, title, jobs)
85 if err != nil {
86 if s.Log != nil {
87 s.Log.Error("pipeline", "err", err)
88 }
89 return 0
90 }
91 if mr != nil {
92 _ = s.Store.AttachPipelineMR(ctx, id, mr.ID)
93 }
94 s.cancelOlder(ctx, repo.ID, ref, id)
95 return id
96}
97
98func (s *Server) cancelOlder(ctx context.Context, repoID int64, ref string, keep int64) {
99 running, pipes, err := s.Store.CancelInterruptible(ctx, repoID, ref, keep)
100 if err != nil {
101 if s.Log != nil {
102 s.Log.Error("interruptible", "err", err)
103 }
104 return
105 }
106 if s.Runner != nil {
107 s.Runner.Interrupt(running)
108 }
109 for _, id := range pipes {
110 if _, err := s.Store.RefreshPipelineStatus(ctx, id); err != nil && s.Log != nil {
111 s.Log.Error("pipelinestatus", "err", err)
112 }
113 }
114}
115
116func gitOne(ctx context.Context, gitBin, dir string, args ...string) string {
117 out, err := exec.CommandContext(ctx, gitBin, append([]string{"-C", dir}, args...)...).Output()
118 if err != nil {
119 return ""
120 }
121 return strings.TrimSpace(string(out))
122}
123
124func gitLines(ctx context.Context, gitBin, dir string, args ...string) []string {
125 out := gitOne(ctx, gitBin, dir, args...)
126 if out == "" {
127 return []string{}
128 }
129 return strings.Split(out, "\n")
130}
131
132func changedFiles(ctx context.Context, gitBin, dir, sha, before string, all []string) []string {
133 if before == "" || strings.Trim(before, "0") == "" {
134 parent := gitOne(ctx, gitBin, dir, "rev-parse", "--verify", sha+"^")
135 if parent == "" {
136 return all
137 }
138 before = parent
139 }
140 out, err := exec.CommandContext(ctx, gitBin, "-C", dir, "diff", "--name-only", before, sha).Output()
141 if err != nil {
142 return nil
143 }
144 text := strings.TrimSpace(string(out))
145 if text == "" {
146 return []string{}
147 }
148 return strings.Split(text, "\n")
149}
150
151func pushEvent(repo store.Repo, kind, branch, commit, actor, summary, path string) webhook.Event {
152 return webhook.Event{
153 Type: kind, Project: repo.FullPath(), Branch: branch, Commit: commit,
154 Actor: actor, Summary: summary, URL: path,
155 }
156}
157
158func (s *Server) Dispatch(repoID int64, ev webhook.Event) {
159 ctx := context.Background()
160 repo, err := s.Store.RepoByID(ctx, repoID)
161 if err != nil {
162 return
163 }
164 if ev.Project == "" {
165 ev.Project = repo.FullPath()
166 }
167 if !strings.HasPrefix(ev.URL, "http") {
168 ev.URL = strings.TrimRight(s.Cfg.BaseURL, "/") + ev.URL
169 }
170 if repo.OwnerKind == "group" {
171 if g, err := s.Store.GroupByID(ctx, repo.OwnerID); err == nil {
172 ev.Group = g.Path
173 }
174 }
175 patterns, _ := s.Store.ProtectedPatterns(ctx, repo.ID)
176 protected := access.BranchProtected(patterns, ev.Branch)
177 s.deliver(ctx, "repo", repo.ID, ev, protected)
178 if repo.OwnerKind == "group" {
179 s.deliver(ctx, "group", repo.OwnerID, ev, protected)
180 }
181 if ev.Type == webhook.EventPipelineFailure {
182 s.queueFailureMail(repo, ev)
183 }
184}
185
186func (s *Server) deliver(ctx context.Context, kind string, scopeID int64, ev webhook.Event, refProtected bool) {
187 hooks, err := s.Store.ListWebhooks(ctx, kind, scopeID)
188 if err != nil {
189 return
190 }
191 secrets, err := s.Store.SecretValues(ctx, kind, scopeID, refProtected)
192 if err != nil {
193 s.Log.Error("geheimen voor webhook", "err", err)
194 return
195 }
196 client := ssrf.NewClient(10 * time.Second)
197 for _, h := range hooks {
198 if !h.Active {
199 continue
200 }
201 ok, err := webhook.Allows(webhook.Hook{Preset: h.Preset, Events: h.Events, BranchFilter: h.BranchFilter}, ev)
202 if err != nil {
203 _ = s.Store.AddDelivery(ctx, h.ID, ev.Type, 0, err.Error())
204 continue
205 }
206 if !ok {
207 continue
208 }
209 rawURL, err := webhook.Expand(h.URLTemplate, ev, secrets)
210 if err != nil {
211 _ = s.Store.AddDelivery(ctx, h.ID, ev.Type, 0, err.Error())
212 continue
213 }
214 target, err := urlParse(rawURL)
215 if err != nil {
216 _ = s.Store.AddDelivery(ctx, h.ID, ev.Type, 0, err.Error())
217 continue
218 }
219 if err := ssrf.ValidateURL(target); err != nil {
220 _ = s.Store.AddDelivery(ctx, h.ID, ev.Type, 0, err.Error())
221 continue
222 }
223 headers, err := webhook.RenderHeaders(h.Preset, h.Headers, ev, secrets)
224 if err != nil {
225 _ = s.Store.AddDelivery(ctx, h.ID, ev.Type, 0, err.Error())
226 continue
227 }
228 body, err := webhook.RenderBody(h.BodyTemplate, ev, secrets)
229 if err != nil {
230 _ = s.Store.AddDelivery(ctx, h.ID, ev.Type, 0, err.Error())
231 continue
232 }
233 method := h.Method
234 if method == "" {
235 method = http.MethodPost
236 }
237 req, err := http.NewRequestWithContext(ctx, method, rawURL, bytes.NewReader(body))
238 if err != nil {
239 _ = s.Store.AddDelivery(ctx, h.ID, ev.Type, 0, err.Error())
240 continue
241 }
242 for k, v := range headers {
243 if strings.ContainsAny(k, "\r\n") || strings.ContainsAny(v, "\r\n") {
244 continue
245 }
246 req.Header.Set(k, v)
247 }
248 res, err := client.Do(req)
249 if err != nil {
250 _ = s.Store.AddDelivery(ctx, h.ID, ev.Type, 0, err.Error())
251 continue
252 }
253 _, _ = io.Copy(io.Discard, io.LimitReader(res.Body, 1<<20))
254 res.Body.Close()
255 _ = s.Store.AddDelivery(ctx, h.ID, ev.Type, res.StatusCode, "")
256 }
257}
258
259func urlParse(raw string) (*url.URL, error) {
260 u, err := url.Parse(raw)
261 if err != nil {
262 return nil, i18n.E("err.whURL")
263 }
264 return u, nil
265}
266
267func gitSHA(r *http.Request, gitBin, dir, rev string) (string, error) {
268 out, err := exec.CommandContext(r.Context(), gitBin, "-C", dir, "rev-parse", "--verify", rev+"^{commit}").Output()
269 if err != nil {
270 return "", err
271 }
272 return strings.TrimSpace(string(out)), nil
273}