From b0097d60789a6531e07f123e0f297fd4d9f817a6 Mon Sep 17 00:00:00 2001
From: holyfei <yangfeiyu2@huawei.com>
Date: Sun, 15 Nov 2020 22:00:43 +0800
Subject: [PATCH 3/3] kata-runtime: fix the block device not removed in
 devManager

reason: In the case of hotpluging the block device number exceed
the number of max capacity of sandbox, kata-runtime need to rollback
to remove the device info in the devManager, otherwise the created
device info will write into persist.json file, which leads to problem.

Conflict: NA
Reference:https://gitee.com/src-openeuler/kata-containers
Signed-off-by: holyfei <yangfeiyu2@huawei.com>
---
 virtcontainers/container.go | 11 ++++++++++-
 1 file changed, 10 insertions(+), 1 deletion(-)

diff --git a/virtcontainers/container.go b/virtcontainers/container.go
index 1b703825..29a7fb52 100644
--- a/virtcontainers/container.go
+++ b/virtcontainers/container.go
@@ -1462,6 +1462,7 @@ func (c *Container) plugDevice(devicePath string) error {
 	}
 
 	if c.checkBlockDeviceSupport() && stat.Mode&unix.S_IFBLK == unix.S_IFBLK {
+		var err error
 		b, err := c.sandbox.devManager.NewDevice(config.DeviceInfo{
 			HostPath:      devicePath,
 			ContainerPath: filepath.Join(kataGuestSharedDir(), c.id),
@@ -1473,10 +1474,18 @@ func (c *Container) plugDevice(devicePath string) error {
 			return fmt.Errorf("device manager failed to create rootfs device for %q: %v", devicePath, err)
 		}
 
+		defer func() {
+			if err != nil {
+				if newErr := c.sandbox.devManager.RemoveDevice(b.DeviceID()); newErr != nil {
+					c.Logger().WithError(newErr).Error("fail rollback to remove block device")
+				}
+			}
+		}()
+
 		c.state.BlockDeviceID = b.DeviceID()
 
 		// attach rootfs device
-		if err := c.sandbox.devManager.AttachDevice(b.DeviceID(), c.sandbox); err != nil {
+		if err = c.sandbox.devManager.AttachDevice(b.DeviceID(), c.sandbox); err != nil {
 			return err
 		}
 	}
-- 
2.23.0

