From faffb26c307556e1d84399060d7aef1753e9f41a Mon Sep 17 00:00:00 2001
From: jiangpengfei <jiangpengfei9@huawei.com>
Date: Mon, 21 Sep 2020 21:52:48 -0400
Subject: [PATCH] runtime: fix sandboxRuntimeRootPath left problem

reason: If pod_sandbox type container deleted before pod_container
type containers in the sandbox, which leads to kata-runtime delete
pod_container process create a new sandboxRuntimeRootPath in the
/run/vc/sbs/<sandbox-id> dir.

So, we fix this problem by check sandboxRuntimeRootPath is exist
before fetchSandbox function is called.

Signed-off-by: jiangpengfei <jiangpengfei9@huawei.com>
---
 cli/delete.go             |  2 +-
 virtcontainers/sandbox.go | 18 ++++++++++++++++++
 2 files changed, 19 insertions(+), 1 deletion(-)

diff --git a/cli/delete.go b/cli/delete.go
index 871ac40d..09552b9a 100644
--- a/cli/delete.go
+++ b/cli/delete.go
@@ -87,7 +87,7 @@ func delete(ctx context.Context, containerID string, force bool) error {
 		// container is deleted before pod_container type container, just return nil
 		// and let containerd delete container operations continue
 		if strings.Contains(err.Error(), "no such file or directory") {
-			kataLog.Warnf("pod_sandbox deleted before pod_container: %v", err)
+			kataLog.Warnf("pod_sandbox container deleted before pod_container in the sandbox: %v", err)
 			return nil
 		}
 
diff --git a/virtcontainers/sandbox.go b/virtcontainers/sandbox.go
index de8652fc..9f5d3c08 100644
--- a/virtcontainers/sandbox.go
+++ b/virtcontainers/sandbox.go
@@ -729,6 +729,13 @@ func fetchSandbox(ctx context.Context, sandboxID string) (sandbox *Sandbox, err
 
 	var config SandboxConfig
 
+	// check sandbox runtime root path(for example: /run/vc/sbs/<sandbox-id>)
+	// exist or not before fetch sandbox config file
+	if !checkSandboxRuntimeRootPathExist(sandboxID) {
+		sandboxRuntimeRootPath := store.SandboxRuntimeRootPath(sandboxID)
+		return nil, fmt.Errorf("sandbox %s does not exist, %s no such file or directory", sandboxID,sandboxRuntimeRootPath)
+	}
+
 	// Try to load sandbox config from old store at first.
 	c, ctx, err := loadSandboxConfigFromOldStore(ctx, sandboxID)
 	if err != nil {
@@ -2707,3 +2714,14 @@ func updateStaticSandboxResources(sandboxConfig *SandboxConfig) error {
 
 	return nil
 }
+
+// checkSandboxRuntimeRootPathExist check /run/vc/sbs/<sandbox-id>/ dir exist or not
+func checkSandboxRuntimeRootPathExist(sandboxID string) bool {
+	sandboxRuntimeRootPath := store.SandboxRuntimeRootPath(sandboxID)
+	_, err := os.Stat(sandboxRuntimeRootPath)
+	if os.IsNotExist(err) {
+		return false
+	}
+
+	return true
+}
\ No newline at end of file
-- 
2.11.0

