-
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathproxyHandler.go
More file actions
227 lines (203 loc) · 5.96 KB
/
Copy pathproxyHandler.go
File metadata and controls
227 lines (203 loc) · 5.96 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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
package main
import (
"context"
"database/sql"
"errors"
"math/rand/v2"
"net/http"
"net/http/httputil"
"slices"
"strconv"
"strings"
"sync"
"time"
"github.com/PuerkitoBio/goquery"
"github.com/ether/etherpad-proxy/databases/interfaces"
"github.com/ether/etherpad-proxy/metrics"
"github.com/ether/etherpad-proxy/models"
"github.com/ether/etherpad-proxy/ui"
"go.uber.org/zap"
)
type StaticResource struct {
Backend string
FullPath string
}
// staticResources is a concurrency-safe map of scraped static resource names.
type staticResources struct {
mu sync.RWMutex
m map[string]StaticResource
}
func newStaticResources() *staticResources {
return &staticResources{m: make(map[string]StaticResource)}
}
func (s *staticResources) set(name string, r StaticResource) {
s.mu.Lock()
defer s.mu.Unlock()
s.m[name] = r
}
func (s *staticResources) get(name string) (StaticResource, bool) {
s.mu.RLock()
defer s.mu.RUnlock()
r, ok := s.m[name]
return r, ok
}
func (s *staticResources) anyPath() (string, bool) {
s.mu.RLock()
defer s.mu.RUnlock()
for _, r := range s.m {
return r.FullPath, true
}
return "", false
}
type ProxyHandler struct {
p map[string]httputil.ReverseProxy
logger *zap.SugaredLogger
db interfaces.IDB
state *models.BackendState
static *staticResources
}
type ResourceNotFound struct {
newPath string
}
func (m *ResourceNotFound) Error() string { return "Resource not found" }
type ClashInPadId struct {
padId string
}
func (m *ClashInPadId) Error() string { return "Pad clash" }
func ScrapeJSFiles(settings models.Settings, static *staticResources, logger *zap.SugaredLogger) {
go func() {
for {
for key, backend := range settings.Backends {
response, err := http.Get("http://" + backend.Host + ":" + strconv.Itoa(backend.Port) + "/p/test")
if err != nil {
logger.Warnf("Error while scraping JS files: %v", err)
continue
}
doc, err := goquery.NewDocumentFromReader(response.Body)
if err != nil {
logger.Warnf("Error parsing scraped document: %v", err)
_ = response.Body.Close()
continue
}
doc.Find("script").Each(func(_ int, s *goquery.Selection) {
src, ok := s.Attr("src")
if ok && strings.Contains(src, "padbootstrap") {
parts := strings.Split(src, "/")
name := parts[len(parts)-1]
static.set(name, StaticResource{
Backend: key,
FullPath: "http://" + backend.Host + ":" + strconv.Itoa(backend.Port) + "/" + name,
})
}
})
if err = response.Body.Close(); err != nil {
logger.Warnf("Error while closing response body: %v", err)
}
}
time.Sleep(10 * time.Minute)
}
}()
}
// chooseBackend returns the backend key a request should be routed to, or an
// error (ResourceNotFound carries a redirect path; ClashInPadId signals an
// unresolved pad clash).
func (ph *ProxyHandler) chooseBackend(padId *string, r *http.Request) (string, error) {
available := ph.state.SnapshotAvailable()
up := ph.state.SnapshotUp()
if padId == nil {
if len(available) == 0 {
return "", errors.New("no backends available")
}
if strings.Contains(r.URL.Path, "padbootstrap") {
parts := strings.Split(r.URL.Path, "/")
name := parts[len(parts)-1]
if res, ok := ph.static.get(name); ok && slices.Contains(up, res.Backend) {
return res.Backend, nil
}
if path, ok := ph.static.anyPath(); ok {
return "", &ResourceNotFound{newPath: path}
}
return "", &ResourceNotFound{}
}
return available[rand.IntN(len(available))], nil
}
if len(available) == 0 {
return "", errors.New("no backends available")
}
stored, err := ph.db.Get(*padId)
if errors.Is(err, sql.ErrNoRows) {
clashes, cerr := ph.db.GetClashByPadID(*padId)
if cerr != nil && !errors.Is(cerr, sql.ErrNoRows) {
metrics.DBErrorsTotal.Inc()
return "", cerr
}
if len(clashes) == 0 {
candidate := available[rand.IntN(len(available))]
backend, aerr := ph.db.Assign(*padId, candidate)
if aerr != nil {
metrics.DBErrorsTotal.Inc()
return "", aerr
}
metrics.PadAssignmentsTotal.Inc()
return backend, nil
}
ph.logger.Warnf("Pad %s is in a clash with backends: %v", *padId, clashes)
return "", &ClashInPadId{padId: *padId}
} else if err != nil {
metrics.DBErrorsTotal.Inc()
return "", err
}
if slices.Contains(up, stored.Backend) {
return stored.Backend, nil
}
if len(up) == 0 {
return "", errors.New("no backends available")
}
newBackend := up[rand.IntN(len(up))]
if serr := ph.db.Set(*padId, models.DBBackend{Backend: newBackend}); serr != nil {
metrics.DBErrorsTotal.Inc()
ph.logger.Info("Error while setting padId in DB: ", serr)
}
return newBackend, nil
}
func (ph *ProxyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
ph.logger.Debugf("%s %s", r.Method, r.URL)
var padId *string
if strings.Contains(r.URL.Path, "/p/") {
afterP := strings.Split(r.URL.Path, "/p/")[1]
beforeQuery := strings.Split(afterP, "?")[0]
first := strings.Split(beforeQuery, "/")[0]
padId = &first
ph.logger.Infof("Initial request to /p/%s", first)
}
if padId == nil {
if q := r.URL.Query().Get("padId"); q != "" {
padId = &q
}
}
backendKey, err := ph.chooseBackend(padId, r)
if err != nil {
var resourceNotFound *ResourceNotFound
if errors.As(err, &resourceNotFound) && resourceNotFound.newPath != "" {
metrics.RequestsTotal.WithLabelValues("resource_redirect").Inc()
http.Redirect(w, r, resourceNotFound.newPath, http.StatusTemporaryRedirect)
return
}
var clash *ClashInPadId
if errors.As(err, &clash) {
metrics.RequestsTotal.WithLabelValues("clash").Inc()
} else {
metrics.RequestsTotal.WithLabelValues("no_backend").Inc()
}
ph.logger.Error("Error while creating route: ", err)
w.WriteHeader(http.StatusInternalServerError)
template := ui.Error()
if rerr := template.Render(context.Background(), w); rerr != nil {
ph.logger.Error("Error while rendering template: ", rerr)
}
return
}
proxy := ph.p[backendKey]
metrics.RequestsTotal.WithLabelValues("proxied").Inc()
proxy.ServeHTTP(w, r)
}