forked from openfaas/faas-cli
/
deploy.go
615 lines (504 loc) · 18.6 KB
/
deploy.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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
// Copyright (c) Alex Ellis 2017. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
package commands
import (
"encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"path/filepath"
"strings"
"gopkg.in/yaml.v2"
"github.com/docker/docker-credential-helpers/client"
homedir "github.com/mitchellh/go-homedir"
"github.com/openfaas/faas-cli/builder"
"github.com/openfaas/faas-cli/proxy"
"github.com/openfaas/faas-cli/schema"
"github.com/openfaas/faas-cli/stack"
"github.com/spf13/cobra"
)
// DeployFlags holds flags that are to be added to commands.
type DeployFlags struct {
envvarOpts []string
replace bool
update bool
readOnlyRootFilesystem bool
constraints []string
secrets []string
labelOpts []string
annotationOpts []string
sendRegistryAuth bool
}
var deployFlags DeployFlags
func init() {
// Setup flags that are used by multiple commands (variables defined in faas.go)
deployCmd.Flags().StringVar(&fprocess, "fprocess", "", "fprocess value to be run as a serverless function by the watchdog")
deployCmd.Flags().StringVarP(&gateway, "gateway", "g", defaultGateway, "Gateway URL starting with http(s)://")
deployCmd.Flags().StringVar(&handler, "handler", "", "Directory with handler for function, e.g. handler.js")
deployCmd.Flags().StringVar(&image, "image", "", "Docker image name to build")
deployCmd.Flags().StringVar(&language, "lang", "", "Programming language template")
deployCmd.Flags().StringVar(&functionName, "name", "", "Name of the deployed function")
deployCmd.Flags().StringVar(&network, "network", defaultNetwork, "Name of the network")
// Setup flags that are used only by this command (variables defined above)
deployCmd.Flags().StringArrayVarP(&deployFlags.envvarOpts, "env", "e", []string{}, "Set one or more environment variables (ENVVAR=VALUE)")
deployCmd.Flags().StringArrayVarP(&deployFlags.labelOpts, "label", "l", []string{}, "Set one or more label (LABEL=VALUE)")
deployCmd.Flags().StringArrayVarP(&deployFlags.annotationOpts, "annotation", "", []string{}, "Set one or more annotation (ANNOTATION=VALUE)")
deployCmd.Flags().BoolVar(&deployFlags.replace, "replace", false, "Remove and re-create existing function(s)")
deployCmd.Flags().BoolVar(&deployFlags.update, "update", true, "Perform rolling update on existing function(s)")
deployCmd.Flags().StringArrayVar(&deployFlags.constraints, "constraint", []string{}, "Apply a constraint to the function")
deployCmd.Flags().StringArrayVar(&deployFlags.secrets, "secret", []string{}, "Give the function access to a secure secret")
deployCmd.Flags().BoolVar(&deployFlags.readOnlyRootFilesystem, "readonly", false, "Force the root container filesystem to be read only")
deployCmd.Flags().BoolVarP(&deployFlags.sendRegistryAuth, "send-registry-auth", "a", false, "send registryAuth from Docker credentials manager with the request")
deployCmd.Flags().StringVar(&tag, "tag", "", "Override latest tag on function Docker image, takes 'sha' or 'branch'")
deployCmd.Flags().BoolVar(&tlsInsecure, "tls-no-verify", false, "Disable TLS validation")
// Set bash-completion.
_ = deployCmd.Flags().SetAnnotation("handler", cobra.BashCompSubdirsInDir, []string{})
faasCmd.AddCommand(deployCmd)
}
// deployCmd handles deploying OpenFaaS function containers
var deployCmd = &cobra.Command{
Use: `deploy -f YAML_FILE [--replace=false]
faas-cli deploy --image IMAGE_NAME
--name FUNCTION_NAME
[--lang <ruby|python|node|csharp>]
[--gateway GATEWAY_URL]
[--network NETWORK_NAME]
[--handler HANDLER_DIR]
[--fprocess PROCESS]
[--env ENVVAR=VALUE ...]
[--label LABEL=VALUE ...]
[--annotation ANNOTATION=VALUE ...]
[--replace=false]
[--update=false]
[--constraint PLACEMENT_CONSTRAINT ...]
[--regex "REGEX"]
[--filter "WILDCARD"]
[--secret "SECRET_NAME"]
[--tag <sha|branch>]
[--readonly=false]`,
Short: "Deploy OpenFaaS functions",
Long: `Deploys OpenFaaS function containers either via the supplied YAML config using
the "--yaml" flag (which may contain multiple function definitions), or directly
via flags. Note: --replace and --update are mutually exclusive.`,
Example: ` faas-cli deploy -f https://domain/path/myfunctions.yml
faas-cli deploy -f ./stack.yml
faas-cli deploy -f ./stack.yml --label canary=true
faas-cli deploy -f ./stack.yml --annotation user=true
faas-cli deploy -f ./stack.yml --filter "*gif*" --secret dockerhuborg
faas-cli deploy -f ./stack.yml --regex "fn[0-9]_.*"
faas-cli deploy -f ./stack.yml --replace=false --update=true
faas-cli deploy -f ./stack.yml --replace=true --update=false
faas-cli deploy -f ./stack.yml --tag sha
faas-cli deploy -f ./stack.yml --tag branch
faas-cli deploy --image=alexellis/faas-url-ping --name=url-ping
faas-cli deploy --image=my_image --name=my_fn --handler=/path/to/fn/
--gateway=http://remote-site.com:8080 --lang=python
--env=MYVAR=myval`,
PreRunE: preRunDeploy,
RunE: runDeploy,
}
// preRunDeploy validates args & flags
func preRunDeploy(cmd *cobra.Command, args []string) error {
language, _ = validateLanguageFlag(language)
return nil
}
func runDeploy(cmd *cobra.Command, args []string) error {
return runDeployCommand(args, image, fprocess, functionName, deployFlags, tag)
}
func runDeployCommand(args []string, image string, fprocess string, functionName string, deployFlags DeployFlags, tag string) error {
if deployFlags.update && deployFlags.replace {
fmt.Println(`Cannot specify --update and --replace at the same time. One of --update or --replace must be false.
--replace removes an existing deployment before re-creating it
--update performs a rolling update to a new function image or configuration (default true)`)
return fmt.Errorf("cannot specify --update and --replace at the same time")
}
var services stack.Services
if len(yamlFile) > 0 {
parsedServices, err := stack.ParseYAMLFile(yamlFile, regex, filter)
if err != nil {
return err
}
parsedServices.Provider.GatewayURL = getGatewayURL(gateway, defaultGateway, parsedServices.Provider.GatewayURL, os.Getenv(openFaaSURLEnvironment))
// Override network if passed
if len(network) > 0 {
parsedServices.Provider.Network = network
}
if parsedServices != nil {
services = *parsedServices
}
}
var failedStatusCodes = make(map[string]int)
if len(services.Functions) > 0 {
if len(services.Provider.Network) == 0 {
services.Provider.Network = defaultNetwork
}
for k, function := range services.Functions {
function.Name = k
fmt.Printf("Deploying: %s.\n", function.Name)
var functionConstraints []string
if function.Constraints != nil {
functionConstraints = *function.Constraints
} else if len(deployFlags.constraints) > 0 {
functionConstraints = deployFlags.constraints
}
if len(function.Secrets) > 0 {
deployFlags.secrets = mergeSlice(function.Secrets, deployFlags.secrets)
}
if deployFlags.sendRegistryAuth {
dockerConfig := configFile{}
err := readDockerConfig(&dockerConfig)
if err != nil {
log.Printf("Unable to read the docker config - %v", err.Error())
}
function.RegistryAuth = getRegistryAuth(&dockerConfig, function.Image)
}
fileEnvironment, err := readFiles(function.EnvironmentFile)
if err != nil {
return err
}
labelMap := map[string]string{}
if function.Labels != nil {
labelMap = *function.Labels
}
labelArgumentMap, labelErr := parseMap(deployFlags.labelOpts, "label")
if labelErr != nil {
return fmt.Errorf("error parsing labels: %v", labelErr)
}
allLabels := mergeMap(labelMap, labelArgumentMap)
allEnvironment, envErr := compileEnvironment(deployFlags.envvarOpts, function.Environment, fileEnvironment)
if envErr != nil {
return envErr
}
// Get FProcess to use from the ./template/template.yml, if a template is being used
if languageExistsNotDockerfile(function.Language) {
var fprocessErr error
function.FProcess, fprocessErr = deriveFprocess(function)
if fprocessErr != nil {
return fmt.Errorf(`template directory may be missing or invalid, please run "faas template pull"
Error: %s`, fprocessErr.Error())
}
}
functionResourceRequest := proxy.FunctionResourceRequest{
Limits: function.Limits,
Requests: function.Requests,
}
var annotations map[string]string
if function.Annotations != nil {
annotations = *function.Annotations
}
annotationArgs, annotationErr := parseMap(deployFlags.annotationOpts, "annotation")
if annotationErr != nil {
return fmt.Errorf("error parsing annotations: %v", annotationErr)
}
allAnnotations := mergeMap(annotations, annotationArgs)
tagMode := schema.DefaultFormat
var sha string
if strings.ToLower(tag) == "sha" {
sha = builder.GetGitSHA()
tagMode = schema.SHAFormat
}
var branch string
if strings.ToLower(tag) == "branch" {
branch = builder.GetGitBranch()
sha = builder.GetGitSHA()
tagMode = schema.BranchAndSHAFormat
}
function.Image = schema.BuildImageName(tagMode, function.Image, sha, branch)
if deployFlags.readOnlyRootFilesystem {
function.ReadOnlyRootFilesystem = deployFlags.readOnlyRootFilesystem
}
deploySpec := &proxy.DeployFunctionSpec{
FProcess: function.FProcess,
Gateway: services.Provider.GatewayURL,
FunctionName: function.Name,
Image: function.Image,
RegistryAuth: function.RegistryAuth,
Language: function.Language,
Replace: deployFlags.replace,
EnvVars: allEnvironment,
Network: services.Provider.Network,
Constraints: functionConstraints,
Update: deployFlags.update,
Secrets: deployFlags.secrets,
Labels: allLabels,
Annotations: allAnnotations,
FunctionResourceRequest: functionResourceRequest,
ReadOnlyRootFilesystem: function.ReadOnlyRootFilesystem,
TLSInsecure: tlsInsecure,
}
statusCode := proxy.DeployFunction(deploySpec)
if badStatusCode(statusCode) {
failedStatusCodes[k] = statusCode
}
}
} else {
if len(image) == 0 || len(functionName) == 0 {
return fmt.Errorf("To deploy a function give --yaml/-f or a --image and --name flag")
}
gateway = getGatewayURL(gateway, defaultGateway, "", os.Getenv(openFaaSURLEnvironment))
var registryAuth string
if deployFlags.sendRegistryAuth {
dockerConfig := configFile{}
err := readDockerConfig(&dockerConfig)
if err != nil {
log.Printf("Unable to read the docker config - %v\n", err.Error())
}
registryAuth = getRegistryAuth(&dockerConfig, image)
}
// default to a readable filesystem until we get more input about the expected behavior
// and if we want to add another flag for this case
defaultReadOnlyRFS := false
statusCode, err := deployImage(image, fprocess, functionName, registryAuth, deployFlags, tlsInsecure, defaultReadOnlyRFS)
if err != nil {
return err
}
if badStatusCode(statusCode) {
failedStatusCodes[functionName] = statusCode
}
}
if err := deployFailed(failedStatusCodes); err != nil {
return err
}
return nil
}
// deployImage deploys a function with the given image
func deployImage(
image string,
fprocess string,
functionName string,
registryAuth string,
deployFlags DeployFlags,
tlsInsecure bool,
readOnlyRootFilesystem bool,
) (int, error) {
var statusCode int
readOnlyRFS := deployFlags.readOnlyRootFilesystem || readOnlyRootFilesystem
envvars, err := parseMap(deployFlags.envvarOpts, "env")
if err != nil {
return statusCode, fmt.Errorf("error parsing envvars: %v", err)
}
labelMap, labelErr := parseMap(deployFlags.labelOpts, "label")
if labelErr != nil {
return statusCode, fmt.Errorf("error parsing labels: %v", labelErr)
}
annotationMap, annotationErr := parseMap(deployFlags.annotationOpts, "annotation")
if annotationErr != nil {
return statusCode, fmt.Errorf("error parsing annotations: %v", annotationErr)
}
deploySpec := &proxy.DeployFunctionSpec{
FProcess: fprocess,
Gateway: gateway,
FunctionName: functionName,
Image: image,
RegistryAuth: registryAuth,
Language: language,
Replace: deployFlags.replace,
EnvVars: envvars,
Network: network,
Constraints: deployFlags.constraints,
Update: deployFlags.update,
Secrets: deployFlags.secrets,
Labels: labelMap,
Annotations: annotationMap,
FunctionResourceRequest: proxy.FunctionResourceRequest{},
ReadOnlyRootFilesystem: readOnlyRFS,
TLSInsecure: tlsInsecure,
}
statusCode = proxy.DeployFunction(deploySpec)
return statusCode, nil
}
func mergeSlice(values []string, overlay []string) []string {
results := []string{}
added := make(map[string]bool)
for _, value := range overlay {
results = append(results, value)
added[value] = true
}
for _, value := range values {
if exists := added[value]; exists == false {
results = append(results, value)
}
}
return results
}
func readFiles(files []string) (map[string]string, error) {
envs := make(map[string]string)
for _, file := range files {
bytesOut, readErr := ioutil.ReadFile(file)
if readErr != nil {
return nil, readErr
}
envFile := stack.EnvironmentFile{}
unmarshalErr := yaml.Unmarshal(bytesOut, &envFile)
if unmarshalErr != nil {
return nil, unmarshalErr
}
for k, v := range envFile.Environment {
envs[k] = v
}
}
return envs, nil
}
func parseMap(envvars []string, keyName string) (map[string]string, error) {
result := make(map[string]string)
for _, envvar := range envvars {
s := strings.SplitN(strings.TrimSpace(envvar), "=", 2)
if len(s) != 2 {
return nil, fmt.Errorf("label format is not correct, needs key=value")
}
envvarName := s[0]
envvarValue := s[1]
if !(len(envvarName) > 0) {
return nil, fmt.Errorf("empty %s name: [%s]", keyName, envvar)
}
if !(len(envvarValue) > 0) {
return nil, fmt.Errorf("empty %s value: [%s]", keyName, envvar)
}
result[envvarName] = envvarValue
}
return result, nil
}
func mergeMap(i map[string]string, j map[string]string) map[string]string {
merged := make(map[string]string)
for k, v := range i {
merged[k] = v
}
for k, v := range j {
merged[k] = v
}
return merged
}
func compileEnvironment(envvarOpts []string, yamlEnvironment map[string]string, fileEnvironment map[string]string) (map[string]string, error) {
envvarArguments, err := parseMap(envvarOpts, "env")
if err != nil {
return nil, fmt.Errorf("error parsing envvars: %v", err)
}
functionAndStack := mergeMap(yamlEnvironment, fileEnvironment)
return mergeMap(functionAndStack, envvarArguments), nil
}
func deriveFprocess(function stack.Function) (string, error) {
var fprocess string
pathToTemplateYAML := "./template/" + function.Language + "/template.yml"
if _, err := os.Stat(pathToTemplateYAML); os.IsNotExist(err) {
return "", err
}
var langTemplate stack.LanguageTemplate
parsedLangTemplate, err := stack.ParseYAMLForLanguageTemplate(pathToTemplateYAML)
if err != nil {
return "", err
}
if parsedLangTemplate != nil {
langTemplate = *parsedLangTemplate
fprocess = langTemplate.FProcess
}
return fprocess, nil
}
func languageExistsNotDockerfile(language string) bool {
return len(language) > 0 && strings.ToLower(language) != "dockerfile"
}
type authConfig struct {
Auth string `json:"auth,omitempty"`
}
type configFile struct {
AuthConfigs map[string]authConfig `json:"auths"`
CredentialsStore string `json:"credsStore,omitempty"`
}
const (
// docker default settings
configFileName = "config.json"
configFileDir = ".docker"
defaultDockerRegistry = "https://index.docker.io/v1/"
)
var (
configDir = os.Getenv("DOCKER_CONFIG")
)
func readDockerConfig(config *configFile) error {
if configDir == "" {
home, err := homedir.Dir()
if err != nil {
return err
}
configDir = filepath.Join(home, configFileDir)
}
filename := filepath.Join(configDir, configFileName)
file, err := os.Open(filename)
if err != nil {
return err
}
defer file.Close()
content, err := ioutil.ReadAll(file)
if err != nil {
return err
}
err = json.Unmarshal(content, config)
if err != nil {
return err
}
if config.CredentialsStore != "" {
p := client.NewShellProgramFunc("docker-credential-" + config.CredentialsStore)
for k := range config.AuthConfigs {
creds, err := client.Get(p, k)
if err != nil {
return err
}
if config.AuthConfigs[k].Auth == "" {
// apend base64 encoded "auth": "dGVzdDpQdXFxR3E2THZDYzhGQUwyUWtLcA==" (user:pass)
registryAuth := creds.Username + ":" + creds.Secret
registryAuth = base64.StdEncoding.EncodeToString([]byte(registryAuth))
var tmp = config.AuthConfigs[k]
tmp.Auth = registryAuth
config.AuthConfigs[k] = tmp
}
}
}
return nil
}
func getRegistryAuth(config *configFile, image string) string {
// The local library does not require an auth string.
if strings.Contains(image, "/") == false {
return ""
}
if len(config.AuthConfigs) > 0 {
// image format is either:
// <docker registry>/<user>/<image>
// <docker registry>/<image>
// <user>/<image>
// Registry value needs to be obtained / trimmed
var registry string
slashes := strings.Count(image, "/")
if slashes > 1 {
regS := strings.Split(image, "/")
registry = regS[0]
} else {
if slashes == 1 {
regS := strings.Split(image, "/")
if strings.Contains(regS[0], ".") || strings.Contains(regS[0], ":") {
registry = regS[0]
}
}
}
if registry != "" {
return config.AuthConfigs[registry].Auth
} else if (registry == "") && (config.AuthConfigs[defaultDockerRegistry].Auth != "") {
return config.AuthConfigs[defaultDockerRegistry].Auth
}
}
return ""
}
func deployFailed(status map[string]int) error {
if len(status) == 0 {
return nil
}
var allErrors []string
for funcName, funcStatus := range status {
err := fmt.Errorf("Function '%s' failed to deploy with status code: %d", funcName, funcStatus)
allErrors = append(allErrors, err.Error())
}
return fmt.Errorf(strings.Join(allErrors, "\n"))
}
func badStatusCode(statusCode int) bool {
return statusCode != http.StatusAccepted && statusCode != http.StatusOK
}