-
Notifications
You must be signed in to change notification settings - Fork 681
/
invoker.go
247 lines (216 loc) · 6.29 KB
/
invoker.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
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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
package invoker
import (
"context"
"fmt"
"net"
"net/http"
"strconv"
"strings"
"sync"
"github.com/datawire/ambassador/pkg/supervisor"
"github.com/datawire/ambassador/pkg/tpu"
"github.com/datawire/dlib/dhttp"
)
type invoker struct {
Snapshots chan string
mux sync.Mutex
invokedSnapshots map[int]string
id int
notify []string
apiServerAuthority string
// This stores the latest snapshot, but we don't assign an id
// unless/until we invoke... some of these will be discarded
// by the rate limiting/coalescing logic
latestSnapshot string
process *supervisor.Process
}
func NewInvoker(addr string, notify []string) *invoker {
return &invoker{
Snapshots: make(chan string),
invokedSnapshots: make(map[int]string),
notify: notify,
apiServerAuthority: addr,
}
}
func (a *invoker) Work(p *supervisor.Process) error {
// The general strategy here is:
//
// 1. Be continuously reading all available snapshots from
// a.Snapshots and store them in the potentialSnapshot
// variable. This means at any given point (modulo caveats
// below), the potentialSnapshot variable will have the
// latest and greatest snapshot available.
//
// 2. At the same time, whenever there is capacity to write
// down the invoking channel, we send potentialSnapshot to
// be invoked.
//
// The anonymous goroutine below will be constantly reading
// from the invoking channel and performing a blocking
// a.invoke(). This means that we can only *write* to the
// invoking channel when we are not currently processing a
// snapshot, but when that happens, we will still read from
// a.Snapshots and update potentialSnapshot.
//
// There are two caveats to the above:
//
// 1. At startup, we don't yet have a snapshot to write, but
// we're not invoking anything, so we will try to write
// something down the invoking channel. To cope with this,
// the invoking goroutine will ignore snapshots that
// consist of the empty string.
//
// 2. If we process a snapshot quickly, or if there aren't new
// snapshots available, then we end up busy looping and
// sending the same potentialSnapshot value down the
// invoking channel multiple times. To cope with this,
// whenever we have successfully written to the invoking
// channel, we do a *blocking* read of the next snapshot
// from a.Snapshots.
a.process = p
p.Ready()
invoking := make(chan string)
go func() {
for snapshot := range invoking {
// ignore empty snapshots to deal with the
// corner case where we haven't yet received a
// snapshot
if snapshot != "" {
a.latestSnapshot = snapshot
a.invoke()
}
}
}()
potentialSnapshot := ""
for {
select {
case potentialSnapshot = <-a.Snapshots:
// if a new snapshot is available to be read,
// and we can't write to the invoking channel,
// then we will overwrite potentialSnapshot
// with a newer snapshot
case invoking <- potentialSnapshot:
// if we aren't currently blocked in
// a.invoke() then the above goroutine will be
// reading from the invoking channel and we
// will send the current potentialSnapshot
// value over the invoking channel to be
// processed
select {
case potentialSnapshot = <-a.Snapshots:
// whenever we write a
// potentialSnapshot to invoking, we
// also need to do a synchronous read
// from a.Snapshots to make sure we
// won't ever invoke the same snapshot
// twice
case <-p.Shutdown():
p.Logf("shutdown initiated")
return nil
}
case <-p.Shutdown():
p.Logf("shutdown initiated")
return nil
}
}
}
func (a *invoker) storeSnapshot(snapshot string) int {
a.mux.Lock()
defer a.mux.Unlock()
a.id += 1
a.invokedSnapshots[a.id] = snapshot
a.gcSnapshots()
return a.id
}
func (a *invoker) gcSnapshots() {
for k := range a.invokedSnapshots {
if k <= a.id-10 {
delete(a.invokedSnapshots, k)
a.process.Debugf("deleting snapshot %d", k)
}
}
}
func (a *invoker) getSnapshot(id int) string {
a.mux.Lock()
defer a.mux.Unlock()
return a.invokedSnapshots[id]
}
func (a *invoker) getKeys() (result []int) {
for i := range a.invokedSnapshots {
result = append(result, i)
}
return
}
func (a *invoker) invoke() {
id := a.storeSnapshot(a.latestSnapshot)
for _, n := range a.notify {
k := tpu.NewKeeper("notify", fmt.Sprintf("%s http://%s/snapshots/%d", n, a.apiServerAuthority, id))
k.Limit = 1
k.Start()
k.Wait()
}
}
type apiServer struct {
listenNetwork string
listenAddress string
invoker *invoker
}
type APIServer interface {
Work(*supervisor.Process) error
}
func NewAPIServer(net, addr string, invoker *invoker) APIServer {
return &apiServer{
listenNetwork: net,
listenAddress: addr,
invoker: invoker,
}
}
func (s *apiServer) Work(p *supervisor.Process) error {
mux := http.NewServeMux()
mux.HandleFunc("/snapshots/", func(w http.ResponseWriter, r *http.Request) {
relpath := strings.TrimPrefix(r.URL.Path, "/snapshots/")
if relpath == "" {
w.Header().Set("content-type", "text/html")
if _, err := w.Write([]byte(s.index())); err != nil {
p.Logf("write index error: %v", err)
}
} else {
id, err := strconv.Atoi(relpath)
if err != nil {
http.Error(w, "ID is not an integer", http.StatusBadRequest)
return
}
snapshot := s.invoker.getSnapshot(id)
if snapshot == "" {
w.WriteHeader(http.StatusNotFound)
return
}
w.Header().Set("content-type", "application/json")
if _, err := w.Write([]byte(snapshot)); err != nil {
p.Logf("write snapshot error: %v", err)
}
}
})
listener, err := net.Listen(s.listenNetwork, s.listenAddress)
if err != nil {
return err
}
p.Ready()
p.Logf("snapshot server listening on: %s:%s", s.listenNetwork, s.listenAddress)
srv := &dhttp.ServerConfig{
Handler: mux,
}
ctx, cancel := context.WithCancel(p.Context())
return p.DoClean(
func() error { return srv.Serve(ctx, listener) },
func() error { cancel(); return nil })
}
func (s *apiServer) index() string {
var result strings.Builder
result.WriteString("<html><body><ul>\n")
for _, v := range s.invoker.getKeys() {
result.WriteString(fmt.Sprintf(" <li><a href=\"%d\">%d</a></li>\n", v, v))
}
result.WriteString("</ul></body></html>\n")
return result.String()
}