[#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
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
}

View file

@ -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
}

View file

@ -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)

View file

@ -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

View file

@ -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
}

View file

@ -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
}
}

View file

@ -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 {

View file

@ -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{

View file

@ -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
}

View file

@ -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
}

View file

@ -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
}
}

View file

@ -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()),

View file

@ -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()))

View file

@ -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

View file

@ -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

View file

@ -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
}

View file

@ -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

View file

@ -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) {

View file

@ -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 != "" {

View file

@ -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 {

View file

@ -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()

View file

@ -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

View file

@ -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

View file

@ -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),

View file

@ -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)

View file

@ -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

View file

@ -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 {

View file

@ -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{}

View file

@ -1,6 +1,7 @@
package network
import (
"errors"
"fmt"
"net"
"net/url"
@ -18,6 +19,8 @@ import (
URIAddr strings: "<scheme://>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)

View file

@ -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)
}

View file

@ -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

View file

@ -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)

View file

@ -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)
}

View file

@ -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)

View file

@ -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.

View file

@ -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
}

View file

@ -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
}

View file

@ -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

View file

@ -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 {