-
Notifications
You must be signed in to change notification settings - Fork 70
Expand file tree
/
Copy pathinvoke.go
More file actions
316 lines (283 loc) · 8.27 KB
/
Copy pathinvoke.go
File metadata and controls
316 lines (283 loc) · 8.27 KB
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
/*
* Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package commands
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"strings"
"errors"
"github.com/fnproject/cli/client"
"github.com/fnproject/cli/common"
"github.com/fnproject/cli/objects/app"
"github.com/fnproject/cli/objects/fn"
"github.com/fnproject/fn_go/clientv2"
"github.com/fnproject/fn_go/provider"
"github.com/urfave/cli"
)
// FnInvokeEndpointAnnotation is the annotation that exposes the fn invoke endpoint as defined in models/fn.go
const (
FnInvokeEndpointAnnotation = "fnproject.io/fn/invokeEndpoint"
CallIDHeader = "Fn-Call-Id"
)
type invokeCmd struct {
provider provider.Provider
client *clientv2.Fn
}
// InvokeFnFlags used to invoke and fn
var InvokeFnFlags = []cli.Flag{
cli.StringFlag{
Name: "endpoint",
Usage: "Specify the function invoke endpoint for this function, the app-name and func-name parameters will be ignored",
},
cli.StringFlag{
Name: "content-type",
Usage: "The payload Content-Type for the function invocation.",
},
cli.BoolFlag{
Name: "display-call-id",
Usage: "whether display call ID or not",
},
cli.StringFlag{
Name: "output",
Usage: "Output format (json)",
},
cli.StringFlag{
Name: "fn-intent",
Usage: "Optional intent header for function invocation, e.g. httprequest or cloudevent",
},
cli.BoolFlag{
Name: "is-dry-run",
Usage: "Send the invocation as a dry run without executing the function when supported by the server",
},
cli.StringFlag{
Name: "fn-invoke-type",
Usage: "Invoke type for Oracle Functions: sync or detached",
},
}
var InvokeDetachedFnFlags = []cli.Flag{
cli.StringFlag{
Name: "endpoint",
Usage: "Specify the function invoke endpoint for this function, the app-name and func-name parameters will be ignored",
},
cli.StringFlag{
Name: "content-type",
Usage: "The payload Content-Type for the function invocation.",
},
cli.BoolFlag{
Name: "display-call-id",
Usage: "whether display call ID or not",
},
cli.StringFlag{
Name: "output",
Usage: "Output format (json)",
},
cli.StringFlag{
Name: "fn-intent",
Usage: "Optional intent header for function invocation, e.g. httprequest or cloudevent",
},
cli.BoolFlag{
Name: "is-dry-run",
Usage: "Send the invocation as a dry run without executing the function when supported by the server",
},
}
// InvokeCommand returns call cli.command
func InvokeCommand() cli.Command {
cl := invokeCmd{}
return cli.Command{
Name: "invoke",
Usage: "\tInvoke a remote function",
Aliases: []string{"iv"},
Before: func(c *cli.Context) error {
var err error
cl.provider, err = client.CurrentProvider()
if err != nil {
return err
}
cl.client = cl.provider.APIClientv2()
return nil
},
ArgsUsage: "[app-name] [function-name]",
Flags: InvokeFnFlags,
Subcommands: []cli.Command{
{
Name: "detached",
Usage: "\tInvoke a remote function in detached mode",
ArgsUsage: "[app-name] [function-name]",
Flags: InvokeDetachedFnFlags,
Action: cl.InvokeDetached,
BashComplete: func(c *cli.Context) {
switch len(c.Args()) {
case 0:
app.BashCompleteApps(c)
case 1:
fn.BashCompleteFns(c)
}
},
},
},
Category: "DEVELOPMENT COMMANDS",
Description: `This command invokes a function. Users may send input to their function by passing input to this command via STDIN.`,
Action: cl.Invoke,
BashComplete: func(c *cli.Context) {
switch len(c.Args()) {
case 0:
app.BashCompleteApps(c)
case 1:
fn.BashCompleteFns(c)
}
},
}
}
func (cl *invokeCmd) Invoke(c *cli.Context) error {
return cl.invoke(c, "")
}
func (cl *invokeCmd) InvokeDetached(c *cli.Context) error {
return cl.invoke(c, "detached")
}
func (cl *invokeCmd) invoke(c *cli.Context, forcedInvokeType string) error {
var contentType string
invokeURL := c.String("endpoint")
if invokeURL == "" {
appName := c.Args().Get(0)
fnName := c.Args().Get(1)
if appName == "" || fnName == "" {
return errors.New("missing app and function name")
}
app, err := app.GetAppByName(cl.client, appName)
if err != nil {
return err
}
fn, err := fn.GetFnByName(cl.client, app.ID, fnName)
if err != nil {
return err
}
var ok bool
invokeURL, ok = fn.Annotations[FnInvokeEndpointAnnotation].(string)
if !ok {
return fmt.Errorf("Fn invoke url annotation not present, %s", FnInvokeEndpointAnnotation)
}
}
content := stdin()
wd := common.GetWd()
invokeType := strings.ToLower(strings.TrimSpace(forcedInvokeType))
if invokeType == "" {
invokeType = strings.ToLower(strings.TrimSpace(c.String("fn-invoke-type")))
}
if invokeType != "" && invokeType != "sync" && invokeType != "detached" {
return fmt.Errorf("invalid value for --fn-invoke-type: %q", invokeType)
}
if invokeType == "detached" && !common.IsOracleProvider(cl.provider) {
fmt.Fprintln(os.Stderr, "Warning: --fn-invoke-type=detached is only supported with an oracle provider and will be ignored.")
invokeType = ""
}
fnIntent := strings.TrimSpace(c.String("fn-intent"))
if c.String("content-type") != "" {
contentType = c.String("content-type")
} else {
_, ff, err := common.FindAndParseFuncFileV20180708(wd)
if err == nil && ff.Content_type != "" {
contentType = ff.Content_type
}
}
resp, err := client.Invoke(cl.provider,
client.InvokeRequest{
URL: invokeURL,
Content: content,
Env: c.StringSlice("e"),
ContentType: contentType,
FnIntent: fnIntent,
IsDryRun: c.Bool("is-dry-run"),
FnInvokeType: invokeType,
},
)
if err != nil {
return err
}
defer resp.Body.Close()
outputFormat := strings.ToLower(c.String("output"))
if outputFormat == "json" {
outputJSON(os.Stdout, resp)
} else {
outputNormal(os.Stdout, resp, c.Bool("display-call-id"))
}
// TODO we should have a 'raw' option to output the raw http request, it may be useful, idk
return nil
}
func outputJSON(output io.Writer, resp *http.Response) {
var b bytes.Buffer
// TODO this is lame
io.Copy(&b, resp.Body)
i := struct {
Body string `json:"body"`
Headers http.Header `json:"headers"`
StatusCode int `json:"status_code"`
}{
Body: b.String(),
Headers: resp.Header,
StatusCode: resp.StatusCode,
}
enc := json.NewEncoder(output)
enc.SetIndent("", " ")
enc.Encode(i)
}
func outputNormal(output io.Writer, resp *http.Response, includeCallID bool) {
if cid, ok := resp.Header[CallIDHeader]; ok && includeCallID {
fmt.Fprint(output, fmt.Sprintf("Call ID: %v\n", cid[0]))
}
var body io.Reader = resp.Body
if resp.StatusCode >= 400 {
// if we don't get json, we need to buffer the input so that we can
// display the user's function output as it was...
var b bytes.Buffer
body = io.TeeReader(resp.Body, &b)
var msg struct {
Message string `json:"message"`
}
err := json.NewDecoder(body).Decode(&msg)
if err == nil && msg.Message != "" {
// this is likely from fn, so unravel this...
// TODO this should be stderr maybe? meh...
fmt.Fprintf(output, "Error invoking function. status: %v message: %v\n", resp.StatusCode, msg.Message)
return
}
// read anything written to buffer first, then copy out rest of body
body = io.MultiReader(&b, resp.Body)
}
// at this point, it's not an fn error, so output function output as is
lcc := lastCharChecker{reader: body}
body = &lcc
io.Copy(output, body)
// #1408 - flush stdout
if lcc.last != '\n' {
fmt.Fprintln(output)
}
}
// lastCharChecker wraps an io.Reader to return the last read character
type lastCharChecker struct {
reader io.Reader
last byte
}
func (l *lastCharChecker) Read(b []byte) (int, error) {
n, err := l.reader.Read(b)
if n > 0 {
l.last = b[n-1]
}
return n, err
}