|
| 1 | +package lsblk |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "encoding/json" |
| 6 | + "fmt" |
| 7 | + "path/filepath" |
| 8 | + "time" |
| 9 | +) |
| 10 | + |
| 11 | +// GetBlockDevices returns a list of block devices and their details |
| 12 | +func (l *LsblkUtil) GetBlockDevices(ctx context.Context) ([]BlockDevice, error) { |
| 13 | + // Run the lsblk command with --json option |
| 14 | + bytes, err := l.command.ExecuteWithTimeout(ctx, "lsblk", 10*time.Second, false, "-o", |
| 15 | + "NAME,KNAME,TYPE,SIZE,MOUNTPOINT", "--json") |
| 16 | + if err != nil { |
| 17 | + return nil, fmt.Errorf("error running lsblk: %v", err) |
| 18 | + } |
| 19 | + |
| 20 | + // Parse the JSON output |
| 21 | + var results LsblkResults |
| 22 | + err = json.Unmarshal(bytes, &results) |
| 23 | + if err != nil { |
| 24 | + return nil, fmt.Errorf("error parsing lsblk json output: %v", err) |
| 25 | + } |
| 26 | + return results.BlockDevices, nil |
| 27 | +} |
| 28 | + |
| 29 | +// FindParentDevice finds the parent block device for a given device name or path |
| 30 | +func (l *LsblkUtil) FindParentDevice( |
| 31 | + ctx context.Context, deviceName string, devices []BlockDevice, parent *BlockDevice, |
| 32 | +) (*BlockDevice, error) { |
| 33 | + // Recursive function to find a parent device |
| 34 | + var findParentDevice func(devices []BlockDevice, parent *BlockDevice) *BlockDevice |
| 35 | + findParentDevice = func(devices []BlockDevice, parent *BlockDevice) *BlockDevice { |
| 36 | + for _, device := range devices { |
| 37 | + if device.Name == deviceName { |
| 38 | + return parent |
| 39 | + } |
| 40 | + if len(device.Children) > 0 { |
| 41 | + found := findParentDevice(device.Children, &device) |
| 42 | + if found != nil { |
| 43 | + return found |
| 44 | + } |
| 45 | + } |
| 46 | + } |
| 47 | + return nil |
| 48 | + } |
| 49 | + |
| 50 | + // Find the parent device |
| 51 | + parentDevice := findParentDevice(devices, nil) |
| 52 | + if parentDevice == nil { |
| 53 | + return nil, fmt.Errorf("parent device for '%s' not found", deviceName) |
| 54 | + } else { |
| 55 | + return parentDevice, nil |
| 56 | + } |
| 57 | +} |
| 58 | + |
| 59 | +// GetParentDmDeviceKname returns the kernel name (e.g. "dm-0") of the parent device |
| 60 | +// (e.g. "/dev/mapper/luks-<UUID>", aka "dm-1") for a given device name |
| 61 | +func (l *LsblkUtil) GetParentDeviceKname(ctx context.Context, deviceName string) (string, error) { |
| 62 | + // Get just the name if a path was passed in |
| 63 | + deviceName = filepath.Base(deviceName) |
| 64 | + devices, err := l.GetBlockDevices(ctx) |
| 65 | + if err != nil { |
| 66 | + return "", err |
| 67 | + } |
| 68 | + |
| 69 | + parentDevice, err := l.FindParentDevice(ctx, deviceName, devices, nil) |
| 70 | + if err != nil { |
| 71 | + return "", err |
| 72 | + } |
| 73 | + |
| 74 | + return parentDevice.KName, nil |
| 75 | +} |
0 commit comments