-
Notifications
You must be signed in to change notification settings - Fork 118
/
Copy pathhttp_runner.go
205 lines (162 loc) · 4.58 KB
/
http_runner.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
package executor
import (
"context"
"fmt"
"io"
"io/ioutil"
"log"
"net"
"net/http"
"net/url"
"os"
"os/exec"
"os/signal"
"sync"
"syscall"
"time"
)
// HTTPFunctionRunner creates and maintains one process responsible for handling all calls
type HTTPFunctionRunner struct {
ExecTimeout time.Duration // ExecTimeout the maxmium duration or an upstream function call
ReadTimeout time.Duration
WriteTimeout time.Duration
Process string
ProcessArgs []string
Command *exec.Cmd
StdinPipe io.WriteCloser
StdoutPipe io.ReadCloser
Stderr io.Writer
Mutex sync.Mutex
Client *http.Client
UpstreamURL *url.URL
}
// Start forks the process used for processing incoming requests
func (f *HTTPFunctionRunner) Start() error {
cmd := exec.Command(f.Process, f.ProcessArgs...)
var stdinErr error
var stdoutErr error
f.Command = cmd
f.StdinPipe, stdinErr = cmd.StdinPipe()
if stdinErr != nil {
return stdinErr
}
f.StdoutPipe, stdoutErr = cmd.StdoutPipe()
if stdoutErr != nil {
return stdoutErr
}
errPipe, _ := cmd.StderrPipe()
// Prints stderr to console and is picked up by container logging driver.
go func() {
log.Println("Started logging stderr from function.")
for {
errBuff := make([]byte, 256)
_, err := errPipe.Read(errBuff)
if err != nil {
log.Fatalf("Error reading stderr: %s", err)
} else {
log.Printf("stderr: %s", errBuff)
}
}
}()
go func() {
log.Println("Started logging stdout from function.")
for {
errBuff := make([]byte, 256)
_, err := f.StdoutPipe.Read(errBuff)
if err != nil {
log.Fatalf("Error reading stdout: %s", err)
} else {
log.Printf("stdout: %s", errBuff)
}
}
}()
f.Client = makeProxyClient(f.ExecTimeout)
go func() {
sig := make(chan os.Signal, 1)
signal.Notify(sig, syscall.SIGTERM)
<-sig
cmd.Process.Signal(syscall.SIGTERM)
}()
return cmd.Start()
}
// Run a function with a long-running process with a HTTP protocol for communication
func (f *HTTPFunctionRunner) Run(req FunctionRequest, contentLength int64, r *http.Request, w http.ResponseWriter) error {
startedTime := time.Now()
upstreamURL := f.UpstreamURL.String()
if len(r.RequestURI) > 0 {
upstreamURL += r.RequestURI
}
request, _ := http.NewRequest(r.Method, upstreamURL, r.Body)
for h := range r.Header {
request.Header.Set(h, r.Header.Get(h))
}
request.Host = r.Host
copyHeaders(request.Header, &r.Header)
ctx, cancel := context.WithTimeout(context.Background(), f.ExecTimeout)
defer cancel()
res, err := f.Client.Do(request.WithContext(ctx))
if err != nil {
log.Printf("Upstream HTTP request error: %s\n", err.Error())
// Error unrelated to context / deadline
if ctx.Err() == nil {
w.Header().Set("X-Duration-Seconds", fmt.Sprintf("%f", time.Since(startedTime).Seconds()))
w.WriteHeader(http.StatusInternalServerError)
return nil
}
select {
case <-ctx.Done():
{
if ctx.Err() != nil {
// Error due to timeout / deadline
log.Printf("Upstream HTTP killed due to exec_timeout: %s\n", f.ExecTimeout)
w.Header().Set("X-Duration-Seconds", fmt.Sprintf("%f", time.Since(startedTime).Seconds()))
w.WriteHeader(http.StatusGatewayTimeout)
return nil
}
}
}
w.Header().Set("X-Duration-Seconds", fmt.Sprintf("%f", time.Since(startedTime).Seconds()))
w.WriteHeader(http.StatusInternalServerError)
return err
}
copyHeaders(w.Header(), &res.Header)
w.Header().Set("X-Duration-Seconds", fmt.Sprintf("%f", time.Since(startedTime).Seconds()))
w.WriteHeader(res.StatusCode)
if res.Body != nil {
defer res.Body.Close()
bodyBytes, bodyErr := ioutil.ReadAll(res.Body)
if bodyErr != nil {
log.Println("read body err", bodyErr)
}
w.Write(bodyBytes)
}
log.Printf("%s %s - %s - ContentLength: %d", r.Method, r.RequestURI, res.Status, res.ContentLength)
return 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 makeProxyClient(dialTimeout time.Duration) *http.Client {
proxyClient := http.Client{
Transport: &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: dialTimeout,
KeepAlive: 10 * time.Second,
}).DialContext,
MaxIdleConns: 100,
MaxIdleConnsPerHost: 100,
DisableKeepAlives: false,
IdleConnTimeout: 500 * time.Millisecond,
ExpectContinueTimeout: 1500 * time.Millisecond,
},
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
}
return &proxyClient
}