-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
178 lines (162 loc) · 3.9 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
package main
import (
"context"
"encoding/json"
"errors"
"flag"
"log"
"net/http"
"os"
"os/exec"
"path"
"strings"
"sync"
"time"
)
type config struct {
URL string // Repository URL
Path string // Docker context
File string // Dockerfile
}
var (
// m is used to lock JSON files
m sync.RWMutex
URLToBuild = make(chan string)
triggerMirror = make(chan struct{}, 1)
)
func expect(target, err error) {
if err != nil && err != target && !errors.Is(err, target) {
panic(err)
}
}
func readJSON(file string, v interface{}) {
m.RLock()
defer m.RUnlock()
b, err := os.ReadFile(file)
expect(nil, err)
if err := json.Unmarshal(b, v); err != nil {
log.Println("Cannot unmarshal JSON file", err)
}
}
func webhooks() (webhooksToCall []string) {
readJSON("webhooks.json", &webhooksToCall)
return
}
func imagesToBuild() (images map[string]config) {
readJSON("build.json", &images)
return
}
func imagesToMirror() (images []string) {
readJSON("mirror.json", &images)
return
}
func run(name string, args ...string) bool {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)
defer cancel()
log.Println(name, args)
b, err := exec.CommandContext(ctx, name, args...).CombinedOutput()
if err == nil {
return true
}
if _, ok := err.(*exec.ExitError); !ok {
panic(err)
}
log.Println(name, args, string(b), err, ctx.Err())
return false
}
func mirror() {
for {
nextTime := time.Now().AddDate(0, 0, 1)
for _, image := range imagesToMirror() {
if run("docker", "pull", image) &&
run("docker", "tag", image, "docker.01-edu.org/"+image) {
run("docker", "push", "docker.01-edu.org/"+image)
}
}
select {
case <-time.After(time.Until(nextTime)):
case <-triggerMirror:
}
}
}
func build() {
for URL := range URLToBuild {
dir := path.Join("repositories", strings.TrimSuffix(path.Base(URL), ".git"))
if _, err := os.Stat(dir); os.IsNotExist(err) && !run("git", "clone", URL, dir) {
continue
} else if !run("git", "-C", dir, "pull", "--ff-only") {
continue
}
for image, cfg := range imagesToBuild() {
if URL == cfg.URL {
dir := path.Join(dir, cfg.Path)
file := path.Join(dir, cfg.File)
if run("docker", "build", "--tag", "docker.01-edu.org/"+image, "--file", file, dir) &&
run("docker", "push", "docker.01-edu.org/"+image) {
for _, webhook := range webhooks() {
req, err := http.NewRequest("PUT", webhook, nil)
expect(nil, err)
resp, err := (&http.Client{Timeout: 15 * time.Second}).Do(req)
if err != nil {
log.Println(webhook, err)
} else {
resp.Body.Close()
}
}
}
}
}
}
}
func buildAllImages() {
go func() {
URL := map[string]struct{}{}
for _, cfg := range imagesToBuild() {
URL[cfg.URL] = struct{}{}
}
for URL := range URL {
URLToBuild <- URL
}
}()
}
func handleWebhook(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost { // GitHub webhooks are POST requests
return
}
var payload struct {
Ref string
Repository struct {
URL string `json:"ssh_url"`
}
}
if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
log.Println("Cannot decode webhook", err)
} else if payload.Ref != "refs/heads/master" && payload.Ref != "refs/heads/main" {
log.Println("Branch is not master/main", payload.Ref)
} else if payload.Repository.URL == "[email protected]:01-edu/registry.git" {
m.Lock()
run("git", "pull", "--ff-only")
m.Unlock()
buildAllImages()
select {
case triggerMirror <- struct{}{}:
default:
}
} else if payload.Repository.URL != "" {
URLToBuild <- payload.Repository.URL
}
}
func main() {
go mirror()
go build()
buildAllImages()
http.HandleFunc("/", handleWebhook)
port := flag.String("port", "8080", "listening port")
flag.Parse()
srv := http.Server{
Addr: ":" + *port,
ReadTimeout: 15 * time.Second,
WriteTimeout: 15 * time.Second,
}
expect(http.ErrServerClosed, srv.ListenAndServe())
}