From d433b492658fe50d87a6bb51fde80180fd804d47 Mon Sep 17 00:00:00 2001 From: Dmitrii Stepanov Date: Mon, 11 Mar 2024 17:55:50 +0300 Subject: [PATCH] [#973] node: Resolve perfsprint linter `fmt.Errorf can be replaced with errors.New` and `fmt.Sprintf can be replaced with string addition` Signed-off-by: Dmitrii Stepanov --- .../internal/modules/morph/ape/ape_util.go | 17 ++++++++++++----- .../internal/modules/morph/helper/contract.go | 2 +- .../internal/modules/morph/helper/download.go | 4 +++- .../modules/morph/helper/initialize_ctx.go | 10 ++++++++-- .../internal/modules/morph/helper/netmap.go | 4 +++- .../internal/modules/morph/notary/notary.go | 5 ++++- .../internal/modules/morph/policy/policy.go | 5 ++++- cmd/frostfs-cli/internal/client/client.go | 4 +++- cmd/frostfs-cli/modules/control/list_rules.go | 10 ++++++++-- cmd/frostfs-cli/modules/object/nodes.go | 4 +++- cmd/frostfs-cli/modules/util/ape.go | 3 ++- cmd/frostfs-ir/httpcomponent.go | 13 ++++++------- cmd/frostfs-ir/pprof.go | 5 ++--- cmd/frostfs-node/config.go | 4 ++-- cmd/frostfs-node/config/engine/shard/config.go | 4 +--- cmd/frostfs-node/config/morph/config.go | 6 ++++-- cmd/frostfs-node/httpcomponent.go | 3 +-- cmd/frostfs-node/main.go | 6 +++--- cmd/internal/common/config/viper.go | 5 ++++- internal/ape/converter.go | 2 +- pkg/ape/chainbase/boltdb.go | 4 +++- .../processors/container/process_container.go | 5 ++++- .../blobstor/blobovniczatree/blobovnicza.go | 3 +-- pkg/local_object_storage/metabase/counter.go | 9 +++++++-- pkg/local_object_storage/metabase/delete.go | 4 +++- pkg/local_object_storage/metabase/util.go | 6 ++++-- pkg/local_object_storage/pilorama/forest.go | 5 ++++- pkg/morph/client/netmap/peer.go | 5 ++++- pkg/network/address.go | 5 ++++- pkg/services/container/ape.go | 6 ++++-- pkg/services/container/morph/executor.go | 4 +++- pkg/services/control/ir/server/calls.go | 6 +++--- pkg/services/control/server/convert.go | 3 +-- pkg/services/control/server/evacuate.go | 4 +++- pkg/services/object/ape/checker.go | 3 ++- pkg/services/object/ape/errors.go | 4 +--- pkg/services/object/ape/service.go | 5 ++++- pkg/services/object/put/single.go | 4 +++- pkg/util/sdnotify/sdnotify.go | 14 ++++++++++---- 39 files changed, 143 insertions(+), 72 deletions(-) diff --git a/cmd/frostfs-adm/internal/modules/morph/ape/ape_util.go b/cmd/frostfs-adm/internal/modules/morph/ape/ape_util.go index 97f748da..253e130a 100644 --- a/cmd/frostfs-adm/internal/modules/morph/ape/ape_util.go +++ b/cmd/frostfs-adm/internal/modules/morph/ape/ape_util.go @@ -1,7 +1,7 @@ package ape import ( - "fmt" + "errors" "strings" "git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/modules/morph/constants" @@ -28,6 +28,13 @@ var mChainName = map[string]apechain.Name{ s3: apechain.S3, } +var ( + errUnknownTargetType = errors.New("unknown target type") + errChainIDCannotBeEmpty = errors.New("chain id cannot be empty") + errRuleIsNotParsed = errors.New("rule is not passed") + errUnsupportedChainName = errors.New("unsupported chain name") +) + func parseTarget(cmd *cobra.Command) policyengine.Target { var targetType policyengine.TargetType typ, _ := cmd.Flags().GetString(targetTypeFlag) @@ -37,7 +44,7 @@ func parseTarget(cmd *cobra.Command) policyengine.Target { case containerTarget: targetType = policyengine.Container default: - commonCmd.ExitOnErr(cmd, "read target type error: %w", fmt.Errorf("unknown target type")) + commonCmd.ExitOnErr(cmd, "read target type error: %w", errUnknownTargetType) } name, _ := cmd.Flags().GetString(targetNameFlag) @@ -51,7 +58,7 @@ func parseChainID(cmd *cobra.Command) apechain.ID { chainID, _ := cmd.Flags().GetString(chainIDFlag) if chainID == "" { commonCmd.ExitOnErr(cmd, "read chain id error: %w", - fmt.Errorf("chain id cannot be empty")) + errChainIDCannotBeEmpty) } return apechain.ID(chainID) } @@ -64,7 +71,7 @@ func parseChain(cmd *cobra.Command) *apechain.Chain { } else if encPath, _ := cmd.Flags().GetString(pathFlag); encPath != "" { commonCmd.ExitOnErr(cmd, "decode binary or json error: %w", parseutil.ParseAPEChainBinaryOrJSON(chain, encPath)) } else { - commonCmd.ExitOnErr(cmd, "parser error: %w", fmt.Errorf("rule is not passed")) + commonCmd.ExitOnErr(cmd, "parser error: %w", errRuleIsNotParsed) } chain.ID = parseChainID(cmd) @@ -79,7 +86,7 @@ func parseChainName(cmd *cobra.Command) apechain.Name { chainName, _ := cmd.Flags().GetString(chainNameFlag) apeChainName, ok := mChainName[strings.ToLower(chainName)] if !ok { - commonCmd.ExitOnErr(cmd, "", fmt.Errorf("unsupported chain name")) + commonCmd.ExitOnErr(cmd, "", errUnsupportedChainName) } return apeChainName } diff --git a/cmd/frostfs-adm/internal/modules/morph/helper/contract.go b/cmd/frostfs-adm/internal/modules/morph/helper/contract.go index a740f3f0..7326ec1f 100644 --- a/cmd/frostfs-adm/internal/modules/morph/helper/contract.go +++ b/cmd/frostfs-adm/internal/modules/morph/helper/contract.go @@ -116,7 +116,7 @@ func GetContractDeployData(c *InitializeContext, ctrName string, keysParam []any case constants.PolicyContract: items = append(items, c.Contracts[constants.ProxyContract].Hash) default: - panic(fmt.Sprintf("invalid contract name: %s", ctrName)) + panic("invalid contract name: " + ctrName) } return items, nil } diff --git a/cmd/frostfs-adm/internal/modules/morph/helper/download.go b/cmd/frostfs-adm/internal/modules/morph/helper/download.go index 08d427a4..71528a5d 100644 --- a/cmd/frostfs-adm/internal/modules/morph/helper/download.go +++ b/cmd/frostfs-adm/internal/modules/morph/helper/download.go @@ -14,6 +14,8 @@ import ( "github.com/spf13/cobra" ) +var errNoReleasesFound = errors.New("attempt to fetch contracts archive from the offitial repository failed: no releases found") + func downloadContracts(cmd *cobra.Command, url string) (io.ReadCloser, error) { cmd.Printf("Downloading contracts archive from '%s'\n", url) @@ -61,7 +63,7 @@ func downloadContractsFromRepository(cmd *cobra.Command) (io.ReadCloser, error) } if latestRelease == nil { - return nil, fmt.Errorf("attempt to fetch contracts archive from the offitial repository failed: no releases found") + return nil, errNoReleasesFound } cmd.Printf("Found release %s (%s)\n", latestRelease.TagName, latestRelease.Title) diff --git a/cmd/frostfs-adm/internal/modules/morph/helper/initialize_ctx.go b/cmd/frostfs-adm/internal/modules/morph/helper/initialize_ctx.go index 09d64b35..b5b6adf0 100644 --- a/cmd/frostfs-adm/internal/modules/morph/helper/initialize_ctx.go +++ b/cmd/frostfs-adm/internal/modules/morph/helper/initialize_ctx.go @@ -3,6 +3,7 @@ package helper import ( "encoding/hex" "encoding/json" + "errors" "fmt" io2 "io" "os" @@ -33,6 +34,11 @@ import ( "github.com/spf13/viper" ) +var ( + errNegativeDuration = errors.New("epoch duration must be positive") + errNegativeSize = errors.New("max object size must be positive") +) + type ContractState struct { NEF *nef.File RawNEF []byte @@ -166,11 +172,11 @@ func validateInit(cmd *cobra.Command) error { return nil } if viper.GetInt64(commonflags.EpochDurationInitFlag) <= 0 { - return fmt.Errorf("epoch duration must be positive") + return errNegativeDuration } if viper.GetInt64(commonflags.MaxObjectSizeInitFlag) <= 0 { - return fmt.Errorf("max object size must be positive") + return errNegativeSize } return nil diff --git a/cmd/frostfs-adm/internal/modules/morph/helper/netmap.go b/cmd/frostfs-adm/internal/modules/morph/helper/netmap.go index 732a5e11..f68fbefa 100644 --- a/cmd/frostfs-adm/internal/modules/morph/helper/netmap.go +++ b/cmd/frostfs-adm/internal/modules/morph/helper/netmap.go @@ -29,6 +29,8 @@ var NetmapConfigKeys = []string{ netmap.MaintenanceModeAllowedConfig, } +var errFailedToFetchListOfNetworkKeys = errors.New("can't fetch list of network config keys from the netmap contract") + func GetDefaultNetmapContractConfigMap() map[string]any { m := make(map[string]any) m[netmap.EpochDurationConfig] = viper.GetInt64(commonflags.EpochDurationInitFlag) @@ -95,7 +97,7 @@ func GetNetConfigFromNetmapContract(roInvoker *invoker.Invoker) ([]stackitem.Ite } arr, err := unwrap.Array(roInvoker.Call(nmHash, "listConfig")) if err != nil { - return nil, fmt.Errorf("can't fetch list of network config keys from the netmap contract") + return nil, errFailedToFetchListOfNetworkKeys } return arr, err } diff --git a/cmd/frostfs-adm/internal/modules/morph/notary/notary.go b/cmd/frostfs-adm/internal/modules/morph/notary/notary.go index 6d65a828..9b213da4 100644 --- a/cmd/frostfs-adm/internal/modules/morph/notary/notary.go +++ b/cmd/frostfs-adm/internal/modules/morph/notary/notary.go @@ -1,6 +1,7 @@ package notary import ( + "errors" "fmt" "math/big" "strconv" @@ -31,6 +32,8 @@ const ( notaryDepositTillFlag = "till" ) +var errInvalidNotaryDepositLifetime = errors.New("notary deposit lifetime must be a positive integer") + func depositNotary(cmd *cobra.Command, _ []string) error { w, err := openWallet(cmd) if err != nil { @@ -78,7 +81,7 @@ func depositNotary(cmd *cobra.Command, _ []string) error { if tillStr != "" { till, err = strconv.ParseInt(tillStr, 10, 64) if err != nil || till <= 0 { - return fmt.Errorf("notary deposit lifetime must be a positive integer") + return errInvalidNotaryDepositLifetime } } diff --git a/cmd/frostfs-adm/internal/modules/morph/policy/policy.go b/cmd/frostfs-adm/internal/modules/morph/policy/policy.go index 440e73a1..a11ca270 100644 --- a/cmd/frostfs-adm/internal/modules/morph/policy/policy.go +++ b/cmd/frostfs-adm/internal/modules/morph/policy/policy.go @@ -2,6 +2,7 @@ package policy import ( "bytes" + "errors" "fmt" "strconv" "strings" @@ -24,6 +25,8 @@ const ( setFeeParam = "FeePerByte" ) +var errInvalidParameterFormat = errors.New("invalid parameter format, must be Parameter=Value") + func SetPolicyCmd(cmd *cobra.Command, args []string) error { wCtx, err := helper.NewInitializeContext(cmd, viper.GetViper()) if err != nil { @@ -34,7 +37,7 @@ func SetPolicyCmd(cmd *cobra.Command, args []string) error { for i := range args { k, v, found := strings.Cut(args[i], "=") if !found { - return fmt.Errorf("invalid parameter format, must be Parameter=Value") + return errInvalidParameterFormat } switch k { diff --git a/cmd/frostfs-cli/internal/client/client.go b/cmd/frostfs-cli/internal/client/client.go index f5ccabbe..a6d9968c 100644 --- a/cmd/frostfs-cli/internal/client/client.go +++ b/cmd/frostfs-cli/internal/client/client.go @@ -21,6 +21,8 @@ import ( "git.frostfs.info/TrueCloudLab/frostfs-sdk-go/version" ) +var errMissingHeaderInResponse = errors.New("missing header in response") + // BalanceOfPrm groups parameters of BalanceOf operation. type BalanceOfPrm struct { commonPrm @@ -654,7 +656,7 @@ func HeadObject(ctx context.Context, prm HeadObjectPrm) (*HeadObjectRes, error) var hdr objectSDK.Object if !res.ReadHeader(&hdr) { - return nil, fmt.Errorf("missing header in response") + return nil, errMissingHeaderInResponse } return &HeadObjectRes{ diff --git a/cmd/frostfs-cli/modules/control/list_rules.go b/cmd/frostfs-cli/modules/control/list_rules.go index 4598320d..b345ecbf 100644 --- a/cmd/frostfs-cli/modules/control/list_rules.go +++ b/cmd/frostfs-cli/modules/control/list_rules.go @@ -1,6 +1,7 @@ package control import ( + "errors" "fmt" "strings" @@ -35,6 +36,11 @@ const ( targetTypeDesc = "Resource type(container/namespace)" ) +var ( + errSettingDefaultValueWasDeclined = errors.New("setting default value was declined") + errUnknownTargetType = errors.New("unknown target type") +) + func parseTarget(cmd *cobra.Command) *control.ChainTarget { typ, _ := cmd.Flags().GetString(targetTypeFlag) name, _ := cmd.Flags().GetString(targetNameFlag) @@ -45,7 +51,7 @@ func parseTarget(cmd *cobra.Command) *control.ChainTarget { commonCmd.ExitOnErr(cmd, "read line error: %w", err) ln = strings.ToLower(ln) if len(ln) > 0 && (ln[0] == 'n') { - commonCmd.ExitOnErr(cmd, "read namespace error: %w", fmt.Errorf("setting default value was declined")) + commonCmd.ExitOnErr(cmd, "read namespace error: %w", errSettingDefaultValueWasDeclined) } name = defaultNamespace } @@ -61,7 +67,7 @@ func parseTarget(cmd *cobra.Command) *control.ChainTarget { Type: control.ChainTarget_CONTAINER, } default: - commonCmd.ExitOnErr(cmd, "read target type error: %w", fmt.Errorf("unknown target type")) + commonCmd.ExitOnErr(cmd, "read target type error: %w", errUnknownTargetType) } return nil } diff --git a/cmd/frostfs-cli/modules/object/nodes.go b/cmd/frostfs-cli/modules/object/nodes.go index 70a3eb75..50c47e82 100644 --- a/cmd/frostfs-cli/modules/object/nodes.go +++ b/cmd/frostfs-cli/modules/object/nodes.go @@ -30,6 +30,8 @@ const ( verifyPresenceAllFlag = "verify-presence-all" ) +var errNoAvailableEndpoint = errors.New("failed to create client: no available endpoint") + type objectNodesInfo struct { containerID cid.ID objectID oid.ID @@ -299,7 +301,7 @@ func createClient(ctx context.Context, cmd *cobra.Command, candidate netmapSDK.N return nil, lastErr } if cli == nil { - return nil, fmt.Errorf("failed to create client: no available endpoint") + return nil, errNoAvailableEndpoint } return cli, nil } diff --git a/cmd/frostfs-cli/modules/util/ape.go b/cmd/frostfs-cli/modules/util/ape.go index 1500f0c5..d2dd0ced 100644 --- a/cmd/frostfs-cli/modules/util/ape.go +++ b/cmd/frostfs-cli/modules/util/ape.go @@ -24,6 +24,7 @@ var ( errMixedTypesInRule = errors.New("found mixed type of actions and conditions in rule") errNoActionsInRule = errors.New("there are no actions in rule") errUnsupportedResourceFormat = errors.New("unsupported resource format") + errFailedToParseAllAny = errors.New("any/all is not parsed") ) // PrintHumanReadableAPEChain print APE chain rules. @@ -188,7 +189,7 @@ func parseAnyAll(lexeme string) (bool, error) { case "all": return false, nil default: - return false, fmt.Errorf("any/all is not parsed") + return false, errFailedToParseAllAny } } diff --git a/cmd/frostfs-ir/httpcomponent.go b/cmd/frostfs-ir/httpcomponent.go index 3a6d77d8..2792c354 100644 --- a/cmd/frostfs-ir/httpcomponent.go +++ b/cmd/frostfs-ir/httpcomponent.go @@ -1,7 +1,6 @@ package main import ( - "fmt" "net/http" "time" @@ -26,7 +25,7 @@ const ( ) func (c *httpComponent) init() { - log.Info(fmt.Sprintf("init %s", c.name)) + log.Info("init " + c.name) c.enabled = cfg.GetBool(c.name + enabledKeyPostfix) c.address = cfg.GetString(c.name + addressKeyPostfix) c.shutdownDur = cfg.GetDuration(c.name + shutdownTimeoutKeyPostfix) @@ -40,14 +39,14 @@ func (c *httpComponent) init() { httputil.WithShutdownTimeout(c.shutdownDur), ) } else { - log.Info(fmt.Sprintf("%s is disabled, skip", c.name)) + log.Info(c.name + " is disabled, skip") c.srv = nil } } func (c *httpComponent) start() { if c.srv != nil { - log.Info(fmt.Sprintf("start %s", c.name)) + log.Info("start " + c.name) wg.Add(1) go func() { defer wg.Done() @@ -58,7 +57,7 @@ func (c *httpComponent) start() { func (c *httpComponent) shutdown() error { if c.srv != nil { - log.Info(fmt.Sprintf("shutdown %s", c.name)) + log.Info("shutdown " + c.name) return c.srv.Shutdown() } return nil @@ -72,9 +71,9 @@ func (c *httpComponent) needReload() bool { } func (c *httpComponent) reload() { - log.Info(fmt.Sprintf("reload %s", c.name)) + log.Info("reload " + c.name) if c.needReload() { - log.Info(fmt.Sprintf("%s config updated", c.name)) + log.Info(c.name + " config updated") if err := c.shutdown(); err != nil { log.Debug(logs.FrostFSIRCouldNotShutdownHTTPServer, zap.String("error", err.Error()), diff --git a/cmd/frostfs-ir/pprof.go b/cmd/frostfs-ir/pprof.go index d67c463f..ff564200 100644 --- a/cmd/frostfs-ir/pprof.go +++ b/cmd/frostfs-ir/pprof.go @@ -1,7 +1,6 @@ package main import ( - "fmt" "runtime" "git.frostfs.info/TrueCloudLab/frostfs-node/internal/logs" @@ -53,9 +52,9 @@ func (c *pprofComponent) needReload() bool { } func (c *pprofComponent) reload() { - log.Info(fmt.Sprintf("reload %s", c.name)) + log.Info("reload " + c.name) if c.needReload() { - log.Info(fmt.Sprintf("%s config updated", c.name)) + log.Info(c.name + " config updated") if err := c.shutdown(); err != nil { log.Debug(logs.FrostFSIRCouldNotShutdownHTTPServer, zap.String("error", err.Error())) diff --git a/cmd/frostfs-node/config.go b/cmd/frostfs-node/config.go index 166d36b0..48b76ac0 100644 --- a/cmd/frostfs-node/config.go +++ b/cmd/frostfs-node/config.go @@ -1004,12 +1004,12 @@ func (c *cfg) loggerPrm() (*logger.Prm, error) { err := c.dynamicConfiguration.logger.SetLevelString(c.LoggerCfg.level) if err != nil { // not expected since validation should be performed before - panic(fmt.Sprintf("incorrect log level format: %s", c.LoggerCfg.level)) + panic("incorrect log level format: " + c.LoggerCfg.level) } err = c.dynamicConfiguration.logger.SetDestination(c.LoggerCfg.destination) if err != nil { // not expected since validation should be performed before - panic(fmt.Sprintf("incorrect log destination format: %s", c.LoggerCfg.destination)) + panic("incorrect log destination format: " + c.LoggerCfg.destination) } return c.dynamicConfiguration.logger, nil diff --git a/cmd/frostfs-node/config/engine/shard/config.go b/cmd/frostfs-node/config/engine/shard/config.go index 16100c3a..f9cfdf2a 100644 --- a/cmd/frostfs-node/config/engine/shard/config.go +++ b/cmd/frostfs-node/config/engine/shard/config.go @@ -1,8 +1,6 @@ package shardconfig import ( - "fmt" - "git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-node/config" blobstorconfig "git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-node/config/engine/shard/blobstor" gcconfig "git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-node/config/engine/shard/gc" @@ -158,7 +156,7 @@ func (x *Config) Mode() (m mode.Mode) { case "disabled": m = mode.Disabled default: - panic(fmt.Sprintf("unknown shard mode: %s", s)) + panic("unknown shard mode: " + s) } return diff --git a/cmd/frostfs-node/config/morph/config.go b/cmd/frostfs-node/config/morph/config.go index 4ab608ef..86622307 100644 --- a/cmd/frostfs-node/config/morph/config.go +++ b/cmd/frostfs-node/config/morph/config.go @@ -1,7 +1,7 @@ package morphconfig import ( - "fmt" + "errors" "strconv" "time" @@ -27,6 +27,8 @@ const ( SwitchIntervalDefault = 2 * time.Minute ) +var errNoMorphEndpoints = errors.New("no morph chain RPC endpoints, see `morph.rpc_endpoint` section") + // RPCEndpoint returns list of the values of "rpc_endpoint" config parameter // from "morph" section. // @@ -54,7 +56,7 @@ func RPCEndpoint(c *config.Config) []client.Endpoint { } if len(es) == 0 { - panic(fmt.Errorf("no morph chain RPC endpoints, see `morph.rpc_endpoint` section")) + panic(errNoMorphEndpoints) } return es } diff --git a/cmd/frostfs-node/httpcomponent.go b/cmd/frostfs-node/httpcomponent.go index 373a5e5c..2ec20d84 100644 --- a/cmd/frostfs-node/httpcomponent.go +++ b/cmd/frostfs-node/httpcomponent.go @@ -2,7 +2,6 @@ package main import ( "context" - "fmt" "net/http" "time" @@ -23,7 +22,7 @@ type httpComponent struct { func (cmp *httpComponent) init(c *cfg) { if !cmp.enabled { - c.log.Info(fmt.Sprintf("%s is disabled", cmp.name)) + c.log.Info(cmp.name + " is disabled") return } // Init server with parameters diff --git a/cmd/frostfs-node/main.go b/cmd/frostfs-node/main.go index f91a6dec..e1eeb686 100644 --- a/cmd/frostfs-node/main.go +++ b/cmd/frostfs-node/main.go @@ -75,7 +75,7 @@ func main() { func initAndLog(c *cfg, name string, initializer func(*cfg)) { c.log.Info(fmt.Sprintf("initializing %s service...", name)) initializer(c) - c.log.Info(fmt.Sprintf("%s service has been successfully initialized", name)) + c.log.Info(name + " service has been successfully initialized") } func initApp(ctx context.Context, c *cfg) { @@ -124,7 +124,7 @@ func runAndLog(ctx context.Context, c *cfg, name string, logSuccess bool, starte starter(ctx, c) if logSuccess { - c.log.Info(fmt.Sprintf("%s service started successfully", name)) + c.log.Info(name + " service started successfully") } } @@ -138,7 +138,7 @@ func stopAndLog(c *cfg, name string, stopper func() error) { ) } - c.log.Debug(fmt.Sprintf("%s service has been stopped", name)) + c.log.Debug(name + " service has been stopped") } func bootUp(ctx context.Context, c *cfg) { diff --git a/cmd/internal/common/config/viper.go b/cmd/internal/common/config/viper.go index 41b8831f..f06d407c 100644 --- a/cmd/internal/common/config/viper.go +++ b/cmd/internal/common/config/viper.go @@ -1,6 +1,7 @@ package config import ( + "errors" "fmt" "strings" @@ -15,6 +16,8 @@ const ( EnvSeparator = "_" ) +var errProvideViperInOpts = errors.New("provide viper in opts") + func CreateViper(opts ...Option) (*viper.Viper, error) { o := defaultOpts() for i := range opts { @@ -59,7 +62,7 @@ func ReloadViper(opts ...Option) error { } if o.v == nil { - return fmt.Errorf("provide viper in opts") + return errProvideViperInOpts } if o.path != "" { diff --git a/internal/ape/converter.go b/internal/ape/converter.go index f629e262..2adc7645 100644 --- a/internal/ape/converter.go +++ b/internal/ape/converter.go @@ -18,7 +18,7 @@ func (e *ConvertEACLError) Error() string { if e == nil { return "" } - return fmt.Sprintf("failed to convert eACL table to policy engine chain: %s", e.nested.Error()) + return "failed to convert eACL table to policy engine chain: " + e.nested.Error() } func (e *ConvertEACLError) Unwrap() error { diff --git a/pkg/ape/chainbase/boltdb.go b/pkg/ape/chainbase/boltdb.go index a1dfc256..27bfd846 100644 --- a/pkg/ape/chainbase/boltdb.go +++ b/pkg/ape/chainbase/boltdb.go @@ -34,6 +34,8 @@ var ( ErrTargetNameBucketNotFound = logicerr.New("target name bucket not found") ErrBucketNotContainsChainID = logicerr.New("chain id not found in bucket") + + errChainIDIsNotSet = errors.New("chain ID is not set") ) // NewBoltLocalOverrideDatabase returns storage wrapper for storing access policy engine @@ -167,7 +169,7 @@ func getTargetBucketCreateIfEmpty(tx *bbolt.Tx, name chain.Name, target policyen func (cs *boltLocalOverrideStorage) AddOverride(name chain.Name, target policyengine.Target, c *chain.Chain) (chain.ID, error) { if len(c.ID) == 0 { - return chain.ID{}, fmt.Errorf("chain ID is not set") + return chain.ID{}, errChainIDIsNotSet } serializedChain := c.Bytes() diff --git a/pkg/innerring/processors/container/process_container.go b/pkg/innerring/processors/container/process_container.go index 2ad863b2..a950997f 100644 --- a/pkg/innerring/processors/container/process_container.go +++ b/pkg/innerring/processors/container/process_container.go @@ -1,6 +1,7 @@ package container import ( + "errors" "fmt" "strings" @@ -31,6 +32,8 @@ type putContainerContext struct { d containerSDK.Domain } +var errContainerAndOwnerNamespaceDontMatch = errors.New("container and owner namespaces do not match") + // Process a new container from the user by checking the container sanity // and sending approve tx back to the morph. func (cp *Processor) processContainerPut(put putEvent) bool { @@ -193,7 +196,7 @@ func (cp *Processor) checkNNS(ctx *putContainerContext, cnr containerSDK.Contain } if subject.Namespace != namespace { - return fmt.Errorf("container and owner namespaces do not match") + return errContainerAndOwnerNamespaceDontMatch } return nil diff --git a/pkg/local_object_storage/blobstor/blobovniczatree/blobovnicza.go b/pkg/local_object_storage/blobstor/blobovniczatree/blobovnicza.go index 9f295009..be51509b 100644 --- a/pkg/local_object_storage/blobstor/blobovniczatree/blobovnicza.go +++ b/pkg/local_object_storage/blobstor/blobovniczatree/blobovnicza.go @@ -2,7 +2,6 @@ package blobovniczatree import ( "errors" - "fmt" "strconv" "strings" "sync" @@ -117,7 +116,7 @@ func u64ToHexStringExt(ind uint64) string { func u64FromHexString(str string) uint64 { v, err := strconv.ParseUint(strings.TrimSuffix(str, dbExtension), 16, 64) if err != nil { - panic(fmt.Sprintf("blobovnicza name is not an index %s", str)) + panic("blobovnicza name is not an index " + str) } return v diff --git a/pkg/local_object_storage/metabase/counter.go b/pkg/local_object_storage/metabase/counter.go index ee1ab41d..dc85b469 100644 --- a/pkg/local_object_storage/metabase/counter.go +++ b/pkg/local_object_storage/metabase/counter.go @@ -24,6 +24,11 @@ var ( objectUserCounterKey = []byte("user_counter") ) +var ( + errInvalidKeyLenght = errors.New("invalid key length") + errInvalidValueLenght = errors.New("invalid value length") +) + type objectType uint8 const ( @@ -474,7 +479,7 @@ func containerCounterValue(entity ObjectCounters) []byte { func parseContainerCounterKey(buf []byte) (cid.ID, error) { if len(buf) != cidSize { - return cid.ID{}, fmt.Errorf("invalid key length") + return cid.ID{}, errInvalidKeyLenght } var cnrID cid.ID if err := cnrID.Decode(buf); err != nil { @@ -486,7 +491,7 @@ func parseContainerCounterKey(buf []byte) (cid.ID, error) { // parseContainerCounterValue return phy, logic values. func parseContainerCounterValue(buf []byte) (ObjectCounters, error) { if len(buf) != 24 { - return ObjectCounters{}, fmt.Errorf("invalid value length") + return ObjectCounters{}, errInvalidValueLenght } return ObjectCounters{ Phy: binary.LittleEndian.Uint64(buf), diff --git a/pkg/local_object_storage/metabase/delete.go b/pkg/local_object_storage/metabase/delete.go index e5a98ff0..e591b866 100644 --- a/pkg/local_object_storage/metabase/delete.go +++ b/pkg/local_object_storage/metabase/delete.go @@ -20,6 +20,8 @@ import ( "go.opentelemetry.io/otel/trace" ) +var errFailedToRemoveUniqueIndexes = errors.New("can't remove unique indexes") + // DeletePrm groups the parameters of Delete operation. type DeletePrm struct { addrs []oid.Address @@ -325,7 +327,7 @@ func (db *DB) deleteObject( ) error { err := delUniqueIndexes(tx, obj, isParent) if err != nil { - return fmt.Errorf("can't remove unique indexes") + return errFailedToRemoveUniqueIndexes } err = updateListIndexes(tx, obj, delListIndexItem) diff --git a/pkg/local_object_storage/metabase/util.go b/pkg/local_object_storage/metabase/util.go index c04aff61..d46a421a 100644 --- a/pkg/local_object_storage/metabase/util.go +++ b/pkg/local_object_storage/metabase/util.go @@ -3,7 +3,7 @@ package meta import ( "bytes" "crypto/sha256" - "fmt" + "errors" cid "git.frostfs.info/TrueCloudLab/frostfs-sdk-go/container/id" objectSDK "git.frostfs.info/TrueCloudLab/frostfs-sdk-go/object" @@ -25,6 +25,8 @@ var ( containerCounterBucketName = []byte{containerCountersPrefix} zeroValue = []byte{0xFF} + + errInvalidLength = errors.New("invalid length") ) // Prefix bytes for database keys. All ids and addresses are encoded in binary @@ -198,7 +200,7 @@ func addressKey(addr oid.Address, key []byte) []byte { // parses object address formed by addressKey. func decodeAddressFromKey(dst *oid.Address, k []byte) error { if len(k) != addressKeySize { - return fmt.Errorf("invalid length") + return errInvalidLength } var cnr cid.ID diff --git a/pkg/local_object_storage/pilorama/forest.go b/pkg/local_object_storage/pilorama/forest.go index 8276490b..dbfc9dcc 100644 --- a/pkg/local_object_storage/pilorama/forest.go +++ b/pkg/local_object_storage/pilorama/forest.go @@ -2,6 +2,7 @@ package pilorama import ( "context" + "errors" "fmt" "sort" "strings" @@ -10,6 +11,8 @@ import ( cid "git.frostfs.info/TrueCloudLab/frostfs-sdk-go/container/id" ) +var errInvalidKeyFormat = errors.New("invalid format: key must be cid and treeID") + // memoryForest represents multiple replicating trees sharing a single storage. type memoryForest struct { // treeMap maps tree identifier (container ID + name) to the replicated log. @@ -291,7 +294,7 @@ func (f *memoryForest) TreeListTrees(_ context.Context, prm TreeListTreesPrm) (* for idx < len(tmpSlice) { cidAndTree := strings.Split(tmpSlice[idx], "/") if len(cidAndTree) != 2 { - return nil, fmt.Errorf("invalid format: key must be cid and treeID") + return nil, errInvalidKeyFormat } var contID cid.ID if err := contID.DecodeString(cidAndTree[0]); err != nil { diff --git a/pkg/morph/client/netmap/peer.go b/pkg/morph/client/netmap/peer.go index 30f51f69..764bbc89 100644 --- a/pkg/morph/client/netmap/peer.go +++ b/pkg/morph/client/netmap/peer.go @@ -1,12 +1,15 @@ package netmap import ( + "errors" "fmt" "git.frostfs.info/TrueCloudLab/frostfs-node/pkg/morph/client" "git.frostfs.info/TrueCloudLab/frostfs-sdk-go/netmap" ) +var errFailedToRemovePeerWithoutNotary = errors.New("peer can be forcefully removed only in notary environment") + // AddPeerPrm groups parameters of AddPeer operation. type AddPeerPrm struct { nodeInfo netmap.NodeInfo @@ -46,7 +49,7 @@ func (c *Client) AddPeer(p AddPeerPrm) error { // If vub > 0, vub will be used as valid until block value. func (c *Client) ForceRemovePeer(nodeInfo netmap.NodeInfo, vub uint32) (uint32, error) { if !c.client.WithNotary() { - return 0, fmt.Errorf("peer can be forcefully removed only in notary environment") + return 0, errFailedToRemovePeerWithoutNotary } prm := UpdatePeerPrm{} diff --git a/pkg/network/address.go b/pkg/network/address.go index aeb64788..88f4a571 100644 --- a/pkg/network/address.go +++ b/pkg/network/address.go @@ -1,6 +1,7 @@ package network import ( + "errors" "fmt" "net" "net/url" @@ -18,6 +19,8 @@ import ( URIAddr strings: "127.0.0.1:8080" */ +var errHostIsEmpty = errors.New("host is empty") + // Address represents the FrostFS node // network address. type Address struct { @@ -89,7 +92,7 @@ func (a *Address) FromString(s string) error { // multiaddrStringFromHostAddr converts "localhost:8080" to "/dns4/localhost/tcp/8080". func multiaddrStringFromHostAddr(host string) (string, error) { if len(host) == 0 { - return "", fmt.Errorf("host is empty") + return "", errHostIsEmpty } endpoint, port, err := net.SplitHostPort(host) diff --git a/pkg/services/container/ape.go b/pkg/services/container/ape.go index c01ad8a1..83361257 100644 --- a/pkg/services/container/ape.go +++ b/pkg/services/container/ape.go @@ -41,6 +41,8 @@ var ( errEmptyBodySignature = errors.New("malformed request: empty body signature") errMissingOwnerID = errors.New("malformed request: missing owner ID") errSubjectNotFound = errors.New("subject not found") + errOwnerIDIsNotSet = errors.New("owner id is not set") + errInvalidDomainZone = errors.New("invalid domain zone: no namespace is expected") undefinedContainerID = cid.ID{} ) @@ -566,7 +568,7 @@ func isContainerNode(nm *netmapSDK.NetMap, pk, binCnrID []byte, cont *containerc func (ac *apeChecker) namespaceByOwner(owner *refs.OwnerID) (string, error) { var ownerSDK user.ID if owner == nil { - return "", fmt.Errorf("owner id is not set") + return "", errOwnerIDIsNotSet } if err := ownerSDK.ReadFromV2(*owner); err != nil { return "", err @@ -603,7 +605,7 @@ func validateNamespace(cnrV2 *container.Container, ownerIDNamespace string) erro if hasNamespace { if cntNamespace != ownerIDNamespace { if ownerIDNamespace == "" { - return fmt.Errorf("invalid domain zone: no namespace is expected") + return errInvalidDomainZone } return fmt.Errorf("invalid domain zone: expected namespace %s, but got %s", ownerIDNamespace, cntNamespace) } diff --git a/pkg/services/container/morph/executor.go b/pkg/services/container/morph/executor.go index f1217705..a653fa06 100644 --- a/pkg/services/container/morph/executor.go +++ b/pkg/services/container/morph/executor.go @@ -16,6 +16,8 @@ import ( "git.frostfs.info/TrueCloudLab/frostfs-sdk-go/user" ) +var errMissingUserID = errors.New("missing user ID") + type morphExecutor struct { rdr Reader wrt Writer @@ -177,7 +179,7 @@ func (s *morphExecutor) Get(_ context.Context, body *container.GetRequestBody) ( func (s *morphExecutor) List(_ context.Context, body *container.ListRequestBody) (*container.ListResponseBody, error) { idV2 := body.GetOwnerID() if idV2 == nil { - return nil, fmt.Errorf("missing user ID") + return nil, errMissingUserID } var id user.ID diff --git a/pkg/services/control/ir/server/calls.go b/pkg/services/control/ir/server/calls.go index 58610b0d..2447a8a7 100644 --- a/pkg/services/control/ir/server/calls.go +++ b/pkg/services/control/ir/server/calls.go @@ -121,7 +121,7 @@ func (s *Server) RemoveContainer(_ context.Context, req *control.RemoveContainer if len(req.GetBody().GetContainerId()) > 0 { var containerID cid.ID if err := containerID.Decode(req.GetBody().GetContainerId()); err != nil { - return nil, status.Error(codes.InvalidArgument, fmt.Sprintf("failed to parse container ID: %s", err.Error())) + return nil, status.Error(codes.InvalidArgument, "failed to parse container ID: "+err.Error()) } var err error vub, err = s.removeContainer(containerID, req.GetBody().GetVub()) @@ -131,11 +131,11 @@ func (s *Server) RemoveContainer(_ context.Context, req *control.RemoveContainer } else { var ownerID refs.OwnerID if err := ownerID.Unmarshal(req.GetBody().GetOwner()); err != nil { - return nil, status.Error(codes.InvalidArgument, fmt.Sprintf("failed to parse ownerID: %s", err.Error())) + return nil, status.Error(codes.InvalidArgument, "failed to parse ownerID: %s"+err.Error()) } var owner user.ID if err := owner.ReadFromV2(ownerID); err != nil { - return nil, status.Error(codes.InvalidArgument, fmt.Sprintf("failed to read owner: %s", err.Error())) + return nil, status.Error(codes.InvalidArgument, "failed to read owner: "+err.Error()) } cids, err := s.containerClient.ContainersOf(&owner) diff --git a/pkg/services/control/server/convert.go b/pkg/services/control/server/convert.go index 4f313235..61d7e41c 100644 --- a/pkg/services/control/server/convert.go +++ b/pkg/services/control/server/convert.go @@ -1,7 +1,6 @@ package control import ( - "fmt" "time" "git.frostfs.info/TrueCloudLab/frostfs-node/pkg/local_object_storage/engine" @@ -16,7 +15,7 @@ func stateToResponse(state *engine.EvacuationState) (*control.GetShardEvacuation for _, shID := range state.ShardIDs() { id, err := base58.Decode(shID) if err != nil { - return nil, status.Error(codes.Internal, fmt.Sprintf("invalid shard id format: %s", shID)) + return nil, status.Error(codes.Internal, "invalid shard id format: "+shID) } shardIDs = append(shardIDs, id) } diff --git a/pkg/services/control/server/evacuate.go b/pkg/services/control/server/evacuate.go index 99082b30..462ab211 100644 --- a/pkg/services/control/server/evacuate.go +++ b/pkg/services/control/server/evacuate.go @@ -23,6 +23,8 @@ import ( "google.golang.org/grpc/status" ) +var errFailedToBuildListOfContainerNodes = errors.New("can't build a list of container nodes") + func (s *Server) EvacuateShard(ctx context.Context, req *control.EvacuateShardRequest) (*control.EvacuateShardResponse, error) { err := s.isValidRequest(req) if err != nil { @@ -157,7 +159,7 @@ func (s *Server) getContainerNodes(contID cid.ID) ([]netmap.NodeInfo, error) { ns, err := nm.ContainerNodes(c.Value.PlacementPolicy(), binCnr) if err != nil { - return nil, fmt.Errorf("can't build a list of container nodes") + return nil, errFailedToBuildListOfContainerNodes } nodes := placement.FlattenNodes(ns) diff --git a/pkg/services/object/ape/checker.go b/pkg/services/object/ape/checker.go index 13b2729e..13dab0ec 100644 --- a/pkg/services/object/ape/checker.go +++ b/pkg/services/object/ape/checker.go @@ -2,6 +2,7 @@ package ape import ( "context" + "errors" "fmt" objectV2 "git.frostfs.info/TrueCloudLab/frostfs-api-go/v2/object" @@ -50,7 +51,7 @@ type Prm struct { SoftAPECheck bool } -var errMissingOID = fmt.Errorf("object ID is not set") +var errMissingOID = errors.New("object ID is not set") // CheckAPE checks if a request or a response is permitted creating an ape request and passing // it to chain router. diff --git a/pkg/services/object/ape/errors.go b/pkg/services/object/ape/errors.go index 7c2a82df..1b2024ed 100644 --- a/pkg/services/object/ape/errors.go +++ b/pkg/services/object/ape/errors.go @@ -1,13 +1,11 @@ package ape import ( - "fmt" - apistatus "git.frostfs.info/TrueCloudLab/frostfs-sdk-go/client/status" ) func toStatusErr(err error) error { errAccessDenied := &apistatus.ObjectAccessDenied{} - errAccessDenied.WriteReason(fmt.Sprintf("ape denied request: %s", err.Error())) + errAccessDenied.WriteReason("ape denied request: " + err.Error()) return errAccessDenied } diff --git a/pkg/services/object/ape/service.go b/pkg/services/object/ape/service.go index f05bdaa8..cc18a0bc 100644 --- a/pkg/services/object/ape/service.go +++ b/pkg/services/object/ape/service.go @@ -3,6 +3,7 @@ package ape import ( "context" "encoding/hex" + "errors" "fmt" objectV2 "git.frostfs.info/TrueCloudLab/frostfs-api-go/v2/object" @@ -16,6 +17,8 @@ import ( nativeschema "git.frostfs.info/TrueCloudLab/policy-engine/schema/native" ) +var errFailedToCastToRequestContext = errors.New("failed cast to RequestContext") + type Service struct { log *logger.Logger @@ -101,7 +104,7 @@ func requestContext(ctx context.Context) (*objectSvc.RequestContext, error) { } rc, ok := untyped.(*objectSvc.RequestContext) if !ok { - return nil, fmt.Errorf("failed cast to RequestContext") + return nil, errFailedToCastToRequestContext } return rc, nil } diff --git a/pkg/services/object/put/single.go b/pkg/services/object/put/single.go index 183b2310..09e1eb09 100644 --- a/pkg/services/object/put/single.go +++ b/pkg/services/object/put/single.go @@ -32,6 +32,8 @@ import ( "go.uber.org/zap" ) +var errInvalidPayloadChecksum = errors.New("incorrect payload checksum") + type putSingleRequestSigner struct { req *objectAPI.PutSingleRequest keyStorage *svcutil.KeyStorage @@ -125,7 +127,7 @@ func (s *Service) validatePutSingleChecksum(obj *objectSDK.Object) error { } if !bytes.Equal(hash.Sum(nil), cs.Value()) { - return fmt.Errorf("incorrect payload checksum") + return errInvalidPayloadChecksum } return nil diff --git a/pkg/util/sdnotify/sdnotify.go b/pkg/util/sdnotify/sdnotify.go index 7c3d2f1d..fe4ad1c3 100644 --- a/pkg/util/sdnotify/sdnotify.go +++ b/pkg/util/sdnotify/sdnotify.go @@ -1,6 +1,7 @@ package sdnotify import ( + "errors" "fmt" "net" "os" @@ -13,14 +14,19 @@ const ( ReloadingEnabled = "RELOADING=1" ) -var socket *net.UnixAddr +var ( + socket *net.UnixAddr + + errSocketVariableIsNotPresent = errors.New("\"NOTIFY_SOCKET\" environment variable is not present") + errSocketIsNotInitialized = errors.New("socket is not initialized") +) // Initializes socket with provided name of // environment variable. func InitSocket() error { notifySocket := os.Getenv("NOTIFY_SOCKET") if notifySocket == "" { - return fmt.Errorf("\"NOTIFY_SOCKET\" environment variable is not present") + return errSocketVariableIsNotPresent } socket = &net.UnixAddr{ Name: notifySocket, @@ -38,14 +44,14 @@ func FlagAndStatus(status string) error { // Status sends systemd notify STATUS=%s{status}. func Status(status string) error { - return Send(fmt.Sprintf("STATUS=%s", status)) + return Send("STATUS=" + status) } // Send state through the notify socket if any. // If the notify socket was not detected, it returns an error. func Send(state string) error { if socket == nil { - return fmt.Errorf("socket is not initialized") + return errSocketIsNotInitialized } conn, err := net.DialUnix(socket.Net, nil, socket) if err != nil {