From 489f69209650aa743ffd6e53571b822ad0b63c2d Mon Sep 17 00:00:00 2001
From: xiadanni1 <xiadanni1@huawei.com>
Date: Sat, 18 Jan 2020 04:18:22 +0800
Subject: [PATCH] containerd:  add pid check to avoid poststop hook
 execute twice

reason:If start a container at docker 1.11.2, upgrade docker to 18.09,
downgrade to 1.11.2, stop/restart container, upgrade to 18.09 again,
poststop hook will execute again when containerd load task.
So we add pid check to avoid poststop hook execute twice.

Change-Id: I8b88b69bfa0a4141bd9595da8ad4e786666e114b
Signed-off-by: xiadanni1 <xiadanni1@huawei.com>
---
 legacy/legacy.go            | 21 +++++++++++++++++++++
 runtime/v1/linux/runtime.go | 10 ++++++----
 2 files changed, 27 insertions(+), 4 deletions(-)

diff --git a/legacy/legacy.go b/legacy/legacy.go
index 219508c..644f94a 100644
--- a/legacy/legacy.go
+++ b/legacy/legacy.go
@@ -44,6 +44,25 @@ func IsLegacy(id string) bool {
 	return false
 }
 
+func IsSamePid(id string) bool {
+	pid120, err := ioutil.ReadFile(filepath.Join(Config120, id, "init.pid"))
+	if err != nil {
+		logrus.Infof("read 1.2.0 init.pid file error: %v", err)
+		return false
+	}
+	pid028, err := ioutil.ReadFile(filepath.Join(State028, id, "init", "pid"))
+	if err != nil {
+		logrus.Infof("read 0.2.8 pid file error: %v", err)
+		return false
+	}
+	logrus.Infof("pid1.2.0: %v, pid0.2.8: %v", string(pid120), string(pid028))
+	if string(pid120) != string(pid028) {
+		return false
+	}
+
+	return true
+}
+
 // IsRunning is used to detect whether legacy container is running.
 func IsRunning(id string) bool {
 	path := State028 + id + "/init/pid"
@@ -111,6 +130,8 @@ func InitBundle(root string, id string) error {
 	logrus.Devour(err)
 	_, err = CopyFile(Config120+id+"/init.pid", State028+id+"/init/pid")
 	logrus.Devour(err)
+	_, err = CopyFile(Config120+id+"/starttime", State028+id+"/init/starttime")
+	logrus.Devour(err)
 	return nil
 }
 
diff --git a/runtime/v1/linux/runtime.go b/runtime/v1/linux/runtime.go
index 08e563d..96ad815 100644
--- a/runtime/v1/linux/runtime.go
+++ b/runtime/v1/linux/runtime.go
@@ -517,10 +517,12 @@ func (r *Runtime) terminate(ctx context.Context, bundle *bundle, ns, id string)
 		return err
 	}
 
-	if err := rt.Delete(ctx, id, &runc.DeleteOpts{
-		Force: true,
-	}); err != nil {
-		log.G(ctx).WithError(err).Warnf("delete runtime state %s", id)
+	if !legacy.IsLegacy(id) || legacy.IsSamePid(id) {
+		if err := rt.Delete(ctx, id, &runc.DeleteOpts{
+			Force: true,
+		}); err != nil {
+			log.G(ctx).WithError(err).Warnf("delete runtime state %s", id)
+		}
 	}
 
 	if !legacy.IsLegacy(id) {
-- 
1.8.3.1

