-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
211 lines (178 loc) · 4.94 KB
/
Copy pathmain.go
File metadata and controls
211 lines (178 loc) · 4.94 KB
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
package main
import (
"bytes"
"context"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"log"
"net/http"
"net/http/httputil"
"net/url"
"os"
"os/exec"
"os/signal"
"regexp"
"slices"
"strings"
"sync"
"syscall"
"time"
)
type Config struct {
Upstream string `json:"upstream"`
Addr string `json:"addr"`
ExcludePath []string `json:"exclude_path"`
IncludeMethod []string `json:"include_method"`
Script Script `json:"script"`
VerboseNotification bool `json:"verbose_notification"`
}
type Script struct {
Backup string `json:"backup"`
Notify string `json:"notify"`
}
func loadConfig(configFile string) (*Config, error) {
b, err := os.ReadFile(configFile)
if err != nil {
return nil, fmt.Errorf("failed to read config file: %w", err)
}
var c Config
err = json.Unmarshal(b, &c)
if err != nil {
return nil, fmt.Errorf("failed to unmarshal config: %w", err)
}
// Verify patterns
for _, pattern := range c.ExcludePath {
if _, err := regexp.Compile(pattern); err != nil {
return nil, fmt.Errorf("invalid exclude_path pattern %s: %w", pattern, err)
}
}
return &c, nil
}
func main() {
configFile := flag.String("config", "trigger.json", "")
flag.Parse()
config, err := loadConfig(*configFile)
if err != nil {
log.Fatalf("failed to load config: %v", err)
}
log.Printf("loaded config: %+v\n", config)
var wgConsumer, wgProducer sync.WaitGroup
var taskCh = make(chan string)
var quitCh = make(chan struct{})
upstream, err := url.Parse(config.Upstream)
if err != nil || upstream.String() == "" {
log.Fatalf("invalid upstream URL: %v", err)
}
proxy := httputil.NewSingleHostReverseProxy(upstream)
proxy.ModifyResponse = func(response *http.Response) (_ error) {
// nil r.Request? i dont care
method, path, status := response.Request.Method, response.Request.URL.Path, response.StatusCode
// exclude failed requests
if status < http.StatusOK || status >= http.StatusMultipleChoices {
return
}
if !slices.Contains(config.IncludeMethod, method) || isExcludedPath(config.ExcludePath, path) {
return
}
task := formatRequest(method, path, status)
wgProducer.Add(1)
go func() {
defer wgProducer.Done()
log.Println("queueing task:", task)
defer log.Println("queued task", task)
taskCh <- task
}()
return
}
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { proxy.ServeHTTP(w, r) })
server := &http.Server{Addr: config.Addr, Handler: nil}
go func() {
log.Println("listening on", config.Addr)
if err := server.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
log.Printf("server error: %v\n", err)
}
close(quitCh)
}()
wgConsumer.Add(1)
go func() {
defer wgConsumer.Done()
for task := range taskCh {
handleTask(task, config)
}
}()
notifier := make(chan os.Signal, 1)
signal.Notify(notifier, os.Interrupt, syscall.SIGTERM)
select {
case sig := <-notifier:
log.Println("received sig", sig.String())
break
case <-quitCh:
break
}
// by default, docker compose will forcefully kill the container after 10 seconds,
// if there is no task in the queue, this notification won't be successfully executed,
// a better way is `docker compose stop/down -t 300`
go execute(config.Script.Notify, "shutting down")
shutdownServer(server)
// make sure all the tasks been handled
wgProducer.Wait()
close(taskCh)
wgConsumer.Wait()
}
func isExcludedPath(patterns []string, path string) bool {
for _, pattern := range patterns {
if regexp.MustCompile(pattern).MatchString(path) {
return true
}
}
return false
}
func formatRequest(method, path string, status int) string {
safePath := strings.Map(func(b rune) rune {
if b == '/' || ('0' <= b && b <= '9') || ('a' <= b && b <= 'z') || ('A' <= b && b <= 'Z') {
return b
}
return '-'
}, path)
return fmt.Sprintf("(%s)(%d)(%s)", method, status, safePath)
}
func handleTask(task string, config *Config) {
log.Println("handling task", task)
defer log.Println("handled task", task)
output, err := execute(config.Script.Backup)
if err != nil {
msg := fmt.Sprintf("%s failed: %s", task, err.Error())
log.Println(msg)
if config.VerboseNotification {
msg = output + "\n" + msg
}
execute(config.Script.Notify, msg)
return
}
msg := fmt.Sprintf("%s succeed", task)
log.Println(msg)
execute(config.Script.Notify, msg)
}
func execute(name string, arg ...string) (string, error) {
cmd := exec.Command(name, arg...)
var output bytes.Buffer
cmd.Stdout = io.MultiWriter(os.Stdout, &output)
cmd.Stderr = io.MultiWriter(os.Stderr, &output)
err := cmd.Run()
if err != nil {
return "", fmt.Errorf("command execution failed: %w", err)
}
return output.String(), nil
}
func shutdownServer(server *http.Server) {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
if err := server.Shutdown(ctx); err != nil {
log.Println("server shutdown error:", err)
} else {
log.Println("server gracefully stopped")
}
}