forked from openfaas/of-watchdog
-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
229 lines (180 loc) · 5.5 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
package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"path/filepath"
"strings"
"github.com/openfaas-incubator/of-watchdog/config"
"github.com/openfaas-incubator/of-watchdog/executor"
)
func main() {
watchdogConfig, configErr := config.New(os.Environ())
if configErr != nil {
fmt.Fprintf(os.Stderr, configErr.Error())
os.Exit(-1)
}
if len(watchdogConfig.FunctionProcess) == 0 {
fmt.Fprintf(os.Stderr, "Provide a \"function_process\" or \"fprocess\" environmental variable for your function.\n")
os.Exit(-1)
}
s := &http.Server{
Addr: fmt.Sprintf(":%d", watchdogConfig.TCPPort),
ReadTimeout: watchdogConfig.HTTPReadTimeout,
WriteTimeout: watchdogConfig.HTTPWriteTimeout,
MaxHeaderBytes: 1 << 20, // Max header of 1MB
}
requestHandler := buildRequestHandler(watchdogConfig)
log.Printf("OperationalMode: %s\n", config.WatchdogMode(watchdogConfig.OperationalMode))
if err := lock(); err != nil {
log.Panic(err.Error())
}
http.HandleFunc("/", requestHandler)
log.Fatal(s.ListenAndServe())
}
func buildRequestHandler(watchdogConfig config.WatchdogConfig) http.HandlerFunc {
var requestHandler http.HandlerFunc
switch watchdogConfig.OperationalMode {
case config.ModeStreaming:
requestHandler = makeForkRequestHandler(watchdogConfig)
break
case config.ModeSerializing:
requestHandler = makeSerializingForkRequestHandler(watchdogConfig)
break
case config.ModeAfterBurn:
requestHandler = makeAfterBurnRequestHandler(watchdogConfig)
break
case config.ModeHTTP:
requestHandler = makeHTTPRequestHandler(watchdogConfig)
break
default:
log.Panicf("unknown watchdog mode: %d", watchdogConfig.OperationalMode)
break
}
return requestHandler
}
func lock() error {
lockFile := filepath.Join(os.TempDir(), ".lock")
log.Printf("Writing lock file at: %s", lockFile)
return ioutil.WriteFile(lockFile, nil, 0600)
}
func makeAfterBurnRequestHandler(watchdogConfig config.WatchdogConfig) func(http.ResponseWriter, *http.Request) {
commandName, arguments := watchdogConfig.Process()
functionInvoker := executor.AfterBurnFunctionRunner{
Process: commandName,
ProcessArgs: arguments,
}
fmt.Printf("Forking - %s %s\n", commandName, arguments)
functionInvoker.Start()
return func(w http.ResponseWriter, r *http.Request) {
req := executor.FunctionRequest{
Process: commandName,
ProcessArgs: arguments,
InputReader: r.Body,
OutputWriter: w,
}
functionInvoker.Mutex.Lock()
err := functionInvoker.Run(req, r.ContentLength, r, w)
if err != nil {
w.WriteHeader(500)
w.Write([]byte(err.Error()))
}
functionInvoker.Mutex.Unlock()
}
}
func makeSerializingForkRequestHandler(watchdogConfig config.WatchdogConfig) func(http.ResponseWriter, *http.Request) {
functionInvoker := executor.SerializingForkFunctionRunner{
ExecTimeout: watchdogConfig.ExecTimeout,
}
return func(w http.ResponseWriter, r *http.Request) {
var environment []string
if watchdogConfig.InjectCGIHeaders {
environment = getEnvironment(r)
}
commandName, arguments := watchdogConfig.Process()
req := executor.FunctionRequest{
Process: commandName,
ProcessArgs: arguments,
InputReader: r.Body,
ContentLength: &r.ContentLength,
OutputWriter: w,
Environment: environment,
}
w.Header().Set("Content-Type", watchdogConfig.ContentType)
err := functionInvoker.Run(req, w)
if err != nil {
log.Println(err)
}
}
}
func makeForkRequestHandler(watchdogConfig config.WatchdogConfig) func(http.ResponseWriter, *http.Request) {
functionInvoker := executor.ForkFunctionRunner{
ExecTimeout: watchdogConfig.ExecTimeout,
}
return func(w http.ResponseWriter, r *http.Request) {
var environment []string
if watchdogConfig.InjectCGIHeaders {
environment = getEnvironment(r)
}
commandName, arguments := watchdogConfig.Process()
req := executor.FunctionRequest{
Process: commandName,
ProcessArgs: arguments,
InputReader: r.Body,
OutputWriter: w,
Environment: environment,
}
w.Header().Set("Content-Type", watchdogConfig.ContentType)
err := functionInvoker.Run(req)
if err != nil {
log.Println(err.Error())
// Probably cannot write to client if we already have written a header
// w.WriteHeader(500)
// w.Write([]byte(err.Error()))
}
}
}
func getEnvironment(r *http.Request) []string {
var envs []string
envs = os.Environ()
for k, v := range r.Header {
kv := fmt.Sprintf("Http_%s=%s", strings.Replace(k, "-", "_", -1), v[0])
envs = append(envs, kv)
}
envs = append(envs, fmt.Sprintf("Http_Method=%s", r.Method))
if len(r.URL.RawQuery) > 0 {
envs = append(envs, fmt.Sprintf("Http_Query=%s", r.URL.RawQuery))
}
if len(r.URL.Path) > 0 {
envs = append(envs, fmt.Sprintf("Http_Path=%s", r.URL.Path))
}
return envs
}
func makeHTTPRequestHandler(watchdogConfig config.WatchdogConfig) func(http.ResponseWriter, *http.Request) {
commandName, arguments := watchdogConfig.Process()
functionInvoker := executor.HTTPFunctionRunner{
ExecTimeout: watchdogConfig.ExecTimeout,
Process: commandName,
ProcessArgs: arguments,
}
fmt.Printf("Forking - %s %s\n", commandName, arguments)
functionInvoker.Start()
return func(w http.ResponseWriter, r *http.Request) {
req := executor.FunctionRequest{
Process: commandName,
ProcessArgs: arguments,
InputReader: r.Body,
OutputWriter: w,
}
if r.Body != nil {
defer r.Body.Close()
}
err := functionInvoker.Run(req, r.ContentLength, r, w)
if err != nil {
w.WriteHeader(500)
w.Write([]byte(err.Error()))
}
}
}