From cee7fe1f070c8b61ce440dc2cb45c5da066775bc Mon Sep 17 00:00:00 2001
From: Patrick <dreamlike.sky@foxmail.com>
Date: Thu, 2 Jul 2020 09:51:07 +0800
Subject: [PATCH] add CreateTempWithValue in zookeeper client

---
 remoting/zookeeper/client.go                  | 38 +++++++++++++++++++
 .../curator_discovery/service_discovery.go    |  2 +-
 2 files changed, 39 insertions(+), 1 deletion(-)

diff --git a/remoting/zookeeper/client.go b/remoting/zookeeper/client.go
index 349faff2b..ea7142993 100644
--- a/remoting/zookeeper/client.go
+++ b/remoting/zookeeper/client.go
@@ -432,6 +432,44 @@ func (z *ZookeeperClient) CreateWithValue(basePath string, value []byte) error {
 	return nil
 }
 
+// CreateTempWithValue will create the node recursively, which means that if the parent node is absent,
+// it will create parent node first锛宎nd set value in last child path
+func (z *ZookeeperClient) CreateTempWithValue(basePath string, value []byte) error {
+	var (
+		err     error
+		tmpPath string
+	)
+
+	logger.Debugf("zookeeperClient.Create(basePath{%s})", basePath)
+	conn := z.getConn()
+	err = errNilZkClientConn
+	if conn == nil {
+		return perrors.WithMessagef(err, "zk.Create(path:%s)", basePath)
+	}
+
+	pathSlice := strings.Split(basePath, "/")[1:]
+	length := len(pathSlice)
+	for i, str := range pathSlice {
+		tmpPath = path.Join(tmpPath, "/", str)
+		// last child need be ephemeral
+		if i == length-1 {
+			_, err = conn.Create(tmpPath, value, zk.FlagEphemeral, zk.WorldACL(zk.PermAll))
+		} else {
+			_, err = conn.Create(tmpPath, []byte{}, 0, zk.WorldACL(zk.PermAll))
+		}
+		if err != nil {
+			if err == zk.ErrNodeExists {
+				logger.Debugf("zk.create(\"%s\") exists", tmpPath)
+			} else {
+				logger.Errorf("zk.create(\"%s\") error(%v)", tmpPath, perrors.WithStack(err))
+				return perrors.WithMessagef(err, "zk.Create(path:%s)", basePath)
+			}
+		}
+	}
+
+	return nil
+}
+
 // nolint
 func (z *ZookeeperClient) Delete(basePath string) error {
 	err := errNilZkClientConn
diff --git a/remoting/zookeeper/curator_discovery/service_discovery.go b/remoting/zookeeper/curator_discovery/service_discovery.go
index fc37d5c1d..6c7ec15e9 100644
--- a/remoting/zookeeper/curator_discovery/service_discovery.go
+++ b/remoting/zookeeper/curator_discovery/service_discovery.go
@@ -70,7 +70,7 @@ func (sd *ServiceDiscovery) registerService(instance *ServiceInstance) error {
 	if err != nil {
 		return err
 	}
-	err = sd.client.CreateWithValue(path, data)
+	err = sd.client.CreateTempWithValue(path, data)
 	if err != nil {
 		return err
 	}
-- 
GitLab