Skip to content

Commit

Permalink
chore: Update client get license key (#1487)
Browse files Browse the repository at this point in the history
  • Loading branch information
NRhzhao authored Jul 21, 2023
1 parent 2c96acc commit 89c0cb4
Show file tree
Hide file tree
Showing 17 changed files with 104 additions and 168 deletions.
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ require (
github.com/jedib0t/go-pretty/v6 v6.4.4
github.com/joshdk/go-junit v0.0.0-20210226021600-6145f504ca0d
github.com/mitchellh/go-homedir v1.1.0
github.com/newrelic/newrelic-client-go/v2 v2.12.0
github.com/newrelic/newrelic-client-go/v2 v2.19.6
github.com/pkg/errors v0.9.1
github.com/shirou/gopsutil/v3 v3.22.12
github.com/sirupsen/logrus v1.9.0
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,8 @@ github.com/mitchellh/hashstructure/v2 v2.0.2/go.mod h1:MG3aRVU/N29oo/V/IhBX8GR/z
github.com/mitchellh/mapstructure v1.4.3 h1:OVowDSCllw/YjdLkam3/sm7wEtOy59d8ndGgCcyj8cs=
github.com/newrelic/newrelic-client-go/v2 v2.12.0 h1:w1gCmKkQqQtG/z4HNDs/5dT2lQAssMaJamTH+Vo2P8Y=
github.com/newrelic/newrelic-client-go/v2 v2.12.0/go.mod h1:xDZ6IDWI6fpl7MhTI4Hk75alJLAIfXzOt/rINEolxhQ=
github.com/newrelic/newrelic-client-go/v2 v2.19.6 h1:nKMVor/8ujdF37dipVzk+Tq13Mv3bEfGDDSW63C8PY0=
github.com/newrelic/newrelic-client-go/v2 v2.19.6/go.mod h1:VPWTvEfKvnTZLunAC7fiW33y4e0srznNfN5HJH2cOp8=
github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A=
github.com/nxadm/tail v1.4.8 h1:nPr65rt6Y5JFSKQO7qToXr7pePgD6Gwiw05lkbyAQTE=
github.com/nxadm/tail v1.4.8/go.mod h1:+ncqLTQzXmGhMZNUePPaPqPvBxHAIsmXswZKocGu+AU=
Expand Down
31 changes: 29 additions & 2 deletions internal/client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"errors"
"fmt"
"sort"

"github.com/spf13/cobra"

Expand All @@ -24,6 +25,10 @@ var (
serviceName = "newrelic-cli"
)

const (
PreferredIngestKeyName = "Installer Ingest License Key"
)

// NewClient initializes the New Relic client.
func NewClient(profileName string) (*newrelic.NewRelic, error) {
apiKey := configAPI.GetProfileString(profileName, config.APIKey)
Expand Down Expand Up @@ -119,9 +124,31 @@ func execLicenseKeyRequest(ctx context.Context, client *newrelic.NewRelic, accou
return "", err
}

if len(keys) > 0 {
return keys[0].Key, nil
key := getPreferredLicenseKey(keys)
if key != "" {
return key, nil
}

return "", types.ErrorFetchingLicenseKey
}

// Prefer using the earliest created APIKS license key named "Installer Ingest License Key" if exists.
// Otherwise, fallback to the Account Provisioning "Original account license key"
func getPreferredLicenseKey(keys []apiaccess.APIKey) string {
key := ""
if len(keys) > 0 {
sort.Slice(keys, func(i, j int) bool {
return keys[i].CreatedAt < keys[j].CreatedAt
})

key = keys[0].Key
for _, k := range keys {
if k.Name == PreferredIngestKeyName {
key = k.Key
break
}
}
}

return key
}
43 changes: 43 additions & 0 deletions internal/client/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"github.com/stretchr/testify/require"

"github.com/newrelic/newrelic-cli/internal/config"
"github.com/newrelic/newrelic-client-go/v2/pkg/apiaccess"
)

func TestClientFetchLicenseKey(t *testing.T) {
Expand All @@ -30,3 +31,45 @@ func TestClientFetchLicenseKey(t *testing.T) {
require.NoError(t, err)
require.NotNil(t, result)
}

func TestClientGetLicenseKey(t *testing.T) {

keys := []apiaccess.APIKey{
{
APIAccessKey: apiaccess.APIAccessKey{
Key: "key1",
CreatedAt: 1,
},
},
{
APIAccessKey: apiaccess.APIAccessKey{
Key: "key2",
CreatedAt: 2,
},
},
}

key := getPreferredLicenseKey(keys)

require.Equal(t, "key1", key, "Get License Key should return earlist if no prefer key name")

keys = append(keys, apiaccess.APIKey{
APIAccessKey: apiaccess.APIAccessKey{
Key: "preferKey1",
CreatedAt: 3,
Name: PreferredIngestKeyName,
},
})

keys = append(keys, apiaccess.APIKey{
APIAccessKey: apiaccess.APIAccessKey{
Key: "preferKey2",
CreatedAt: 4,
Name: PreferredIngestKeyName,
},
})

key = getPreferredLicenseKey(keys)

require.Equal(t, "preferKey1", key, "Get License Key should return earlist key with prefer key name")
}
6 changes: 2 additions & 4 deletions internal/install/command.go
Original file line number Diff line number Diff line change
Expand Up @@ -156,10 +156,8 @@ func validateProfile(maxTimeoutSeconds int, sg *segment.Segment) *types.DetailEr
return detailErr
}

if licenseKey != configAPI.GetActiveProfileString(config.LicenseKey) {
os.Setenv("NEW_RELIC_LICENSE_KEY", licenseKey)
log.Debugf("using license key %s", utils.Obfuscate(licenseKey))
}
os.Setenv("NEW_RELIC_LICENSE_KEY", licenseKey)
log.Debugf("using license key %s", utils.Obfuscate(licenseKey))

return nil
}
Expand Down
2 changes: 1 addition & 1 deletion internal/install/execution/mock_recipe_var_provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,6 @@ func NewMockRecipeVarProvider() *MockRecipeVarProvider {
return &MockRecipeVarProvider{}
}

func (rvp *MockRecipeVarProvider) Prepare(m types.DiscoveryManifest, r types.OpenInstallationRecipe, assumeYes bool, licenseKey string) (types.RecipeVars, error) {
func (rvp *MockRecipeVarProvider) Prepare(m types.DiscoveryManifest, r types.OpenInstallationRecipe, assumeYes bool) (types.RecipeVars, error) {
return rvp.Vars, rvp.Error
}
13 changes: 4 additions & 9 deletions internal/install/execution/recipe_var_provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package execution

import (
"encoding/json"
"errors"
"fmt"
"net/url"
"os"
Expand Down Expand Up @@ -39,7 +38,7 @@ func NewRecipeVarProvider() *RecipeVarProvider {
return &RecipeVarProvider{}
}

func (re *RecipeVarProvider) Prepare(m types.DiscoveryManifest, r types.OpenInstallationRecipe, assumeYes bool, licenseKey string) (types.RecipeVars, error) {
func (re *RecipeVarProvider) Prepare(m types.DiscoveryManifest, r types.OpenInstallationRecipe, assumeYes bool) (types.RecipeVars, error) {
log.WithFields(log.Fields{
"name": r.Name,
}).Debug("preparing recipe")
Expand All @@ -50,7 +49,7 @@ func (re *RecipeVarProvider) Prepare(m types.DiscoveryManifest, r types.OpenInst

systemInfoResult := varsFromSystemInfo(m)

profileResult, err := varsFromProfile(licenseKey)
profileResult, err := varsFromProfile()
if err != nil {
return types.RecipeVars{}, err
}
Expand All @@ -77,18 +76,14 @@ func (re *RecipeVarProvider) Prepare(m types.DiscoveryManifest, r types.OpenInst
return vars, nil
}

func varsFromProfile(licenseKey string) (types.RecipeVars, error) {
func varsFromProfile() (types.RecipeVars, error) {
accountID := configAPI.GetActiveProfileString(config.AccountID)
apiKey := configAPI.GetActiveProfileString(config.APIKey)
region := configAPI.GetActiveProfileString(config.Region)

if licenseKey == "" {
return types.RecipeVars{}, errors.New("license key not found")
}

vars := make(types.RecipeVars)

vars["NEW_RELIC_LICENSE_KEY"] = licenseKey
vars["NEW_RELIC_LICENSE_KEY"] = os.Getenv("NEW_RELIC_LICENSE_KEY")
vars["NEW_RELIC_ACCOUNT_ID"] = accountID
vars["NEW_RELIC_API_KEY"] = apiKey
vars["NEW_RELIC_REGION"] = region
Expand Down
28 changes: 15 additions & 13 deletions internal/install/execution/recipe_var_provider_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ func TestRecipeVarProvider_Basic(t *testing.T) {
Install: string(installYamlBytes),
}

v, err := e.Prepare(m, r, false, "testLicenseKey")
v, err := e.Prepare(m, r, false)
require.NoError(t, err)
require.Contains(t, m.OS, v["OS"])
require.Contains(t, m.Platform, v["Platform"])
Expand All @@ -84,14 +84,16 @@ func TestRecipeVarProvider_Basic(t *testing.T) {
require.Contains(t, "https://download.newrelic.com/", v["NEW_RELIC_DOWNLOAD_URL"])

os.Setenv(EnvInstallCustomAttributes, "test:123,bad")
v, err = e.Prepare(m, r, false, "testLicenseKey")
v, err = e.Prepare(m, r, false)
require.NoError(t, err)
require.Equal(t, "custom_attributes:\n test: \"123\"\n", v["NRIA_CUSTOM_ATTRIBUTES"])

os.Setenv(EnvNriaCustomAttributes, "{\"owning_team\":\"virtuoso\"}")
v, err = e.Prepare(m, r, false, "testLicenseKey")
os.Setenv("NEW_RELIC_LICENSE_KEY", "my_license")
v, err = e.Prepare(m, r, false)
require.NoError(t, err)
require.Equal(t, "custom_attributes:\n owning_team: virtuoso\n test: \"123\"\n", v["NRIA_CUSTOM_ATTRIBUTES"])
require.Equal(t, "my_license", v["NEW_RELIC_LICENSE_KEY"])
}

func TestRecipeVarProvider_UserInputVars(t *testing.T) {
Expand Down Expand Up @@ -156,7 +158,7 @@ func TestRecipeVarProvider_UserInputVars(t *testing.T) {
InputVars: inputVars,
}

v, err := e.Prepare(m, r, false, "testLicenseKey")
v, err := e.Prepare(m, r, false)
require.NoError(t, err)
require.Contains(t, m.OS, v["OS"])
require.Contains(t, m.Platform, v["Platform"])
Expand All @@ -175,7 +177,7 @@ func TestRecipeVarProvider_UserInputVars(t *testing.T) {
InputVars: inputVars,
}

v, err = e.Prepare(m, r, true, "testLicenseKey")
v, err = e.Prepare(m, r, true)
require.NoError(t, err)
require.Contains(t, "123", v["a-default"])
}
Expand Down Expand Up @@ -243,7 +245,7 @@ func TestRecipeVarProvider_CommandLineEnvarsDirectlyPassedToRecipeContext(t *tes
clusterName := "sweet-cluster-name"
os.Setenv("NR_CLI_CLUSTERNAME", clusterName)

v, err := e.Prepare(m, r, false, "testLicenseKey")
v, err := e.Prepare(m, r, false)
require.NoError(t, err)
require.Contains(t, v["OS"], m.OS)
assert.Contains(t, m.Platform, v["Platform"])
Expand Down Expand Up @@ -314,7 +316,7 @@ func TestRecipeVarProvider_CommandLineTagsPassedFormattedToRecipeContext(t *test
expectedCliTags := "some:tag;another:something;nr_deployed_by:unit_test"
os.Setenv(EnvInstallCustomAttributes, cliTags)

v, err := e.Prepare(m, r, false, "testLicenseKey")
v, err := e.Prepare(m, r, false)
require.NoError(t, err)
require.Contains(t, v["OS"], m.OS)
assert.Contains(t, m.Platform, v["Platform"])
Expand Down Expand Up @@ -462,7 +464,7 @@ func TestRecipeVarProvider_OverrideDownloadURL(t *testing.T) {
// Test for NEW_RELIC_DOWNLOAD_URL
os.Setenv("NEW_RELIC_DOWNLOAD_URL", "https://another.download.newrelic.com/")

v, err := e.Prepare(m, r, false, "testLicenseKey")
v, err := e.Prepare(m, r, false)
require.NoError(t, err)
require.Contains(t, "https://another.download.newrelic.com/", v["NEW_RELIC_DOWNLOAD_URL"])
}
Expand Down Expand Up @@ -526,7 +528,7 @@ func TestRecipeVarProvider_AllowInfraStaging(t *testing.T) {
// Test for NEW_RELIC_DOWNLOAD_URL
os.Setenv("NEW_RELIC_DOWNLOAD_URL", "https://nr-downloads-ohai-staging.s3.amazonaws.com/")

v, err := e.Prepare(m, r, false, "testLicenseKey")
v, err := e.Prepare(m, r, false)
require.NoError(t, err)
require.Contains(t, "https://nr-downloads-ohai-staging.s3.amazonaws.com/", v["NEW_RELIC_DOWNLOAD_URL"])
}
Expand Down Expand Up @@ -590,7 +592,7 @@ func TestRecipeVarProvider_AllowInfraTesting(t *testing.T) {
// Test for NEW_RELIC_DOWNLOAD_URL
os.Setenv("NEW_RELIC_DOWNLOAD_URL", "https://nr-downloads-ohai-testing.s3.amazonaws.com/")

v, err := e.Prepare(m, r, false, "testLicenseKey")
v, err := e.Prepare(m, r, false)
require.NoError(t, err)
require.Contains(t, "https://nr-downloads-ohai-testing.s3.amazonaws.com/", v["NEW_RELIC_DOWNLOAD_URL"])
}
Expand Down Expand Up @@ -654,7 +656,7 @@ func TestRecipeVarProvider_DisallowUnknownInfraTesting(t *testing.T) {
// Test for NEW_RELIC_DOWNLOAD_URL
os.Setenv("NEW_RELIC_DOWNLOAD_URL", "https://nr-downloads-ohai-unknown.s3.amazonaws.com/")

v, err := e.Prepare(m, r, false, "testLicenseKey")
v, err := e.Prepare(m, r, false)
require.NoError(t, err)
require.Contains(t, "https://download.newrelic.com/", v["NEW_RELIC_DOWNLOAD_URL"])
}
Expand Down Expand Up @@ -718,7 +720,7 @@ func TestRecipeVarProvider_OverrideDownloadURL_RefusedNotHttps(t *testing.T) {
// Test for NEW_RELIC_DOWNLOAD_URL
os.Setenv("NEW_RELIC_DOWNLOAD_URL", "http://another.download.newrelic.com/")

v, err := e.Prepare(m, r, false, "testLicenseKey")
v, err := e.Prepare(m, r, false)
require.NoError(t, err)
require.Contains(t, "https://download.newrelic.com/", v["NEW_RELIC_DOWNLOAD_URL"])
}
Expand Down Expand Up @@ -782,7 +784,7 @@ func TestRecipeVarProvider_OverrideDownloadURL_RefusedNotNewRelic(t *testing.T)
// Test for NEW_RELIC_DOWNLOAD_URL
os.Setenv("NEW_RELIC_DOWNLOAD_URL", "http://github.com/")

v, err := e.Prepare(m, r, false, "testLicenseKey")
v, err := e.Prepare(m, r, false)
require.NoError(t, err)
require.Contains(t, "https://download.newrelic.com/", v["NEW_RELIC_DOWNLOAD_URL"])
}
2 changes: 1 addition & 1 deletion internal/install/interfaces.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ type AgentValidator interface {
}

type RecipeVarPreparer interface {
Prepare(m types.DiscoveryManifest, r types.OpenInstallationRecipe, assumeYes bool, licenseKey string) (types.RecipeVars, error)
Prepare(m types.DiscoveryManifest, r types.OpenInstallationRecipe, assumeYes bool) (types.RecipeVars, error)
}

// RecipeInstaller wrapper responsible for performing recipe validation, installation, and reporting install status
Expand Down
45 changes: 0 additions & 45 deletions internal/install/license_key_fetcher.go

This file was deleted.

29 changes: 0 additions & 29 deletions internal/install/license_key_fetcher_test.go

This file was deleted.

Loading

0 comments on commit 89c0cb4

Please sign in to comment.