[#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 <d.stepanov@yadro.com>
This commit is contained in:
Dmitrii Stepanov 2024-03-11 17:55:50 +03:00
parent 66a26b7775
commit d433b49265
39 changed files with 143 additions and 72 deletions

View file

@ -1,7 +1,7 @@
package ape package ape
import ( import (
"fmt" "errors"
"strings" "strings"
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/modules/morph/constants" "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, 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 { func parseTarget(cmd *cobra.Command) policyengine.Target {
var targetType policyengine.TargetType var targetType policyengine.TargetType
typ, _ := cmd.Flags().GetString(targetTypeFlag) typ, _ := cmd.Flags().GetString(targetTypeFlag)
@ -37,7 +44,7 @@ func parseTarget(cmd *cobra.Command) policyengine.Target {
case containerTarget: case containerTarget:
targetType = policyengine.Container targetType = policyengine.Container
default: 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) name, _ := cmd.Flags().GetString(targetNameFlag)
@ -51,7 +58,7 @@ func parseChainID(cmd *cobra.Command) apechain.ID {
chainID, _ := cmd.Flags().GetString(chainIDFlag) chainID, _ := cmd.Flags().GetString(chainIDFlag)
if chainID == "" { if chainID == "" {
commonCmd.ExitOnErr(cmd, "read chain id error: %w", commonCmd.ExitOnErr(cmd, "read chain id error: %w",
fmt.Errorf("chain id cannot be empty")) errChainIDCannotBeEmpty)
} }
return apechain.ID(chainID) return apechain.ID(chainID)
} }
@ -64,7 +71,7 @@ func parseChain(cmd *cobra.Command) *apechain.Chain {
} else if encPath, _ := cmd.Flags().GetString(pathFlag); encPath != "" { } else if encPath, _ := cmd.Flags().GetString(pathFlag); encPath != "" {
commonCmd.ExitOnErr(cmd, "decode binary or json error: %w", parseutil.ParseAPEChainBinaryOrJSON(chain, encPath)) commonCmd.ExitOnErr(cmd, "decode binary or json error: %w", parseutil.ParseAPEChainBinaryOrJSON(chain, encPath))
} else { } else {
commonCmd.ExitOnErr(cmd, "parser error: %w", fmt.Errorf("rule is not passed")) commonCmd.ExitOnErr(cmd, "parser error: %w", errRuleIsNotParsed)
} }
chain.ID = parseChainID(cmd) chain.ID = parseChainID(cmd)
@ -79,7 +86,7 @@ func parseChainName(cmd *cobra.Command) apechain.Name {
chainName, _ := cmd.Flags().GetString(chainNameFlag) chainName, _ := cmd.Flags().GetString(chainNameFlag)
apeChainName, ok := mChainName[strings.ToLower(chainName)] apeChainName, ok := mChainName[strings.ToLower(chainName)]
if !ok { if !ok {
commonCmd.ExitOnErr(cmd, "", fmt.Errorf("unsupported chain name")) commonCmd.ExitOnErr(cmd, "", errUnsupportedChainName)
} }
return apeChainName return apeChainName
} }

View file

@ -116,7 +116,7 @@ func GetContractDeployData(c *InitializeContext, ctrName string, keysParam []any
case constants.PolicyContract: case constants.PolicyContract:
items = append(items, c.Contracts[constants.ProxyContract].Hash) items = append(items, c.Contracts[constants.ProxyContract].Hash)
default: default:
panic(fmt.Sprintf("invalid contract name: %s", ctrName)) panic("invalid contract name: " + ctrName)
} }
return items, nil return items, nil
} }

View file

@ -14,6 +14,8 @@ import (
"github.com/spf13/cobra" "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) { func downloadContracts(cmd *cobra.Command, url string) (io.ReadCloser, error) {
cmd.Printf("Downloading contracts archive from '%s'\n", url) cmd.Printf("Downloading contracts archive from '%s'\n", url)
@ -61,7 +63,7 @@ func downloadContractsFromRepository(cmd *cobra.Command) (io.ReadCloser, error)
} }
if latestRelease == nil { 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) cmd.Printf("Found release %s (%s)\n", latestRelease.TagName, latestRelease.Title)

View file

@ -3,6 +3,7 @@ package helper
import ( import (
"encoding/hex" "encoding/hex"
"encoding/json" "encoding/json"
"errors"
"fmt" "fmt"
io2 "io" io2 "io"
"os" "os"
@ -33,6 +34,11 @@ import (
"github.com/spf13/viper" "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 { type ContractState struct {
NEF *nef.File NEF *nef.File
RawNEF []byte RawNEF []byte
@ -166,11 +172,11 @@ func validateInit(cmd *cobra.Command) error {
return nil return nil
} }
if viper.GetInt64(commonflags.EpochDurationInitFlag) <= 0 { if viper.GetInt64(commonflags.EpochDurationInitFlag) <= 0 {
return fmt.Errorf("epoch duration must be positive") return errNegativeDuration
} }
if viper.GetInt64(commonflags.MaxObjectSizeInitFlag) <= 0 { if viper.GetInt64(commonflags.MaxObjectSizeInitFlag) <= 0 {
return fmt.Errorf("max object size must be positive") return errNegativeSize
} }
return nil return nil

View file

@ -29,6 +29,8 @@ var NetmapConfigKeys = []string{
netmap.MaintenanceModeAllowedConfig, netmap.MaintenanceModeAllowedConfig,
} }
var errFailedToFetchListOfNetworkKeys = errors.New("can't fetch list of network config keys from the netmap contract")
func GetDefaultNetmapContractConfigMap() map[string]any { func GetDefaultNetmapContractConfigMap() map[string]any {
m := make(map[string]any) m := make(map[string]any)
m[netmap.EpochDurationConfig] = viper.GetInt64(commonflags.EpochDurationInitFlag) 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")) arr, err := unwrap.Array(roInvoker.Call(nmHash, "listConfig"))
if err != nil { 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 return arr, err
} }

View file

@ -1,6 +1,7 @@
package notary package notary
import ( import (
"errors"
"fmt" "fmt"
"math/big" "math/big"
"strconv" "strconv"
@ -31,6 +32,8 @@ const (
notaryDepositTillFlag = "till" notaryDepositTillFlag = "till"
) )
var errInvalidNotaryDepositLifetime = errors.New("notary deposit lifetime must be a positive integer")
func depositNotary(cmd *cobra.Command, _ []string) error { func depositNotary(cmd *cobra.Command, _ []string) error {
w, err := openWallet(cmd) w, err := openWallet(cmd)
if err != nil { if err != nil {
@ -78,7 +81,7 @@ func depositNotary(cmd *cobra.Command, _ []string) error {
if tillStr != "" { if tillStr != "" {
till, err = strconv.ParseInt(tillStr, 10, 64) till, err = strconv.ParseInt(tillStr, 10, 64)
if err != nil || till <= 0 { if err != nil || till <= 0 {
return fmt.Errorf("notary deposit lifetime must be a positive integer") return errInvalidNotaryDepositLifetime
} }
} }

View file

@ -2,6 +2,7 @@ package policy
import ( import (
"bytes" "bytes"
"errors"
"fmt" "fmt"
"strconv" "strconv"
"strings" "strings"
@ -24,6 +25,8 @@ const (
setFeeParam = "FeePerByte" setFeeParam = "FeePerByte"
) )
var errInvalidParameterFormat = errors.New("invalid parameter format, must be Parameter=Value")
func SetPolicyCmd(cmd *cobra.Command, args []string) error { func SetPolicyCmd(cmd *cobra.Command, args []string) error {
wCtx, err := helper.NewInitializeContext(cmd, viper.GetViper()) wCtx, err := helper.NewInitializeContext(cmd, viper.GetViper())
if err != nil { if err != nil {
@ -34,7 +37,7 @@ func SetPolicyCmd(cmd *cobra.Command, args []string) error {
for i := range args { for i := range args {
k, v, found := strings.Cut(args[i], "=") k, v, found := strings.Cut(args[i], "=")
if !found { if !found {
return fmt.Errorf("invalid parameter format, must be Parameter=Value") return errInvalidParameterFormat
} }
switch k { switch k {

View file

@ -21,6 +21,8 @@ import (
"git.frostfs.info/TrueCloudLab/frostfs-sdk-go/version" "git.frostfs.info/TrueCloudLab/frostfs-sdk-go/version"
) )
var errMissingHeaderInResponse = errors.New("missing header in response")
// BalanceOfPrm groups parameters of BalanceOf operation. // BalanceOfPrm groups parameters of BalanceOf operation.
type BalanceOfPrm struct { type BalanceOfPrm struct {
commonPrm commonPrm
@ -654,7 +656,7 @@ func HeadObject(ctx context.Context, prm HeadObjectPrm) (*HeadObjectRes, error)
var hdr objectSDK.Object var hdr objectSDK.Object
if !res.ReadHeader(&hdr) { if !res.ReadHeader(&hdr) {
return nil, fmt.Errorf("missing header in response") return nil, errMissingHeaderInResponse
} }
return &HeadObjectRes{ return &HeadObjectRes{

View file

@ -1,6 +1,7 @@
package control package control
import ( import (
"errors"
"fmt" "fmt"
"strings" "strings"
@ -35,6 +36,11 @@ const (
targetTypeDesc = "Resource type(container/namespace)" 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 { func parseTarget(cmd *cobra.Command) *control.ChainTarget {
typ, _ := cmd.Flags().GetString(targetTypeFlag) typ, _ := cmd.Flags().GetString(targetTypeFlag)
name, _ := cmd.Flags().GetString(targetNameFlag) name, _ := cmd.Flags().GetString(targetNameFlag)
@ -45,7 +51,7 @@ func parseTarget(cmd *cobra.Command) *control.ChainTarget {
commonCmd.ExitOnErr(cmd, "read line error: %w", err) commonCmd.ExitOnErr(cmd, "read line error: %w", err)
ln = strings.ToLower(ln) ln = strings.ToLower(ln)
if len(ln) > 0 && (ln[0] == 'n') { 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 name = defaultNamespace
} }
@ -61,7 +67,7 @@ func parseTarget(cmd *cobra.Command) *control.ChainTarget {
Type: control.ChainTarget_CONTAINER, Type: control.ChainTarget_CONTAINER,
} }
default: 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 return nil
} }

View file

@ -30,6 +30,8 @@ const (
verifyPresenceAllFlag = "verify-presence-all" verifyPresenceAllFlag = "verify-presence-all"
) )
var errNoAvailableEndpoint = errors.New("failed to create client: no available endpoint")
type objectNodesInfo struct { type objectNodesInfo struct {
containerID cid.ID containerID cid.ID
objectID oid.ID objectID oid.ID
@ -299,7 +301,7 @@ func createClient(ctx context.Context, cmd *cobra.Command, candidate netmapSDK.N
return nil, lastErr return nil, lastErr
} }
if cli == nil { if cli == nil {
return nil, fmt.Errorf("failed to create client: no available endpoint") return nil, errNoAvailableEndpoint
} }
return cli, nil return cli, nil
} }

View file

@ -24,6 +24,7 @@ var (
errMixedTypesInRule = errors.New("found mixed type of actions and conditions in rule") errMixedTypesInRule = errors.New("found mixed type of actions and conditions in rule")
errNoActionsInRule = errors.New("there are no actions in rule") errNoActionsInRule = errors.New("there are no actions in rule")
errUnsupportedResourceFormat = errors.New("unsupported resource format") errUnsupportedResourceFormat = errors.New("unsupported resource format")
errFailedToParseAllAny = errors.New("any/all is not parsed")
) )
// PrintHumanReadableAPEChain print APE chain rules. // PrintHumanReadableAPEChain print APE chain rules.
@ -188,7 +189,7 @@ func parseAnyAll(lexeme string) (bool, error) {
case "all": case "all":
return false, nil return false, nil
default: default:
return false, fmt.Errorf("any/all is not parsed") return false, errFailedToParseAllAny
} }
} }

View file

@ -1,7 +1,6 @@
package main package main
import ( import (
"fmt"
"net/http" "net/http"
"time" "time"
@ -26,7 +25,7 @@ const (
) )
func (c *httpComponent) init() { 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.enabled = cfg.GetBool(c.name + enabledKeyPostfix)
c.address = cfg.GetString(c.name + addressKeyPostfix) c.address = cfg.GetString(c.name + addressKeyPostfix)
c.shutdownDur = cfg.GetDuration(c.name + shutdownTimeoutKeyPostfix) c.shutdownDur = cfg.GetDuration(c.name + shutdownTimeoutKeyPostfix)
@ -40,14 +39,14 @@ func (c *httpComponent) init() {
httputil.WithShutdownTimeout(c.shutdownDur), httputil.WithShutdownTimeout(c.shutdownDur),
) )
} else { } else {
log.Info(fmt.Sprintf("%s is disabled, skip", c.name)) log.Info(c.name + " is disabled, skip")
c.srv = nil c.srv = nil
} }
} }
func (c *httpComponent) start() { func (c *httpComponent) start() {
if c.srv != nil { if c.srv != nil {
log.Info(fmt.Sprintf("start %s", c.name)) log.Info("start " + c.name)
wg.Add(1) wg.Add(1)
go func() { go func() {
defer wg.Done() defer wg.Done()
@ -58,7 +57,7 @@ func (c *httpComponent) start() {
func (c *httpComponent) shutdown() error { func (c *httpComponent) shutdown() error {
if c.srv != nil { if c.srv != nil {
log.Info(fmt.Sprintf("shutdown %s", c.name)) log.Info("shutdown " + c.name)
return c.srv.Shutdown() return c.srv.Shutdown()
} }
return nil return nil
@ -72,9 +71,9 @@ func (c *httpComponent) needReload() bool {
} }
func (c *httpComponent) reload() { func (c *httpComponent) reload() {
log.Info(fmt.Sprintf("reload %s", c.name)) log.Info("reload " + c.name)
if c.needReload() { if c.needReload() {
log.Info(fmt.Sprintf("%s config updated", c.name)) log.Info(c.name + " config updated")
if err := c.shutdown(); err != nil { if err := c.shutdown(); err != nil {
log.Debug(logs.FrostFSIRCouldNotShutdownHTTPServer, log.Debug(logs.FrostFSIRCouldNotShutdownHTTPServer,
zap.String("error", err.Error()), zap.String("error", err.Error()),

View file

@ -1,7 +1,6 @@
package main package main
import ( import (
"fmt"
"runtime" "runtime"
"git.frostfs.info/TrueCloudLab/frostfs-node/internal/logs" "git.frostfs.info/TrueCloudLab/frostfs-node/internal/logs"
@ -53,9 +52,9 @@ func (c *pprofComponent) needReload() bool {
} }
func (c *pprofComponent) reload() { func (c *pprofComponent) reload() {
log.Info(fmt.Sprintf("reload %s", c.name)) log.Info("reload " + c.name)
if c.needReload() { if c.needReload() {
log.Info(fmt.Sprintf("%s config updated", c.name)) log.Info(c.name + " config updated")
if err := c.shutdown(); err != nil { if err := c.shutdown(); err != nil {
log.Debug(logs.FrostFSIRCouldNotShutdownHTTPServer, log.Debug(logs.FrostFSIRCouldNotShutdownHTTPServer,
zap.String("error", err.Error())) zap.String("error", err.Error()))

View file

@ -1004,12 +1004,12 @@ func (c *cfg) loggerPrm() (*logger.Prm, error) {
err := c.dynamicConfiguration.logger.SetLevelString(c.LoggerCfg.level) err := c.dynamicConfiguration.logger.SetLevelString(c.LoggerCfg.level)
if err != nil { if err != nil {
// not expected since validation should be performed before // 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) err = c.dynamicConfiguration.logger.SetDestination(c.LoggerCfg.destination)
if err != nil { if err != nil {
// not expected since validation should be performed before // 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 return c.dynamicConfiguration.logger, nil

View file

@ -1,8 +1,6 @@
package shardconfig package shardconfig
import ( import (
"fmt"
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-node/config" "git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-node/config"
blobstorconfig "git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-node/config/engine/shard/blobstor" 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" 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": case "disabled":
m = mode.Disabled m = mode.Disabled
default: default:
panic(fmt.Sprintf("unknown shard mode: %s", s)) panic("unknown shard mode: " + s)
} }
return return

View file

@ -1,7 +1,7 @@
package morphconfig package morphconfig
import ( import (
"fmt" "errors"
"strconv" "strconv"
"time" "time"
@ -27,6 +27,8 @@ const (
SwitchIntervalDefault = 2 * time.Minute 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 // RPCEndpoint returns list of the values of "rpc_endpoint" config parameter
// from "morph" section. // from "morph" section.
// //
@ -54,7 +56,7 @@ func RPCEndpoint(c *config.Config) []client.Endpoint {
} }
if len(es) == 0 { if len(es) == 0 {
panic(fmt.Errorf("no morph chain RPC endpoints, see `morph.rpc_endpoint` section")) panic(errNoMorphEndpoints)
} }
return es return es
} }

View file

@ -2,7 +2,6 @@ package main
import ( import (
"context" "context"
"fmt"
"net/http" "net/http"
"time" "time"
@ -23,7 +22,7 @@ type httpComponent struct {
func (cmp *httpComponent) init(c *cfg) { func (cmp *httpComponent) init(c *cfg) {
if !cmp.enabled { if !cmp.enabled {
c.log.Info(fmt.Sprintf("%s is disabled", cmp.name)) c.log.Info(cmp.name + " is disabled")
return return
} }
// Init server with parameters // Init server with parameters

View file

@ -75,7 +75,7 @@ func main() {
func initAndLog(c *cfg, name string, initializer func(*cfg)) { func initAndLog(c *cfg, name string, initializer func(*cfg)) {
c.log.Info(fmt.Sprintf("initializing %s service...", name)) c.log.Info(fmt.Sprintf("initializing %s service...", name))
initializer(c) 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) { 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) starter(ctx, c)
if logSuccess { 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) { func bootUp(ctx context.Context, c *cfg) {

View file

@ -1,6 +1,7 @@
package config package config
import ( import (
"errors"
"fmt" "fmt"
"strings" "strings"
@ -15,6 +16,8 @@ const (
EnvSeparator = "_" EnvSeparator = "_"
) )
var errProvideViperInOpts = errors.New("provide viper in opts")
func CreateViper(opts ...Option) (*viper.Viper, error) { func CreateViper(opts ...Option) (*viper.Viper, error) {
o := defaultOpts() o := defaultOpts()
for i := range opts { for i := range opts {
@ -59,7 +62,7 @@ func ReloadViper(opts ...Option) error {
} }
if o.v == nil { if o.v == nil {
return fmt.Errorf("provide viper in opts") return errProvideViperInOpts
} }
if o.path != "" { if o.path != "" {

View file

@ -18,7 +18,7 @@ func (e *ConvertEACLError) Error() string {
if e == nil { if e == nil {
return "" 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 { func (e *ConvertEACLError) Unwrap() error {

View file

@ -34,6 +34,8 @@ var (
ErrTargetNameBucketNotFound = logicerr.New("target name bucket not found") ErrTargetNameBucketNotFound = logicerr.New("target name bucket not found")
ErrBucketNotContainsChainID = logicerr.New("chain id not found in bucket") 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 // 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) { func (cs *boltLocalOverrideStorage) AddOverride(name chain.Name, target policyengine.Target, c *chain.Chain) (chain.ID, error) {
if len(c.ID) == 0 { if len(c.ID) == 0 {
return chain.ID{}, fmt.Errorf("chain ID is not set") return chain.ID{}, errChainIDIsNotSet
} }
serializedChain := c.Bytes() serializedChain := c.Bytes()

View file

@ -1,6 +1,7 @@
package container package container
import ( import (
"errors"
"fmt" "fmt"
"strings" "strings"
@ -31,6 +32,8 @@ type putContainerContext struct {
d containerSDK.Domain 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 // Process a new container from the user by checking the container sanity
// and sending approve tx back to the morph. // and sending approve tx back to the morph.
func (cp *Processor) processContainerPut(put putEvent) bool { func (cp *Processor) processContainerPut(put putEvent) bool {
@ -193,7 +196,7 @@ func (cp *Processor) checkNNS(ctx *putContainerContext, cnr containerSDK.Contain
} }
if subject.Namespace != namespace { if subject.Namespace != namespace {
return fmt.Errorf("container and owner namespaces do not match") return errContainerAndOwnerNamespaceDontMatch
} }
return nil return nil

View file

@ -2,7 +2,6 @@ package blobovniczatree
import ( import (
"errors" "errors"
"fmt"
"strconv" "strconv"
"strings" "strings"
"sync" "sync"
@ -117,7 +116,7 @@ func u64ToHexStringExt(ind uint64) string {
func u64FromHexString(str string) uint64 { func u64FromHexString(str string) uint64 {
v, err := strconv.ParseUint(strings.TrimSuffix(str, dbExtension), 16, 64) v, err := strconv.ParseUint(strings.TrimSuffix(str, dbExtension), 16, 64)
if err != nil { if err != nil {
panic(fmt.Sprintf("blobovnicza name is not an index %s", str)) panic("blobovnicza name is not an index " + str)
} }
return v return v

View file

@ -24,6 +24,11 @@ var (
objectUserCounterKey = []byte("user_counter") objectUserCounterKey = []byte("user_counter")
) )
var (
errInvalidKeyLenght = errors.New("invalid key length")
errInvalidValueLenght = errors.New("invalid value length")
)
type objectType uint8 type objectType uint8
const ( const (
@ -474,7 +479,7 @@ func containerCounterValue(entity ObjectCounters) []byte {
func parseContainerCounterKey(buf []byte) (cid.ID, error) { func parseContainerCounterKey(buf []byte) (cid.ID, error) {
if len(buf) != cidSize { if len(buf) != cidSize {
return cid.ID{}, fmt.Errorf("invalid key length") return cid.ID{}, errInvalidKeyLenght
} }
var cnrID cid.ID var cnrID cid.ID
if err := cnrID.Decode(buf); err != nil { if err := cnrID.Decode(buf); err != nil {
@ -486,7 +491,7 @@ func parseContainerCounterKey(buf []byte) (cid.ID, error) {
// parseContainerCounterValue return phy, logic values. // parseContainerCounterValue return phy, logic values.
func parseContainerCounterValue(buf []byte) (ObjectCounters, error) { func parseContainerCounterValue(buf []byte) (ObjectCounters, error) {
if len(buf) != 24 { if len(buf) != 24 {
return ObjectCounters{}, fmt.Errorf("invalid value length") return ObjectCounters{}, errInvalidValueLenght
} }
return ObjectCounters{ return ObjectCounters{
Phy: binary.LittleEndian.Uint64(buf), Phy: binary.LittleEndian.Uint64(buf),

View file

@ -20,6 +20,8 @@ import (
"go.opentelemetry.io/otel/trace" "go.opentelemetry.io/otel/trace"
) )
var errFailedToRemoveUniqueIndexes = errors.New("can't remove unique indexes")
// DeletePrm groups the parameters of Delete operation. // DeletePrm groups the parameters of Delete operation.
type DeletePrm struct { type DeletePrm struct {
addrs []oid.Address addrs []oid.Address
@ -325,7 +327,7 @@ func (db *DB) deleteObject(
) error { ) error {
err := delUniqueIndexes(tx, obj, isParent) err := delUniqueIndexes(tx, obj, isParent)
if err != nil { if err != nil {
return fmt.Errorf("can't remove unique indexes") return errFailedToRemoveUniqueIndexes
} }
err = updateListIndexes(tx, obj, delListIndexItem) err = updateListIndexes(tx, obj, delListIndexItem)

View file

@ -3,7 +3,7 @@ package meta
import ( import (
"bytes" "bytes"
"crypto/sha256" "crypto/sha256"
"fmt" "errors"
cid "git.frostfs.info/TrueCloudLab/frostfs-sdk-go/container/id" cid "git.frostfs.info/TrueCloudLab/frostfs-sdk-go/container/id"
objectSDK "git.frostfs.info/TrueCloudLab/frostfs-sdk-go/object" objectSDK "git.frostfs.info/TrueCloudLab/frostfs-sdk-go/object"
@ -25,6 +25,8 @@ var (
containerCounterBucketName = []byte{containerCountersPrefix} containerCounterBucketName = []byte{containerCountersPrefix}
zeroValue = []byte{0xFF} zeroValue = []byte{0xFF}
errInvalidLength = errors.New("invalid length")
) )
// Prefix bytes for database keys. All ids and addresses are encoded in binary // 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. // parses object address formed by addressKey.
func decodeAddressFromKey(dst *oid.Address, k []byte) error { func decodeAddressFromKey(dst *oid.Address, k []byte) error {
if len(k) != addressKeySize { if len(k) != addressKeySize {
return fmt.Errorf("invalid length") return errInvalidLength
} }
var cnr cid.ID var cnr cid.ID

View file

@ -2,6 +2,7 @@ package pilorama
import ( import (
"context" "context"
"errors"
"fmt" "fmt"
"sort" "sort"
"strings" "strings"
@ -10,6 +11,8 @@ import (
cid "git.frostfs.info/TrueCloudLab/frostfs-sdk-go/container/id" 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. // memoryForest represents multiple replicating trees sharing a single storage.
type memoryForest struct { type memoryForest struct {
// treeMap maps tree identifier (container ID + name) to the replicated log. // 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) { for idx < len(tmpSlice) {
cidAndTree := strings.Split(tmpSlice[idx], "/") cidAndTree := strings.Split(tmpSlice[idx], "/")
if len(cidAndTree) != 2 { if len(cidAndTree) != 2 {
return nil, fmt.Errorf("invalid format: key must be cid and treeID") return nil, errInvalidKeyFormat
} }
var contID cid.ID var contID cid.ID
if err := contID.DecodeString(cidAndTree[0]); err != nil { if err := contID.DecodeString(cidAndTree[0]); err != nil {

View file

@ -1,12 +1,15 @@
package netmap package netmap
import ( import (
"errors"
"fmt" "fmt"
"git.frostfs.info/TrueCloudLab/frostfs-node/pkg/morph/client" "git.frostfs.info/TrueCloudLab/frostfs-node/pkg/morph/client"
"git.frostfs.info/TrueCloudLab/frostfs-sdk-go/netmap" "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. // AddPeerPrm groups parameters of AddPeer operation.
type AddPeerPrm struct { type AddPeerPrm struct {
nodeInfo netmap.NodeInfo 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. // If vub > 0, vub will be used as valid until block value.
func (c *Client) ForceRemovePeer(nodeInfo netmap.NodeInfo, vub uint32) (uint32, error) { func (c *Client) ForceRemovePeer(nodeInfo netmap.NodeInfo, vub uint32) (uint32, error) {
if !c.client.WithNotary() { if !c.client.WithNotary() {
return 0, fmt.Errorf("peer can be forcefully removed only in notary environment") return 0, errFailedToRemovePeerWithoutNotary
} }
prm := UpdatePeerPrm{} prm := UpdatePeerPrm{}

View file

@ -1,6 +1,7 @@
package network package network
import ( import (
"errors"
"fmt" "fmt"
"net" "net"
"net/url" "net/url"
@ -18,6 +19,8 @@ import (
URIAddr strings: "<scheme://>127.0.0.1:8080" URIAddr strings: "<scheme://>127.0.0.1:8080"
*/ */
var errHostIsEmpty = errors.New("host is empty")
// Address represents the FrostFS node // Address represents the FrostFS node
// network address. // network address.
type Address struct { type Address struct {
@ -89,7 +92,7 @@ func (a *Address) FromString(s string) error {
// multiaddrStringFromHostAddr converts "localhost:8080" to "/dns4/localhost/tcp/8080". // multiaddrStringFromHostAddr converts "localhost:8080" to "/dns4/localhost/tcp/8080".
func multiaddrStringFromHostAddr(host string) (string, error) { func multiaddrStringFromHostAddr(host string) (string, error) {
if len(host) == 0 { if len(host) == 0 {
return "", fmt.Errorf("host is empty") return "", errHostIsEmpty
} }
endpoint, port, err := net.SplitHostPort(host) endpoint, port, err := net.SplitHostPort(host)

View file

@ -41,6 +41,8 @@ var (
errEmptyBodySignature = errors.New("malformed request: empty body signature") errEmptyBodySignature = errors.New("malformed request: empty body signature")
errMissingOwnerID = errors.New("malformed request: missing owner ID") errMissingOwnerID = errors.New("malformed request: missing owner ID")
errSubjectNotFound = errors.New("subject not found") 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{} 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) { func (ac *apeChecker) namespaceByOwner(owner *refs.OwnerID) (string, error) {
var ownerSDK user.ID var ownerSDK user.ID
if owner == nil { if owner == nil {
return "", fmt.Errorf("owner id is not set") return "", errOwnerIDIsNotSet
} }
if err := ownerSDK.ReadFromV2(*owner); err != nil { if err := ownerSDK.ReadFromV2(*owner); err != nil {
return "", err return "", err
@ -603,7 +605,7 @@ func validateNamespace(cnrV2 *container.Container, ownerIDNamespace string) erro
if hasNamespace { if hasNamespace {
if cntNamespace != ownerIDNamespace { if cntNamespace != ownerIDNamespace {
if 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) return fmt.Errorf("invalid domain zone: expected namespace %s, but got %s", ownerIDNamespace, cntNamespace)
} }

View file

@ -16,6 +16,8 @@ import (
"git.frostfs.info/TrueCloudLab/frostfs-sdk-go/user" "git.frostfs.info/TrueCloudLab/frostfs-sdk-go/user"
) )
var errMissingUserID = errors.New("missing user ID")
type morphExecutor struct { type morphExecutor struct {
rdr Reader rdr Reader
wrt Writer 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) { func (s *morphExecutor) List(_ context.Context, body *container.ListRequestBody) (*container.ListResponseBody, error) {
idV2 := body.GetOwnerID() idV2 := body.GetOwnerID()
if idV2 == nil { if idV2 == nil {
return nil, fmt.Errorf("missing user ID") return nil, errMissingUserID
} }
var id user.ID var id user.ID

View file

@ -121,7 +121,7 @@ func (s *Server) RemoveContainer(_ context.Context, req *control.RemoveContainer
if len(req.GetBody().GetContainerId()) > 0 { if len(req.GetBody().GetContainerId()) > 0 {
var containerID cid.ID var containerID cid.ID
if err := containerID.Decode(req.GetBody().GetContainerId()); err != nil { 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 var err error
vub, err = s.removeContainer(containerID, req.GetBody().GetVub()) vub, err = s.removeContainer(containerID, req.GetBody().GetVub())
@ -131,11 +131,11 @@ func (s *Server) RemoveContainer(_ context.Context, req *control.RemoveContainer
} else { } else {
var ownerID refs.OwnerID var ownerID refs.OwnerID
if err := ownerID.Unmarshal(req.GetBody().GetOwner()); err != nil { 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 var owner user.ID
if err := owner.ReadFromV2(ownerID); err != nil { 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) cids, err := s.containerClient.ContainersOf(&owner)

View file

@ -1,7 +1,6 @@
package control package control
import ( import (
"fmt"
"time" "time"
"git.frostfs.info/TrueCloudLab/frostfs-node/pkg/local_object_storage/engine" "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() { for _, shID := range state.ShardIDs() {
id, err := base58.Decode(shID) id, err := base58.Decode(shID)
if err != nil { 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) shardIDs = append(shardIDs, id)
} }

View file

@ -23,6 +23,8 @@ import (
"google.golang.org/grpc/status" "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) { func (s *Server) EvacuateShard(ctx context.Context, req *control.EvacuateShardRequest) (*control.EvacuateShardResponse, error) {
err := s.isValidRequest(req) err := s.isValidRequest(req)
if err != nil { 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) ns, err := nm.ContainerNodes(c.Value.PlacementPolicy(), binCnr)
if err != nil { if err != nil {
return nil, fmt.Errorf("can't build a list of container nodes") return nil, errFailedToBuildListOfContainerNodes
} }
nodes := placement.FlattenNodes(ns) nodes := placement.FlattenNodes(ns)

View file

@ -2,6 +2,7 @@ package ape
import ( import (
"context" "context"
"errors"
"fmt" "fmt"
objectV2 "git.frostfs.info/TrueCloudLab/frostfs-api-go/v2/object" objectV2 "git.frostfs.info/TrueCloudLab/frostfs-api-go/v2/object"
@ -50,7 +51,7 @@ type Prm struct {
SoftAPECheck bool 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 // CheckAPE checks if a request or a response is permitted creating an ape request and passing
// it to chain router. // it to chain router.

View file

@ -1,13 +1,11 @@
package ape package ape
import ( import (
"fmt"
apistatus "git.frostfs.info/TrueCloudLab/frostfs-sdk-go/client/status" apistatus "git.frostfs.info/TrueCloudLab/frostfs-sdk-go/client/status"
) )
func toStatusErr(err error) error { func toStatusErr(err error) error {
errAccessDenied := &apistatus.ObjectAccessDenied{} errAccessDenied := &apistatus.ObjectAccessDenied{}
errAccessDenied.WriteReason(fmt.Sprintf("ape denied request: %s", err.Error())) errAccessDenied.WriteReason("ape denied request: " + err.Error())
return errAccessDenied return errAccessDenied
} }

View file

@ -3,6 +3,7 @@ package ape
import ( import (
"context" "context"
"encoding/hex" "encoding/hex"
"errors"
"fmt" "fmt"
objectV2 "git.frostfs.info/TrueCloudLab/frostfs-api-go/v2/object" objectV2 "git.frostfs.info/TrueCloudLab/frostfs-api-go/v2/object"
@ -16,6 +17,8 @@ import (
nativeschema "git.frostfs.info/TrueCloudLab/policy-engine/schema/native" nativeschema "git.frostfs.info/TrueCloudLab/policy-engine/schema/native"
) )
var errFailedToCastToRequestContext = errors.New("failed cast to RequestContext")
type Service struct { type Service struct {
log *logger.Logger log *logger.Logger
@ -101,7 +104,7 @@ func requestContext(ctx context.Context) (*objectSvc.RequestContext, error) {
} }
rc, ok := untyped.(*objectSvc.RequestContext) rc, ok := untyped.(*objectSvc.RequestContext)
if !ok { if !ok {
return nil, fmt.Errorf("failed cast to RequestContext") return nil, errFailedToCastToRequestContext
} }
return rc, nil return rc, nil
} }

View file

@ -32,6 +32,8 @@ import (
"go.uber.org/zap" "go.uber.org/zap"
) )
var errInvalidPayloadChecksum = errors.New("incorrect payload checksum")
type putSingleRequestSigner struct { type putSingleRequestSigner struct {
req *objectAPI.PutSingleRequest req *objectAPI.PutSingleRequest
keyStorage *svcutil.KeyStorage keyStorage *svcutil.KeyStorage
@ -125,7 +127,7 @@ func (s *Service) validatePutSingleChecksum(obj *objectSDK.Object) error {
} }
if !bytes.Equal(hash.Sum(nil), cs.Value()) { if !bytes.Equal(hash.Sum(nil), cs.Value()) {
return fmt.Errorf("incorrect payload checksum") return errInvalidPayloadChecksum
} }
return nil return nil

View file

@ -1,6 +1,7 @@
package sdnotify package sdnotify
import ( import (
"errors"
"fmt" "fmt"
"net" "net"
"os" "os"
@ -13,14 +14,19 @@ const (
ReloadingEnabled = "RELOADING=1" 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 // Initializes socket with provided name of
// environment variable. // environment variable.
func InitSocket() error { func InitSocket() error {
notifySocket := os.Getenv("NOTIFY_SOCKET") notifySocket := os.Getenv("NOTIFY_SOCKET")
if notifySocket == "" { if notifySocket == "" {
return fmt.Errorf("\"NOTIFY_SOCKET\" environment variable is not present") return errSocketVariableIsNotPresent
} }
socket = &net.UnixAddr{ socket = &net.UnixAddr{
Name: notifySocket, Name: notifySocket,
@ -38,14 +44,14 @@ func FlagAndStatus(status string) error {
// Status sends systemd notify STATUS=%s{status}. // Status sends systemd notify STATUS=%s{status}.
func Status(status string) error { func Status(status string) error {
return Send(fmt.Sprintf("STATUS=%s", status)) return Send("STATUS=" + status)
} }
// Send state through the notify socket if any. // Send state through the notify socket if any.
// If the notify socket was not detected, it returns an error. // If the notify socket was not detected, it returns an error.
func Send(state string) error { func Send(state string) error {
if socket == nil { if socket == nil {
return fmt.Errorf("socket is not initialized") return errSocketIsNotInitialized
} }
conn, err := net.DialUnix(socket.Net, nil, socket) conn, err := net.DialUnix(socket.Net, nil, socket)
if err != nil { if err != nil {