-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
275 lines (243 loc) · 6.84 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
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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
package main
import (
"bufio"
"bytes"
"fmt"
"log/slog"
"math/rand"
"net"
"net/http"
"os"
"os/exec"
"os/signal"
"syscall"
"time"
stomp "github.com/go-stomp/stomp/v3"
scyllaridae "github.com/lehigh-university-libraries/scyllaridae/internal/config"
"github.com/lehigh-university-libraries/scyllaridae/pkg/api"
)
var (
config *scyllaridae.ServerConfig
)
func init() {
var err error
config, err = scyllaridae.ReadConfig("scyllaridae.yml")
if err != nil {
slog.Error("Could not read YML", "err", err)
os.Exit(1)
}
}
func main() {
// either subscribe to activemq directly
if config.QueueName != "" {
subscribed := make(chan bool)
stopChan := make(chan os.Signal, 1)
signal.Notify(stopChan, os.Interrupt, syscall.SIGTERM)
go RecvStompMessages(config.QueueName, subscribed)
select {
case <-subscribed:
slog.Info("Subscription to queue successful")
case <-stopChan:
slog.Info("Received stop signal, exiting")
return
}
<-stopChan
slog.Info("Shutting down message listener")
} else {
// or make this an available API ala crayfish
http.HandleFunc("/healthcheck", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
fmt.Fprintln(w, "OK")
})
http.HandleFunc("/", MessageHandler)
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
slog.Info("Server listening", "port", port)
if err := http.ListenAndServe(":"+port, nil); err != nil {
panic(err)
}
}
}
func MessageHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
if r.Header.Get("Apix-Ldp-Resource") == "" {
http.Error(w, "Bad request", http.StatusBadRequest)
return
}
defer r.Body.Close()
// Read the Alpaca message payload
auth := ""
if config.ForwardAuth {
auth = r.Header.Get("Authorization")
}
message, err := api.DecodeAlpacaMessage(r, auth)
if err != nil {
slog.Error("Error decoding alpaca message", "err", err)
http.Error(w, "Internal error", http.StatusInternalServerError)
return
}
// Stream the file contents from the source URL
req, err := http.NewRequest("GET", message.Attachment.Content.SourceURI, nil)
if err != nil {
slog.Error("Error creating request to source", "source", message.Attachment.Content.SourceURI, "err", err)
http.Error(w, "Bad request", http.StatusBadRequest)
return
}
if config.ForwardAuth {
req.Header.Set("Authorization", auth)
}
sourceResp, err := http.DefaultClient.Do(req)
if err != nil {
slog.Error("Error fetching source file contents", "err", err)
http.Error(w, "Internal error", http.StatusInternalServerError)
return
}
defer sourceResp.Body.Close()
if sourceResp.StatusCode != http.StatusOK {
slog.Error("SourceURI sent a bad status code", "code", sourceResp.StatusCode, "uri", message.Attachment.Content.SourceURI)
http.Error(w, "Bad request", http.StatusBadRequest)
return
}
cmd, err := scyllaridae.BuildExecCommand(message, config)
if err != nil {
slog.Error("Error building command", "err", err)
http.Error(w, "Bad request", http.StatusBadRequest)
return
}
cmd.Stdin = sourceResp.Body
// Create a buffer to stream the output of the command
var stdErr bytes.Buffer
cmd.Stderr = &stdErr
// send stdout to the ResponseWriter stream
cmd.Stdout = w
slog.Info("Running command", "cmd", cmd.String())
if err := cmd.Run(); err != nil {
slog.Error("Error running command", "cmd", cmd.String(), "err", stdErr.String())
http.Error(w, "Internal error", http.StatusInternalServerError)
return
}
}
func RecvStompMessages(queueName string, subscribed chan bool) {
defer close(subscribed)
attempt := 0
maxAttempts := 30
for attempt = 0; attempt < maxAttempts; attempt += 1 {
if err := connectAndSubscribe(queueName, subscribed); err != nil {
slog.Error("resubscribing", "error", err)
if err := retryWithExponentialBackoff(attempt, maxAttempts); err != nil {
slog.Error("Failed subscribing after too many failed attempts", "attempts", attempt)
return
}
}
}
}
func connectAndSubscribe(queueName string, subscribed chan bool) error {
addr := os.Getenv("STOMP_SERVER_ADDR")
if addr == "" {
addr = "activemq:61613"
}
c, err := net.Dial("tcp", addr)
if err != nil {
slog.Error("cannot connect to port", "err", err.Error())
return err
}
tcpConn := c.(*net.TCPConn)
err = tcpConn.SetKeepAlive(true)
if err != nil {
slog.Error("cannot set keepalive", "err", err.Error())
return err
}
err = tcpConn.SetKeepAlivePeriod(10 * time.Second)
if err != nil {
slog.Error("cannot set keepalive period", "err", err.Error())
return err
}
conn, err := stomp.Connect(tcpConn, stomp.ConnOpt.HeartBeat(10*time.Second, 0*time.Second))
if err != nil {
slog.Error("cannot connect to stomp server", "err", err.Error())
return err
}
defer func() {
err := conn.Disconnect()
if err != nil {
slog.Error("problem disconnecting from stomp server", "err", err)
}
}()
sub, err := conn.Subscribe(queueName, stomp.AckAuto)
if err != nil {
slog.Error("cannot subscribe to queue", "queue", queueName, "err", err.Error())
return err
}
defer func() {
if !sub.Active() {
return
}
err := sub.Unsubscribe()
if err != nil {
slog.Error("problem unsubscribing", "err", err)
}
}()
slog.Info("Server subscribed to", "queue", queueName)
subscribed <- true
for msg := range sub.C {
if msg == nil || len(msg.Body) == 0 {
// if the subscription isn't active return so we can try reconnecting
if !sub.Active() {
return fmt.Errorf("no longer subscribed to %s", queueName)
}
// else just try reading again. There's probably just no messages in the queue
continue
}
handleStompMessage(msg)
}
return nil
}
func handleStompMessage(msg *stomp.Message) {
message, err := api.DecodeEventMessage(msg.Body)
if err != nil {
slog.Error("could not read the event message", "err", err, "msg", string(msg.Body))
return
}
message.Authorization = msg.Header.Get("Authorization")
cmd, err := scyllaridae.BuildExecCommand(message, config)
if err != nil {
slog.Error("Error building command", "err", err)
return
}
runCommand(cmd)
}
func runCommand(cmd *exec.Cmd) {
stdout, err := cmd.StdoutPipe()
if err != nil {
slog.Error("error creating stdout pipe", "err", err)
return
}
scanner := bufio.NewScanner(stdout)
go func() {
for scanner.Scan() {
slog.Info("cmd output", "stdout", scanner.Text())
}
}()
var stdErr bytes.Buffer
cmd.Stderr = &stdErr
if err := cmd.Start(); err != nil {
slog.Error("Error starting command", "cmd", cmd.String(), "err", stdErr.String())
return
}
if err := cmd.Wait(); err != nil {
slog.Error("command finished with error", "err", stdErr.String())
}
}
func retryWithExponentialBackoff(attempt int, maxAttempts int) error {
if attempt >= maxAttempts {
return fmt.Errorf("maximum retry attempts reached")
}
wait := time.Duration(rand.Intn(1<<attempt)) * time.Second
time.Sleep(wait)
return nil
}