forked from knative/func
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdeploy.go
More file actions
1042 lines (896 loc) · 39.1 KB
/
deploy.go
File metadata and controls
1042 lines (896 loc) · 39.1 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
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
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package cmd
import (
"errors"
"fmt"
"io"
"os"
"os/exec"
"strconv"
"strings"
"github.com/AlecAivazis/survey/v2"
"github.com/google/go-containerregistry/pkg/name"
"github.com/ory/viper"
"github.com/spf13/cobra"
"k8s.io/apimachinery/pkg/api/resource"
"knative.dev/client/pkg/util"
"knative.dev/func/pkg/builders"
"knative.dev/func/pkg/config"
fn "knative.dev/func/pkg/functions"
"knative.dev/func/pkg/k8s"
"knative.dev/func/pkg/knative"
"knative.dev/func/pkg/utils"
)
func NewDeployCmd(newClient ClientFactory) *cobra.Command {
cmd := &cobra.Command{
Use: "deploy",
Short: "Deploy a function",
Long: `
NAME
{{rootCmdUse}} deploy - Deploy a function
SYNOPSIS
{{rootCmdUse}} deploy [-R|--remote] [-r|--registry] [-i|--image] [-n|--namespace]
[-e|--env] [-g|--git-url] [-t|--git-branch] [-d|--git-dir]
[-b|--build] [--builder] [--builder-image] [-p|--push]
[--domain] [--platform] [--build-timestamp] [--pvc-size]
[--service-account] [-c|--confirm] [-v|--verbose]
[--registry-insecure] [--registry-authfile] [--remote-storage-class]
DESCRIPTION
Deploys a function to the currently configured Knative-enabled cluster.
By default the function in the current working directory is deployed, or at
the path defined by --path.
A function which was previously deployed will be updated when re-deployed.
The function is built into a container for transport to the destination
cluster by way of a registry. Therefore --registry must be provided or have
previously been configured for the function. This registry is also used to
determine the final built image tag for the function. This final image name
can be provided explicitly using --image, in which case it is used in place
of --registry.
To run deploy using an interactive mode, use the --confirm (-c) option.
This mode is useful for the first deployment in particular, since subsequent
deployments remember most of the settings provided.
Building
By default the function will be built if it has not yet been built, or if
changes are detected in the function's source. The --build flag can be
used to override this behavior and force building either on or off.
Pushing
By default the function's image will be pushed to the configured container
registry after being successfully built. The --push flag can be used
to disable pushing. This could be used, for example, to trigger a redeploy
of a service without needing to build, or even have the container available
locally with '{{rootCmdUse}} deploy --build=false --push==false'.
Remote
Building and pushing (deploying) is by default run on localhost. This
process can also be triggered to run remotely in a Tekton-enabled cluster.
The --remote flag indicates that a build and deploy pipeline should be
invoked in the remote. Deploying with '{{rootCmdUse}} deploy --remote' will
send the function's source code to be built and deployed by the cluster,
eliminating the need for a local container engine. To trigger deployment
of a git repository instead of local source, combine with '--git-url':
'{{rootCmdUse}} deploy --remote --git-url=git.example.com/alice/f.git'
Domain
When deploying, a function's route is automatically generated using the
default domain with which the target platform has been configured. The
optional flag --domain can be used to choose this domain explicitly for
clusters which have been configured with support for function domain
selectors. Note that the domain specified must be one of those configured
or the flag will be ignored.
EXAMPLES
o Deploy the function
$ {{rootCmdUse}} deploy
o Deploy the function using interactive prompts. This is useful for the first
deployment, since most settings will be remembered for future deployments.
$ {{rootCmdUse}} deploy -c
o Deploy the function in the current working directory.
The function image will be pushed to "ghcr.io/alice/<Function Name>"
$ {{rootCmdUse}} deploy --registry ghcr.io/alice
o Deploy the function in the current working directory, manually specifying
the final image name and target cluster namespace.
$ {{rootCmdUse}} deploy --image ghcr.io/alice/myfunc --namespace myns
o Deploy the current function's source code by sending it to the cluster to
be built and deployed:
$ {{rootCmdUse}} deploy --remote
o Trigger a remote deploy, which instructs the cluster to build and deploy
the function in the specified git repository.
$ {{rootCmdUse}} deploy --remote --git-url=https://example.com/alice/myfunc.git
o Deploy the function, rebuilding the image even if no changes have been
detected in the local filesystem (source).
$ {{rootCmdUse}} deploy --build
o Deploy without rebuilding, even if changes have been detected in the
local filesystem.
$ {{rootCmdUse}} deploy --build=false
o Redeploy a function which has already been built and pushed. Works without
the use of a local container engine. For example, if the function was
manually deleted from the cluster, it can be quickly redeployed with:
$ {{rootCmdUse}} deploy --build=false --push=false
`,
SuggestFor: []string{"delpoy", "deplyo"},
PreRunE: bindEnv("build", "build-timestamp", "builder", "builder-image",
"base-image", "confirm", "domain", "env", "git-branch", "git-dir",
"git-url", "image", "namespace", "path", "platform", "push", "pvc-size",
"service-account", "deployer", "registry", "registry-insecure",
"registry-authfile", "remote", "username", "password", "token", "verbose",
"remote-storage-class"),
RunE: func(cmd *cobra.Command, args []string) error {
return runDeploy(cmd, newClient)
},
}
// Global Config
cfg, err := config.NewDefault()
if err != nil {
fmt.Fprintf(cmd.OutOrStdout(), "error loading config at '%v'. %v\n", config.File(), err)
}
// Function Context
f, _ := fn.NewFunction(effectivePath())
if f.Initialized() {
cfg = cfg.Apply(f)
}
// Flags
//
// Globally-Configurable Flags:
// Options whose value may be defined globally may also exist on the
// contextually relevant function; but sets are flattened via cfg.Apply(f)
cmd.Flags().StringP("builder", "b", cfg.Builder,
fmt.Sprintf("Builder to use when creating the function's container. Currently supported builders are %s.", KnownBuilders()))
cmd.Flags().StringP("registry", "r", cfg.Registry,
"Container registry + registry namespace. (ex 'ghcr.io/myuser'). The full image name is automatically determined using this along with function name. ($FUNC_REGISTRY)")
cmd.Flags().Bool("registry-insecure", cfg.RegistryInsecure, "Skip TLS certificate verification when communicating in HTTPS with the registry ($FUNC_REGISTRY_INSECURE)")
cmd.Flags().String("registry-authfile", "", "Path to a authentication file containing registry credentials ($FUNC_REGISTRY_AUTHFILE)")
// Function-Context Flags:
// Options whose value is available on the function with context only
// (persisted but not globally configurable)
builderImage := f.Build.BuilderImages[f.Build.Builder]
cmd.Flags().String("builder-image", builderImage,
"Specify a custom builder image for use by the builder other than its default. ($FUNC_BUILDER_IMAGE)")
cmd.Flags().StringP("base-image", "", f.Build.BaseImage,
"Override the base image for your function (host builder only)")
cmd.Flags().StringP("image", "i", f.Image,
"Full image name in the form [registry]/[namespace]/[name]:[tag]@[digest]. This option takes precedence over --registry. Specifying digest is optional, but if it is given, 'build' and 'push' phases are disabled. ($FUNC_IMAGE)")
cmd.Flags().StringArrayP("env", "e", []string{},
"Environment variable to set in the form NAME=VALUE. "+
"You may provide this flag multiple times for setting multiple environment variables. "+
"To unset, specify the environment variable name followed by a \"-\" (e.g., NAME-).")
cmd.Flags().String("domain", f.Domain,
"Domain to use for the function's route. Cluster must be configured with domain matching for the given domain (ignored if unrecognized) ($FUNC_DOMAIN)")
cmd.Flags().StringP("git-url", "g", f.Build.Git.URL,
"Repository url containing the function to build ($FUNC_GIT_URL)")
cmd.Flags().StringP("git-branch", "t", f.Build.Git.Revision,
"Git revision (branch) to be used when deploying via the Git repository ($FUNC_GIT_BRANCH)")
cmd.Flags().StringP("git-dir", "d", f.Build.Git.ContextDir,
"Directory in the Git repository containing the function (default is the root) ($FUNC_GIT_DIR)")
cmd.Flags().BoolP("remote", "R", f.Local.Remote,
"Trigger a remote deployment. Default is to deploy and build from the local system ($FUNC_REMOTE)")
cmd.Flags().StringP("remote-storage-class", "", f.Build.RemoteStorageClass,
"Specify a storage class to use for the volume on-cluster during remote builds")
cmd.Flags().String("pvc-size", f.Build.PVCSize,
"When triggering a remote deployment, set a custom volume size to allocate for the build operation ($FUNC_PVC_SIZE)")
cmd.Flags().String("service-account", f.Deploy.ServiceAccountName,
"Service account to be used in the deployed function ($FUNC_SERVICE_ACCOUNT)")
cmd.Flags().String("deployer", f.Deploy.Deployer,
fmt.Sprintf("Type of deployment to use: '%s' for Knative Service (default) or '%s' for Kubernetes Deployment ($FUNC_DEPLOY_TYPE)", knative.KnativeDeployerName, k8s.KubernetesDeployerName))
// Static Flags:
// Options which have static defaults only (not globally configurable nor
// persisted with the function)
cmd.Flags().String("build", "auto",
"Build the function. [auto|true|false]. ($FUNC_BUILD)")
cmd.Flags().Lookup("build").NoOptDefVal = "true" // register `--build` as equivalient to `--build=true`
cmd.Flags().BoolP("push", "u", true,
"Push the function image to registry before deploying. ($FUNC_PUSH)")
cmd.Flags().String("platform", "",
"Optionally specify a specific platform to build for (e.g. linux/amd64). ($FUNC_PLATFORM)")
cmd.Flags().StringP("username", "", "",
"Username to use when pushing to the registry.")
cmd.Flags().StringP("password", "", "",
"Password to use when pushing to the registry.")
cmd.Flags().StringP("token", "", "",
"Token to use when pushing to the registry.")
cmd.Flags().BoolP("build-timestamp", "", false, "Use the actual time as the created time for the docker image. This is only useful for buildpacks builder.")
cmd.Flags().StringP("namespace", "n", defaultNamespace(f, false),
"Deploy into a specific namespace. Will use the function's current namespace by default if already deployed, and the currently active context if it can be determined. ($FUNC_NAMESPACE)")
// Temporarily Hidden Basic Auth Flags
// Username, Password and Token flags, which plumb through basic auth, are
// currently only available on "host" builder.
_ = cmd.Flags().MarkHidden("username")
_ = cmd.Flags().MarkHidden("password")
_ = cmd.Flags().MarkHidden("token")
// Oft-shared flags:
addConfirmFlag(cmd, cfg.Confirm)
addPathFlag(cmd)
addVerboseFlag(cmd, cfg.Verbose)
// Tab Completion
if err := cmd.RegisterFlagCompletionFunc("builder", CompleteBuilderList); err != nil {
fmt.Println("internal: error while calling RegisterFlagCompletionFunc: ", err)
}
if err := cmd.RegisterFlagCompletionFunc("builder-image", CompleteBuilderImageList); err != nil {
fmt.Println("internal: error while calling RegisterFlagCompletionFunc: ", err)
}
if err := cmd.RegisterFlagCompletionFunc("deployer", CompleteDeployerList); err != nil {
fmt.Println("internal: error while calling RegisterFlagCompletionFunc: ", err)
}
return cmd
}
// wrapInvalidKubeconfigError returns a user-friendly error for invalid kubeconfig paths
func wrapInvalidKubeconfigError(err error) error {
kubeconfigPath := os.Getenv("KUBECONFIG")
if kubeconfigPath == "" {
kubeconfigPath = "~/.kube/config (default)"
}
return fmt.Errorf(`%w
The kubeconfig file at '%s' does not exist or is not accessible.
Try this:
export KUBECONFIG=~/.kube/config Use default kubeconfig
kubectl config view Verify current config
ls -la ~/.kube/config Check if config file exists
For more options, run 'func deploy --help'`, fn.ErrInvalidKubeconfig, kubeconfigPath)
}
// wrapClusterNotAccessibleError returns a user-friendly error for cluster connection failures
func wrapClusterNotAccessibleError(err error) error {
errMsg := err.Error()
// Case 1: Empty/no cluster configuration in kubeconfig
if strings.Contains(errMsg, "no configuration has been provided") ||
strings.Contains(errMsg, "invalid configuration") {
return fmt.Errorf(`%w
Cannot connect to Kubernetes cluster. No valid cluster configuration found.
Try this:
minikube start Start Minikube cluster
kind create cluster Start Kind cluster
kubectl cluster-info Verify cluster is running
kubectl config get-contexts List available contexts
For more options, run 'func deploy --help'`, fn.ErrClusterNotAccessible)
}
// Case 2: Cluster is down, network issues, auth errors, etc
return fmt.Errorf(`%w
Cannot connect to Kubernetes cluster.
Try this:
kubectl cluster-info Verify cluster is accessible
minikube status Check Minikube cluster status
kubectl get nodes Test cluster connection
For more options, run 'func deploy --help'`, fn.ErrClusterNotAccessible)
}
func runDeploy(cmd *cobra.Command, newClient ClientFactory) (err error) {
var (
cfg deployConfig
f fn.Function
)
// Initialize config first
cfg = newDeployConfig(cmd)
// Create function object to check if initialized
if f, err = fn.NewFunction(cfg.Path); err != nil {
return
}
// Check if function exists BEFORE prompting for config
if !f.Initialized() {
if !cfg.Remote || f.Build.Git.URL == "" {
// Only error if this is not a fully remote build
// Layer 2: Wrap technical error with CLI-specific guidance
var errNotInit *fn.ErrNotInitialized
notInitErr := fn.NewErrNotInitialized(f.Root)
if errors.As(notInitErr, &errNotInit) {
return wrapNotInitializedError(notInitErr, "deploy")
}
return notInitErr
} else {
// TODO: this case is not supported because the pipeline
// implementation requires the function's name, which is in the
// remote repository. We should inspect the remote repository.
// For now, give a more helpful error.
return errors.New("please ensure the function's source is also available locally")
}
}
// Now that we know function exists, proceed with prompting
if cfg, err = cfg.Prompt(); err != nil {
// Layer 2: Catch technical errors and provide CLI-specific user-friendly messages
if errors.Is(err, fn.ErrRegistryRequired) {
return wrapRegistryRequiredError(err, "deploy")
}
return
}
if err = cfg.Validate(cmd); err != nil {
// Layer 2: Catch technical errors and provide CLI-specific user-friendly messages
if errors.Is(err, fn.ErrInvalidDomain) {
return fmt.Errorf(`%w
Domain names must be valid DNS subdomains:
- Lowercase letters, numbers, hyphens (-), and dots (.) only
- Start and end with a letter or number
- Max 253 characters total, each part between dots max 63 characters
Valid examples:
func deploy --registry ghcr.io/user --domain example.com
func deploy --registry ghcr.io/user --domain api.example.com
Note: Domain must be configured on your Knative cluster, or it will be ignored.
For more options, run 'func deploy --help'`, err)
}
if errors.Is(err, fn.ErrInvalidNamespace) {
return fmt.Errorf(`%w
Invalid namespace name. Kubernetes namespaces must:
- Contain only lowercase letters, numbers, and hyphens (-)
- Start with a letter and end with a letter or number
- Be 63 characters or less
Valid examples:
func deploy --namespace myapp
func deploy --namespace my-app-123
For more options, run 'func deploy --help'`, err)
}
if errors.Is(err, fn.ErrConflictingImageAndRegistry) {
return fmt.Errorf(`%w
Cannot use both --image and --registry together. Choose one:
Use --image for complete image name:
func deploy --image example.com/user/myfunc
Use --registry for automatic naming:
func deploy --registry example.com/user
Note: FUNC_REGISTRY environment variable doesn't conflict with --image flag
For more options, run 'func deploy --help'`, err)
}
if errors.Is(err, fn.ErrPlatformNotSupported) {
return fmt.Errorf(`%w
The --platform flag is only supported with the S2I builder.
Try this:
func deploy --registry <registry> --builder=s2i --platform linux/amd64
Or remove the --platform flag:
func deploy --registry <registry>
For more options, run 'func deploy --help'`, err)
}
return
}
if f, err = cfg.Configure(f); err != nil { // Updates f with deploy cfg
return
}
cmd.SetContext(cfg.WithValues(cmd.Context())) // Some optional settings are passed via context
changingNamespace := func(f fn.Function) bool {
// We're changing namespace if:
return f.Deploy.Namespace != "" && // it's already deployed
f.Namespace != "" && // a specific (new) namespace is requested
(f.Namespace != f.Deploy.Namespace) // and it's different
}
// If we're changing namespace in an OpenShift cluster, we have to
// also update the registry because there is a registry per namespace,
// and their name includes the namespace.
// This saves needing a manual flag ``--registry={destination namespace registry}``
if changingNamespace(f) && k8s.IsOpenShift() {
// TODO(lkingland): this appears to force use of the openshift
// internal registry.
f.Registry = "image-registry.openshift-image-registry.svc:5000/" + f.Namespace
if cfg.Verbose {
fmt.Fprintf(cmd.OutOrStdout(), "Info: Overriding openshift registry to %s\n", f.Registry)
}
}
// Informative non-error messages regarding the final deployment request
printDeployMessages(cmd.OutOrStdout(), f)
// Get options based on the value of the config such as concrete impls
// of builders and pushers based on the value of the --builder flag
clientOptions, err := cfg.clientOptions()
if err != nil {
return
}
client, done := newClient(ClientConfig{Verbose: cfg.Verbose, InsecureSkipVerify: cfg.RegistryInsecure}, clientOptions...)
defer done()
// Deploy
if cfg.Remote {
var url string
// Invoke a remote build/push/deploy pipeline
// Returned is the function with fields like Registry, f.Deploy.Image &
// f.Deploy.Namespace populated.
if url, f, err = client.RunPipeline(cmd.Context(), f); err != nil {
if errors.Is(err, fn.ErrInvalidKubeconfig) {
return wrapInvalidKubeconfigError(err)
}
if errors.Is(err, fn.ErrClusterNotAccessible) {
return wrapClusterNotAccessibleError(err)
}
return
}
fmt.Fprintf(cmd.OutOrStdout(), "Function Deployed at %v\n", url)
} else {
var buildOptions []fn.BuildOption
if buildOptions, err = cfg.buildOptions(); err != nil {
return
}
var (
digested bool
justBuilt bool
justPushed bool
)
// Validate the image and check whether its digested or not
if cfg.Image != "" {
digested, err = isDigested(cfg.Image)
if err != nil {
return
}
// image is valid and undigested
if !digested {
f.Deploy.Image = cfg.Image
}
}
// If user provided --image with digest, they are requesting that specific
// image to be used which means building phase should be skipped and image
// should be deployed as is
if digested {
f.Deploy.Image = cfg.Image
} else {
// NOT digested, build & push the Function unless specified otherwise
if f, justBuilt, err = build(cmd, cfg.Build, f, client, buildOptions); err != nil {
return
}
if cfg.Push {
if f, justPushed, err = client.Push(cmd.Context(), f); err != nil {
return
}
}
// TODO: gauron99 - temporary fix for undigested image direct deploy
// (w/out build) This might be more complex to do than leaving like this
// image digests are created via the registry on push.
if (justBuilt || justPushed) && f.Build.Image != "" {
// f.Build.Image is set in Push for now, just set it as a deployed image
f.Deploy.Image = f.Build.Image
}
}
if f, err = client.Deploy(cmd.Context(), f, fn.WithDeploySkipBuildCheck(cfg.Build == "false")); err != nil {
if errors.Is(err, fn.ErrInvalidKubeconfig) {
return wrapInvalidKubeconfigError(err)
}
if errors.Is(err, fn.ErrClusterNotAccessible) {
return wrapClusterNotAccessibleError(err)
}
return
}
}
// Write
if err = f.Write(); err != nil {
return
}
// Stamp is a performance optimization: treat the function as being built
// (cached) unless the fs changes.
// Updates the build stamp because building must have been accomplished
// during this process, and a future call to deploy without any appreciable
// changes to the filesystem should not rebuild again unless `--build`
return f.Stamp()
}
// build when flag == 'auto' and the function is out-of-date, or when the
// flag value is explicitly truthy such as 'true' or '1'. Error if flag
// is neither 'auto' nor parseable as a boolean. Return CLI-specific error
// message verbeage suitable for both Deploy and Run commands which feature an
// optional build step. Boolean return value signifies if the image has gone
// through a build process.
func build(cmd *cobra.Command, flag string, f fn.Function, client *fn.Client, buildOptions []fn.BuildOption) (fn.Function, bool, error) {
var err error
if flag == "auto" {
if f.Built() {
fmt.Fprintln(cmd.OutOrStdout(), "function up-to-date. Force rebuild with --build")
return f, false, nil
} else {
if f, err = client.Build(cmd.Context(), f, buildOptions...); err != nil {
return f, false, err
}
}
} else if build, _ := strconv.ParseBool(flag); build {
if f, err = client.Build(cmd.Context(), f, buildOptions...); err != nil {
return f, false, err
}
} else if _, err = strconv.ParseBool(flag); err != nil {
return f, false, fmt.Errorf("invalid value for the build flag (%q), valid value is either 'auto' or a boolean", flag)
} else if !build {
return f, false, nil
}
return f, true, nil
}
func NewRegistryValidator(path string) survey.Validator {
return func(val interface{}) error {
// if the value passed in is the zero value of the appropriate type
if len(val.(string)) == 0 {
return fn.ErrRegistryRequired
}
f, err := fn.NewFunction(path)
if err != nil {
return err
}
// Set the function's registry to that provided
f.Registry = val.(string)
_, err = f.ImageName() //image can be derived without any error
if err != nil {
return fmt.Errorf("invalid registry [%q]: %w", val.(string), err)
}
return nil
}
}
// ValidateBuilder ensures that the given builder is one that the CLI
// knows how to instantiate, returning a builkder.ErrUnknownBuilder otherwise.
func ValidateBuilder(name string) (err error) {
for _, known := range KnownBuilders() {
if name == known {
return
}
}
return builders.ErrUnknownBuilder{Name: name, Known: KnownBuilders()}
}
// KnownBuilders are a typed string slice of builder short names which this
// CLI understands. Includes a customized String() representation intended
// for use in flags and help text.
func KnownBuilders() builders.Known {
// The set of builders supported by this CLI will likely always equate to
// the set of builders enumerated in the builders pacakage.
// However, future third-party integrations may support less than, or more
// builders, and certain environmental considerations may alter this list.
// Also a good place to stick feature-flags.
return builders.All()
}
type deployConfig struct {
buildConfig // further embeds config.Global
// Perform build using the settings from the embedded buildConfig struct.
// Acceptable values are the keyword 'auto', or a truthy value such as
// 'true', 'false, '1' or '0'.
Build string
// Env variables. May include removals using a "-"
Env []string
// Domain to use for the function's route. Default is to let the cluster
// apply its default. If configured to use domain matching, the given domain
// will be used. This configuration, in short, is to configure the
// cluster's config-domain map to match on the `func.domain` label and use
// its value as the domain... presuming it is one of those explicitly
// enumerated. This allows a function to be deployed explicitly choosing
// a route from one of the domains in a cluster with multiple configured
// domains. Example:
// func create -l go hello && func deploy --domain domain2.org
// -> Func created as hello.[namespace].domain2.org
// This can also be useful to configure a cluster to deploy functions at
// the domain root when requested, but only be cluster-local (unexposed) by
// default. This is accomplished by configuring the cluster-domain map to
// have the domain "cluster.local" as the default (empty selector), and
// the domain map template to omit the namespace interstitial.
// Example:
// func create -l go myclusterservice && func deploy
// -> func creates myclusterservice.cluster.local which is not exposed
// publicly outside the cluster
// func create -l go www && func deploy --domain example.com
// -> func deploys www.example.com as a publicly exposed service.
// TODO: allow for a simplified syntax of simply using the function's name
// as its route, and automatically parse off the domain suffix and validate
// the prefix is a dns label (ideally even validating the domain suffix is
// currently available and configured on the cluster).
// Example:
// func create -l go www.example.com
// -> func creates service www, with label func.domain as example.com, which
// is one which the cluster has configured to server, so it is deployed with
// a publicly accessible route
// -> func create -l go myclusterservice.cluster.local
// is equivalent to `func create -l go myclusterservice`
// All func commands which operate on function name now instead can use
// the FWDN. Example `func delete www.example.com`
Domain string
// Git branch for remote builds
GitBranch string
// Directory in the git repo where the function is located
GitDir string
// Git repo url for remote builds
GitURL string
// Namespace override for the deployed function. If provided, the
// underlying platform will be instructed to deploy the function to the given
// namespace (if such a setting is applicable; such as for Kubernetes
// clusters). If not provided, the currently configured namespace will be
// used. For instance, that which would be used by default by `kubectl`
// (~/.kube/config) in the case of Kubernetes.
Namespace string
//Service account to be used in deployed function
ServiceAccountName string
// Deployer specifies the type of deployment: "knative" or "raw"
Deployer string
// Remote indicates the deployment (and possibly build) process are to
// be triggered in a remote environment rather than run locally.
Remote bool
// RemoteStorageClass defines the storage class to use for the remote
// volume when building on-cluster.
RemoteStorageClass string
// PVCSize configures the PVC size used by the pipeline if --remote flag is set.
PVCSize string
// Timestamp the built contaienr with the current date and time.
// This is currently only supported by the Pack builder.
Timestamp bool
}
// newDeployConfig creates a buildConfig populated from command flags and
// environment variables; in that precedence.
func newDeployConfig(cmd *cobra.Command) deployConfig {
cfg := deployConfig{
buildConfig: newBuildConfig(),
Build: viper.GetString("build"),
Env: viper.GetStringSlice("env"),
Domain: viper.GetString("domain"),
GitBranch: viper.GetString("git-branch"),
GitDir: viper.GetString("git-dir"),
GitURL: viper.GetString("git-url"),
Namespace: viper.GetString("namespace"),
Remote: viper.GetBool("remote"),
RemoteStorageClass: viper.GetString("remote-storage-class"),
PVCSize: viper.GetString("pvc-size"),
Timestamp: viper.GetBool("build-timestamp"),
ServiceAccountName: viper.GetString("service-account"),
Deployer: viper.GetString("deployer"),
}
// NOTE: .Env should be viper.GetStringSlice, but this returns unparsed
// results and appears to be an open issue since 2017:
// https://github.com/spf13/viper/issues/380
var err error
if cfg.Env, err = cmd.Flags().GetStringArray("env"); err != nil {
fmt.Fprintf(cmd.OutOrStdout(), "error reading envs: %v", err)
}
return cfg
}
// Configure the given function. Updates a function struct with all
// configurable values. Note that the config already includes function's
// current values, as they were passed through via flag defaults.
func (c deployConfig) Configure(f fn.Function) (fn.Function, error) {
var err error
// Bubble configure request
//
// The member values on the config object now take absolute precedence
// because they include 1) static config 2) user's global config
// 3) Environment variables and 4) flag values (which were set with their
// default being 1-3).
f = c.buildConfig.Configure(f) // also configures .buildConfig.Global
// Configure basic members
f.Domain = c.Domain
f.Namespace = c.Namespace
f.Build.Git.URL = c.GitURL
f.Build.Git.ContextDir = c.GitDir
f.Build.Git.Revision = c.GitBranch // TODO: should match; perhaps "refSpec"
f.Build.RemoteStorageClass = c.RemoteStorageClass
f.Deploy.ServiceAccountName = c.ServiceAccountName
f.Deploy.Deployer = c.Deployer
f.Local.Remote = c.Remote
// PVCSize
// If a specific value is requested, ensure it parses as a resource.Quantity
if c.PVCSize != "" {
if _, err = resource.ParseQuantity(c.PVCSize); err != nil {
return f, fmt.Errorf("cannot parse PVC size %q. %w", c.PVCSize, err)
}
f.Build.PVCSize = c.PVCSize
}
// Envs
// Preprocesses any Envs provided (which may include removals) into a final
// set
f.Run.Envs, err = applyEnvs(f.Run.Envs, c.Env)
if err != nil {
return f, err
}
// .Revision
// TODO: the system should support specifying revision (refSpec) as a URL
// fragment (<url>[#<refspec>]) throughout, which, when implemented, removes
// the need for the below split into separate members:
if parts := strings.SplitN(c.GitURL, "#", 2); len(parts) == 2 {
f.Build.Git.URL = parts[0]
f.Build.Git.Revision = parts[1]
}
return f, nil
}
// Apply Env additions/removals to a set of extant envs, returning the final
// merged list.
func applyEnvs(current []fn.Env, args []string) (final []fn.Env, err error) {
// TODO: validate env test cases completely validate this functionality
// Parse and Merge
inserts, removals, err := util.OrderedMapAndRemovalListFromArray(args, "=")
if err != nil {
return
}
final, _, err = mergeEnvs(current, inserts, removals)
return
}
// Prompt the user with value of config members, allowing for interactive changes.
// Skipped if not in an interactive terminal (non-TTY), or if --yes (agree to
// all prompts) was explicitly set.
func (c deployConfig) Prompt() (deployConfig, error) {
var err error
if c.buildConfig, err = c.buildConfig.Prompt(); err != nil {
return c, err
}
if !interactiveTerminal() || !c.Confirm {
return c, nil
}
var qs = []*survey.Question{
{
Name: "namespace",
Prompt: &survey.Input{
Message: "Destination namespace:",
Default: c.Namespace,
},
},
{
Name: "remote",
Prompt: &survey.Confirm{
Message: "Trigger a remote (on-cluster) build?",
Default: c.Remote,
},
},
}
if err = survey.Ask(qs, &c); err != nil {
return c, err
}
if c.Remote {
qs = []*survey.Question{
{
Name: "GitURL",
Prompt: &survey.Input{
Message: "URL to Git Repository for the remote to use (default is to send local source code)",
Default: c.GitURL,
},
},
}
if err = survey.Ask(qs, &c); err != nil {
return c, err
}
}
// TODO: prompt for optional additional git settings here:
// if c.GitURL != "" {
// }
return c, err
}
// Validate the config passes an initial consistency check
func (c deployConfig) Validate(cmd *cobra.Command) (err error) {
// Bubble validation
if err = c.buildConfig.Validate(cmd); err != nil {
return
}
// Validate domain format if provided
if c.Domain != "" {
if err = utils.ValidateDomain(c.Domain); err != nil {
// Wrap the validation error as fn.ErrInvalidDomain for layer consistency
return fn.ErrInvalidDomain
}
}
// Validate namespace format if provided
if c.Namespace != "" {
if err = utils.ValidateNamespace(c.Namespace); err != nil {
// Wrap the validation error as fn.ErrInvalidNamespace for layer consistency
return fn.ErrInvalidNamespace
}
}
// Check Image Digest was included
var digest bool
if c.Image != "" {
if digest, err = isDigested(c.Image); err != nil {
return
}
}
// --build can be "auto"|true|false
if c.Build != "auto" {
if _, err := strconv.ParseBool(c.Build); err != nil {
return fmt.Errorf("unrecognized value for --build '%v'. Accepts 'auto', 'true' or 'false' (or similarly truthy value)", c.Build)
}
}
// Can not enable build when specifying an --image with digest (already built)
truthy := func(s string) bool {
v, _ := strconv.ParseBool(s)
return v
}
// Can not build when specifying an --image with digest
if digest && truthy(c.Build) {
return errors.New("building can not be enabled when using an image with digest")
}
// Can not push when specifying an --image with digest
if digest && c.Push {
return errors.New("pushing is not valid when specifying an image with digest")
}
// Git references can only be supplied explicitly when coupled with --remote
// See `printDeployMessages` which issues informative messages to the user
// regarding this potentially confusing nuance.
if !c.Remote && (cmd.Flags().Changed("git-url") || cmd.Flags().Changed("git-dir") || cmd.Flags().Changed("git-branch")) {
return errors.New("git settings (--git-url --git-dir and --git-branch) are only applicable when triggering remote deployments (--remote)")
}
// Git URL can contain at maximum one '#'
urlParts := strings.Split(c.GitURL, "#")
if len(urlParts) > 2 {
return fmt.Errorf("invalid --git-url '%v'", c.GitURL)
}
// NOTE: There is no explicit check for --registry or --image here, because
// this logic is baked into core, which will validate the cases and return
// an fn.ErrNameRequired, fn.ErrImageRequired etc. as needed.
return
}
// clientOptions returns client options specific to deploy, including the appropriate deployer
func (c deployConfig) clientOptions() ([]fn.Option, error) {
// Start with build config options
o, err := c.buildConfig.clientOptions()
if err != nil {
return o, err
}
t := newTransport(c.RegistryInsecure)
creds := newCredentialsProvider(config.Dir(), t, c.RegistryAuthfile)
// Override the pipelines provider to use custom credentials
// This is needed for remote builds (deploy --remote)
o = append(o, fn.WithPipelinesProvider(newTektonPipelinesProvider(creds, c.Verbose)))
// Add the appropriate deployer based on deploy type
deployer := c.Deployer
if deployer == "" {
deployer = knative.KnativeDeployerName // default to knative for backwards compatibility
}
switch deployer {
case knative.KnativeDeployerName:
o = append(o, fn.WithDeployer(newKnativeDeployer(c.Verbose)))
case k8s.KubernetesDeployerName:
o = append(o, fn.WithDeployer(newK8sDeployer(c.Verbose)))
default:
return o, fmt.Errorf("unsupported deploy type: %s (supported: %s, %s)", deployer, knative.KnativeDeployerName, k8s.KubernetesDeployerName)
}
return o, nil
}
// printDeployMessages to the output. Non-error deployment messages.
func printDeployMessages(out io.Writer, f fn.Function) {
digest, err := isDigested(f.Image)
if err == nil && digest {
fmt.Fprintf(out, "Deploying image '%v', which has a digest. Build and push are disabled.\n", f.Image)
}
// Namespace
// ---------
currentNamespace := f.Deploy.Namespace // will be "" if no initialed f at path.
targetNamespace := f.Namespace
if targetNamespace == "" {
return
}
// If creating a duplicate deployed function in a different
// namespace.
if targetNamespace != currentNamespace && currentNamespace != "" {
fmt.Fprintf(out, "Info: chosen namespace has changed from '%s' to '%s'. Undeploying function from '%s' and deploying new in '%s'.\n", currentNamespace, targetNamespace, currentNamespace, targetNamespace)
}
// Namespace Changing
// -------------------
// If the target namespace is provided but differs from active, warn because
// the function won't be visible to other commands such as kubectl unless
// context namespace is switched.
activeNamespace, err := k8s.GetDefaultNamespace()
if err == nil && targetNamespace != "" && targetNamespace != activeNamespace {
fmt.Fprintf(out, "Warning: namespace chosen is '%s', but currently active namespace is '%s'. Continuing with deployment to '%s'.\n", targetNamespace, activeNamespace, targetNamespace)
}
// Git Args
// -----------------
// Print a warning if the function already contains Git attributes, but the
// current invocation is not remote. (providing Git attributes directly
// via flags without --remote will error elsewhere).
//
// When invoking a remote build with --remote, the --git-X arguments
// are persisted to the local function's source code such that the reference
// is retained. Subsequent runs of deploy then need not have these arguments
// present.
//
// However, when building _locally_ thereafter, the deploy command should
// prefer the local source code, ignoring the values for --git-url etc.
// Since this might be confusing, a warning is issued below that the local
// function source does include a reference to a git repository, but that it
// will be ignored in favor of the local source code since --remote was not
// specified.
// TODO update names of these to Source--Revision--Dir
if !f.Local.Remote && (f.Build.Git.URL != "" || f.Build.Git.Revision != "" || f.Build.Git.ContextDir != "") {
fmt.Fprintf(out, "Warning: git settings are only applicable when running with --remote. Local source code will be used.")
}