From c785f8f744050155102664d56de5bfb55e91915d Mon Sep 17 00:00:00 2001
From: Evan Foster <efoster@adobe.com>
Date: Mon, 13 Jul 2020 12:53:40 -0600
Subject: [PATCH 18/50] sandbox: Stop and clean up containers that fail to
 create

A container that is created and added to a sandbox can still fail
the final creation steps. In this case, the container must be stopped
and have its resources cleaned up to prevent leaking sandbox mounts.

Fixes #2816

cherry-pick from: https://github.com/kata-containers/runtime/pull/2826

Signed-off-by: Evan Foster <efoster@adobe.com>
Signed-off-by: jiangpengfei <jiangpengfei9@huawei.com>
---
 virtcontainers/sandbox.go | 11 +++++++++++
 1 file changed, 11 insertions(+)

diff --git a/virtcontainers/sandbox.go b/virtcontainers/sandbox.go
index a8522b96..3dbf640e 100644
--- a/virtcontainers/sandbox.go
+++ b/virtcontainers/sandbox.go
@@ -1,4 +1,5 @@
 // Copyright (c) 2016 Intel Corporation
+// Copyright (c) 2020 Adobe Inc.
 //
 // SPDX-License-Identifier: Apache-2.0
 //
@@ -1172,6 +1173,16 @@ func (s *Sandbox) CreateContainer(contConfig ContainerConfig) (VCContainer, erro
 	defer func() {
 		// Rollback if error happens.
 		if err != nil {
+			logger := s.Logger().WithFields(logrus.Fields{"container-id": c.id, "sandox-id": s.id, "rollback": true})
+
+			logger.Warning("Cleaning up partially created container")
+
+			if err2 := c.stop(true); err2 != nil {
+				logger.WithError(err2).Warning("Could not delete container")
+			}
+
+			logger.Debug("Removing stopped container from sandbox store")
+
 			s.removeContainer(c.id)
 		}
 	}()
-- 
2.14.3 (Apple Git-98)

