cleanup: address gomnd warnings

Direct usage of numbers should be avoided.

Issue reported:
mnd: Magic number: X, in <argument> detected (gomnd)

Signed-off-by: Yug <yuggupta27@gmail.com>
This commit is contained in:
Yug 2020-07-21 10:40:13 +05:30 committed by mergify[bot]
parent e73fe64a0d
commit 71ddf51544
11 changed files with 38 additions and 22 deletions

View File

@ -39,6 +39,9 @@ const (
rbdDefaultName = "rbd.csi.ceph.com" rbdDefaultName = "rbd.csi.ceph.com"
cephfsDefaultName = "cephfs.csi.ceph.com" cephfsDefaultName = "cephfs.csi.ceph.com"
livenessDefaultName = "liveness.csi.ceph.com" livenessDefaultName = "liveness.csi.ceph.com"
pollTime = 60 // seconds
probeTimeout = 3 // seconds
) )
var ( var (
@ -65,8 +68,8 @@ func init() {
// liveness/grpc metrics related flags // liveness/grpc metrics related flags
flag.IntVar(&conf.MetricsPort, "metricsport", 8080, "TCP port for liveness/grpc metrics requests") flag.IntVar(&conf.MetricsPort, "metricsport", 8080, "TCP port for liveness/grpc metrics requests")
flag.StringVar(&conf.MetricsPath, "metricspath", "/metrics", "path of prometheus endpoint where metrics will be available") flag.StringVar(&conf.MetricsPath, "metricspath", "/metrics", "path of prometheus endpoint where metrics will be available")
flag.DurationVar(&conf.PollTime, "polltime", time.Second*60, "time interval in seconds between each poll") flag.DurationVar(&conf.PollTime, "polltime", time.Second*pollTime, "time interval in seconds between each poll")
flag.DurationVar(&conf.PoolTimeout, "timeout", time.Second*3, "probe timeout in seconds") flag.DurationVar(&conf.PoolTimeout, "timeout", time.Second*probeTimeout, "probe timeout in seconds")
flag.BoolVar(&conf.EnableGRPCMetrics, "enablegrpcmetrics", false, "[DEPRECATED] enable grpc metrics") flag.BoolVar(&conf.EnableGRPCMetrics, "enablegrpcmetrics", false, "[DEPRECATED] enable grpc metrics")
flag.StringVar(&conf.HistogramOption, "histogramoption", "0.5,2,6", flag.StringVar(&conf.HistogramOption, "histogramoption", "0.5,2,6",

View File

@ -47,6 +47,7 @@ var (
fusePidRx = regexp.MustCompile(`(?m)^ceph-fuse\[(.+)\]: starting fuse$`) fusePidRx = regexp.MustCompile(`(?m)^ceph-fuse\[(.+)\]: starting fuse$`)
// nolint:gomnd // numbers specify Kernel versions.
quotaSupport = []util.KernelVersion{ quotaSupport = []util.KernelVersion{
{ {
Version: 4, Version: 4,
@ -176,7 +177,10 @@ func mountFuse(ctx context.Context, mountPoint string, cr *util.Credentials, vol
// and PID of the ceph-fuse daemon for unmount // and PID of the ceph-fuse daemon for unmount
match := fusePidRx.FindSubmatch(stderr) match := fusePidRx.FindSubmatch(stderr)
if len(match) != 2 { // validMatchLength is set to 2 as match is expected
// to have 2 items, starting fuse and PID of the fuse daemon
const validMatchLength = 2
if len(match) != validMatchLength {
return fmt.Errorf("ceph-fuse failed: %s", stderr) return fmt.Errorf("ceph-fuse failed: %s", stderr)
} }

View File

@ -118,7 +118,8 @@ func (s *nonBlockingGRPCServer) serve(endpoint, hstOptions string, ids csi.Ident
util.DefaultLog("Listening for connections on address: %#v", listener.Addr()) util.DefaultLog("Listening for connections on address: %#v", listener.Addr())
if metrics { if metrics {
ho := strings.Split(hstOptions, ",") ho := strings.Split(hstOptions, ",")
if len(ho) != 3 { const expectedHo = 3
if len(ho) != expectedHo {
klog.Fatalf("invalid histogram options provided: %v", hstOptions) klog.Fatalf("invalid histogram options provided: %v", hstOptions)
} }
start, e := strconv.ParseFloat(ho[0], 32) start, e := strconv.ParseFloat(ho[0], 32)

View File

@ -401,7 +401,7 @@ func (conn *Connection) UndoReservation(ctx context.Context,
cj := conn.config cj := conn.config
if volName != "" { if volName != "" {
if len(volName) < 36 { if len(volName) < uuidEncodedLength {
return fmt.Errorf("unable to parse UUID from %s, too short", volName) return fmt.Errorf("unable to parse UUID from %s, too short", volName)
} }

View File

@ -234,11 +234,13 @@ func (rv *rbdVolume) flattenCloneImage(ctx context.Context) error {
// can flatten the parent images before use to avoid the stale omap entries. // can flatten the parent images before use to avoid the stale omap entries.
hardLimit := rbdHardMaxCloneDepth hardLimit := rbdHardMaxCloneDepth
softLimit := rbdSoftMaxCloneDepth softLimit := rbdSoftMaxCloneDepth
if rbdHardMaxCloneDepth < 2 { // choosing 2 so that we don't need to flatten the image in the request.
hardLimit = rbdHardMaxCloneDepth - 2 const depthToAvoidFlatten = 2
if rbdHardMaxCloneDepth < depthToAvoidFlatten {
hardLimit = rbdHardMaxCloneDepth - depthToAvoidFlatten
} }
if rbdSoftMaxCloneDepth < 2 { if rbdSoftMaxCloneDepth < depthToAvoidFlatten {
softLimit = rbdSoftMaxCloneDepth - 2 softLimit = rbdSoftMaxCloneDepth - depthToAvoidFlatten
} }
err := tempClone.getImageInfo() err := tempClone.getImageInfo()
if err == nil { if err == nil {

View File

@ -65,6 +65,7 @@ var (
kernelRelease = "" kernelRelease = ""
// deepFlattenSupport holds the list of kernel which support mapping rbd // deepFlattenSupport holds the list of kernel which support mapping rbd
// image with deep-flatten image feature // image with deep-flatten image feature
// nolint:gomnd // numbers specify Kernel versions.
deepFlattenSupport = []util.KernelVersion{ deepFlattenSupport = []util.KernelVersion{
{ {
Version: 5, Version: 5,

View File

@ -62,9 +62,6 @@ const (
rbdImageRequiresEncryption = "requiresEncryption" rbdImageRequiresEncryption = "requiresEncryption"
// image metadata key for encryption // image metadata key for encryption
encryptionMetaKey = ".rbd.csi.ceph.com/encrypted" encryptionMetaKey = ".rbd.csi.ceph.com/encrypted"
// go-ceph will provide rbd.ImageOptionCloneFormat
imageOptionCloneFormat = librbd.RbdImageOption(12)
) )
// rbdVolume represents a CSI volume and its RBD image specifics. // rbdVolume represents a CSI volume and its RBD image specifics.
@ -856,7 +853,7 @@ func (rv *rbdVolume) cloneRbdImageFromSnapshot(ctx context.Context, pSnapOpts *r
} }
} }
err = options.SetUint64(imageOptionCloneFormat, 2) err = options.SetUint64(librbd.ImageOptionCloneFormat, 2)
if err != nil { if err != nil {
return fmt.Errorf("failed to set image features: %w", err) return fmt.Errorf("failed to set image features: %w", err)
} }
@ -1006,7 +1003,8 @@ func (ri *rbdImageMetadataStash) String() string {
// JSON format. // JSON format.
func stashRBDImageMetadata(volOptions *rbdVolume, path string) error { func stashRBDImageMetadata(volOptions *rbdVolume, path string) error {
var imgMeta = rbdImageMetadataStash{ var imgMeta = rbdImageMetadataStash{
Version: 2, // there are no checks for this at present // there are no checks for this at present
Version: 2, // nolint:gomnd // number specifies version.
Pool: volOptions.Pool, Pool: volOptions.Pool,
ImageName: volOptions.RbdImageName, ImageName: volOptions.RbdImageName,
Encrypted: volOptions.Encrypted, Encrypted: volOptions.Encrypted,

View File

@ -52,7 +52,8 @@ func GetTopologyFromDomainLabels(domainLabels, nodeName, driverName string) (map
// size checks on domain label prefix // size checks on domain label prefix
topologyPrefix := strings.ToLower("topology." + driverName) topologyPrefix := strings.ToLower("topology." + driverName)
if len(topologyPrefix) > 63 { const lenLimit = 63
if len(topologyPrefix) > lenLimit {
return nil, fmt.Errorf("computed topology label prefix (%s) for node exceeds length limits", topologyPrefix) return nil, fmt.Errorf("computed topology label prefix (%s) for node exceeds length limits", topologyPrefix)
} }
// driverName is validated, and we are adding a lowercase "topology." to it, so no validation for conformance // driverName is validated, and we are adding a lowercase "topology." to it, so no validation for conformance

View File

@ -125,7 +125,8 @@ func ValidateDriverName(driverName string) error {
return errors.New("driver name is empty") return errors.New("driver name is empty")
} }
if len(driverName) > 63 { const reqDriverNameLen = 63
if len(driverName) > reqDriverNameLen {
return errors.New("driver name length should be less than 63 chars") return errors.New("driver name length should be less than 63 chars")
} }
var err error var err error
@ -191,7 +192,8 @@ func CheckKernelSupport(release string, supportedVersions []KernelVersion) bool
return false return false
} }
sublevel := 0 sublevel := 0
if len(vers) >= 3 { const minLenForSublvl = 3
if len(vers) >= minLenForSublvl {
sublevel, err = strconv.Atoi(vers[2]) sublevel, err = strconv.Atoi(vers[2])
if err != nil { if err != nil {
klog.Errorf("failed to parse sublevel from %s: %v", release, err) klog.Errorf("failed to parse sublevel from %s: %v", release, err)
@ -200,7 +202,8 @@ func CheckKernelSupport(release string, supportedVersions []KernelVersion) bool
} }
extra := strings.SplitN(release, "-", 2) extra := strings.SplitN(release, "-", 2)
extraversion := 0 extraversion := 0
if len(extra) == 2 { const expectedExtraLen = 2
if len(extra) == expectedExtraLen {
// ignore errors, 1st component of extraversion does not need to be an int // ignore errors, 1st component of extraversion does not need to be an int
extraversion, err = strconv.Atoi(strings.Split(extra[1], ".")[0]) extraversion, err = strconv.Atoi(strings.Split(extra[1], ".")[0])
if err != nil { if err != nil {

View File

@ -151,7 +151,7 @@ func (kms *VaultKMS) GetPassphrase(key string) (string, error) {
} }
defer resp.Body.Close() defer resp.Body.Close()
if resp.StatusCode == 404 { if resp.StatusCode == http.StatusNotFound {
return "", MissingPassphrase{fmt.Errorf("passphrase for %s not found", key)} return "", MissingPassphrase{fmt.Errorf("passphrase for %s not found", key)}
} }
err = kms.processError(resp, fmt.Sprintf("get passphrase for %s", key)) err = kms.processError(resp, fmt.Sprintf("get passphrase for %s", key))
@ -219,7 +219,7 @@ func (kms *VaultKMS) DeletePassphrase(key string) error {
return fmt.Errorf("delete passphrase at %s request to vault failed: %s", key, err) return fmt.Errorf("delete passphrase at %s request to vault failed: %s", key, err)
} }
defer resp.Body.Close() defer resp.Body.Close()
if resp.StatusCode != 404 { if resp.StatusCode != http.StatusNotFound {
err = kms.processError(resp, "delete passphrase") err = kms.processError(resp, "delete passphrase")
if err != nil { if err != nil {
return err return err

View File

@ -127,9 +127,12 @@ func (ci *CSIIdentifier) DecomposeCSIID(composedCSIID string) (err error) {
ci.ClusterID = composedCSIID[10 : 10+clusterIDLength] ci.ClusterID = composedCSIID[10 : 10+clusterIDLength]
// additional 1 for '-' separator // additional 1 for '-' separator
bytesToProcess -= (clusterIDLength + 1) bytesToProcess -= (clusterIDLength + 1)
nextFieldStartIdx := 10 + clusterIDLength + 1 nextFieldStartIdx := (10 + clusterIDLength + 1)
if bytesToProcess < 17 { // minLenToDecode is now 17 as composedCSIID should include
// atleast 16 for poolID encoding and 1 for '-' separator.
const minLenToDecode = 17
if bytesToProcess < minLenToDecode {
return errors.New("failed to decode CSI identifier, string underflow") return errors.New("failed to decode CSI identifier, string underflow")
} }
buf64, err := hex.DecodeString(composedCSIID[nextFieldStartIdx : nextFieldStartIdx+16]) buf64, err := hex.DecodeString(composedCSIID[nextFieldStartIdx : nextFieldStartIdx+16])