Skip to content

Commit

Permalink
add device utils unit tests
Browse files Browse the repository at this point in the history
Add unit tests fpr device utils package
  • Loading branch information
jharrod authored Dec 19, 2024
1 parent 9e3b007 commit 5bdc66a
Show file tree
Hide file tree
Showing 14 changed files with 1,222 additions and 143 deletions.
55 changes: 55 additions & 0 deletions mocks/mock_utils/mock_devices/mock_size_getter_client.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

35 changes: 24 additions & 11 deletions utils/devices/devices.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Copyright 2024 NetApp, Inc. All Rights Reserved.

//go:generate mockgen -destination=../../mocks/mock_utils/mock_devices/mock_devices_client.go github.com/netapp/trident/utils/devices Devices
//go:generate mockgen -destination=../../mocks/mock_utils/mock_devices/mock_size_getter_client.go github.com/netapp/trident/utils/devices SizeGetter

package devices

Expand Down Expand Up @@ -74,17 +75,28 @@ type Devices interface {
) error
}

type SizeGetter interface {
GetDiskSize(ctx context.Context, devicePath string) (int64, error)
}

type DiskSizeGetter struct{}

func NewDiskSizeGetter() *DiskSizeGetter {
return &DiskSizeGetter{}
}

type Client struct {
chrootPathPrefix string
command exec.Command
osFs afero.Afero
SizeGetter
}

func New() *Client {
return NewDetailed(exec.NewCommand(), afero.NewOsFs())
return NewDetailed(exec.NewCommand(), afero.NewOsFs(), NewDiskSizeGetter())
}

func NewDetailed(command exec.Command, osFs afero.Fs) *Client {
func NewDetailed(command exec.Command, osFs afero.Fs, diskSizeGetter SizeGetter) *Client {
chrootPathPrefix := ""
if os.Getenv("DOCKER_PLUGIN_MODE") != "" {
chrootPathPrefix = "/host"
Expand All @@ -93,6 +105,7 @@ func NewDetailed(command exec.Command, osFs afero.Fs) *Client {
chrootPathPrefix: chrootPathPrefix,
command: command,
osFs: afero.Afero{Fs: osFs},
SizeGetter: diskSizeGetter,
}
}

Expand Down Expand Up @@ -297,7 +310,7 @@ func (c *Client) FindDevicesForMultipathDevice(ctx context.Context, device strin
devices := make([]string, 0)

slavesDir := c.chrootPathPrefix + "/sys/block/" + device + "/slaves"
if dirs, err := os.ReadDir(slavesDir); err == nil {
if dirs, err := c.osFs.ReadDir(slavesDir); err == nil {
for _, f := range dirs {
name := f.Name()
if strings.HasPrefix(name, "sd") {
Expand Down Expand Up @@ -585,7 +598,7 @@ func (c *Client) GetMultipathDeviceDisks(
multipathDevice := strings.TrimPrefix(multipathDevicePath, "/dev/")

diskPath := c.chrootPathPrefix + fmt.Sprintf("/sys/block/%s/slaves/", multipathDevice)
diskDirs, err := os.ReadDir(diskPath)
diskDirs, err := c.osFs.ReadDir(diskPath)
if err != nil {
Logc(ctx).WithError(err).Errorf("Could not read %s", diskPath)
return nil, fmt.Errorf("failed to identify multipath device disks; unable to read '%s'", diskPath)
Expand All @@ -607,7 +620,7 @@ func (c *Client) GetMultipathDeviceDisks(
func (c *Client) GetMultipathDeviceBySerial(ctx context.Context, hexSerial string) (string, error) {
sysPath := c.chrootPathPrefix + "/sys/block/"

blockDirs, err := os.ReadDir(sysPath)
blockDirs, err := c.osFs.ReadDir(sysPath)
if err != nil {
Logc(ctx).WithError(err).Errorf("Could not read %s", sysPath)
return "", fmt.Errorf("failed to find multipath device by serial; unable to read '%s'", sysPath)
Expand Down Expand Up @@ -647,12 +660,12 @@ func (c *Client) GetMultipathDeviceUUID(multipathDevicePath string) (string, err

deviceUUIDPath := c.chrootPathPrefix + fmt.Sprintf("/sys/block/%s/dm/uuid", multipathDevice)

exists, err := PathExists(deviceUUIDPath)
exists, err := PathExists(c.osFs, deviceUUIDPath)
if !exists || err != nil {
return "", errors.NotFoundError("multipath device '%s' UUID not found", multipathDevice)
}

UUID, err := os.ReadFile(deviceUUIDPath)
UUID, err := c.osFs.ReadFile(deviceUUIDPath)
if err != nil {
return "", err
}
Expand All @@ -666,15 +679,15 @@ func (c *Client) RemoveDevice(ctx context.Context, devices []string, ignoreError
defer Logc(ctx).Debug("<<<< devices.removeDevice")

var (
f *os.File
f afero.File
err error
)

c.ListAllDevices(ctx)
for _, deviceName := range devices {

filename := fmt.Sprintf(c.chrootPathPrefix+"/sys/block/%s/device/delete", deviceName)
if f, err = os.OpenFile(filename, os.O_APPEND|os.O_WRONLY, 0o200); err != nil {
if f, err = c.osFs.OpenFile(filename, os.O_APPEND|os.O_WRONLY, 0o200); err != nil {
Logc(ctx).WithField("file", filename).Warning("Could not open file for writing.")
if ignoreErrors {
continue
Expand Down Expand Up @@ -746,7 +759,7 @@ func (c *Client) GetLUKSDeviceForMultipathDevice(multipathDevice string) (string
dmDevice := strings.TrimSuffix(strings.TrimPrefix(multipathDevice, "/dev/"), "/")

// Get holder of mpath device
dirents, err := os.ReadDir(fmt.Sprintf("/sys/block/%s/holders/", dmDevice))
dirents, err := c.osFs.ReadDir(fmt.Sprintf("/sys/block/%s/holders/", dmDevice))
if err != nil {
return "", err
}
Expand All @@ -759,7 +772,7 @@ func (c *Client) GetLUKSDeviceForMultipathDevice(multipathDevice string) (string
holder := dirents[0].Name()

// Verify holder is LUKS device
b, err := os.ReadFile(fmt.Sprintf("/sys/block/%s/dm/uuid", holder))
b, err := c.osFs.ReadFile(fmt.Sprintf("/sys/block/%s/dm/uuid", holder))
if err != nil {
return "", err
}
Expand Down
2 changes: 1 addition & 1 deletion utils/devices/devices_darwin.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ func (c *Client) VerifyMultipathDeviceSize(ctx context.Context, multipathDevice,
}

// GetDiskSize unused stub function
func (c *Client) GetDiskSize(ctx context.Context, _ string) (int64, error) {
func (c *DiskSizeGetter) GetDiskSize(ctx context.Context, _ string) (int64, error) {
Logc(ctx).Debug(">>>> devices_darwin.GetDiskSize")
defer Logc(ctx).Debug("<<<< devices_darwin.GetDiskSize")
return 0, errors.UnsupportedError("GetDiskSize is not supported for darwin")
Expand Down
4 changes: 2 additions & 2 deletions utils/devices/devices_darwin_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import (
func TestFlushOneDevice(t *testing.T) {
ctx := context.Background()

devices := NewDetailed(exec.NewCommand(), afero.NewMemMapFs())
devices := NewDetailed(exec.NewCommand(), afero.NewMemMapFs(), nil)
result := devices.FlushOneDevice(ctx, "/test/path")
assert.Error(t, result, "no error")
assert.True(t, errors.IsUnsupportedError(result), "not UnsupportedError")
Expand All @@ -25,7 +25,7 @@ func TestFlushOneDevice(t *testing.T) {
func TestGetISCSIDiskSize(t *testing.T) {
ctx := context.Background()

devices := NewDetailed(exec.NewCommand(), afero.NewMemMapFs())
devices := NewDetailed(exec.NewCommand(), afero.NewMemMapFs(), NewDiskSizeGetter())
result, err := devices.GetDiskSize(ctx, "/test/path")
assert.Equal(t, result, int64(0), "received disk size")
assert.Error(t, err, "no error")
Expand Down
21 changes: 5 additions & 16 deletions utils/devices/devices_linux.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ package devices
import (
"fmt"
"os"
"os/exec"
"strings"
"syscall"
"time"
Expand All @@ -19,22 +18,12 @@ import (
"github.com/netapp/trident/internal/fiji"
. "github.com/netapp/trident/logging"
"github.com/netapp/trident/utils/errors"
execCmd "github.com/netapp/trident/utils/exec"
"github.com/netapp/trident/utils/filesystem"
)

const (
luksCloseTimeout = 30 * time.Second
luksCypherMode = "aes-xts-plain64"
luksType = "luks2"

// Return codes for `cryptsetup status`
cryptsetupStatusDeviceDoesExistStatusCode = 0
cryptsetupStatusDeviceDoesNotExistStatusCode = 4

// Return codes for `cryptsetup isLuks`
cryptsetupIsLuksDeviceIsLuksStatusCode = 0
cryptsetupIsLuksDeviceIsNotLuksStatusCode = 1

luksCloseTimeout = 30 * time.Second
luksCloseMaxWaitDuration = 2 * time.Minute
)

Expand Down Expand Up @@ -71,7 +60,7 @@ func (c *Client) FlushOneDevice(ctx context.Context, devicePath string) error {
}

// GetDiskSize queries the current block size in bytes
func (c *Client) GetDiskSize(ctx context.Context, devicePath string) (int64, error) {
func (c *DiskSizeGetter) GetDiskSize(ctx context.Context, devicePath string) (int64, error) {
fields := LogFields{"rawDevicePath": devicePath}
Logc(ctx).WithFields(fields).Debug(">>>> devices_linux.GetDiskSize")
defer Logc(ctx).WithFields(fields).Debug("<<<< devices_linux.GetDiskSize")
Expand Down Expand Up @@ -203,7 +192,7 @@ func (c *Client) GetDeviceFSType(ctx context.Context, device string) (string, er
if errors.IsTimeoutError(err) {
c.ListAllDevices(ctx)
return "", err
} else if exitErr, ok := err.(*exec.ExitError); ok && exitErr.ExitCode() == 2 {
} else if exitErr, ok := err.(execCmd.ExitError); ok && exitErr.ExitCode() == 2 {
// EITHER: Disk device is unformatted.
// OR: For 'blkid', if the specified token (TYPE/PTTYPE, etc) was
// not found, or no (specified) devices could be identified, an
Expand Down Expand Up @@ -293,7 +282,7 @@ func (c *Client) WaitForDevice(ctx context.Context, device string) error {
Logc(ctx).WithFields(fields).Debug(">>>> devices.waitForDevice")
defer Logc(ctx).WithFields(fields).Debug("<<<< devices.waitForDevice")

exists, err := PathExists(device)
exists, err := PathExists(c.osFs, device)
if !exists || err != nil {
return errors.New("device not yet present")
} else {
Expand Down
Loading

0 comments on commit 5bdc66a

Please sign in to comment.