internal/mirror/mirror.go
174 lines · 4807 bytes
1// Package mirror synchronizes repositories with foreign remotes: push
2// mirrors propagate local refs outward after each receive, pull mirrors
3// keep a local copy fresh from an upstream. Sync runs in a background
4// worker, never in the push path; outcomes are recorded per mirror so
5// `repo mirror list` shows failure states like webhook deliveries do.
6package mirror
7
8import (
9 "context"
10 "fmt"
11 "log/slog"
12 "net"
13 "net/url"
14 "os"
15 "os/exec"
16 "path/filepath"
17 "strings"
18 "time"
19
20 "gitbay.org/gitbay/internal/config"
21 "gitbay.org/gitbay/internal/control"
22 "gitbay.org/gitbay/internal/store"
23 "gitbay.org/gitbay/internal/toolpath"
24 "gitbay.org/gitbay/internal/webhook"
25)
26
27const askpassScript = `#!/bin/sh
28case "$1" in
29 Username*) echo "${GITBAY_MIRROR_USER}" ;;
30 *) echo "${GITBAY_MIRROR_TOKEN}" ;;
31esac
32`
33
34type Worker struct {
35 St *store.Store
36 Cfg config.Config
37 Tick time.Duration
38 // Lookup resolves a mirror's host immediately before each sync.
39 Lookup func(ctx context.Context, host string) ([]net.IP, error)
40}
41
42func New(st *store.Store, cfg config.Config) *Worker {
43 tick := 10 * time.Second
44 if v := os.Getenv("GITBAY_MIRROR_TICK"); v != "" {
45 if d, err := time.ParseDuration(v); err == nil {
46 tick = d
47 }
48 }
49 return &Worker{St: st, Cfg: cfg, Tick: tick,
50 Lookup: func(ctx context.Context, host string) ([]net.IP, error) {
51 return net.DefaultResolver.LookupIP(ctx, "ip", host)
52 }}
53}
54
55func (w *Worker) Run(ctx context.Context) {
56 t := time.NewTicker(w.Tick)
57 defer t.Stop()
58 for {
59 select {
60 case <-ctx.Done():
61 return
62 case <-t.C:
63 w.sweep()
64 }
65 }
66}
67
68func (w *Worker) sweep() {
69 interval := w.Cfg.Mirrors.PullIntervalMinutes * 60
70 due, err := w.St.DueMirrors(interval)
71 if err != nil {
72 slog.Error("mirror: listing due", "err", err)
73 return
74 }
75 for _, m := range due {
76 if err := w.sync(m); err != nil {
77 slog.Warn("mirror sync failed", "mirror", m.ID, "url", m.URL, "err", err)
78 w.St.SetMirrorResult(m.ID, err.Error())
79 } else {
80 w.St.SetMirrorResult(m.ID, "")
81 }
82 }
83}
84
85func (w *Worker) sync(m store.Mirror) error {
86 repo, err := w.St.RepoByID(m.RepoID)
87 if err != nil {
88 return err
89 }
90 dir := control.RepoDir(w.Cfg.Server.Root, repo.OwnerName, repo.Name)
91 u, err := url.Parse(m.URL)
92 if err != nil {
93 return err
94 }
95 if u.Scheme != "https" && u.Scheme != "http" {
96 return fmt.Errorf("mirror URL scheme %q is not http or https", u.Scheme)
97 }
98
99 ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)
100 defer cancel()
101 // The URL was checked when saved, but DNS can answer differently
102 // now. Check what it resolves to at sync time, then let git connect
103 // to exactly those addresses.
104 ips, err := w.Lookup(ctx, u.Hostname())
105 if err != nil {
106 return fmt.Errorf("resolving %s: %w", u.Hostname(), err)
107 }
108 if len(ips) == 0 {
109 // An empty resolve list would leave curl to resolve the host itself.
110 return fmt.Errorf("%s resolves to no address", u.Hostname())
111 }
112 if err := webhook.CheckAddrs(u.Hostname(), ips, w.Cfg.Webhooks.AllowLocal); err != nil {
113 return err
114 }
115
116 env := []string{"GIT_TERMINAL_PROMPT=0", "HOME=" + w.Cfg.Server.Root}
117 if m.Token != "" {
118 askpass := filepath.Join(w.Cfg.Server.Root, "mirror-askpass.sh")
119 if err := os.WriteFile(askpass, []byte(askpassScript), 0o700); err != nil {
120 return err
121 }
122 user := m.Username
123 if user == "" {
124 user = "x-access-token"
125 }
126 env = append(env,
127 "GIT_ASKPASS="+askpass,
128 "GITBAY_MIRROR_USER="+user,
129 "GITBAY_MIRROR_TOKEN="+m.Token)
130 }
131
132 args := append(pinArgs(u, ips), "-C", dir)
133 if m.Direction == "push" {
134 // Branches and tags only: internal refs (merge-requests) stay home.
135 args = append(args, "push", "--prune", m.URL,
136 "+refs/heads/*:refs/heads/*", "+refs/tags/*:refs/tags/*")
137 } else {
138 args = append(args, "fetch", "--prune", m.URL,
139 "+refs/heads/*:refs/heads/*", "+refs/tags/*:refs/tags/*")
140 }
141 cmd := exec.CommandContext(ctx, toolpath.Look("git"), args...)
142 cmd.Env = env
143 if out, err := cmd.CombinedOutput(); err != nil {
144 return fmt.Errorf("git %s: %v: %.300s", m.Direction, err, out)
145 }
146 return nil
147}
148
149// pinArgs keeps git on the addresses just checked: curl's resolve list
150// pins the host, and with redirects off a server cannot send git on to
151// a host nobody checked. An address literal needs no pin.
152func pinArgs(u *url.URL, ips []net.IP) []string {
153 args := []string{"-c", "http.followRedirects=false"}
154 host := u.Hostname()
155 if net.ParseIP(host) != nil {
156 return args
157 }
158 port := u.Port()
159 if port == "" {
160 port = "443"
161 if u.Scheme == "http" {
162 port = "80"
163 }
164 }
165 addrs := make([]string, len(ips))
166 for i, ip := range ips {
167 if ip.To4() == nil {
168 addrs[i] = "[" + ip.String() + "]"
169 } else {
170 addrs[i] = ip.String()
171 }
172 }
173 return append(args, "-c", "http.curloptResolve="+host+":"+port+":"+strings.Join(addrs, ","))
174}