From 200ae6f4b733f8a869aac36a730da90e79213387 Mon Sep 17 00:00:00 2001
From: jingrui <jingrui@huawei.com>
Date: Sun, 10 Feb 2019 18:40:59 +0800
Subject: [PATCH 14/27] event:  resend exit event when detect
 containerd restarted

reason: testCE_docker_containerd_ABN.026.sh
fix docker stop no effect.

Change-Id: I024b2f6a03d74fcbb5623c696212dcbfb624b285
Signed-off-by: jingrui <jingrui@huawei.com>
---
 cmd/containerd-shim/main_unix.go | 38 +++++++++++++++++++++++++++++++++++++-
 1 file changed, 37 insertions(+), 1 deletion(-)

diff --git a/cmd/containerd-shim/main_unix.go b/cmd/containerd-shim/main_unix.go
index 6c59cd1..d1f41b0 100644
--- a/cmd/containerd-shim/main_unix.go
+++ b/cmd/containerd-shim/main_unix.go
@@ -24,12 +24,14 @@ import (
 	"flag"
 	"fmt"
 	"io"
+	"io/ioutil"
 	"net"
 	"os"
 	"os/exec"
 	"os/signal"
 	"runtime"
 	"runtime/debug"
+	"strconv"
 	"strings"
 	"sync"
 	"syscall"
@@ -263,7 +265,7 @@ type remoteEventsPublisher struct {
 	address string
 }
 
-func (l *remoteEventsPublisher) Publish(ctx context.Context, topic string, event events.Event) error {
+func (l *remoteEventsPublisher) doPublish(ctx context.Context, topic string, event events.Event) error {
 	ns, _ := namespaces.Namespace(ctx)
 	encoded, err := typeurl.MarshalAny(event)
 	if err != nil {
@@ -288,3 +290,37 @@ func (l *remoteEventsPublisher) Publish(ctx context.Context, topic string, event
 	}
 	return nil
 }
+
+func getContainerdPid() int {
+	pidFile := "/var/run/docker/containerd/containerd.pid"
+	data, err := ioutil.ReadFile(pidFile)
+	if err != nil {
+		return -1
+	}
+	pid, err := strconv.Atoi(string(data))
+	if err != nil {
+		return -1
+	}
+	return pid
+}
+
+func (l *remoteEventsPublisher) Publish(ctx context.Context, topic string, event events.Event) error {
+	old := getContainerdPid()
+	for i := 1; i <= 10; i++ {
+		err := l.doPublish(ctx, topic, event)
+		logrus.Infof("try publish event(%d) %s %v %v", i, topic, event, err)
+		if err == nil {
+			new := getContainerdPid()
+			if old == new {
+				return nil
+			}
+			logrus.Warnf("containerd pid %d changed to %d", old, new)
+			old = new
+		}
+		if i == 10 {
+			return err
+		}
+		time.Sleep(time.Duration(i) * time.Second)
+	}
+	return nil
+}
-- 
2.7.4.3

