From 21afb41e02886df0b5251889cc443f28b7da274f Mon Sep 17 00:00:00 2001
From: jikai <jikai11@huawei.com>
Date: Thu, 11 Apr 2024 01:21:34 +0000
Subject: [PATCH 54/69] ensure sandbox can be removed if sandbox container
 removed

Signed-off-by: jikai <jikai11@huawei.com>
---
 .../sandbox/controller/shim/shim_controller.cc   | 16 ++++++++++++----
 src/daemon/sandbox/sandbox.cc                    |  3 ++-
 2 files changed, 14 insertions(+), 5 deletions(-)

diff --git a/src/daemon/sandbox/controller/shim/shim_controller.cc b/src/daemon/sandbox/controller/shim/shim_controller.cc
index 593fade9..4da637c7 100644
--- a/src/daemon/sandbox/controller/shim/shim_controller.cc
+++ b/src/daemon/sandbox/controller/shim/shim_controller.cc
@@ -517,12 +517,20 @@ bool ShimController::Shutdown(const std::string &sandboxId, Errors &error)
     container_delete_response *response {nullptr};
     int ret = m_cb->container.remove(request, &response);
     auto responseWrapper = makeUniquePtrCStructWrapper<container_delete_response>(response, free_container_delete_response);
+    if (ret == 0) {
+        return true;
+    }
 
-    if (ret != 0) {
-        std::string msg = (response != nullptr && response->errmsg != nullptr) ? response->errmsg : "internal";
-        ERROR("Failed to remove sandbox %s: %s", sandboxId.c_str(), msg.c_str());
-        error.SetError(msg);
+    std::string errMsg = "internal";
+    if (response != nullptr && response->errmsg != nullptr) {
+        if (strstr(response->errmsg, "No such container") != nullptr) {
+            ERROR("Container for sandbox %s not found", sandboxId.c_str());
+            return true;
+        }
+        errMsg = response->errmsg;
     }
+    ERROR("Failed to remove sandbox %s: %s", sandboxId.c_str(), errMsg.c_str());
+    error.SetError(errMsg);
     return error.Empty();
 }
 
diff --git a/src/daemon/sandbox/sandbox.cc b/src/daemon/sandbox/sandbox.cc
index c70116c1..bae5b8db 100644
--- a/src/daemon/sandbox/sandbox.cc
+++ b/src/daemon/sandbox/sandbox.cc
@@ -757,7 +757,8 @@ auto Sandbox::Remove(Errors &error) -> bool
 
     WriteGuard<RWMutex> lock(m_mutex);
 
-    if (!DoStop(DEFAULT_STOP_TIMEOUT, error)) {
+    // Only stop the sandbox when it is running
+    if (IsReady() && !DoStop(DEFAULT_STOP_TIMEOUT, error)) {
         ERROR("Failed to stop Sandbox before removing, id='%s'", m_id.c_str());
         return false;
     }
-- 
2.34.1

