-
Notifications
You must be signed in to change notification settings - Fork 41
/
envproxy.go
327 lines (285 loc) · 10.3 KB
/
envproxy.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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
package fission
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"os"
"path"
"strings"
"time"
"github.com/fission/fission"
"github.com/fission/fission-workflows/pkg/apiserver"
"github.com/fission/fission-workflows/pkg/types"
"github.com/fission/fission-workflows/pkg/types/typedvalues"
"github.com/fission/fission-workflows/pkg/types/typedvalues/httpconv"
"github.com/fission/fission-workflows/pkg/util"
"github.com/fission/fission/router"
"github.com/golang/protobuf/jsonpb"
"github.com/hashicorp/golang-lru"
"github.com/opentracing/opentracing-go"
"github.com/sirupsen/logrus"
)
const fissionIDsCacheSize = 1E4
// Proxy between Fission and Workflows to ensure that invocations comply with Fission function interface. This
// ensures that workflows can be executed exactly like Fission functions are executed.
type Proxy struct {
client *apiserver.Client
fissionIds *lru.Cache // map[string]bool
defaultTimeout time.Duration
}
// NewEnvironmentProxyServer creates a proxy server to adheres to the Fission Environment specification.
func NewEnvironmentProxyServer(client *apiserver.Client, defaultTimeout time.Duration) *Proxy {
cache, err := lru.New(fissionIDsCacheSize)
if err != nil {
panic(err)
}
if defaultTimeout <= 0 {
panic("default timeout for the Fission Proxy must be larger than 0")
}
return &Proxy{
client: client,
fissionIds: cache,
defaultTimeout: defaultTimeout,
}
}
// RegisterServer adds the endpoints needed for the Fission Environment interface to the mux server.
func (fp *Proxy) RegisterServer(mux *http.ServeMux) {
mux.HandleFunc("/", fp.handleRequest)
mux.HandleFunc("/v2/specialize", fp.handleSpecialize)
mux.HandleFunc("/healthz", fp.handleHealthCheck)
}
func (fp *Proxy) handleHealthCheck(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
}
func (fp *Proxy) handleRequest(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
// Optional: Parse opentracing
spanCtx, err := opentracing.GlobalTracer().Extract(opentracing.HTTPHeaders,
opentracing.HTTPHeadersCarrier(r.Header))
if err != nil && err != opentracing.ErrSpanContextNotFound {
logrus.Warnf("Failed to extract tracer from proxy requrest: %v", err)
}
var opts []opentracing.StartSpanOption
if spanCtx != nil {
opts = append(opts, opentracing.ChildOf(spanCtx))
}
span := opentracing.StartSpan("fnenv/fission/envproxy.handleRequest", opts...)
defer span.Finish()
// Fetch the workflow based on the received Fission function metadata
meta := router.HeadersToMetadata(router.HEADERS_FISSION_FUNCTION_PREFIX, r.Header)
fnID := string(meta.UID)
if len(meta.UID) == 0 {
logrus.WithField("meta", meta).Error("Fission function name is missing")
http.Error(w, "Fission function name is missing", 400)
return
}
// Check if the workflow engine contains the workflow associated with the Fission function UID
_, ok := fp.fissionIds.Get(fnID)
if !ok {
// Fallback 1 : check if it is in the event store somewhere
if fp.hasWorkflow(ctx, fnID) {
logrus.WithField("fnID", fnID).Error("Unknown fission function name")
http.Error(w, "Unknown fission function name; not specialized", 400)
return
}
fp.fissionIds.Add(fnID, true)
}
// Map request to workflow inputs
inputs, err := httpconv.ParseRequest(r)
if err != nil {
logrus.Errorf("Failed to parse inputs: %v", err)
http.Error(w, "Failed to parse inputs", 400)
return
}
deadline := fp.determineDeadline(r)
wfSpec := types.NewWorkflowInvocationSpec(fnID, deadline)
wfSpec.Inputs = inputs
// Temporary: in case of query header 'X-Async' being present, make request async
if logrus.GetLevel() == logrus.DebugLevel {
inputs, err := typedvalues.UnwrapMapTypedValue(wfSpec.Inputs)
util.LogIfError(err)
logrus.Debugf("Fission proxy request: %v - %v", wfSpec.WorkflowId, inputs)
}
if len(r.Header.Get("X-Async")) > 0 {
invocationID, invokeErr := fp.client.Invocation.Invoke(ctx, wfSpec)
if invokeErr != nil {
logrus.Errorf("Failed to invoke: %v", invokeErr)
http.Error(w, invokeErr.Error(), 500)
return
}
w.WriteHeader(200)
w.Write([]byte(invocationID.Id))
return
}
// Otherwise, the request synchronous like other Fission functions
wi, err := fp.client.Invocation.InvokeSync(ctx, wfSpec)
if err != nil {
logrus.Errorf("Failed to invoke: %v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Format output or error to the response
if !wi.Status.Successful() && wi.Status.Error == nil {
logrus.Warn("Failed invocation does not contain error")
wi.Status.Error = &types.Error{
Message: "Unknown error",
}
}
// Get output
httpconv.FormatResponse(w, wi.Status.Output, wi.Status.OutputHeaders, wi.Status.Error)
// Logging
if !wi.Status.Successful() {
logrus.Errorf("Invocation not successful, was '%v': %v", wi.Status.Status.String(), wi.Status.Error.Error())
} else if wi.Status.Output == nil {
logrus.Debugf("Invocation '%v' has no output.", fnID)
} else {
logrus.Debugf("Response Content-Type: %v", w.Header().Get("Content-Type"))
}
}
func (fp *Proxy) handleSpecialize(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
logrus.Info("Specializing...")
bs, err := ioutil.ReadAll(r.Body)
if err != nil {
logrus.Errorf("Failed to read body: %v", err)
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("failed to read body: " + err.Error()))
return
}
logrus.Info("Received specialization body:", string(bs))
// Parse the function load request
flr := &fission.FunctionLoadRequest{}
err = json.Unmarshal(bs, flr)
if err != nil {
logrus.Errorf("Failed to parse body: %v", err)
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("Failed to parse body: " + err.Error()))
return
}
// Attempt to specialize with the provided function load request
wfIDs, err := fp.specialize(ctx, flr)
if err != nil {
logrus.Errorf("failed to specialize: %v", err)
if os.IsNotExist(err) {
w.WriteHeader(http.StatusNotFound)
} else {
w.WriteHeader(http.StatusInternalServerError)
}
w.Write([]byte(err.Error()))
return
}
logrus.Infof("Specialized successfully wf '%s'", wfIDs)
w.WriteHeader(http.StatusOK)
// TODO change this to a more structured output once specialization protocol has been formalized
w.Write([]byte(strings.Join(wfIDs, ";")))
}
// specialize creates workflows provided by a Fission Load Request.
//
// The Fission package can either exist out of a single workflow file, or out of a directory filled with
// solely workflow definitions.
//
// In the FunctionLoadRequest this function expects FilePath, and the objectmetadata, with the UID and Name, to be set.
func (fp *Proxy) specialize(ctx context.Context, flr *fission.FunctionLoadRequest) ([]string, error) {
if flr == nil {
return nil, errors.New("no function load request provided")
}
// Check if request contains the expected metadata
metadata := flr.FunctionMetadata
if metadata == nil {
logrus.Errorf("No workflow metadata provided: %v", metadata)
return nil, errors.New("no metadata provided in function load request")
}
// Search provided package for workflow definitions
wfPaths, err := fp.findWorkflowFiles(ctx, flr)
if err != nil {
return nil, err
}
var wfIDs []string
// Create workflows for each detected workflow definition
logrus.Infof("Files: %v", wfPaths)
for _, wfPath := range wfPaths {
wfID, err := fp.createWorkflowFromFile(ctx, flr, wfPath)
if err != nil {
return nil, fmt.Errorf("failed to specialize package: %v", err)
}
wfIDs = append(wfIDs, wfID)
}
return wfIDs, nil
}
// findWorkflowFiles searches for all of the workflow definitions in a Fission package
func (fp *Proxy) findWorkflowFiles(ctx context.Context, flr *fission.FunctionLoadRequest) ([]string, error) {
fi, err := os.Stat(flr.FilePath)
if err != nil {
return nil, fmt.Errorf("no file present at '%v", flr.FilePath)
}
if fi.IsDir() {
// User provided a package
contents, err := ioutil.ReadDir(flr.FilePath)
if err != nil {
return nil, fmt.Errorf("failed to read package: '%v", flr.FilePath)
}
if len(contents) == 0 {
return nil, fmt.Errorf("package is empty")
}
var paths []string
for _, n := range contents {
// Note: this assumes that all files in package are workflow definitions!
file := path.Join(flr.FilePath, n.Name())
paths = append(paths, file)
}
// TODO maybe change to []string to provide all generated ids
return paths, nil
}
// Provided workflow is a file
return []string{flr.FilePath}, nil
}
// createWorkflowFromFile creates a workflow given a path to the file containing the workflow definition
func (fp *Proxy) createWorkflowFromFile(ctx context.Context, flr *fission.FunctionLoadRequest, path string) (string, error) {
rdr, err := os.Open(path)
if err != nil {
return "", fmt.Errorf("failed to open file '%v': %v", path, err)
}
raw, err := ioutil.ReadAll(rdr)
if err != nil {
return "", fmt.Errorf("failed to read file '%v': %v", path, err)
}
logrus.Infof("received definition: '%s'", string(raw))
wfSpec := &types.WorkflowSpec{}
err = jsonpb.Unmarshal(bytes.NewReader(raw), wfSpec)
if err != nil {
return "", fmt.Errorf("failed to parse bytes to workflow specification: %v", err)
}
logrus.WithField("wfSpec", wfSpec).Info("Received valid WorkflowSpec from fetcher.")
// Synchronize the workflow id with the fission id
fissionID := string(flr.FunctionMetadata.GetUID())
wfSpec.ForceId = fissionID
wfSpec.Name = flr.FunctionName
resp, err := fp.client.Workflow.CreateSync(ctx, wfSpec)
if err != nil {
return "", fmt.Errorf("failed to store workflow internally: %v", err)
}
wfID := resp.ID()
// Cache the id so we don't have to check whether the workflow engine already has it.
fp.fissionIds.Add(fissionID, true)
return wfID, nil
}
func (fp *Proxy) hasWorkflow(ctx context.Context, fnID string) bool {
wf, err := fp.client.Workflow.Get(ctx, &types.ObjectMetadata{Id: fnID})
if err != nil {
logrus.Errorf("Failed to get workflow: %v; assuming it is non-existent", err)
}
return wf != nil
}
func (fp *Proxy) determineDeadline(r *http.Request) time.Time {
// Try to parse the X-Fission-Function-Timeout
deadlineString := r.Header.Get(fmt.Sprintf("X-%s-Timeout", router.HEADERS_FISSION_FUNCTION_PREFIX))
if duration, err := time.ParseDuration(deadlineString); err == nil {
return time.Now().Add(duration)
}
// Final fallback, use the default set in the proxy
return time.Now().Add(fp.defaultTimeout)
}