Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow reconnection to a session from a saved session id and passwd #63

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 28 additions & 5 deletions conn.go
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@ type Conn struct {
watchers map[watchPathType][]chan Event
watchersLock sync.Mutex
closeChan chan struct{} // channel to tell send loop stop
sessionLock sync.RWMutex

// Debug (used by unit tests)
reconnectLatch chan struct{}
Expand Down Expand Up @@ -310,6 +311,15 @@ func WithMaxConnBufferSize(maxBufferSize int) connOption {
}
}

// WithSessionIdAndPasswd sets the session id and password to be used
// for the first connection attempt
func WithSessionIdAndPasswd(sessionID int64, passwd []byte) connOption {
return func(c *Conn) {
c.sessionID = sessionID
c.passwd = passwd
}
}

// Close will submit a close request with ZK and signal the connection to stop
// sending and receiving packets.
func (c *Conn) Close() {
Expand All @@ -330,7 +340,16 @@ func (c *Conn) State() State {

// SessionID returns the current session id of the connection.
func (c *Conn) SessionID() int64 {
return atomic.LoadInt64(&c.sessionID)
c.sessionLock.RLock()
defer c.sessionLock.RUnlock()
return c.sessionID
}

// SessionPassword returns the current session password of the connection.
func (c *Conn) SessionPasswd() []byte {
c.sessionLock.RLock()
defer c.sessionLock.RUnlock()
return c.passwd
}

// SetLogger sets the logger to be used for printing errors.
Expand Down Expand Up @@ -637,7 +656,7 @@ func (c *Conn) authenticate() error {
LastZxidSeen: c.lastZxid,
TimeOut: c.sessionTimeoutMs,
SessionID: c.SessionID(),
Passwd: c.passwd,
Passwd: c.SessionPasswd(),
})
if err != nil {
return err
Expand Down Expand Up @@ -676,16 +695,20 @@ func (c *Conn) authenticate() error {
return err
}
if r.SessionID == 0 {
atomic.StoreInt64(&c.sessionID, int64(0))
c.sessionLock.Lock()
c.sessionID = 0
c.passwd = emptyPassword
c.sessionLock.Unlock()
c.lastZxid = 0
c.setState(StateExpired)
return ErrSessionExpired
}

atomic.StoreInt64(&c.sessionID, r.SessionID)
c.setTimeouts(r.TimeOut)
c.sessionLock.Lock()
c.sessionID = r.SessionID
c.passwd = r.Passwd
c.sessionLock.Unlock()
c.setTimeouts(r.TimeOut)
c.setState(StateHasSession)

return nil
Expand Down
26 changes: 13 additions & 13 deletions server_java_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -153,19 +153,19 @@ func (sc ServerConfig) Marshall(w io.Writer) error {

// this is a helper to wait for the zk connection to at least get to the HasSession state
func waitForSession(ctx context.Context, eventChan <-chan Event) error {
select {
case event, ok := <-eventChan:
// The eventChan is used solely to determine when the ZK conn has
// stopped.
if !ok {
return fmt.Errorf("connection closed before state reached")
for {
select {
case event, ok := <-eventChan:
// The eventChan is used solely to determine when the ZK conn has
// stopped.
if !ok {
return fmt.Errorf("connection closed before state reached")
}
if event.State == StateHasSession {
return nil
}
case <-ctx.Done():
return ctx.Err()
}
if event.State == StateHasSession {
return nil
}
case <-ctx.Done():
return ctx.Err()
}

return nil
}
54 changes: 54 additions & 0 deletions zk_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1112,6 +1112,60 @@ func TestMaxBufferSize(t *testing.T) {
}
}

func TestSessionReconnectionFromSavedID(t *testing.T) {
ts, err := StartTestCluster(t, 1, nil, logWriter{t: t, p: "[ZKERR] "})
if err != nil {
t.Fatal(err)
}
defer ts.Stop()

zk, eventChan, err := ts.ConnectAll()
if err != nil {
t.Fatal(err)
}
defer zk.Close()
// Prevent reconnection from this client
zk.reconnectLatch = make(chan struct{})

ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()
err = waitForSession(ctx, eventChan)
if err != nil {
t.Fatal(err)
}

sessionID := zk.SessionID()
passwd := zk.SessionPasswd()

// Simulate network error by brutally closing the network connection.
_ = zk.conn.Close()

// Re-establish the session from a different client with the session id and passwd
zk, eventChan, err = ts.ConnectWithOptions(15*time.Second, WithSessionIdAndPasswd(sessionID, passwd))
if err != nil {
t.Fatal(err)
}
defer zk.Close()

ctx, cancel = context.WithTimeout(context.Background(), time.Second*5)
defer cancel()
err = waitForSession(ctx, eventChan)
if err != nil {
t.Fatal(err)
}

sessionID2 := zk.SessionID()
passwd2 := zk.SessionPasswd()

if sessionID != sessionID2 {
t.Fatalf("session id mismatch: %d %d", sessionID, sessionID2)
}

if !reflect.DeepEqual(passwd, passwd2) {
t.Fatalf("session password mismatch: %v %v", passwd, passwd2)
}
}

func startSlowProxy(t *testing.T, up, down Rate, upstream string, adj func(ln *Listener)) (string, chan bool, error) {
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
Expand Down