-
Notifications
You must be signed in to change notification settings - Fork 71
Expand file tree
/
Copy pathdeploy.go
More file actions
1304 lines (1179 loc) · 44.4 KB
/
deploy.go
File metadata and controls
1304 lines (1179 loc) · 44.4 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 compute
import (
"context"
"errors"
"fmt"
"io"
"io/fs"
"net/http"
"os"
"os/signal"
"path/filepath"
"strconv"
"strings"
"syscall"
"time"
"github.com/kennygrant/sanitize"
"github.com/mholt/archiver/v3"
"github.com/fastly/go-fastly/v12/fastly"
"github.com/fastly/cli/pkg/api"
"github.com/fastly/cli/pkg/api/undocumented"
"github.com/fastly/cli/pkg/argparser"
"github.com/fastly/cli/pkg/commands/compute/setup"
"github.com/fastly/cli/pkg/debug"
fsterr "github.com/fastly/cli/pkg/errors"
"github.com/fastly/cli/pkg/global"
"github.com/fastly/cli/pkg/internal/beacon"
"github.com/fastly/cli/pkg/lookup"
"github.com/fastly/cli/pkg/manifest"
"github.com/fastly/cli/pkg/text"
"github.com/fastly/cli/pkg/undo"
)
const (
manageServiceBaseURL = "https://manage.fastly.com/configure/services/"
trialNotActivated = "Valid values for 'type' are: 'vcl'"
)
// ErrPackageUnchanged is an error that indicates the package hasn't changed.
var ErrPackageUnchanged = errors.New("package is unchanged")
// DeployCommand deploys an artifact previously produced by build.
type DeployCommand struct {
argparser.Base
manifestPath string
// NOTE: these are public so that the "publish" composite command can set the
// values appropriately before calling the Exec() function.
Comment argparser.OptionalString
Dir string
Domain string
Env string
NoDefaultDomain argparser.OptionalBool
PackagePath string
ServiceName argparser.OptionalServiceNameID
ServiceVersion argparser.OptionalServiceVersion
StatusCheckCode int
StatusCheckOff bool
StatusCheckPath string
StatusCheckTimeout int
SkipChangeDir bool // set by parent composite commands (e.g. serve, publish)
}
// NewDeployCommand returns a usable command registered under the parent.
func NewDeployCommand(parent argparser.Registerer, g *global.Data) *DeployCommand {
var c DeployCommand
c.Globals = g
c.CmdClause = parent.Command("deploy", "Deploy a package to a Fastly Compute service")
// NOTE: when updating these flags, be sure to update the composite command:
// `compute publish`.
c.RegisterFlag(argparser.StringFlagOpts{
Name: argparser.FlagServiceIDName,
Description: argparser.FlagServiceIDDesc,
Dst: &c.Globals.Manifest.Flag.ServiceID,
Short: 's',
})
c.RegisterFlag(argparser.StringFlagOpts{
Action: c.ServiceName.Set,
Name: argparser.FlagServiceName,
Description: argparser.FlagServiceNameDesc,
Dst: &c.ServiceName.Value,
})
c.RegisterFlag(argparser.StringFlagOpts{
Action: c.ServiceVersion.Set,
Description: argparser.FlagVersionDesc,
Dst: &c.ServiceVersion.Value,
Name: argparser.FlagVersionName,
})
c.CmdClause.Flag("comment", "Human-readable comment").Action(c.Comment.Set).StringVar(&c.Comment.Value)
c.CmdClause.Flag("dir", "Project directory (default: current directory)").Short('C').StringVar(&c.Dir)
c.CmdClause.Flag("domain", "The name of the domain associated to the package").StringVar(&c.Domain)
c.CmdClause.Flag("env", "The manifest environment config to use (e.g. 'stage' will attempt to read 'fastly.stage.toml')").StringVar(&c.Env)
c.CmdClause.Flag("no-default-domain", "Skip default domain creation").Action(c.NoDefaultDomain.Set).BoolVar(&c.NoDefaultDomain.Value)
c.CmdClause.Flag("package", "Path to a package tar.gz").Short('p').StringVar(&c.PackagePath)
c.CmdClause.Flag("status-check-code", "Set the expected status response for the service availability check").IntVar(&c.StatusCheckCode)
c.CmdClause.Flag("status-check-off", "Disable the service availability check").BoolVar(&c.StatusCheckOff)
c.CmdClause.Flag("status-check-path", "Specify the URL path for the service availability check").Default("/").StringVar(&c.StatusCheckPath)
c.CmdClause.Flag("status-check-timeout", "Set a timeout (in seconds) for the service availability check").Default("120").IntVar(&c.StatusCheckTimeout)
return &c
}
// Exec implements the command interface.
func (c *DeployCommand) Exec(in io.Reader, out io.Writer) (err error) {
manifestFilename := EnvironmentManifest(c.Env)
if c.Env != "" {
if c.Globals.Verbose() {
text.Info(out, EnvManifestMsg, manifestFilename, manifest.Filename)
}
}
wd, err := os.Getwd()
if err != nil {
return fmt.Errorf("failed to get current working directory: %w", err)
}
defer func() {
_ = os.Chdir(wd)
}()
c.manifestPath = filepath.Join(wd, manifestFilename)
var projectDir string
if !c.SkipChangeDir {
projectDir, err = ChangeProjectDirectory(c.Dir)
if err != nil {
return err
}
if projectDir != "" {
if c.Globals.Verbose() {
text.Info(out, ProjectDirMsg, projectDir)
}
c.manifestPath = filepath.Join(projectDir, manifestFilename)
}
}
spinner, err := text.NewSpinner(out)
if err != nil {
return err
}
err = spinner.Process(fmt.Sprintf("Verifying %s", manifestFilename), func(_ *text.SpinnerWrapper) error {
// The check for c.SkipChangeDir here is because we might need to attempt
// another read of the manifest file. To explain: if we're skipping the
// change of directory, it means we were called from a composite command,
// which has already changed directory to one that contains the fastly.toml
// file. This means we should try reading the manifest file from the new
// location as the potential ReadError() would have been based on the
// initial directory the CLI was invoked from.
if c.SkipChangeDir || projectDir != "" || c.Env != "" {
err = c.Globals.Manifest.File.Read(c.manifestPath)
} else {
err = c.Globals.Manifest.File.ReadError()
}
if err != nil {
// If the user hasn't specified a package to deploy, then we'll just check
// the read error and return it.
if c.PackagePath == "" {
if errors.Is(err, os.ErrNotExist) {
err = fsterr.ErrReadingManifest
}
c.Globals.ErrLog.Add(err)
return err
}
// Otherwise, we'll attempt to read the manifest from within the given
// package archive.
if err := readManifestFromPackageArchive(c.Globals.Manifest, c.PackagePath, manifestFilename); err != nil {
return err
}
if c.Globals.Verbose() {
text.Info(out, "Using %s within --package archive: %s\n\n", manifestFilename, c.PackagePath)
}
}
return nil
})
if err != nil {
return err
}
text.Break(out)
fnActivateTrial, serviceID, err := c.Setup(out)
if err != nil {
return err
}
noExistingService := serviceID == ""
undoStack := undo.NewStack()
undoStack.Push(func() error {
if noExistingService && serviceID != "" {
return c.CleanupNewService(serviceID, manifestFilename, out)
}
return nil
})
defer func(errLog fsterr.LogInterface) {
if err != nil {
errLog.Add(err)
}
undoStack.RunIfError(out, err)
}(c.Globals.ErrLog)
signalCh := make(chan os.Signal, 1)
signal.Notify(signalCh, syscall.SIGINT, syscall.SIGTERM)
go monitorSignals(signalCh, noExistingService, out, undoStack, spinner)
var serviceVersion *fastly.Version
if noExistingService {
serviceID, serviceVersion, err = c.NewService(manifestFilename, fnActivateTrial, spinner, in, out)
if err != nil {
return err
}
if serviceID == "" {
return nil // user declined service creation prompt
}
} else {
// ErrPackageUnchanged is returned AFTER identifying the service version.
// nosemgrep: trailofbits.go.invalid-usage-of-modified-variable.invalid-usage-of-modified-variable
serviceVersion, err = c.ExistingServiceVersion(serviceID, out)
if err != nil {
if errors.Is(err, ErrPackageUnchanged) {
text.Info(out, "Skipping package deployment, local and service version are identical. (service %s, version %d) ", serviceID, fastly.ToValue(serviceVersion.Number))
return nil
}
return err
}
if c.Globals.Manifest.File.Setup.Defined() && !c.Globals.Flags.Quiet {
text.Info(out, "\nProcessing of the %s [setup] configuration happens only for a new service. Once a service is created, any further changes to the service or its resources must be made manually.\n\n", manifestFilename)
}
}
var sr ServiceResources
serviceVersionNumber := fastly.ToValue(serviceVersion.Number)
// NOTE: A 'domain' resource isn't strictly part of the [setup] config.
// It's part of the implementation so that we can utilise the same interface.
// A domain is required regardless of whether it's a new service or existing.
sr.domains = &setup.Domains{
APIClient: c.Globals.APIClient,
AcceptDefaults: c.Globals.Flags.AcceptDefaults,
NoDefaultDomain: c.NoDefaultDomain.WasSet,
NonInteractive: c.Globals.Flags.NonInteractive,
PackageDomain: c.Domain,
RetryLimit: 5,
ServiceID: serviceID,
ServiceVersion: serviceVersionNumber,
Stdin: in,
Stdout: out,
Verbose: c.Globals.Verbose(),
}
if err = sr.domains.Validate(); err != nil {
errLogService(c.Globals.ErrLog, err, serviceID, serviceVersionNumber)
return fmt.Errorf("error configuring service domains: %w", err)
}
if noExistingService {
c.ConstructNewServiceResources(
&sr, serviceID, serviceVersionNumber, in, out,
)
}
if sr.domains.Missing() {
if err := sr.domains.Configure(); err != nil {
errLogService(c.Globals.ErrLog, err, serviceID, serviceVersionNumber)
return fmt.Errorf("error configuring service domains: %w", err)
}
}
if noExistingService {
if err = c.ConfigureServiceResources(sr, serviceID, serviceVersionNumber); err != nil {
return err
}
}
if sr.domains.Missing() {
sr.domains.Spinner = spinner
if err := sr.domains.Create(); err != nil {
c.Globals.ErrLog.AddWithContext(err, map[string]any{
"Accept defaults": c.Globals.Flags.AcceptDefaults,
"Auto-yes": c.Globals.Flags.AutoYes,
"Non-interactive": c.Globals.Flags.NonInteractive,
"Service ID": serviceID,
"Service Version": serviceVersion,
})
return err
}
}
if noExistingService {
if err = c.CreateServiceResources(sr, spinner, serviceID, serviceVersionNumber); err != nil {
return err
}
}
err = c.UploadPackage(spinner, serviceID, serviceVersionNumber)
if err != nil {
c.Globals.ErrLog.AddWithContext(err, map[string]any{
"Package path": c.PackagePath,
"Service ID": serviceID,
"Service Version": serviceVersion,
})
return err
}
if err = c.ProcessService(serviceID, serviceVersionNumber, spinner); err != nil {
return err
}
serviceURL, err := c.GetServiceURL(serviceID, serviceVersionNumber)
if err != nil {
return err
}
if !c.StatusCheckOff && noExistingService && serviceURL != "" {
c.StatusCheck(serviceURL, spinner, out)
}
if !noExistingService {
text.Break(out)
}
displayDeployOutput(out, manageServiceBaseURL, serviceID, serviceURL, serviceVersionNumber)
return nil
}
// StatusCheck checks the service URL and identifies when it's ready.
func (c *DeployCommand) StatusCheck(serviceURL string, spinner text.Spinner, out io.Writer) {
var (
err error
status int
)
if status, err = checkingServiceAvailability(serviceURL+c.StatusCheckPath, spinner, c); err != nil {
if re, ok := err.(fsterr.RemediationError); ok {
text.Warning(out, re.Remediation)
}
}
// Because the service availability can return an error (which we ignore),
// then we need to check for the 'no error' scenarios.
if err == nil {
switch {
case validStatusCodeRange(c.StatusCheckCode) && status != c.StatusCheckCode:
// If the user set a specific status code expectation...
text.Warning(out, "The service path `%s` responded with a status code (%d) that didn't match what was expected (%d).", c.StatusCheckPath, status, c.StatusCheckCode)
case !validStatusCodeRange(c.StatusCheckCode) && status >= http.StatusBadRequest:
// If no status code was specified, and the actual status response was an error...
text.Info(out, "The service path `%s` responded with a non-successful status code (%d). Please check your application code if this is an unexpected response.", c.StatusCheckPath, status)
default:
text.Break(out)
}
}
}
func displayDeployOutput(out io.Writer, manageServiceBaseURL, serviceID, serviceURL string, serviceVersion int) {
text.Description(out, "Manage this service at", fmt.Sprintf("%s%s", manageServiceBaseURL, serviceID))
if serviceURL != "" {
text.Description(out, "View this service at", serviceURL)
}
text.Success(out, "Deployed package (service %s, version %v)", serviceID, serviceVersion)
}
// validStatusCodeRange checks the status is a valid status code.
// e.g. >= 100 and <= 999.
func validStatusCodeRange(status int) bool {
if status >= 100 && status <= 999 {
return true
}
return false
}
// Setup prepares the environment.
//
// - Check if there is an API token missing.
// - Acquire the Service ID/Version.
// - Validate there is a package to deploy.
// - Determine if a trial needs to be activated on the user's account.
func (c *DeployCommand) Setup(out io.Writer) (fnActivateTrial Activator, serviceID string, err error) {
defaultActivator := func(_ string) error { return nil }
token, s := c.Globals.Token()
if s == lookup.SourceUndefined {
return defaultActivator, "", fsterr.ErrNoToken
}
// IMPORTANT: We don't handle the error when looking up the Service ID.
// This is because later in the Exec() flow we might create a 'new' service.
serviceID, source, flag, err := argparser.ServiceID(c.ServiceName, *c.Globals.Manifest, c.Globals.APIClient, c.Globals.ErrLog)
if err == nil && c.Globals.Verbose() {
argparser.DisplayServiceID(serviceID, flag, source, out)
}
if c.PackagePath == "" {
projectName, source := c.Globals.Manifest.Name()
if source == manifest.SourceUndefined {
return defaultActivator, serviceID, fsterr.ErrReadingManifest
}
c.PackagePath = filepath.Join("pkg", fmt.Sprintf("%s.tar.gz", sanitize.BaseName(projectName)))
}
err = validatePackage(c.PackagePath)
if err != nil {
c.Globals.ErrLog.AddWithContext(err, map[string]any{
"Package path": c.PackagePath,
})
return defaultActivator, serviceID, err
}
endpoint, _ := c.Globals.APIEndpoint()
fnActivateTrial = preconfigureActivateTrial(endpoint, token, c.Globals.HTTPClient, c.Globals.Env.DebugMode)
return fnActivateTrial, serviceID, err
}
// validatePackage checks the package and returns its path, which can change
// depending on the user flow scenario.
func validatePackage(pkgPath string) error {
pkgSize, err := packageSize(pkgPath)
if err != nil {
return fsterr.RemediationError{
Inner: fmt.Errorf("error reading package size: %w", err),
Remediation: "Run `fastly compute build` to produce a Compute package, alternatively use the --package flag to reference a package outside of the current project.",
}
}
if pkgSize > MaxPackageSize {
return fsterr.RemediationError{
Inner: fmt.Errorf("package size is too large (%d bytes)", pkgSize),
Remediation: fsterr.PackageSizeRemediation,
}
}
return validatePackageContent(pkgPath)
}
// readManifestFromPackageArchive extracts the manifest file from the given
// package archive file and reads it into memory.
func readManifestFromPackageArchive(data *manifest.Data, packageFlag, manifestFilename string) error {
dst, err := os.MkdirTemp("", fmt.Sprintf("%s-*", manifestFilename))
if err != nil {
return err
}
defer os.RemoveAll(dst)
if err = archiver.Unarchive(packageFlag, dst); err != nil {
return fmt.Errorf("error extracting package '%s': %w", packageFlag, err)
}
files, err := os.ReadDir(dst)
if err != nil {
return err
}
extractedDirName := files[0].Name()
manifestPath, err := locateManifest(filepath.Join(dst, extractedDirName), manifestFilename)
if err != nil {
return err
}
err = data.File.Read(manifestPath)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
err = fsterr.ErrReadingManifest
}
return err
}
return nil
}
// locateManifest attempts to find the manifest within the given path's
// directory tree.
func locateManifest(path, manifestFilename string) (string, error) {
root, err := filepath.Abs(path)
if err != nil {
return "", err
}
var foundManifest string
err = filepath.WalkDir(root, func(path string, entry fs.DirEntry, err error) error {
if err != nil {
return err
}
if !entry.IsDir() && filepath.Base(path) == manifestFilename {
foundManifest = path
return fsterr.ErrStopWalk
}
return nil
})
if err != nil {
// If the error isn't ErrStopWalk, then the WalkDir() function had an
// issue processing the directory tree.
if err != fsterr.ErrStopWalk {
return "", err
}
return foundManifest, nil
}
return "", fmt.Errorf("error locating manifest within the given path: %s", path)
}
// packageSize returns the size of the .tar.gz package.
//
// Reference:
// https://docs.fastly.com/products/compute-at-edge-billing-and-resource-limits#resource-limits
func packageSize(path string) (size int64, err error) {
fi, err := os.Stat(path)
if err != nil {
return size, err
}
return fi.Size(), nil
}
// Activator represents a function that calls an undocumented API endpoint for
// activating a Compute free trial on the given customer account.
//
// It is preconfigured with the Fastly API endpoint, a user token and a simple
// HTTP Client.
//
// This design allows us to pass an Activator rather than passing multiple
// unrelated arguments through several nested functions.
type Activator func(customerID string) error
// preconfigureActivateTrial activates a free trial on the customer account.
func preconfigureActivateTrial(endpoint, token string, httpClient api.HTTPClient, debugMode string) Activator {
debug, _ := strconv.ParseBool(debugMode)
return func(customerID string) error {
_, err := undocumented.Call(undocumented.CallOptions{
APIEndpoint: endpoint,
HTTPClient: httpClient,
Method: http.MethodPost,
Path: fmt.Sprintf(undocumented.EdgeComputeTrial, customerID),
Token: token,
Debug: debug,
})
if err != nil {
apiErr, ok := err.(undocumented.APIError)
if !ok {
return err
}
// 409 Conflict == The Compute trial has already been created.
if apiErr.StatusCode != http.StatusConflict {
return fmt.Errorf("%w: %d %s", err, apiErr.StatusCode, http.StatusText(apiErr.StatusCode))
}
}
return nil
}
}
// NewService handles creating a new service when no Service ID is found.
func (c *DeployCommand) NewService(manifestFilename string, fnActivateTrial Activator, spinner text.Spinner, in io.Reader, out io.Writer) (string, *fastly.Version, error) {
var (
err error
serviceID string
serviceVersion *fastly.Version
)
if !c.Globals.Flags.AutoYes && !c.Globals.Flags.NonInteractive {
text.Output(out, "There is no Fastly service associated with this package. To connect to an existing service add the Service ID to the %s file, otherwise follow the prompts to create a service now.\n\n", manifestFilename)
text.Output(out, "Press ^C at any time to quit.")
if c.Globals.Manifest.File.Setup.Defined() {
text.Info(out, "\nProcessing of the %s [setup] configuration happens only when there is no existing service. Once a service is created, any further changes to the service or its resources must be made manually.", manifestFilename)
}
text.Break(out)
answer, err := text.AskYesNo(out, "Create new service: [y/N] ", in)
if err != nil {
return serviceID, serviceVersion, err
}
if !answer {
return serviceID, serviceVersion, nil
}
text.Break(out)
}
defaultServiceName := c.Globals.Manifest.File.Name
var serviceName string
// The service name will be whatever is set in the --service-name flag.
// If the flag isn't set, and we're non-interactive, we'll use the default.
// If the flag isn't set, and we're interactive, we'll prompt the user.
switch {
case c.ServiceName.WasSet:
serviceName = c.ServiceName.Value
case c.Globals.Flags.AcceptDefaults || c.Globals.Flags.NonInteractive:
serviceName = defaultServiceName
default:
serviceName, err = text.Input(out, text.Prompt(fmt.Sprintf("Service name: [%s] ", defaultServiceName)), in)
if err != nil || serviceName == "" {
serviceName = defaultServiceName
}
}
// There is no service and so we'll do a one time creation of the service
//
// NOTE: we're shadowing the `serviceID` and `serviceVersion` variables.
serviceID, serviceVersion, err = createService(c.Globals, serviceName, fnActivateTrial, spinner, out)
if err != nil {
c.Globals.ErrLog.AddWithContext(err, map[string]any{
"Service name": serviceName,
})
return serviceID, serviceVersion, err
}
err = c.UpdateManifestServiceID(serviceID, c.manifestPath)
// NOTE: Skip error if --package flag is set.
//
// This is because the use of the --package flag suggests the user is not
// within a project directory. If that is the case, then we don't want the
// error to be returned because of course there is no manifest to update.
//
// If the user does happen to be in a project directory and they use the
// --package flag, then the above function call to update the manifest will
// have succeeded and so there will be no error.
if err != nil && c.PackagePath == "" {
c.Globals.ErrLog.AddWithContext(err, map[string]any{
"Service ID": serviceID,
})
return serviceID, serviceVersion, err
}
return serviceID, serviceVersion, nil
}
// createService creates a service to associate with the compute package.
//
// NOTE: If the creation of the service fails because the user has not
// activated a free trial, then we'll trigger the trial for their account.
func createService(
g *global.Data,
serviceName string,
fnActivateTrial Activator,
spinner text.Spinner,
out io.Writer,
) (serviceID string, serviceVersion *fastly.Version, err error) {
f := g.Flags
apiClient := g.APIClient
errLog := g.ErrLog
if !f.AcceptDefaults && !f.NonInteractive {
text.Break(out)
}
err = spinner.Start()
if err != nil {
return "", nil, err
}
msg := "Creating service"
spinner.Message(msg + "...")
service, err := apiClient.CreateService(context.TODO(), &fastly.CreateServiceInput{
Name: &serviceName,
Type: fastly.ToPointer("wasm"),
})
if err != nil {
if strings.Contains(err.Error(), trialNotActivated) {
user, err := apiClient.GetCurrentUser(context.TODO())
if err != nil {
err = fmt.Errorf("unable to identify user associated with the given token: %w", err)
spinner.StopFailMessage(msg)
spinErr := spinner.StopFail()
if spinErr != nil {
return "", nil, fmt.Errorf(text.SpinnerErrWrapper, spinErr, err)
}
return serviceID, serviceVersion, fsterr.RemediationError{
Inner: err,
Remediation: "To ensure you have access to the Compute platform we need your Customer ID. " + fsterr.AuthRemediation,
}
}
customerID := fastly.ToValue(user.CustomerID)
err = fnActivateTrial(customerID)
if err != nil {
err = fmt.Errorf("error creating service: you do not have the Compute free trial enabled on your Fastly account")
spinner.StopFailMessage(msg)
spinErr := spinner.StopFail()
if spinErr != nil {
return "", nil, fmt.Errorf(text.SpinnerErrWrapper, spinErr, err)
}
return serviceID, serviceVersion, fsterr.RemediationError{
Inner: err,
Remediation: fsterr.ComputeTrialRemediation,
}
}
errLog.AddWithContext(err, map[string]any{
"Service Name": serviceName,
"Customer ID": customerID,
})
spinner.StopFailMessage(msg)
err = spinner.StopFail()
if err != nil {
return "", nil, err
}
return createService(g, serviceName, fnActivateTrial, spinner, out)
}
spinner.StopFailMessage(msg)
spinErr := spinner.StopFail()
if spinErr != nil {
return "", nil, spinErr
}
errLog.AddWithContext(err, map[string]any{
"Service Name": serviceName,
})
return serviceID, serviceVersion, fmt.Errorf("error creating service: %w", err)
}
spinner.StopMessage(msg)
err = spinner.Stop()
if err != nil {
return "", nil, err
}
return fastly.ToValue(service.ServiceID), &fastly.Version{Number: fastly.ToPointer(1)}, nil
}
// CleanupNewService is executed if a new service flow has errors.
// It deletes the service, which will cause any contained resources to be deleted.
// It will also strip the Service ID from the fastly.toml manifest file.
func (c *DeployCommand) CleanupNewService(serviceID, manifestFilename string, out io.Writer) error {
text.Info(out, "\nCleaning up service\n\n")
err := c.Globals.APIClient.DeleteService(context.TODO(), &fastly.DeleteServiceInput{
ServiceID: serviceID,
})
if err != nil {
return err
}
text.Info(out, "Removing Service ID from %s\n\n", manifestFilename)
err = c.UpdateManifestServiceID("", c.manifestPath)
if err != nil {
return err
}
text.Output(out, "Cleanup complete")
return nil
}
// UpdateManifestServiceID updates the Service ID in the manifest.
//
// There are two scenarios where this function is called. The first is when we
// have a Service ID to insert into the manifest. The other is when there is an
// error in the deploy flow, and for which the Service ID will be set to an
// empty string (otherwise the service itself will be deleted while the
// manifest will continue to hold a reference to it).
func (c *DeployCommand) UpdateManifestServiceID(serviceID, manifestPath string) error {
if err := c.Globals.Manifest.File.Read(manifestPath); err != nil {
return fmt.Errorf("error reading %s: %w", manifestPath, err)
}
c.Globals.Manifest.File.ServiceID = serviceID
if err := c.Globals.Manifest.File.Write(manifestPath); err != nil {
return fmt.Errorf("error saving %s: %w", manifestPath, err)
}
return nil
}
// errLogService records the error, service id and version into the error log.
func errLogService(l fsterr.LogInterface, err error, sid string, sv int) {
l.AddWithContext(err, map[string]any{
"Service ID": sid,
"Service Version": sv,
})
}
// CompareLocalRemotePackage compares the local package files hash against the
// existing service package version and exits early with message if identical.
//
// NOTE: We can't avoid the first 'no-changes' upload after the initial deploy.
// This is because the fastly.toml manifest does actual change after first deploy.
// When user first deploys, there is no value for service_id.
// That version of the manifest is inside the package we're checking against.
// So on the second deploy, even if user has made no changes themselves, we will
// still upload that package because technically there was a change made by the
// CLI to add the Service ID. Any subsequent deploys will be aborted because
// there will be no changes made by the CLI nor the user.
func (c *DeployCommand) CompareLocalRemotePackage(serviceID string, version int) error {
filesHash, err := getFilesHash(c.PackagePath)
if err != nil {
return err
}
p, err := c.Globals.APIClient.GetPackage(context.TODO(), &fastly.GetPackageInput{
ServiceID: serviceID,
ServiceVersion: version,
})
// IMPORTANT: Skip error as some services won't have a package to compare.
// This happens in situations where a user will create the service outside of
// the CLI and then reference the Service ID in their fastly.toml manifest.
// In that scenario the service might just be an empty service and so trying
// to get the package from the service with 404.
if err == nil && p.Metadata != nil && filesHash == fastly.ToValue(p.Metadata.FilesHash) {
return ErrPackageUnchanged
}
return nil
}
// UploadPackage uploads the package to the specified service and version.
func (c *DeployCommand) UploadPackage(spinner text.Spinner, serviceID string, version int) error {
return spinner.Process("Uploading package", func(_ *text.SpinnerWrapper) error {
_, err := c.Globals.APIClient.UpdatePackage(context.TODO(), &fastly.UpdatePackageInput{
ServiceID: serviceID,
ServiceVersion: version,
PackagePath: fastly.ToPointer(c.PackagePath),
})
if err != nil {
return fmt.Errorf("error uploading package: %w", err)
}
return nil
})
}
// ServiceResources is a collection of backend objects created during setup.
// Objects may be nil.
type ServiceResources struct {
domains *setup.Domains
backends *setup.Backends
configStores *setup.ConfigStores
loggers *setup.Loggers
objectStores *setup.KVStores
kvStores *setup.KVStores
secretStores *setup.SecretStores
}
// ConstructNewServiceResources instantiates multiple [setup] config resources for a
// new Service to process.
func (c *DeployCommand) ConstructNewServiceResources(
sr *ServiceResources,
serviceID string,
serviceVersion int,
in io.Reader,
out io.Writer,
) {
sr.backends = &setup.Backends{
APIClient: c.Globals.APIClient,
AcceptDefaults: c.Globals.Flags.AcceptDefaults,
NonInteractive: c.Globals.Flags.NonInteractive,
ServiceID: serviceID,
ServiceVersion: serviceVersion,
Setup: c.Globals.Manifest.File.Setup.Backends,
Stdin: in,
Stdout: out,
}
sr.configStores = &setup.ConfigStores{
APIClient: c.Globals.APIClient,
AcceptDefaults: c.Globals.Flags.AcceptDefaults,
NonInteractive: c.Globals.Flags.NonInteractive,
ServiceID: serviceID,
ServiceVersion: serviceVersion,
Setup: c.Globals.Manifest.File.Setup.ConfigStores,
Stdin: in,
Stdout: out,
}
sr.loggers = &setup.Loggers{
Setup: c.Globals.Manifest.File.Setup.Loggers,
Stdout: out,
}
sr.objectStores = &setup.KVStores{
APIClient: c.Globals.APIClient,
AcceptDefaults: c.Globals.Flags.AcceptDefaults,
NonInteractive: c.Globals.Flags.NonInteractive,
ServiceID: serviceID,
ServiceVersion: serviceVersion,
Setup: c.Globals.Manifest.File.Setup.ObjectStores,
Stdin: in,
Stdout: out,
}
sr.kvStores = &setup.KVStores{
APIClient: c.Globals.APIClient,
AcceptDefaults: c.Globals.Flags.AcceptDefaults,
NonInteractive: c.Globals.Flags.NonInteractive,
ServiceID: serviceID,
ServiceVersion: serviceVersion,
Setup: c.Globals.Manifest.File.Setup.KVStores,
Stdin: in,
Stdout: out,
}
sr.secretStores = &setup.SecretStores{
APIClient: c.Globals.APIClient,
AcceptDefaults: c.Globals.Flags.AcceptDefaults,
NonInteractive: c.Globals.Flags.NonInteractive,
ServiceID: serviceID,
ServiceVersion: serviceVersion,
Setup: c.Globals.Manifest.File.Setup.SecretStores,
Stdin: in,
Stdout: out,
}
}
// ConfigureServiceResources calls the .Predefined() and .Configure() methods
// for each [setup] resource, which first checks if a [setup] config has been
// defined for the resource type, and if so it prompts the user for details.
func (c *DeployCommand) ConfigureServiceResources(sr ServiceResources, serviceID string, serviceVersion int) error {
// NOTE: A service can't be activated without at least one backend defined.
// This explains why the following block of code isn't wrapped in a call to
// the .Predefined() method, as the call to .Configure() will ensure the
// user is prompted regardless of whether there is a [setup.backends]
// defined in the fastly.toml configuration.
if err := sr.backends.Configure(); err != nil {
errLogService(c.Globals.ErrLog, err, serviceID, serviceVersion)
return fmt.Errorf("error configuring service backends: %w", err)
}
if sr.configStores.Predefined() {
if err := sr.configStores.Configure(); err != nil {
errLogService(c.Globals.ErrLog, err, serviceID, serviceVersion)
return fmt.Errorf("error configuring service config stores: %w", err)
}
}
if sr.loggers.Predefined() {
// NOTE: We don't handle errors from the Configure() method because we
// don't actually do anything other than display a message to the user
// informing them that they need to create a log endpoint and which
// provider type they should be. The reason we don't implement logic for
// creating logging objects is because the API input fields vary
// significantly between providers.
_ = sr.loggers.Configure()
}
if sr.objectStores.Predefined() {
if err := sr.objectStores.Configure(); err != nil {
errLogService(c.Globals.ErrLog, err, serviceID, serviceVersion)
return fmt.Errorf("error configuring service object stores: %w", err)
}
}
if sr.kvStores.Predefined() {
if err := sr.kvStores.Configure(); err != nil {
errLogService(c.Globals.ErrLog, err, serviceID, serviceVersion)
return fmt.Errorf("error configuring service kv stores: %w", err)
}
}
if sr.secretStores.Predefined() {
if err := sr.secretStores.Configure(); err != nil {
errLogService(c.Globals.ErrLog, err, serviceID, serviceVersion)
return fmt.Errorf("error configuring service secret stores: %w", err)
}
}
return nil
}
// CreateServiceResources makes API calls to create resources that have been
// defined in the fastly.toml [setup] configuration.
func (c *DeployCommand) CreateServiceResources(
sr ServiceResources,
spinner text.Spinner,
serviceID string,
serviceVersion int,
) error {
sr.backends.Spinner = spinner
sr.configStores.Spinner = spinner
sr.objectStores.Spinner = spinner
sr.kvStores.Spinner = spinner
sr.secretStores.Spinner = spinner
if err := sr.backends.Create(); err != nil {
c.Globals.ErrLog.AddWithContext(err, map[string]any{
"Accept defaults": c.Globals.Flags.AcceptDefaults,
"Auto-yes": c.Globals.Flags.AutoYes,
"Non-interactive": c.Globals.Flags.NonInteractive,
"Service ID": serviceID,
"Service Version": serviceVersion,
})
return err
}
if err := sr.configStores.Create(); err != nil {
c.Globals.ErrLog.AddWithContext(err, map[string]any{
"Accept defaults": c.Globals.Flags.AcceptDefaults,
"Auto-yes": c.Globals.Flags.AutoYes,
"Non-interactive": c.Globals.Flags.NonInteractive,
"Service ID": serviceID,
"Service Version": serviceVersion,
})
return err
}
if err := sr.objectStores.Create(); err != nil {
c.Globals.ErrLog.AddWithContext(err, map[string]any{
"Accept defaults": c.Globals.Flags.AcceptDefaults,
"Auto-yes": c.Globals.Flags.AutoYes,
"Non-interactive": c.Globals.Flags.NonInteractive,
"Service ID": serviceID,
"Service Version": serviceVersion,
})
return err
}
if err := sr.kvStores.Create(); err != nil {
c.Globals.ErrLog.AddWithContext(err, map[string]any{
"Accept defaults": c.Globals.Flags.AcceptDefaults,
"Auto-yes": c.Globals.Flags.AutoYes,
"Non-interactive": c.Globals.Flags.NonInteractive,
"Service ID": serviceID,
"Service Version": serviceVersion,