From 7581283eb8e235ae0923e8c68677e059895a3c9b Mon Sep 17 00:00:00 2001
From: yangjiaqi <yangjiaqi16@huawei.com>
Date: Thu, 17 Aug 2023 20:12:49 +0800
Subject: [PATCH] clean up run/syscontainer-tools/netns/containerid dir residue

Signed-off-by: yangjiaqi <yangjiaqi16@huawei.com>
---
 hooks/syscontainer-hooks/prestart.go | 22 +++++++++++++++++++++-
 1 file changed, 21 insertions(+), 1 deletion(-)

diff --git a/hooks/syscontainer-hooks/prestart.go b/hooks/syscontainer-hooks/prestart.go
index a71d26b..8b5756e 100644
--- a/hooks/syscontainer-hooks/prestart.go
+++ b/hooks/syscontainer-hooks/prestart.go
@@ -23,11 +23,13 @@ import (
 	"strconv"
 	"strings"
 
+	"github.com/docker/docker/pkg/mount"
 	"github.com/opencontainers/runc/libcontainer/configs"
 	_ "github.com/opencontainers/runc/libcontainer/nsenter"
 	"github.com/opencontainers/runtime-spec/specs-go"
 	"github.com/sirupsen/logrus"
 	"golang.org/x/sys/unix"
+
 	hconfig "isula.org/syscontainer-tools/config"
 	"isula.org/syscontainer-tools/libdevice"
 	"isula.org/syscontainer-tools/libdevice/nsexec"
@@ -251,7 +253,25 @@ func UpdateNetwork(state *configs.HookState, hookConfig *hconfig.ContainerHookCo
 		logrus.Errorf("[device-hook] Failed to Create netns dir %v", err)
 		return err
 	}
-	file, err := os.Create(filepath.Join(hconfig.IsuladToolsDirNetns, state.ID))
+	/*
+		each container can only be in prestart, running or poststop at the same time,
+		so there is no lock protection for the file /run/syscontainer-tools/netns/containerid.
+	*/
+	netnsMountpoint := filepath.Join(hconfig.IsuladToolsDirNetns, state.ID)
+	// see if the current network namespace file is mounted
+	mounted, err := mount.Mounted(netnsMountpoint)
+	if err != nil {
+		logrus.Errorf("[device-hook] Failed to get mount info %v: %v", netnsMountpoint, err)
+	}
+	// has mounted
+	if mounted {
+		// maybe the previous poststop command was not executed or interrupted, resulting in residual
+		if removeErr := RemoveNetworkDevices(state, hookConfig, spec); removeErr != nil {
+			logrus.Errorf("[device-hook] Failed to remove network devices and umount netns file and %v is still mounted: %v",
+				netnsMountpoint, removeErr)
+		}
+	}
+	file, err := os.Create(netnsMountpoint)
 	if err != nil {
 		logrus.Errorf("[device-hook] Failed to Create netns file %v", err)
 		return err
-- 
2.30.0

