From f8206c6e9083651a2450b321f0c1a3b1bd136b92 Mon Sep 17 00:00:00 2001 From: James Lu Date: Thu, 5 Sep 2024 22:27:19 +0800 Subject: [PATCH] fix(encrypt): close encrypted volume if it is opened In normal process of attaching a volume via CSI, the encrypted volume should be in closed or inactivated state before Longhorn attempts to open it. ref: longhorn/longhorn 9385 Signed-off-by: James Lu --- csi/crypto/crypto.go | 12 ++++++++++++ csi/node_server.go | 9 +++++++++ 2 files changed, 21 insertions(+) diff --git a/csi/crypto/crypto.go b/csi/crypto/crypto.go index d22c4ad922..9a0912247a 100644 --- a/csi/crypto/crypto.go +++ b/csi/crypto/crypto.go @@ -145,6 +145,18 @@ func ResizeEncryptoDevice(volume, passphrase string) error { return err } +// IsDeviceOpenAtNullPath determines if encrypted device is already open at unknown device path. The command 'cryptsetup status [device]' show "device: (null)" +func IsDeviceOpenAtNullPath(device string) (bool, error) { + devPath, mappedFile, err := DeviceEncryptionStatus(device) + if err != nil { + return false, err + } + if mappedFile != "" && strings.Contains(devPath, "null") { + return true, nil + } + return false, nil +} + // IsDeviceOpen determines if encrypted device is already open. func IsDeviceOpen(device string) (bool, error) { _, mappedFile, err := DeviceEncryptionStatus(device) diff --git a/csi/node_server.go b/csi/node_server.go index cd49366c3d..8bf18bf7f6 100644 --- a/csi/node_server.go +++ b/csi/node_server.go @@ -487,6 +487,15 @@ func (ns *NodeServer) NodeStageVolume(ctx context.Context, req *csi.NodeStageVol cryptoDevice := crypto.VolumeMapper(volumeID) log.Infof("Volume %s requires crypto device %s", volumeID, cryptoDevice) + if isOpenAtNullPath, err := crypto.IsDeviceOpenAtNullPath(cryptoDevice); err != nil { + return nil, status.Error(codes.Internal, err.Error()) + } else if isOpenAtNullPath { + log.Infof("Volume %s closing active crypto device %s", volumeID, cryptoDevice) + if err := crypto.CloseVolume(volumeID); err != nil { + return nil, status.Error(codes.Internal, err.Error()) + } + } + if err := crypto.OpenVolume(volumeID, devicePath, passphrase); err != nil { return nil, status.Error(codes.Internal, err.Error()) }