From 8c9aefd6c107405125dd772b0a5d6f7bde6e94eb Mon Sep 17 00:00:00 2001 From: Nikita Tokarchuk Date: Wed, 13 Apr 2022 23:44:09 +0200 Subject: [PATCH] Make nodesync structure instance --- go.mod | 5 +++++ go.sum | 2 ++ helpers.go | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ nodesync.go | 28 ++++++++++++++++++++++++++++ 4 files changed, 83 insertions(+) create mode 100644 go.mod create mode 100644 go.sum create mode 100644 helpers.go create mode 100644 nodesync.go diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..d62d54b --- /dev/null +++ b/go.mod @@ -0,0 +1,5 @@ +module code.tokarch.uk/mainnika/nodesync + +go 1.17 + +require github.com/go-zookeeper/zk v1.0.2 diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..5bcac56 --- /dev/null +++ b/go.sum @@ -0,0 +1,2 @@ +github.com/go-zookeeper/zk v1.0.2 h1:4mx0EYENAdX/B/rbunjlt5+4RTA/a9SMHBRuSKdGxPM= +github.com/go-zookeeper/zk v1.0.2/go.mod h1:nOB03cncLtlp4t+UAkGSV+9beXP/akpekBwL+UX1Qcw= diff --git a/helpers.go b/helpers.go new file mode 100644 index 0000000..43cb45b --- /dev/null +++ b/helpers.go @@ -0,0 +1,48 @@ +package sync + +import ( + "github.com/go-zookeeper/zk" + + "fmt" + "strings" +) + +// createRecursively creates zookeeper path recursively +func (s *NodeSync) createRecursively(path string, acl []zk.ACL) error { + + parts := strings.Split(path, "/") + + if len(parts) < 1 { + return fmt.Errorf("path does not contain valid path") + } + + for i := range parts { + Ensuring: + for { + child := fmt.Sprintf("%s", strings.Join(parts[:i+1], "/")) + + if len(child) == 0 { + break + } + + exists, _, err := s.Zk.Exists(child) + switch true { + case err == zk.ErrSessionExpired: + return err + case err != nil: + continue + case exists: + break Ensuring + default: + } + + if _, err = s.Zk.Create(child, nil, 0, acl); err != nil { + continue + } + + break + } + } + + return nil +} diff --git a/nodesync.go b/nodesync.go new file mode 100644 index 0000000..680ab67 --- /dev/null +++ b/nodesync.go @@ -0,0 +1,28 @@ +package sync + +import ( + "github.com/go-zookeeper/zk" +) + +// NodeSync structure +type NodeSync struct { + Zk *zk.Conn + + rootPath string +} + +// Inside private environment keep everything open +var defaultAcl = zk.WorldACL(zk.PermAll) + +// New creates a new nodesync instance +func New(zkconn *zk.Conn, rootPath string) (nodeSync *NodeSync, err error) { + + nodeSync = &NodeSync{Zk: zkconn, rootPath: rootPath} + + err = nodeSync.createRecursively(rootPath, defaultAcl) + if err != nil { + nodeSync = nil + } + + return +}