-
Notifications
You must be signed in to change notification settings - Fork 112
/
deployer.go
1779 lines (1508 loc) · 57.4 KB
/
deployer.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
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
// Copyright © 2017 Chef Software
// Package client contains all the business logic of the command line deployment
// tool. It knows how to talk to Habitat and the grpc client to communicate
// with the server.
package client
import (
"context"
"crypto/rand"
"fmt"
"io/ioutil"
"math/big"
"os"
"os/exec"
"path"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/sirupsen/logrus"
"google.golang.org/grpc/codes"
gstatus "google.golang.org/grpc/status"
dc "github.com/chef/automate/api/config/deployment"
api "github.com/chef/automate/api/interservice/deployment"
"github.com/chef/automate/components/automate-cli/pkg/status"
"github.com/chef/automate/components/automate-deployment/pkg/a1upgrade"
"github.com/chef/automate/components/automate-deployment/pkg/bootstrap"
"github.com/chef/automate/components/automate-deployment/pkg/cli"
"github.com/chef/automate/components/automate-deployment/pkg/deployment"
"github.com/chef/automate/components/automate-deployment/pkg/manifest"
"github.com/chef/automate/components/automate-deployment/pkg/preflight"
"github.com/chef/automate/components/automate-deployment/pkg/target"
"github.com/chef/automate/components/automate-deployment/pkg/toml"
"github.com/chef/automate/lib/io/fileutils"
"github.com/chef/automate/lib/platform/command"
"github.com/chef/automate/lib/platform/pg"
"github.com/chef/automate/lib/platform/sys"
"github.com/chef/automate/lib/user"
)
// deployTimeout is used as the timeout for the deployers initial
// connection to the deployment-service. The gRPC library has built-in
// retries. Thus, we set this to a high timeout to account for the
// fact that it may take some time for deployment service to start up.
var deployTimeout = 5 * time.Minute
const editConfigInstructions = `To change the configuration:
* Respond No to the "Are you ready to continue?" prompt,
* Edit the provided config file,
* Restart the upgrade using the edited config file:
`
const cancelUpgradeInstructionsFmt = `If you would prefer to cancel the upgrade, you will need to delete the following
file to return your Chef Automate v1 installation to a working state:
/var/opt/delivery/delivery/etc/maint.flag
Additionally, you will need to restart the stopped Chef Automate v1 processes
with the following command(s):
%s
Some components of Chef Automate v2 have already started. You can disable them
by running the following:
chef-automate stop
Please contact support@chef.io if you need further assistance.
`
const cancelUpgradeWithRestorePreamble = `
Please contact support@chef.io with the output of this command, along with the
logs of the affected services. You can capture the logs with the following
command:
chef-automate gather-logs --local-fallback
If you wish to cancel the upgrade, you will need to shut down Chef Automate v2,
disable maintenance mode for Chef Automate v1, and then restore Chef Automate
v1 from backup.
The following commands will stop Chef Automate v2 and disengage maintenance
mode on your Chef Automate v1 installation:
systemctl stop chef-automate
systemctl disable chef-automate
rm /var/opt/delivery/delivery/etc/maint.flag
`
const recoverFromFailedCredentialSave = `
To recover from a failed credential save you can reset the admin password after deployment has complete with the following command:
chef-automate iam admin-access restore PASSWORD
`
const howToRestore = `
The following command will restore your Chef Automate v1 installation's data:
%s
`
const howToRestoreFallback = `
A backup of your Chef Automate v1 data was made, but the arguments to the
automate-ctl restore-backup command cannot be determined from your settings.
Please consult the Chef Automate v1 documentation for the correct syntax.
The snapshot created by the upgrade process was named:
%s
`
const consolationPrize = `
Integrated backups were disabled for this upgrade. If you have a custom
backup/restore procedure, you may use that to recover your Chef Automate v1 data.
`
const upgradeSummary = `Ready to upgrade to Chef Automate v2. The upgrade process consists of these steps:
* Preload Chef Automate v2 binaries
* Enable maintenance mode in Chef Automate v1
* Backup your Chef Automate v1 data
* Shutdown your Chef Automate v1 installation
* Start Chef Automate v2 and run stage 1 data migrations
* Run stage 2 data migrations in the background
The stage 2 data migrations are irreversible. You will be required to reinstall
Chef Automate v1 from backup if you wish to revert the upgrade after the stage
2 migrations begin.
`
const optedInToTelemetry = `Users of this Automate deployment may elect to share user-anonymized usage data with
Chef Software, Inc. Chef uses this shared data to improve Automate.
Please visit https://chef.io/privacy-policy for more information about the
information Chef collects, and how that information is used.
`
const pleaseOptInToTelemetry = `Users of this Automate deployment cannot choose to share user-anonymized usage data
with Chef Software, Inc. Chef uses this shared data to improve Automate
Please consider allowing your users to share this data enabling telemetry.
See the Chef Automate v2 telemetry docs for details.
`
const uninstallWarning = `!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! WARNING !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
This command will uninstall Chef Automate and any other applications deployed
with Habitat on this system. All associated data will be permanently destroyed.
If you wish to preserve your data, create a backup before uninstalling.
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! WARNING !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!`
func init() {
if s, err := strconv.Atoi(os.Getenv("AUTOMATE_DEPLOY_TIMEOUT")); err == nil {
deployTimeout = time.Duration(s) * time.Second
}
}
// deployer runs a deployment by coordinating interactions of other types
type deployer struct {
ctx context.Context
client api.DeployClientStreamer
overrideCfg *dc.AutomateConfig
mergedCfg *dc.AutomateConfig
appliedCfg *dc.AutomateConfig
upgrade *a1upgrade.A1Upgrade
err error
deploymentID *api.DeploymentID
target target.Target
writer cli.FormatWriter
manifestProvider manifest.ReleaseManifestProvider
configPath string
cliVersion string
a1BackupNameMemoized string
uninstallOpts UninstallOpts
airgap bool
bootstrapBundlePath string
}
type UninstallOpts struct {
Yes bool
PreservePkgCache bool
}
// newDeployer initializes a deployer with usable values for pure install
func newDeployer(writer cli.FormatWriter,
overrideCfg *dc.AutomateConfig,
manifestProvider manifest.ReleaseManifestProvider,
cliVersion string,
airgap bool) deployer {
return deployer{
ctx: context.Background(),
err: nil,
overrideCfg: overrideCfg,
target: target.NewLocalTarget(airgap),
writer: writer,
manifestProvider: manifestProvider,
cliVersion: cliVersion,
airgap: airgap,
}
}
// newUpgradeDeployer initializes a deployer with usable values for upgrades
func newUpgradeDeployer(writer cli.FormatWriter,
upgrade *a1upgrade.A1Upgrade,
manifestProvider manifest.ReleaseManifestProvider,
cliVersion string,
airgap bool) deployer {
return deployer{
ctx: context.Background(),
upgrade: upgrade,
err: nil,
target: target.NewLocalTarget(airgap),
writer: writer,
manifestProvider: manifestProvider,
cliVersion: cliVersion,
airgap: airgap,
}
}
// newUnDeployer initializes a deployer with usable values for an uninstall
func newUnDeployer(writer cli.FormatWriter, opts UninstallOpts) deployer {
return deployer{
ctx: context.Background(),
target: target.NewLocalTarget(true),
err: nil,
writer: writer,
uninstallOpts: opts,
}
}
// Preflight runs preflight checks for the pure install case
func Preflight(writer cli.FormatWriter,
overrideCfg *dc.AutomateConfig,
cliVersion string,
airgap bool) error {
d := deployer{
ctx: context.Background(),
overrideCfg: overrideCfg,
target: target.NewLocalTarget(airgap),
writer: writer,
cliVersion: cliVersion,
airgap: airgap,
}
d.genMergedConfig()
d.preflight(false)
return d.err
}
// Deploy bootstraps the system and then installs Chef Automate v2
func Deploy(writer cli.FormatWriter,
overrideConfig *dc.AutomateConfig,
skipPreflight bool,
manifestProvider manifest.ReleaseManifestProvider,
cliVersion string,
airgap bool,
bootstrapBundlePath string) error {
d := newDeployer(writer, overrideConfig, manifestProvider, cliVersion, airgap)
d.bootstrapBundlePath = bootstrapBundlePath
d.genMergedConfig()
if !skipPreflight {
d.preflight(false)
}
d.bootstrap()
d.waitForDeploymentService()
d.connect()
d.configureDeployment()
d.deployAll()
d.saveDeploymentCreds()
d.showTelemetryNotice()
return d.err
}
func DeployHA(writer cli.FormatWriter,
overrideConfig *dc.AutomateConfig,
manifestProvider manifest.ReleaseManifestProvider,
cliVersion string,
airgap bool, saas bool) error {
d := newDeployer(writer, overrideConfig, manifestProvider, cliVersion, airgap)
d.genMergedConfig()
ctx := context.Background()
currentM, err := manifestProvider.GetCurrentManifest(ctx, d.mergedCfg.Deployment.V1.Svc.Channel.GetValue())
if err != nil {
logrus.Debug("Failed to get manifest for current channel")
}
b := bootstrap.NewCompatBootstrapper(d.target)
err = bootstrap.FullBootstrapHA(context.Background(), b, d.mergedCfg.Deployment, currentM, writer, saas)
return err
}
func Destroy(writer cli.FormatWriter, opts UninstallOpts) error {
d := newUnDeployer(writer, opts)
d.destroy()
return d.err
}
// A1Upgrade bootstraps the system, copies/moves a1 data to a2, and then installs a2
func A1Upgrade(writer cli.FormatWriter,
upgrade *a1upgrade.A1Upgrade,
acceptDefaults bool,
manifestProvider manifest.ReleaseManifestProvider,
cliVersion string,
airgap bool,
) error {
d := newUpgradeDeployer(writer, upgrade, manifestProvider, cliVersion, airgap)
d.prepare()
d.upgradePreflight()
d.summarizeSteps(acceptDefaults)
d.bootstrap()
d.waitForDeploymentService()
d.connect()
d.configureDeployment()
d.preload()
d.DoA1MaintMode()
d.doA1Backup()
d.migrateEs2Indices()
d.extractA1PostgreSQLData()
d.extractA1UserData()
d.extractA1UserRolesData()
d.extractA1ChefServerCredentials()
d.doA1Shutdown()
d.printUpgradeHeader()
// -- POINT OF NO RETURN (except via a1 restore) --:
// After this point, data has been removed from a1 in ways that we could
// theoretically undo but are probably too complicated to expect customers to
// get right. Failures in subsequent steps should advise customers to restore
// from backup if they want to abort.
d.moveA1ESData()
d.moveA1ComplianceData()
d.writeA1ComplianceSecret()
d.moveA1NotificationData()
d.moveA1WorkflowGitRepos()
d.writeA1WorkflowErlCookie()
d.deployDataServices()
d.restorePostgresData()
d.startNonDataServices()
d.showTelemetryNotice()
d.initialMigrationComplete()
return d.err
}
// A1PgDump runs the PGDump portion of the A1 migration process. It
// is used to create a1migration data artifacts.
func A1PgDump(writer cli.FormatWriter, upgrade *a1upgrade.A1Upgrade) error {
d := newUpgradeDeployer(writer, upgrade, nil, "", false)
d.extractA1PostgreSQLData()
return d.err
}
// A1ExtractUserData runs the A1 user data extraction portion of the A1
// migration process.
func A1ExtractUserData(writer cli.FormatWriter, upgrade *a1upgrade.A1Upgrade) error {
d := newUpgradeDeployer(writer, upgrade, nil, "", false)
d.extractA1UserData()
return d.err
}
// A1ExtractUserRolesData runs the A1 user data extraction portion of the A1
// migration process.
func A1ExtractUserRolesData(writer cli.FormatWriter, upgrade *a1upgrade.A1Upgrade) error {
d := newUpgradeDeployer(writer, upgrade, nil, "", false)
d.extractA1UserRolesData()
return d.err
}
func (d *deployer) prepare() {
if d.err != nil {
return
}
// set the pg superuser password before all other checks
// some of the checks (e.g. saml check) require password
// based authn with postgres, and this sets a known username
// and password that can be used to execute these checks
d.setPgSuperuserPassword()
d.validateUpgradableA1Config()
d.validateUpgradableChefServerConfig()
// TODO @afiune maybe check Workflow Config here?
d.validateUserOverrideConfig()
d.genMergedConfig()
}
func getOrGuessFQDN() string {
// If deployment service is available, try to get FQDN from it
res, err := GetAutomateConfig(int64(DefaultClientTimeout.Seconds()))
if err == nil {
maybeFQDN := res.Config.GetGlobal().GetV1().GetFqdn().GetValue()
// if user is uninstalling because of severe breakage, configuration may
// not be reliable
if maybeFQDN != "" {
return maybeFQDN
}
logrus.Debug("FQDN in deployment service configuration was set to empty string (\"\")")
} else {
logrus.WithError(err).Debug("failed to load configuration from deployment service")
}
// fallback to asking the system
return dc.LbFQDN()
}
func (d *deployer) destroy() {
if !d.uninstallOpts.Yes {
d.writer.LongWarningln(uninstallWarning)
fqdn := getOrGuessFQDN()
prepromptFmt := `The FQDN of your Chef Automate installation is "%s".
Type the FQDN in to continue.`
d.writer.Titlef(prepromptFmt, fqdn)
response, err := d.writer.Prompt("FQDN")
if err != nil {
d.err = err
return
}
if response != fqdn {
d.writer.Titlef("Response did not match \"%s\", canceling uninstall", fqdn)
return
}
}
d.writer.Title("Removing Chef Automate")
d.writer.Body("stopping Automate services")
err := d.target.EnsureStopped()
if err != nil {
d.err = err
return
}
d.writer.Body("removing Automate from system startup configuration")
err = d.target.EnsureDisabled()
if err != nil {
d.err = err
return
}
d.writer.Body("removing Habitat user and configuration")
err = d.target.DestroySupervisor()
if err != nil {
d.err = err
return
}
d.writer.Body("removing Automate data stores")
err = d.target.DestroyData()
if err != nil {
d.err = err
return
}
if !d.uninstallOpts.PreservePkgCache {
d.writer.Body("removing Habitat package cache")
err = d.target.DestroyPkgCache()
if err != nil {
d.err = err
return
}
} else {
d.writer.Body("skipping Habitat package cache removal")
}
d.writer.Title("Chef Automate uninstalled")
}
func (d *deployer) validateUserOverrideConfig() {
if d.err != nil {
return
}
if err := d.getOverrideCfg().ValidateWithGlobalAndDefaults(); err != nil {
d.err = status.Annotate(err, status.ConfigError)
}
}
func (d *deployer) genMergedConfig() {
if d.err != nil {
return
}
// Bootstrapping hab and the deployment service may need defaults, however,
// the defaults should not be appled until after the override config has
// been persisted via the deployment-service. Instead, make a copy with
// defaults and globals applied and use the copy to bootstrap the deployment
// service, then pass the override config to the deployment service during
// the deploy.
mergedCfg, err := dc.MergeWithDefaults(d.getOverrideCfg())
mergedCfg.SetGlobalConfig()
if err != nil {
d.err = status.Annotate(err, status.ConfigError)
return
}
// We may need the proxy configuration for communicating with
// the internet to install hab, etc.
SetProxyEnvironment(mergedCfg.Deployment)
d.mergedCfg = mergedCfg
}
// setPgSuperuserPassword determines if A1 machine has superuser enabled and
// attempts to enable it if it has not. This allows us to connect using to
// the postgresql instance using the http socket with the superuser name and
// password.
func (d *deployer) setPgSuperuserPassword() {
if d.err != nil {
return
}
superuserEnable := d.upgrade.DeliveryRunning.Delivery.PostgreSQL.SuperuserEnable
pass := d.upgrade.DeliverySecrets.Postgresql.SuperuserPassword
user := d.upgrade.DeliveryRunning.Delivery.PostgreSQL.SuperuserUsername
if !superuserEnable {
if err := a1upgrade.PsqlAlterUserWithPassword(user, pass); err != nil {
err = status.Wrap(err,
status.DatabaseError,
"Failed to set the superuser password. If the superuser password is not set the migration cannot export the postgresql databases.",
)
d.err = status.WithRecovery(err, d.cancelUpgradeInstructions())
}
}
}
// In the upgrade case, the A1Upgrade object owns the a2 config, but for a
// plain install, deployer owns it. This getter handles that special case, and
// should be used to get the a2config for all code here unless it only applies
// to one of the cases
func (d *deployer) getOverrideCfg() *dc.AutomateConfig {
if d.upgrade == nil {
return d.overrideCfg
}
return d.upgrade.A2Config
}
// PreflightCheck verifies host is ready for Setup/Bootstrap
func (d *deployer) preflight(skipSharedPortCheck bool) {
if d.err != nil {
return
}
preflightCheckOpts := preflight.DeployPreflightCheckOptions{
SkipSharedPortCheck: skipSharedPortCheck,
Airgap: d.airgap,
AutomateConfig: d.mergedCfg,
}
d.writer.Title("Beginning pre-flight checks")
hartifactsPath := d.mergedCfg.GetDeployment().GetV1().GetSvc().GetHartifactsPath().GetValue()
overrideOrigin := d.mergedCfg.GetDeployment().GetV1().GetSvc().GetOverrideOrigin().GetValue()
channel := d.mergedCfg.GetDeployment().GetV1().GetSvc().GetChannel().GetValue()
if !d.airgap {
err := CLIUpToDateWithLatestManifest(hartifactsPath, overrideOrigin, channel, d.cliVersion)
if err != nil {
d.err = status.Annotate(err, status.PreflightError)
return
}
}
out, err := preflight.RunDeployPreflightCheck(preflightCheckOpts)
if err != nil {
d.err = status.Annotate(err, status.PreflightError)
return
}
d.writer.Title(out)
}
func (d *deployer) upgradePreflight() {
if d.err != nil {
return
}
if d.upgrade.SkipUpgradePreflight {
return
}
d.preflight(true)
if d.err != nil {
return
}
p := a1upgrade.NewPreflightRunner(
d.writer,
d.upgrade.DeliveryRunning,
d.upgrade.DeliverySecrets,
d.upgrade.EnableChefServer,
d.upgrade.EnableWorkflow,
)
if err := p.Run(); err != nil {
d.err = status.Annotate(err, status.PreflightError)
}
}
func (d *deployer) summarizeSteps(acceptDefaults bool) {
if d.err != nil {
return
}
d.writer.Println(upgradeSummary)
if acceptDefaults {
d.writer.Println("Accepting configuration and continuing...")
return
}
d.writeConfigForReview()
if d.err != nil {
return
}
viewConfig, err := d.writer.Confirm("Would you like to review the Chef Automate v2 configuration?")
if err != nil {
d.err = status.Annotate(err, status.InvalidCommandArgsError)
return
}
if viewConfig {
d.displayConfig()
}
d.writer.Titlef("Your Chef Automate v2 configuration has been written to %s\n", d.configPath)
d.writer.Print(editConfigInstructions)
d.writer.Printf("chef-automate migrate-from-v1 --config %s\n", d.configPath)
userReady, err := d.writer.Confirm("Are you ready to continue?")
if err != nil {
d.err = status.Annotate(err, status.InvalidCommandArgsError)
return
}
if !userReady {
d.err = status.New(status.UpgradeError, "User cancelled upgrade")
}
}
func (d *deployer) writeConfigForReview() {
n := time.Now().UTC()
datestamp := n.Format("20060102150405")
wd, err := os.Getwd()
if err != nil {
d.err = status.Wrap(err, status.FileAccessError, "Could not get current working directory to write config")
return
}
emittedConfig := fmt.Sprintf("config-%s.toml", datestamp)
d.configPath = filepath.Join(wd, emittedConfig)
copy, err := d.getOverrideCfg().RedactedCopy()
if err != nil {
d.err = status.Annotate(err, status.ConfigError)
return
}
t, err := copy.MarshalToTOML()
if err != nil {
d.err = status.Annotate(err, status.MarshalError)
return
}
err = ioutil.WriteFile(d.configPath, t, 0600)
if err != nil {
err = status.Wrap(err, status.FileAccessError, "Failed to write config")
d.err = err
return
}
}
func (d *deployer) displayConfig() {
cmd, args := d.getConfigPagerCommand()
if cmd == "" {
// Couldn't find a pager, just print
copy, err := d.getOverrideCfg().RedactedCopy()
if err != nil {
d.err = status.Annotate(err, status.ConfigError)
return
}
t, err := copy.MarshalToTOML()
if err != nil {
d.err = status.Annotate(err, status.MarshalError)
return
}
d.writer.Println(string(t))
return
}
cmdExecutor := command.NewExecExecutor()
err := cmdExecutor.Run(cmd, command.Args(args...), command.Stdin(os.Stdin), command.Stdout(os.Stdout), command.Stderr(os.Stderr))
if err != nil {
d.err = status.Wrapf(err, status.CommandExecutionError, "Failed to display configuration to terminal pager")
return
}
}
func (d *deployer) getConfigPagerCommand() (string, []string) {
// Use the user-provided PAGER if we can find it on the path
userPager := os.Getenv("PAGER")
if userPager != "" {
userPagerPath, err := exec.LookPath(userPager)
if err == nil {
return userPagerPath, []string{d.configPath}
}
d.writer.Warnf("Unable to find $PAGER=%s in PATH. Trying 'less' instead.", userPager)
}
// Try our default pager (less) if it is on the path
lessPath, err := exec.LookPath("less")
if err != nil {
d.writer.Warnln("Unable to find 'less' in $PATH.")
return "", []string{}
}
return lessPath, []string{"-X", "-PUse SPACE to scroll and q to exit", d.configPath}
}
func (d *deployer) bootstrap() {
if d.err != nil {
return
}
d.writer.Title("Bootstrapping Chef Automate")
d.writer.Body("Fetching Release Manifest")
m, err := d.manifestProvider.GetCurrentManifest(d.ctx, d.mergedCfg.Deployment.V1.Svc.Channel.GetValue())
if err != nil {
d.err = status.Annotate(err, status.PackageInstallError)
return
}
b := bootstrap.NewCompatBootstrapper(d.target)
d.err = bootstrap.FullBootstrap(d.ctx, b, m, d.mergedCfg.Deployment, d.bootstrapBundlePath, d.writer)
}
func (d *deployer) waitForDeploymentService() {
if d.err != nil {
return
}
d.writer.Body("Waiting for deployment-service to be ready")
// If 5 minutes isn't enough, we should fix that problem
startTime := time.Now()
timeout := 5 * time.Minute
sleepTime := 10 * time.Second
// I think we could probably use contexts for this, but we are
// using this style of for loop everywhere else.
for attempts := 1; ; attempts++ {
logrus.Debugf("health check attempt %d (%.1fs elapsed) (%.1fs interval)", attempts, time.Since(startTime).Seconds(), sleepTime.Seconds())
_, err := Connection(2 * time.Second)
if err == nil {
break
}
if time.Since(startTime) > timeout {
d.err = status.New(status.TimedOutError, "waiting for deployment-service healthy status")
return
}
time.Sleep(sleepTime)
}
}
func (d *deployer) connect() {
if d.err != nil {
return
}
d.writer.Body("Initializing connection to deployment-service")
client, err := Connection(deployTimeout)
if err != nil {
d.err = err
return
}
d.client = client
}
func (d *deployer) configureDeployment() {
if d.err != nil {
return
}
d.writer.Title("Applying Deployment Configuration")
var errResponse error
sleepTime := 25 * time.Second
req := &api.ConfigureDeploymentRequest{Config: d.getOverrideCfg()}
for retries, maxRetries := 1, 12; retries <= maxRetries; retries++ {
resp, err := d.client.ConfigureDeployment(d.ctx, req)
if err == nil {
d.deploymentID = resp.DeploymentId
d.appliedCfg = resp.Config
return
}
errResponse = status.Wrap(err, status.DeploymentServiceCallError, "Request to configure deployment failed")
retry := false
if grpcStatus, ok := gstatus.FromError(err); ok {
// first test for grpc codes:
// codes.Unavailable means that we can retry
if grpcStatus.Code() == codes.Unavailable {
retry = true
}
// back-compat: old versions of the server don't return a code so we
// should check the message
if grpcStatus.Code() == codes.Unknown {
retry = api.IsDeploymentServicePendingMessage(grpcStatus.Message())
}
}
if retry {
d.writer.Bodyf(
"deployment-service pending updates: retry %d/%d",
retries, maxRetries,
)
Disconnect()
time.Sleep(sleepTime)
d.connect()
continue
}
break
}
d.err = errResponse
}
func (d *deployer) preload() {
if d.err != nil {
return
}
d.writer.Title("Starting preload")
resp, err := d.client.Preload(d.ctx, &api.DeployRequest{})
if err != nil {
d.err = status.Wrap(err, status.DeploymentServiceCallError, "Failed to start preload")
return
}
h := CLIEventWriter{Writer: d.writer}
err = d.client.StreamDeployEvents(resp.TaskId, d.deploymentID, &h)
if err != nil {
d.err = status.Wrap(err, status.DeploymentServiceCallError, "Failed to preload services")
return
}
}
func (d *deployer) DoA1MaintMode() {
if d.err != nil {
return
}
d.writer.Title("Enabling maintenance mode for Chef Automate v1 installation")
if err := a1upgrade.EngageMaintMode(); err != nil {
err = status.Wrap(err, status.FileAccessError, fmt.Sprintf(`Failed to create the file %s
The upgrade command must create this file in order to put Chef Automate v1 into
maintenance mode. Make sure this file can be created by the current user and
try again.
`, a1upgrade.MaintDotFlag))
d.err = status.WithRecovery(err, d.cancelUpgradeInstructions())
return
}
if d.mergedCfg.GetDeployment().GetV1().GetSvc().GetEnableChefServer().GetValue() {
err := a1upgrade.ChefServerCtlStopService("nginx")
if err != nil {
err = status.Wrap(err, status.UpgradeError, `Failed to enable maintenance mode on Chef Automate v1 installation. The upgrade process must stop the Chef Server nginx process to put Chef Automate v1 into maintenance mode. Please ensure the follow commands executes without error and try again:
chef-server-ctl stop nginx
`)
d.err = status.WithRecovery(err, d.cancelUpgradeInstructions())
return
}
}
if err := a1upgrade.VerifyMaintMode(d.mergedCfg); err != nil {
err = status.Wrap(err, status.UpgradeError, `Failed to enable maintenance mode on Chef Automate v1 installation. The upgrade process must put your Chef Automate v1 installation into maintenance mode to ensure all in-flight data is migrated to Chef Automate v2. If you are using a custom load balancer, please ensure requests return 503 and try again.
`)
d.err = status.WithRecovery(err, d.cancelUpgradeInstructions())
return
}
if err := a1upgrade.VerifyA1QueueDrained(d.upgrade.A1Config); err != nil {
err = status.Wrap(err, status.UpgradeError, `Chef Automate v1 failed to process queued data in the allotted time. This may indicate a problem in Chef Automate v1's data collection service or the system may have higher load than expected. The following command returns the count of incoming Chef Automate v1 data records that have not yet been
processed:
PATH=/opt/delivery/embedded/bin:$PATH rabbitmqctl list_queues -p /insights name messages
When this command returns zero records, you may try the upgrade again.
`)
d.err = status.WithRecovery(err, d.cancelUpgradeInstructions())
return
}
}
func (d *deployer) a1BackupName() string {
if d.a1BackupNameMemoized == "" {
t := time.Now().UTC()
n := fmt.Sprintf("a1-migration-backup-%d-%d-%d-%d-%d-%d", t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second())
d.a1BackupNameMemoized = n
}
return d.a1BackupNameMemoized
}
func (d *deployer) a1RestoreInstructions() (string, error) {
n := d.a1BackupName()
z, err := d.zstLocatorFor(n)
if err != nil {
return "", err
}
return fmt.Sprintf("automate-ctl restore-backup %s %s", z, n), nil
}
func (d *deployer) zstLocatorFor(backupName string) (string, error) {
backupType := d.upgrade.A1Config.DeliveryRunning.Delivery.Backup.Type
switch backupType {
case "s3":
// delivery["backup"]["region"]
region := d.upgrade.A1Config.DeliveryRunning.Delivery.Backup.S3Region
if region == "" {
return "", status.New(status.ConfigError, "restore argument type is \"s3\" but region is not set")
}
// delivery["backup"]["bucket"]
bucket := d.upgrade.A1Config.DeliveryRunning.Delivery.Backup.S3Bucket
if bucket == "" {
return "", status.New(status.ConfigError, "restore argument type is \"s3\" but bucket is not set")
}
// e.g., us-east-1:s3_bucket:chef-automate-backup.zst
return fmt.Sprintf("%s:%s:%s.zst", region, bucket, backupName), nil
case "fs":
dir := d.upgrade.A1Config.DeliveryRunning.Delivery.Backup.Location
if dir == "" {
return "", status.New(status.ConfigError, "restore argument type is \"fs\" but location is not set")
}
basename := fmt.Sprintf("%s.zst", backupName)
return filepath.Join(dir, basename), nil
default:
return "", status.Errorf(status.ConfigError, "'%s' in not a valid backup type", backupType)
}
}
func (d *deployer) doA1Backup() {
if d.err != nil {
return
}
if d.upgrade.SkipBackup {
d.writer.Title("Skipping backup of Chef Automate v1 data due to user configuration")
return
}
explanation := `Failed to backup Chef Automate v1. This may indicate that backup of your Chef Automate v1 installation is taking
longer than expected, or it may indicate a larger problem. You may investigate further by checking the Chef Automate v1
logs with the following command:
automate-ctl tail
When you can backup your Chef Automate v1 installation successfully, run the upgrade command again to continue.
`
d.writer.Title("Backing up Chef Automate v1 installation")
d.writer.Bodyf("Creating Chef Automate v1 backup '%s'", d.a1BackupName())
if err := a1upgrade.AutomateCtlCreateBackup(d.a1BackupName()); err != nil {
err = status.Wrap(err, status.BackupError, explanation)
d.err = status.WithRecovery(err, d.cancelUpgradeInstructions())
return
}
esURL := d.upgrade.A1Config.DeliveryRunning.Delivery.Opensearch.NginxProxyURL
repoType := d.upgrade.A1Config.DeliveryRunning.Delivery.Backup.Type
if err := a1upgrade.WaitForEsSnapshot(d.writer, esURL, repoType, d.a1BackupName()); err != nil {
err = status.Wrap(err, status.BackupError, explanation)
d.err = status.WithRecovery(err, d.cancelUpgradeInstructions())
return
}
}
// DevA1Backup runs just the the backup part of an upgrade. This is exposed so
// we can use it in dev CLI tooling to verify backups function correctly.
// TODO: Investigate if we should rm this function
func DevA1Backup(w cli.FormatWriter, u *a1upgrade.A1Upgrade) error {
d := newUpgradeDeployer(w, u, nil, "", false)
d.doA1Backup()
if d.err != nil {
return status.Annotate(d.err, status.BackupError)
}
instructions, err := d.a1RestoreInstructions()
if err != nil {
return status.Annotate(d.err, status.BackupError)
}
d.writer.Title("The backup can be restored with the command:")
d.writer.Body(instructions)
return nil
}
func (d *deployer) migrateEs2Indices() {
if d.err != nil {