forked from openfaas/nats-queue-worker
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
298 lines (234 loc) · 6.92 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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"net"
"os"
"os/signal"
"strconv"
"strings"
"time"
"net/http"
"github.com/nats-io/go-nats-streaming"
"github.com/openfaas/faas/gateway/queue"
)
// AsyncReport is the report from a function executed on a queue worker.
type AsyncReport struct {
FunctionName string `json:"name"`
StatusCode int `json:"statusCode"`
TimeTaken float64 `json:"timeTaken"`
}
func printMsg(m *stan.Msg, i int) {
log.Printf("[#%d] Received on [%s]: '%s'\n", i, m.Subject, m)
}
func makeClient() http.Client {
proxyClient := http.Client{
Transport: &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 0,
}).DialContext,
MaxIdleConns: 1,
DisableKeepAlives: true,
IdleConnTimeout: 120 * time.Millisecond,
ExpectContinueTimeout: 1500 * time.Millisecond,
},
}
return proxyClient
}
func main() {
readConfig := ReadConfig{}
config := readConfig.Read()
log.SetFlags(0)
clusterID := "faas-cluster"
val, _ := os.Hostname()
clientID := "faas-worker-" + val
var durable string
var qgroup string
var unsubscribe bool
client := makeClient()
sc, err := stan.Connect(clusterID, clientID, stan.NatsURL("nats://"+config.NatsAddress+":4222"))
if err != nil {
log.Fatalf("Can't connect: %v\n", err)
}
startOpt := stan.StartWithLastReceived()
i := 0
mcb := func(msg *stan.Msg) {
i++
printMsg(msg, i)
started := time.Now()
req := queue.Request{}
unmarshalErr := json.Unmarshal(msg.Data, &req)
if unmarshalErr != nil {
log.Printf("Unmarshal error: %s with data %s", unmarshalErr, msg.Data)
return
}
xCallID := req.Header.Get("X-Call-Id")
fmt.Printf("Request for %s.\n", req.Function)
if config.DebugPrintBody {
fmt.Println(string(req.Body))
}
queryString := ""
if len(req.QueryString) > 0 {
queryString = fmt.Sprintf("?%s", strings.TrimLeft(req.QueryString, "?"))
}
functionURL := fmt.Sprintf("http://%s%s:8080/%s", req.Function, config.FunctionSuffix, queryString)
request, err := http.NewRequest(http.MethodPost, functionURL, bytes.NewReader(req.Body))
defer request.Body.Close()
copyHeaders(request.Header, &req.Header)
res, err := client.Do(request)
var status int
var functionResult []byte
if err != nil {
status = http.StatusServiceUnavailable
log.Println(err)
timeTaken := time.Since(started).Seconds()
if req.CallbackURL != nil {
log.Printf("Callback to: %s\n", req.CallbackURL.String())
resultStatusCode, resultErr := postResult(&client, res, functionResult, req.CallbackURL.String(), xCallID)
if resultErr != nil {
log.Println(resultErr)
} else {
log.Printf("Posted result: %d", resultStatusCode)
}
}
statusCode, reportErr := postReport(&client, req.Function, status, timeTaken, config.GatewayAddress)
if reportErr != nil {
log.Println(reportErr)
} else {
log.Printf("Posting report - %d\n", statusCode)
}
return
}
if res.Body != nil {
defer res.Body.Close()
resData, err := ioutil.ReadAll(res.Body)
functionResult = resData
if err != nil {
log.Println(err)
}
if config.WriteDebug {
fmt.Println(string(functionResult))
} else {
fmt.Printf("Wrote %d Bytes\n", len(string(functionResult)))
}
}
timeTaken := time.Since(started).Seconds()
fmt.Println(res.Status)
if req.CallbackURL != nil {
log.Printf("Callback to: %s\n", req.CallbackURL.String())
resultStatusCode, resultErr := postResult(&client, res, functionResult, req.CallbackURL.String(), xCallID)
if resultErr != nil {
log.Println(resultErr)
} else {
log.Printf("Posted result: %d", resultStatusCode)
}
}
statusCode, reportErr := postReport(&client, req.Function, res.StatusCode, timeTaken, config.GatewayAddress)
if reportErr != nil {
log.Println(reportErr)
} else {
log.Printf("Posting report - %d\n", statusCode)
}
}
subj := "faas-request"
qgroup = "faas"
ackWait := time.Second * 30
maxInflight := 1
if value, exists := os.LookupEnv("max_inflight"); exists {
val, err := strconv.Atoi(value)
if err != nil {
log.Println("max_inflight error:", err)
} else {
maxInflight = val
}
}
if val, exists := os.LookupEnv("ack_wait"); exists {
ackWaitVal, durationErr := time.ParseDuration(val)
if durationErr != nil {
log.Println("ack_wait error:", durationErr)
} else {
ackWait = ackWaitVal
}
}
log.Println("Wait for ", ackWait)
sub, err := sc.QueueSubscribe(subj, qgroup, mcb, startOpt, stan.DurableName(durable), stan.MaxInflight(maxInflight), stan.AckWait(ackWait))
if err != nil {
log.Panicln(err)
}
log.Printf("Listening on [%s], clientID=[%s], qgroup=[%s] durable=[%s]\n", subj, clientID, qgroup, durable)
// Wait for a SIGINT (perhaps triggered by user with CTRL-C)
// Run cleanup when signal is received
signalChan := make(chan os.Signal, 1)
cleanupDone := make(chan bool)
signal.Notify(signalChan, os.Interrupt)
go func() {
for range signalChan {
fmt.Printf("\nReceived an interrupt, unsubscribing and closing connection...\n\n")
// Do not unsubscribe a durable on exit, except if asked to.
if durable == "" || unsubscribe {
sub.Unsubscribe()
}
sc.Close()
cleanupDone <- true
}
}()
<-cleanupDone
}
func postResult(client *http.Client, functionRes *http.Response, result []byte, callbackURL string, xCallID string) (int, error) {
var reader io.Reader
if result != nil {
reader = bytes.NewReader(result)
}
request, err := http.NewRequest(http.MethodPost, callbackURL, reader)
copyHeaders(request.Header, &functionRes.Header)
if len(xCallID) > 0 {
request.Header.Set("X-Call-Id", xCallID)
}
res, err := client.Do(request)
if err != nil {
return http.StatusBadGateway, fmt.Errorf("error posting result to URL %s %s", callbackURL, err.Error())
}
if request.Body != nil {
defer request.Body.Close()
}
if res.Body != nil {
defer res.Body.Close()
}
return res.StatusCode, nil
}
func copyHeaders(destination http.Header, source *http.Header) {
for k, v := range *source {
vClone := make([]string, len(v))
copy(vClone, v)
(destination)[k] = vClone
}
}
func postReport(client *http.Client, function string, statusCode int, timeTaken float64, gatewayAddress string) (int, error) {
req := AsyncReport{
FunctionName: function,
StatusCode: statusCode,
TimeTaken: timeTaken,
}
targetPostback := "http://" + gatewayAddress + ":8080/system/async-report"
reqBytes, _ := json.Marshal(req)
request, err := http.NewRequest(http.MethodPost, targetPostback, bytes.NewReader(reqBytes))
err = AddBasicAuth(request)
if err != nil {
log.Printf("Error with AddBasicAuth : %s", err.Error())
}
defer request.Body.Close()
res, err := client.Do(request)
if err != nil {
return http.StatusGatewayTimeout, fmt.Errorf("cannot post report to %s: %s", targetPostback, err)
}
if res.Body != nil {
defer res.Body.Close()
}
return res.StatusCode, nil
}