-
Notifications
You must be signed in to change notification settings - Fork 118
/
http_runner.go
209 lines (169 loc) · 5.12 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
206
207
208
209
// Copyright (c) OpenFaaS Author(s) 2021. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
package executor
import (
"bytes"
"context"
"fmt"
"io"
"io/ioutil"
"log"
"net"
"net/http"
"net/url"
"os"
"os/exec"
"os/signal"
"strings"
"syscall"
"time"
)
// HTTPFunctionRunner creates and maintains one process responsible for handling all calls
type HTTPFunctionRunner struct {
ExecTimeout time.Duration // ExecTimeout the maximum duration or an upstream function call
ReadTimeout time.Duration // ReadTimeout for HTTP server
WriteTimeout time.Duration // WriteTimeout for HTTP Server
Process string // Process to run as fprocess
ProcessArgs []string // ProcessArgs to pass to command
Command *exec.Cmd
StdinPipe io.WriteCloser
StdoutPipe io.ReadCloser
Client *http.Client
UpstreamURL *url.URL
BufferHTTPBody bool
LogPrefix bool
LogBufferSize int
}
// 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()
// Logs lines from stderr and stdout to the stderr and stdout of this process
bindLoggingPipe("stderr", errPipe, os.Stderr, f.LogPrefix, f.LogBufferSize)
bindLoggingPipe("stdout", f.StdoutPipe, os.Stdout, f.LogPrefix, f.LogBufferSize)
f.Client = makeProxyClient(f.ExecTimeout)
go func() {
sig := make(chan os.Signal, 1)
signal.Notify(sig, syscall.SIGTERM)
<-sig
cmd.Process.Signal(syscall.SIGTERM)
}()
err := cmd.Start()
go func() {
err := cmd.Wait()
if err != nil {
log.Fatalf("Forked function has terminated: %s", err.Error())
}
}()
return err
}
// 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
}
var body io.Reader
if f.BufferHTTPBody {
reqBody, _ := ioutil.ReadAll(r.Body)
body = bytes.NewReader(reqBody)
} else {
body = r.Body
}
request, err := http.NewRequest(r.Method, upstreamURL, body)
if err != nil {
return err
}
for h := range r.Header {
request.Header.Set(h, r.Header.Get(h))
}
request.Host = r.Host
copyHeaders(request.Header, &r.Header)
var reqCtx context.Context
var cancel context.CancelFunc
if f.ExecTimeout.Nanoseconds() > 0 {
reqCtx, cancel = context.WithTimeout(r.Context(), f.ExecTimeout)
} else {
reqCtx = r.Context()
cancel = func() {
}
}
defer cancel()
res, err := f.Client.Do(request.WithContext(reqCtx))
if err != nil {
log.Printf("Upstream HTTP request error: %s\n", err.Error())
// Error unrelated to context / deadline
if reqCtx.Err() == nil {
w.Header().Set("X-Duration-Seconds", fmt.Sprintf("%f", time.Since(startedTime).Seconds()))
w.WriteHeader(http.StatusInternalServerError)
return nil
}
<-reqCtx.Done()
if reqCtx.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)
}
// Exclude logging for health check probes from the kubelet which can spam
// log collection systems.
if !strings.HasPrefix(r.UserAgent(), "kube-probe") {
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
}