-
Notifications
You must be signed in to change notification settings - Fork 69
/
recipe_installer.go
737 lines (620 loc) · 23 KB
/
recipe_installer.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
package install
import (
"context"
"errors"
"fmt"
"os"
"regexp"
"strconv"
"time"
log "github.com/sirupsen/logrus"
"github.com/newrelic/newrelic-cli/internal/cli"
"github.com/newrelic/newrelic-cli/internal/diagnose"
"github.com/newrelic/newrelic-cli/internal/install/discovery"
"github.com/newrelic/newrelic-cli/internal/install/execution"
"github.com/newrelic/newrelic-cli/internal/install/recipes"
"github.com/newrelic/newrelic-cli/internal/install/segment"
"github.com/newrelic/newrelic-cli/internal/install/types"
"github.com/newrelic/newrelic-cli/internal/install/ux"
"github.com/newrelic/newrelic-cli/internal/install/validation"
"github.com/newrelic/newrelic-cli/internal/utils"
"github.com/newrelic/newrelic-client-go/v2/newrelic"
)
const (
validationTimeout = 5 * time.Minute
)
var infraAgentEntityKey string
type RecipeInstall struct {
types.InstallerContext
discoverer Discoverer
manifestValidator *discovery.ManifestValidator
recipeFetcher recipes.RecipeFetcher
recipeExecutor execution.RecipeExecutor
recipeValidator RecipeValidator
recipeFileFetcher RecipeFileFetcher
recipeLogForwarder execution.LogForwarder
status *execution.InstallStatus
prompter Prompter
configValidator ConfigValidator
recipeVarPreparer RecipeVarPreparer
agentValidator AgentValidator
shouldInstallCore func() bool
bundlerFactory func(ctx context.Context, availableRecipes recipes.RecipeDetectionResults) RecipeBundler
bundleInstallerFactory func(ctx context.Context, manifest *types.DiscoveryManifest, recipeInstallerInterface RecipeInstaller, statusReporter StatusReporter) RecipeBundleInstaller
progressIndicator ux.ProgressIndicator
recipeDetectorFactory func(ctx context.Context, repo *recipes.RecipeRepository, ic *types.InstallerContext) RecipeStatusDetector
processEvaluator recipes.ProcessEvaluatorInterface
}
type RecipeInstallFunc func(ctx context.Context, i *RecipeInstall, m *types.DiscoveryManifest, r *types.OpenInstallationRecipe, recipes []types.OpenInstallationRecipe) error
func NewRecipeInstaller(ic types.InstallerContext, nrClient *newrelic.NewRelic, sg *segment.Segment) *RecipeInstall {
var recipeFetcher recipes.RecipeFetcher
if ic.LocalRecipes != "" {
recipeFetcher = &recipes.LocalRecipeFetcher{
Path: ic.LocalRecipes,
}
} else if len(ic.RecipePaths) > 0 {
recipeFetcher = recipes.NewRecipeFileFetcher(ic.RecipePaths)
} else {
recipeFetcher = recipes.NewEmbeddedRecipeFetcher()
}
mv := discovery.NewManifestValidator()
ff := recipes.NewRecipeFileFetcher([]string{})
lf := execution.NewRecipeLogForwarder()
ers := []execution.StatusSubscriber{
execution.NewNerdStorageStatusReporter(&nrClient.NerdStorage),
execution.NewTerminalStatusReporter(),
execution.NewInstallEventsReporter(&nrClient.InstallEvents),
execution.NewSegmentReporter(sg),
}
slg := execution.NewPlatformLinkGenerator()
statusRollup := execution.NewInstallStatus(ic, ers, slg)
sg.SetInstallID(statusRollup.InstallID)
d := discovery.NewPSUtilDiscoverer()
re := execution.NewGoTaskRecipeExecutor()
v := validation.NewPollingRecipeValidator(&nrClient.Nrdb)
cv := diagnose.NewConfigValidator(nrClient)
p := ux.NewPromptUIPrompter()
rvp := execution.NewRecipeVarProvider()
av := validation.NewAgentValidator()
i := RecipeInstall{
discoverer: d,
manifestValidator: mv,
recipeFetcher: recipeFetcher,
recipeExecutor: re,
recipeValidator: v,
recipeFileFetcher: ff,
recipeLogForwarder: lf,
status: statusRollup,
prompter: p,
configValidator: cv,
recipeVarPreparer: rvp,
agentValidator: av,
progressIndicator: ux.NewSpinnerProgressIndicator(),
processEvaluator: recipes.NewProcessEvaluator(),
}
i.InstallerContext = ic
i.shouldInstallCore = func() bool {
return os.Getenv("NEW_RELIC_CLI_SKIP_CORE") != "1"
}
i.bundlerFactory = func(ctx context.Context, availableRecipes recipes.RecipeDetectionResults) RecipeBundler {
return recipes.NewBundler(ctx, availableRecipes)
}
i.bundleInstallerFactory = func(ctx context.Context, manifest *types.DiscoveryManifest, recipeInstallerInterface RecipeInstaller, statusReporter StatusReporter) RecipeBundleInstaller {
return NewBundleInstaller(ctx, manifest, recipeInstallerInterface, statusReporter)
}
i.recipeDetectorFactory = func(ctx context.Context, repo *recipes.RecipeRepository, ic *types.InstallerContext) RecipeStatusDetector {
return recipes.NewRecipeDetector(ctx, repo, i.processEvaluator, ic)
}
return &i
}
var getLatestCliVersionReleased = func(ctx context.Context) (string, error) {
return cli.GetLatestReleaseVersion(ctx)
}
var isLatestCliVersionInstalled = func(ctx context.Context, version string) (bool, error) {
return cli.IsLatestVersion(ctx, version)
}
func (i *RecipeInstall) promptIfNotLatestCLIVersion(ctx context.Context) error {
latestCliVersion, err := getLatestCliVersionReleased(ctx)
if err != nil {
log.Debug(err)
return nil
}
isMostRecentCliVersion, err := isLatestCliVersionInstalled(ctx, latestCliVersion)
if err != nil {
log.Debug(err)
return nil
}
if !isMostRecentCliVersion {
i.status.UpdateRequired = true
cli.PrintUpdateCLIMessage(latestCliVersion)
err := &types.UpdateRequiredError{
Err: fmt.Errorf(`%s`, cli.FormatUpdateVersionMessage(latestCliVersion)),
Details: "UpdateRequiredError",
}
return err
}
return nil
}
func (i *RecipeInstall) ensureSingleConcurrentInstall(ctx context.Context) error {
processes := i.processEvaluator.GetOrLoadProcesses(ctx)
count := 0
nameRegex := regexp.MustCompile(`(?i)newrelic(\.exe)?`)
for _, p := range processes {
name, err := p.Name()
if err == nil && nameRegex.MatchString(name) {
cmd, err := p.Cmd()
cmdRegex := regexp.MustCompile(`(?i)newrelic(\.exe)? install`)
if err == nil && cmdRegex.MatchString(cmd) {
log.Debugf(fmt.Sprintf("EnsureSingleConcurrentInstall Matched:%s pid:%d", name, p.PID()))
count++
}
}
}
if count > 1 {
message := fmt.Sprintf("only 1 newrelic install command can run at one time, found %d currently executing. Please retry later, or terminate the other newrelic installations", count)
return errors.New(message)
}
return nil
}
func (i *RecipeInstall) Install() error {
fmt.Printf(`
_ _ ____ _ _
| \ | | _____ __ | _ \ ___| (_) ___
| \| |/ _ \ \ /\ / / | |_) / _ | | |/ __|
| |\ | __/\ V V / | _ | __| | | (__
|_| \_|\___| \_/\_/ |_| \_\___|_|_|\___|
Welcome to New Relic. Let's set up full stack observability for your environment.
Our Data Privacy Notice: https://newrelic.com/termsandconditions/services-notices
`)
fmt.Println()
log.Tracef("InstallerContext: %+v", i.InstallerContext)
log.WithFields(log.Fields{
"RecipePathsProvided": i.RecipePathsProvided(),
"RecipeNamesProvided": i.RecipeNamesProvided(),
}).Debug("context summary")
if i.RecipeNamesProvided() {
i.status.SetTargetedInstall(i.RecipeNames)
}
if err := i.ensureSingleConcurrentInstall(utils.SignalCtx); err != nil {
log.Debug(err)
return err
}
hostname, _ := os.Hostname()
if hostname == "" {
message := "This system is not supported for automatic installation, no host info. Please see our documentation for requirements."
return errors.New(message)
}
i.status.InstallStarted()
ctx, cancel := context.WithCancel(utils.SignalCtx)
defer cancel()
errChan := make(chan error)
var err error
err = i.connectToPlatform()
if err != nil {
i.status.InstallComplete(err)
return err
}
// If not in a dev environemt, check to see if
// the installed CLI is up to date.
if !cli.IsDevEnvironment() {
if err = i.promptIfNotLatestCLIVersion(ctx); err != nil {
i.status.InstallComplete(err)
return err
}
}
go func(ctx context.Context) {
errChan <- i.install(ctx)
}(ctx)
select {
case <-ctx.Done():
err = ctx.Err()
i.status.InstallComplete(err)
return err
case err = <-errChan:
if errors.Is(err, types.ErrInterrupt) {
i.status.InstallCanceled()
return err
}
i.status.InstallComplete(err)
return err
}
}
func (i *RecipeInstall) connectToPlatform() error {
loaderChan := make(chan error)
go func() {
err := i.configValidator.Validate(utils.SignalCtx)
if err != nil {
loaderChan <- err
return
}
loaderChan <- nil
}()
i.progressIndicator.Start("Connecting to New Relic Platform")
loaded := <-loaderChan
if loaded == nil {
i.progressIndicator.Success("Connecting to New Relic Platform")
} else {
i.progressIndicator.Fail("Connecting to New Relic Platform")
}
return loaded
}
func (i *RecipeInstall) install(ctx context.Context) error {
installLibraryVersion := i.recipeFetcher.FetchLibraryVersion(ctx)
log.Debugf("Using open-install-library version %s", installLibraryVersion)
i.status.SetVersions(installLibraryVersion)
// Execute the discovery process, exiting on failure.
m, err := i.discover(ctx)
if err != nil {
return err
}
repo := recipes.NewRecipeRepository(func() ([]*types.OpenInstallationRecipe, error) {
recipes, err2 := i.recipeFetcher.FetchRecipes(ctx)
return recipes, err2
}, m)
i.printStartInstallingMessage(repo)
recipeDetector := i.recipeDetectorFactory(ctx, repo, &i.InstallerContext)
availableRecipes, unavailableRecipes, err := recipeDetector.GetDetectedRecipes()
if err != nil {
return err
}
i.reportRecipeStatuses(availableRecipes, unavailableRecipes)
if len(availableRecipes) == 0 && !i.RecipeNamesProvided() {
fmt.Println("This system is not supported by any available recipes for automatic installation. Please see our documentation for requirements.")
return &types.UncaughtError{
Err: fmt.Errorf("no recipes found supporting this system"),
}
}
bundler := i.bundlerFactory(ctx, availableRecipes)
bundleInstaller := i.bundleInstallerFactory(ctx, m, i, i.status)
cbErr := i.installCoreBundle(bundler, bundleInstaller)
if cbErr != nil {
return cbErr
}
abErr := i.installAdditionalBundle(bundler, bundleInstaller, repo)
if abErr != nil {
return abErr
}
i.reportRecipeRecommendations(availableRecipes)
log.Debugf("Done installing.")
return nil
}
func (i *RecipeInstall) printStartInstallingMessage(repo *recipes.RecipeRepository) {
message := "\n\nInstalling New Relic"
if i.RecipeNamesProvided() && len(i.RecipeNames) > 0 {
r := repo.FindRecipeByName(i.RecipeNames[0])
if r != nil {
message = fmt.Sprintf("%s %s", message, r.DisplayName)
}
}
fmt.Println(message)
}
func (i *RecipeInstall) reportRecipeStatuses(availableRecipes recipes.RecipeDetectionResults,
unavailableRecipes recipes.RecipeDetectionResults,
) {
for _, d := range unavailableRecipes {
e := execution.RecipeStatusEvent{Recipe: *d.Recipe, ValidationDurationMs: d.DurationMs}
i.status.ReportStatus(d.Status, e)
}
for _, d := range availableRecipes {
e := execution.RecipeStatusEvent{Recipe: *d.Recipe, ValidationDurationMs: d.DurationMs}
i.status.ReportStatus(execution.RecipeStatusTypes.DETECTED, e)
}
}
func (i *RecipeInstall) reportRecipeRecommendations(availableRecipes recipes.RecipeDetectionResults) {
recipeRecommendations := i.getRecipeRecommendations(availableRecipes)
for _, e := range recipeRecommendations {
i.status.ReportStatus(execution.RecipeStatusTypes.RECOMMENDED, e)
}
}
// Report recommendations for recipes that are available but have not been attempted to be installed
func (i *RecipeInstall) getRecipeRecommendations(availableRecipes recipes.RecipeDetectionResults) []execution.RecipeStatusEvent {
isTargetedInstall := i.RecipeNamesProvided() && len(i.RecipeNames) > 0
recommendations := []execution.RecipeStatusEvent{}
if isTargetedInstall {
for _, d := range availableRecipes {
recipeName := d.Recipe.Name
installed := i.status.RecipeHasStatus(recipeName, execution.RecipeStatusTypes.INSTALLED)
failed := i.status.RecipeHasStatus(recipeName, execution.RecipeStatusTypes.FAILED)
unsupported := i.status.RecipeHasStatus(recipeName, execution.RecipeStatusTypes.UNSUPPORTED)
canceled := i.status.RecipeHasStatus(recipeName, execution.RecipeStatusTypes.CANCELED)
if installed || failed || unsupported || canceled {
continue
}
e := execution.RecipeStatusEvent{Recipe: *d.Recipe, ValidationDurationMs: d.DurationMs}
recommendations = append(recommendations, e)
}
}
return recommendations
}
func (i *RecipeInstall) isTargetInstallRecipe(recipeName string) bool {
for _, r := range i.RecipeNames {
if r == recipeName {
return true
}
}
return false
}
func (i *RecipeInstall) installAdditionalBundle(bundler RecipeBundler, bundleInstaller RecipeBundleInstaller, repo *recipes.RecipeRepository) error {
var additionalBundle *recipes.Bundle
if i.RecipeNamesProvided() {
additionalBundle = bundler.CreateAdditionalTargetedBundle(i.RecipeNames)
i.reportUnsupportedTargetedRecipes(additionalBundle, repo)
log.Debugf("Additional Targeted bundle recipes:%s", additionalBundle)
} else {
additionalBundle = bundler.CreateAdditionalGuidedBundle()
log.Debugf("Additional Guided bundle recipes:%s", additionalBundle)
}
bundleInstaller.InstallContinueOnError(additionalBundle, i.AssumeYes)
if bundleInstaller.InstalledRecipesCount() == 0 {
return &types.UncaughtError{
Err: fmt.Errorf("no recipes were installed"),
}
} else if len(i.RecipeNames) > len(additionalBundle.BundleRecipes) {
return &types.UncaughtError{
Err: fmt.Errorf("one or more selected recipes could not be installed"),
}
}
return nil
}
func (i *RecipeInstall) installCoreBundle(bundler RecipeBundler, bundleInstaller RecipeBundleInstaller) error {
if i.shouldInstallCore() {
coreBundle := bundler.CreateCoreBundle()
log.Debugf("Core bundle recipes:%s", coreBundle)
err := bundleInstaller.InstallStopOnError(coreBundle, i.AssumeYes)
if err != nil {
log.Debugf("error installing core bundle:%s", err)
return err
}
} else {
log.Debugf("Skipping core bundle")
}
return nil
}
func (i *RecipeInstall) assertDiscoveryValid(ctx context.Context, m *types.DiscoveryManifest) error {
err := i.manifestValidator.Validate(m)
if err != nil {
return err
}
log.Debugf("Done asserting valid operating system for OS:%s and PlatformVersion:%s", m.OS, m.PlatformVersion)
return nil
}
func (i *RecipeInstall) discover(ctx context.Context) (*types.DiscoveryManifest, error) {
log.Debug("discovering system information")
m, err := i.discoverer.Discover(ctx)
if err != nil {
return nil, fmt.Errorf("there was an error discovering system info: %s", err)
}
err = i.assertDiscoveryValid(ctx, m)
i.status.DiscoveryComplete(*m)
if err != nil {
return nil, fmt.Errorf("there was an error discovering system info: %s", err)
}
return m, nil
}
func (i *RecipeInstall) reportUnsupportedTargetedRecipes(bundle *recipes.Bundle, repo *recipes.RecipeRepository) {
for _, recipeName := range i.RecipeNames {
br := bundle.GetBundleRecipe(recipeName)
if br == nil {
recipe := repo.FindRecipeByName(recipeName)
if recipe == nil {
recipe = &types.OpenInstallationRecipe{Name: recipeName, DisplayName: recipeName}
}
unsupportedEvent := execution.NewRecipeStatusEvent(recipe)
i.status.RecipeUnsupported(unsupportedEvent)
} else {
if !br.HasStatus(execution.RecipeStatusTypes.AVAILABLE) {
ds := &recipes.DetectedStatusType{
Status: execution.RecipeStatusTypes.UNSUPPORTED,
DurationMs: 0,
}
br.DetectedStatuses = append(br.DetectedStatuses, ds)
}
}
}
}
// installing recipe
func (i *RecipeInstall) executeAndValidate(ctx context.Context, m *types.DiscoveryManifest, r *types.OpenInstallationRecipe, vars types.RecipeVars, assumeYes bool) (string, error) {
i.status.RecipeInstalling(execution.RecipeStatusEvent{Recipe: *r})
// Execute the recipe steps.
if err := i.recipeExecutor.Execute(ctx, *r, vars); err != nil {
if err == types.ErrInterrupt {
return "", err
}
if e, ok := err.(*types.UnsupportedOperatingSystemError); ok {
i.status.RecipeUnsupported(execution.RecipeStatusEvent{
Recipe: *r,
Msg: e.Error(),
Metadata: i.recipeExecutor.GetOutput().Metadata(),
})
return "", err
}
// Needed to move some of the failure CLI output/messaging here. We want to capture metadata on when a user
// opts in/out of sending cli logs, and this must occur before we build the RecipeStatusEvent to post to NR
msg := fmt.Sprintf("execution failed for %s: %s", r.Name, err)
i.optInToSendLogsAndUpdateRecipeMetadata(r.Name)
se := execution.RecipeStatusEvent{
Recipe: *r,
Msg: msg,
Metadata: i.recipeExecutor.GetOutput().Metadata(),
}
if e, ok := err.(types.GoTaskError); ok {
e.SetError(msg)
se.TaskPath = e.TaskPath()
} else {
err = errors.New(msg)
}
i.status.RecipeFailed(se)
return "", err
}
entityGUID := i.recipeExecutor.GetOutput().EntityGUID()
if entityGUID != "" {
log.Debugf("Found entityGuid from recipe execution:%s", entityGUID)
i.status.RecipeInstalled(execution.RecipeStatusEvent{
Recipe: *r,
EntityGUID: entityGUID,
Metadata: i.recipeExecutor.GetOutput().Metadata(),
})
return entityGUID, nil
}
// 'INFRA_KEY' is sent by the infrastructure-agent-installer recipe back to the CLI via the 'Metadata' mechanism writing to 'NR_CLI_OUTPUT'.
// Once retrieved from the 'Metadata' output of the infrastructure agent, it is then made globally available for the rest of the subsequent
// recipes to be installed so they can use it for validation purposes.
if r.Name == types.InfraAgentRecipeName {
infraAgentEntityKey = i.recipeExecutor.GetOutput().Metadata()["INFRA_KEY"]
if infraAgentEntityKey == "" {
log.Debug("empty infrastructure agent entity key")
}
}
// show validation spinner if we need to validate and has no other spinner (Spinner is show when assume yes)
if !assumeYes {
msg := fmt.Sprintf("Validating %s", r.DisplayName)
i.progressIndicator.ShowSpinner(!assumeYes)
i.progressIndicator.Start(msg)
}
validationStart := time.Now()
entityGUID, err := i.validateRecipeViaAllMethods(ctx, r, m, vars, assumeYes)
validationDurationMs := time.Since(validationStart).Milliseconds()
if err != nil {
validationErr := fmt.Errorf("encountered an error while validating receipt of data for %s: %w", r.Name, err)
i.status.RecipeFailed(execution.RecipeStatusEvent{
Recipe: *r,
Msg: validationErr.Error(),
ValidationDurationMs: validationDurationMs,
Metadata: i.recipeExecutor.GetOutput().Metadata(),
})
return "", validationErr
}
i.status.RecipeInstalled(execution.RecipeStatusEvent{
Recipe: *r,
EntityGUID: entityGUID,
ValidationDurationMs: validationDurationMs,
Metadata: i.recipeExecutor.GetOutput().Metadata(),
})
return entityGUID, nil
}
func (i *RecipeInstall) optInToSendLogsAndUpdateRecipeMetadata(recipeName string) {
i.progressIndicator.Fail("Installing " + recipeName)
recipeOutput := i.recipeExecutor.GetRecipeOutput()
logCaptureEnabledForRecipe := i.recipeExecutor.GetOutput().IsCapturedCliOutput()
if len(recipeOutput) > 0 && logCaptureEnabledForRecipe {
userOptIn := i.recipeLogForwarder.PromptUserToSendLogs(os.Stdin)
i.recipeLogForwarder.SetUserOptedIn(userOptIn)
i.recipeExecutor.GetOutput().AddMetadata("SendLogsOptIn", strconv.FormatBool(userOptIn))
}
}
type validationFunc func() (string, error)
// Post install validation
func (i *RecipeInstall) validateRecipeViaAllMethods(ctx context.Context, r *types.OpenInstallationRecipe, m *types.DiscoveryManifest, vars types.RecipeVars, assumeYes bool) (string, error) {
timeoutCtx, cancel := context.WithTimeout(ctx, validationTimeout)
defer cancel()
entityGUIDChan := make(chan string)
validationErrorChan := make(chan error)
validationErrors := []error{}
validationFuncs := []validationFunc{}
// Add agent validation if configured
hasValidationURL := r.ValidationURL != ""
isAbsoluteURL := utils.IsAbsoluteURL(r.ValidationURL)
if hasValidationURL && isAbsoluteURL {
validationFuncs = append(validationFuncs, func() (string, error) {
return i.agentValidator.Validate(timeoutCtx, r.ValidationURL)
})
} else {
log.Debugf("no validationUrl defined, skipping")
}
hasValidationIntegration := r.ValidationIntegration != ""
hasValidationNRQL := r.ValidationNRQL != ""
// Add either Integration Validation or NRQL Validation if configured
if hasValidationIntegration {
integrationName := r.ValidationIntegration
validationFuncs = append(validationFuncs, func() (string, error) {
return validation.ValidateIntegration(integrationName)
})
} else {
log.Debugf("no validationIntegration defined, skipping")
}
if hasValidationNRQL {
validationFuncs = append(validationFuncs, func() (string, error) {
return i.recipeValidator.ValidateRecipe(timeoutCtx, *m, *r, vars)
})
} else {
log.Debugf("no validationNRQL defined, skipping")
}
if len(validationFuncs) == 0 {
return "", nil
}
for _, f := range validationFuncs {
go func(fn validationFunc) {
entityGUID, err := fn()
if err != nil {
validationErrorChan <- err
return
}
entityGUIDChan <- entityGUID
}(f)
}
for {
select {
case entityGUID := <-entityGUIDChan:
return entityGUID, nil
case err := <-validationErrorChan:
validationErrors = append(validationErrors, err)
log.Debugf("validation error encountered: %s", err)
if len(validationErrors) == len(validationFuncs) {
return "", fmt.Errorf("no validation was successful. most recent validation error: %w", err)
}
case <-timeoutCtx.Done():
return "", fmt.Errorf("timed out waiting for validation to succeed")
}
}
}
// Installing recipe
func (i *RecipeInstall) executeAndValidateWithProgress(ctx context.Context, m *types.DiscoveryManifest, r *types.OpenInstallationRecipe, assumeYes bool) (string, error) {
fmt.Println()
msg := fmt.Sprintf("Installing %s", r.DisplayName)
errorChan := make(chan error)
successChan := make(chan string)
go func() {
vars, err := i.recipeVarPreparer.Prepare(*m, *r, assumeYes)
if err != nil {
errorChan <- err
return
}
vars["assumeYes"] = fmt.Sprintf("%v", assumeYes)
if infraAgentEntityKey != "" {
vars["INFRA_KEY"] = infraAgentEntityKey
}
entityGUID, err := i.executeAndValidate(ctx, m, r, vars, assumeYes)
if err != nil {
errorChan <- err
return
}
successChan <- entityGUID
}()
i.progressIndicator.ShowSpinner(assumeYes)
i.progressIndicator.Start(msg)
for {
select {
case entityGUID := <-successChan:
i.progressIndicator.Success("Installing " + r.DisplayName)
return entityGUID, nil
case err := <-errorChan:
if errors.Is(err, types.ErrInterrupt) {
i.progressIndicator.Canceled("Installing " + r.DisplayName)
i.status.RecipeCanceled(execution.RecipeStatusEvent{Recipe: *r})
} else {
// progressIndicator has already been called; we need to finish i.e. message about logs being sent
// and actually post logs to NR if the user has opted-in
i.finishHandlingFailure(r.DisplayName)
}
log.Debugf("install error encountered: %s", err)
return "", err
}
}
}
func (i *RecipeInstall) finishHandlingFailure(recipeName string) {
if i.recipeLogForwarder.HasUserOptedIn() {
i.progressIndicator.Start("Sending logs to New Relic")
i.recipeLogForwarder.SendLogsToNewRelic(recipeName, i.recipeExecutor.GetRecipeOutput())
i.progressIndicator.Success("Complete!")
}
}