Skip to content

Commit

Permalink
refactor: add override capable getters to config provider
Browse files Browse the repository at this point in the history
  • Loading branch information
ctrombley committed Jul 8, 2021
1 parent 7b55db1 commit 3c3f7c7
Show file tree
Hide file tree
Showing 18 changed files with 141 additions and 64 deletions.
24 changes: 4 additions & 20 deletions cmd/newrelic/command.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package main

import (
"os"
"strconv"

log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
Expand All @@ -17,9 +16,6 @@ import (
var (
outputFormat string
outputPlain bool
debug bool
trace bool
accountID int
)

// Command represents the base command when called without any subcommands
Expand All @@ -33,18 +29,6 @@ var Command = &cobra.Command{
}

func initializeCLI(cmd *cobra.Command, args []string) {
if debug {
os.Setenv("NEW_RELIC_CLI_LOG_LEVEL", "debug")
}

if trace {
os.Setenv("NEW_RELIC_CLI_LOG_LEVEL", "trace")
}

if accountID != 0 {
os.Setenv("NEW_RELIC_ACCOUNT_ID", strconv.Itoa(accountID))
}

logLevel := configuration.GetConfigString(configuration.LogLevel)
configuration.InitLogger(logLevel)

Expand Down Expand Up @@ -82,11 +66,11 @@ func init() {
cobra.OnInitialize(initConfig)

Command.PersistentFlags().StringVar(&outputFormat, "format", output.DefaultFormat.String(), "output text format ["+output.FormatOptions()+"]")
Command.PersistentFlags().StringVar(&configuration.SelectedProfileName, "profileName", configuration.DefaultProfileName, "the authentication profile to use")
Command.PersistentFlags().StringVar(&configuration.FlagProfileName, "profileName", configuration.DefaultProfileName, "the authentication profile to use")
Command.PersistentFlags().BoolVar(&outputPlain, "plain", false, "output compact text")
Command.PersistentFlags().BoolVar(&debug, "debug", false, "debug level logging")
Command.PersistentFlags().BoolVar(&trace, "trace", false, "trace level logging")
Command.PersistentFlags().IntVarP(&accountID, "accountId", "a", 0, "trace level logging")
Command.PersistentFlags().BoolVar(&configuration.FlagDebug, "debug", false, "debug level logging")
Command.PersistentFlags().BoolVar(&configuration.FlagTrace, "trace", false, "trace level logging")
Command.PersistentFlags().IntVarP(&configuration.FlagAccountID, "accountId", "a", 0, "trace level logging")
}

func initConfig() {
Expand Down
2 changes: 1 addition & 1 deletion internal/apm/command_application.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ The search command performs a query for an APM application name and/or account I
Example: "newrelic apm application search --name <appName>",
PreRun: client.RequireClient,
Run: func(cmd *cobra.Command, args []string) {
accountID := configuration.GetActiveProfileInt(configuration.AccountID)
accountID := configuration.GetActiveProfileAccountID()

if appGUID == "" && appName == "" && accountID == 0 {
utils.LogIfError(cmd.Help())
Expand Down
65 changes: 61 additions & 4 deletions internal/configuration/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,11 @@ var (
configProvider *ConfigProvider
credentialsProvider *ConfigProvider
BasePath string = configBasePath()
SelectedProfileName string

FlagProfileName string
FlagDebug bool
FlagTrace bool
FlagAccountID int
)

func init() {
Expand Down Expand Up @@ -131,8 +135,8 @@ func initializeConfigProvider() {
}

func GetActiveProfileName() string {
if SelectedProfileName != "" {
return SelectedProfileName
if FlagProfileName != "" {
return FlagProfileName
}

profileName, err := GetDefaultProfileName()
Expand Down Expand Up @@ -177,6 +181,41 @@ func GetProfileString(profileName string, key ConfigKey) string {
return v
}

func GetLogLevel() string {
var override string
if FlagDebug {
override = "debug"
}

if FlagTrace {
override = "trace"
}

return GetConfigStringWithOverride(LogLevel, override)
}

func RequireActiveProfileAccountID() int {
v := GetActiveProfileAccountID()
if v == 0 {
log.Fatalf("%s is required", AccountID)
}

return v
}

func GetActiveProfileAccountID() int {
return GetActiveProfileIntWithOverride(AccountID, FlagAccountID)
}

func RequireActiveProfileIntWithOverride(key ConfigKey, override int) int {
v := GetProfileIntWithOverride(GetActiveProfileName(), key, override)
if v == 0 {
log.Fatalf("%s is required", key)
}

return v
}

func RequireActiveProfileInt(key ConfigKey) int {
v := GetProfileInt(GetActiveProfileName(), key)
if v == 0 {
Expand All @@ -190,6 +229,10 @@ func GetActiveProfileInt(key ConfigKey) int {
return GetProfileInt(GetActiveProfileName(), key)
}

func GetActiveProfileIntWithOverride(key ConfigKey, override int) int {
return GetProfileIntWithOverride(GetActiveProfileName(), key, override)
}

func GetProfileInt(profileName string, key ConfigKey) int {
v, err := credentialsProvider.GetIntWithScope(GetActiveProfileName(), key)
if err != nil {
Expand All @@ -199,8 +242,22 @@ func GetProfileInt(profileName string, key ConfigKey) int {
return int(v)
}

func GetProfileIntWithOverride(profileName string, key ConfigKey, override int) int {
o := int64(override)
v, err := credentialsProvider.GetIntWithScopeAndOverride(GetActiveProfileName(), key, &o)
if err != nil {
log.Fatalf("could not load value %s from config: %s", key, err)
}

return int(v)
}

func GetConfigString(key ConfigKey) string {
v, err := configProvider.GetString(key)
return GetConfigStringWithOverride(key, "")
}

func GetConfigStringWithOverride(key ConfigKey, override string) string {
v, err := configProvider.GetStringWithOverride(key, &override)
if err != nil {
log.Fatalf("could not load value %s from config: %s", key, err)
}
Expand Down
42 changes: 39 additions & 3 deletions internal/configuration/config_provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,11 @@ func (p *ConfigProvider) GetInt(key ConfigKey) (int64, error) {
}

func (p *ConfigProvider) GetString(key ConfigKey) (string, error) {
return p.GetStringWithScope("", key)
return p.GetStringWithScopeAndOverride("", key, nil)
}

func (p *ConfigProvider) GetStringWithOverride(key ConfigKey, override *string) (string, error) {
return p.GetStringWithScopeAndOverride("", key, override)
}

func (p *ConfigProvider) GetTernary(key ConfigKey) (Ternary, error) {
Expand All @@ -172,7 +176,19 @@ func (p *ConfigProvider) GetTernaryWithScope(scope string, key ConfigKey) (Terna
}

func (p *ConfigProvider) GetIntWithScope(scope string, key ConfigKey) (int64, error) {
v, err := p.GetWithScope(scope, key)
return p.GetIntWithScopeAndOverride(scope, key, nil)
}

func (p *ConfigProvider) GetIntWithScopeAndOverride(scope string, key ConfigKey, override *int64) (int64, error) {
var v interface{}
var err error

if override == nil {
v, err = p.GetWithScopeAndOverride(scope, key, nil)
} else {
v, err = p.GetWithScopeAndOverride(scope, key, *override)
}

if err != nil {
return 0, err
}
Expand Down Expand Up @@ -200,7 +216,19 @@ func (p *ConfigProvider) GetIntWithScope(scope string, key ConfigKey) (int64, er
}

func (p *ConfigProvider) GetStringWithScope(scope string, key ConfigKey) (string, error) {
v, err := p.GetWithScope(scope, key)
return p.GetStringWithScopeAndOverride(scope, key, nil)
}

func (p *ConfigProvider) GetStringWithScopeAndOverride(scope string, key ConfigKey, override *string) (string, error) {
var v interface{}
var err error

if override == nil || *override == "" {
v, err = p.GetWithScope(scope, key)
} else {
v, err = p.GetWithScopeAndOverride(scope, key, *override)
}

if err != nil {
return "", err
}
Expand Down Expand Up @@ -228,6 +256,10 @@ func (p *ConfigProvider) Get(key ConfigKey) (interface{}, error) {
}

func (p *ConfigProvider) GetWithScope(scope string, key ConfigKey) (interface{}, error) {
return p.GetWithScopeAndOverride(scope, key, nil)
}

func (p *ConfigProvider) GetWithScopeAndOverride(scope string, key ConfigKey, overridePtr interface{}) (interface{}, error) {
d := p.getFieldDefinition(key)

if d != nil {
Expand All @@ -241,6 +273,10 @@ func (p *ConfigProvider) GetWithScope(scope string, key ConfigKey) (interface{},
}
}

if overridePtr != nil {
return overridePtr, nil
}

res, err := p.getFromConfig(p.getPath(scope, key))
if err != nil {
if d != nil && d.Default != nil {
Expand Down
6 changes: 3 additions & 3 deletions internal/diagnose/config_validator.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ func NewConfigValidator(client *newrelic.NewRelic) *ConfigValidator {
}

func (c *ConfigValidator) Validate(ctx context.Context) error {
accountID := configuration.GetActiveProfileInt(configuration.AccountID)
accountID := configuration.GetActiveProfileAccountID()

if err := c.validateKeys(ctx); err != nil {
return err
Expand Down Expand Up @@ -119,7 +119,7 @@ func (c *ConfigValidator) validateKeys(ctx context.Context) error {
}

func (c *ConfigValidator) validateInsightsInsertKey(ctx context.Context) error {
accountID := configuration.GetActiveProfileInt(configuration.AccountID)
accountID := configuration.GetActiveProfileAccountID()
insightsInsertKey := configuration.GetActiveProfileString(configuration.InsightsInsertKey)
insightsInsertKeys, err := c.client.APIAccess.ListInsightsInsertKeysWithContext(ctx, accountID)
if err != nil {
Expand All @@ -136,7 +136,7 @@ func (c *ConfigValidator) validateInsightsInsertKey(ctx context.Context) error {
}

func (c *ConfigValidator) validateLicenseKey(ctx context.Context) error {
accountID := configuration.GetActiveProfileInt(configuration.AccountID)
accountID := configuration.GetActiveProfileAccountID()
licenseKey := configuration.GetActiveProfileString(configuration.LicenseKey)
params := apiaccess.APIAccessKeySearchQuery{
Scope: apiaccess.APIAccessKeySearchScope{
Expand Down
6 changes: 3 additions & 3 deletions internal/edge/command_trace_observer.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ The list command retrieves the trace observers for the given account ID.
Example: `newrelic edge trace-observer list --accountId 12345678`,
PreRun: client.RequireClient,
Run: func(cmd *cobra.Command, args []string) {
accountID := configuration.RequireActiveProfileInt(configuration.AccountID)
accountID := configuration.RequireActiveProfileAccountID()
traceObservers, err := client.NRClient.Edge.ListTraceObserversWithContext(utils.SignalCtx, accountID)
utils.LogIfFatal(err)

Expand Down Expand Up @@ -72,7 +72,7 @@ Valid provider regions are AWS_US_EAST_1 and AWS_US_EAST_2.
Example: `newrelic edge trace-observer create --name 'My Observer' --accountId 12345678 --providerRegion AWS_US_EAST_1`,
PreRun: client.RequireClient,
Run: func(cmd *cobra.Command, args []string) {
accountID := configuration.RequireActiveProfileInt(configuration.AccountID)
accountID := configuration.RequireActiveProfileAccountID()
if ok := isValidProviderRegion(providerRegion); !ok {
log.Fatalf("%s is not a valid provider region, valid values are %s", providerRegion, validProviderRegions)
}
Expand All @@ -95,7 +95,7 @@ The delete command accepts a trace observer's ID.
Example: `newrelic edge trace-observer delete --accountId 12345678 --id 1234`,
PreRun: client.RequireClient,
Run: func(cmd *cobra.Command, args []string) {
accountID := configuration.RequireActiveProfileInt(configuration.AccountID)
accountID := configuration.RequireActiveProfileAccountID()
_, err := client.NRClient.Edge.DeleteTraceObserver(accountID, id)
utils.LogIfFatal(err)

Expand Down
2 changes: 1 addition & 1 deletion internal/events/command_post.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ represents the custom event's type.
Example: `newrelic events post --accountId 12345 --event '{ "eventType": "Payment", "amount": 123.45 }'`,
PreRun: client.RequireClient,
Run: func(cmd *cobra.Command, args []string) {
accountID := configuration.RequireActiveProfileInt(configuration.AccountID)
accountID := configuration.RequireActiveProfileAccountID()
if configuration.GetActiveProfileString(configuration.InsightsInsertKey) == "" {
log.Fatal("an Insights insert key is required, set one in your default profile or use the NEW_RELIC_INSIGHTS_INSERT_KEY environment variable")
}
Expand Down
2 changes: 1 addition & 1 deletion internal/install/command.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ var Command = &cobra.Command{
}

func assertProfileIsValid() error {
if configuration.GetActiveProfileInt(configuration.AccountID) == 0 {
if configuration.GetActiveProfileAccountID() == 0 {
return fmt.Errorf("accountID is required")
}

Expand Down
2 changes: 1 addition & 1 deletion internal/install/execution/nerdstorage_status_reporter.go
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ func (r NerdstorageStatusReporter) writeStatus(status *InstallStatus) error {
log.Debug("no entity GUIDs available, skipping entity-scoped status updates")
}

accountID := configuration.GetActiveProfileInt(configuration.AccountID)
accountID := configuration.GetActiveProfileAccountID()
_, err = r.client.WriteDocumentWithAccountScope(accountID, i)
if err != nil {
log.Debug("failed to write to account scoped nerd storage")
Expand Down
2 changes: 1 addition & 1 deletion internal/install/execution/platform_link_generator.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ func generateExplorerLink(filter string) string {
return fmt.Sprintf("https://%s/launcher/nr1-core.explorer?platform[filters]=%s&platform[accountId]=%d",
nrPlatformHostname(),
utils.Base64Encode(filter),
configuration.GetActiveProfileInt(configuration.AccountID),
configuration.GetActiveProfileAccountID(),
)
}

Expand Down
2 changes: 1 addition & 1 deletion internal/install/packs/service_packs_installer.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ func (p *ServicePacksInstaller) Install(ctx context.Context, packs []types.OpenI
}

func (p *ServicePacksInstaller) createObservabilityPackDashboard(ctx context.Context, d types.OpenInstallationObservabilityPackDashboard) (*dashboards.DashboardCreateResult, error) {
accountID := configuration.GetActiveProfileInt(configuration.AccountID)
accountID := configuration.GetActiveProfileAccountID()

body, err := getJSONfromURL(d.URL)
if err != nil {
Expand Down
4 changes: 2 additions & 2 deletions internal/nerdstorage/command_collection.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ GUID. A valid Nerdpack package ID is required.

switch strings.ToLower(scope) {
case "account":
accountID := configuration.RequireActiveProfileInt(configuration.AccountID)
accountID := configuration.RequireActiveProfileAccountID()
resp, err = client.NRClient.NerdStorage.GetCollectionWithAccountScopeWithContext(utils.SignalCtx, accountID, input)
case "entity":
resp, err = client.NRClient.NerdStorage.GetCollectionWithEntityScopeWithContext(utils.SignalCtx, entityGUID, input)
Expand Down Expand Up @@ -99,7 +99,7 @@ GUID. A valid Nerdpack package ID is required.

switch strings.ToLower(scope) {
case "account":
accountID := configuration.RequireActiveProfileInt(configuration.AccountID)
accountID := configuration.RequireActiveProfileAccountID()
_, err = client.NRClient.NerdStorage.DeleteCollectionWithAccountScopeWithContext(utils.SignalCtx, accountID, input)
case "entity":
_, err = client.NRClient.NerdStorage.DeleteCollectionWithEntityScopeWithContext(utils.SignalCtx, entityGUID, input)
Expand Down
6 changes: 3 additions & 3 deletions internal/nerdstorage/command_document.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ GUID. A valid Nerdpack package ID is required.

switch strings.ToLower(scope) {
case "account":
accountID := configuration.RequireActiveProfileInt(configuration.AccountID)
accountID := configuration.RequireActiveProfileAccountID()
document, err = client.NRClient.NerdStorage.GetDocumentWithAccountScopeWithContext(utils.SignalCtx, accountID, input)
case "entity":
document, err = client.NRClient.NerdStorage.GetDocumentWithEntityScopeWithContext(utils.SignalCtx, entityGUID, input)
Expand Down Expand Up @@ -107,7 +107,7 @@ GUID. A valid Nerdpack package ID is required.

switch strings.ToLower(scope) {
case "account":
accountID := configuration.RequireActiveProfileInt(configuration.AccountID)
accountID := configuration.RequireActiveProfileAccountID()
_, err = client.NRClient.NerdStorage.WriteDocumentWithAccountScopeWithContext(utils.SignalCtx, accountID, input)
case "entity":
_, err = client.NRClient.NerdStorage.WriteDocumentWithEntityScopeWithContext(utils.SignalCtx, entityGUID, input)
Expand Down Expand Up @@ -155,7 +155,7 @@ GUID. A valid Nerdpack package ID is required.

switch strings.ToLower(scope) {
case "account":
accountID := configuration.RequireActiveProfileInt(configuration.AccountID)
accountID := configuration.RequireActiveProfileAccountID()
_, err = client.NRClient.NerdStorage.DeleteDocumentWithAccountScopeWithContext(utils.SignalCtx, accountID, input)
case "entity":
_, err = client.NRClient.NerdStorage.DeleteDocumentWithEntityScopeWithContext(utils.SignalCtx, entityGUID, input)
Expand Down
2 changes: 1 addition & 1 deletion internal/nrql/command_query.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ issue the query against.
Example: `newrelic nrql query --accountId 12345678 --query 'SELECT count(*) FROM Transaction TIMESERIES'`,
PreRun: client.RequireClient,
Run: func(cmd *cobra.Command, args []string) {
accountID := configuration.RequireActiveProfileInt(configuration.AccountID)
accountID := configuration.RequireActiveProfileAccountID()
result, err := client.NRClient.Nrdb.QueryWithContext(utils.SignalCtx, accountID, nrdb.NRQL(query))
if err != nil {
log.Fatal(err)
Expand Down
Loading

0 comments on commit 3c3f7c7

Please sign in to comment.