diff --git a/consul/state/state_store.go b/consul/state/state_store.go index f194df57c7..4e53983f4e 100644 --- a/consul/state/state_store.go +++ b/consul/state/state_store.go @@ -1084,3 +1084,32 @@ func (s *StateStore) GetSession(sessionID string) (*structs.Session, error) { } return nil, nil } + +// SessionList returns a slice containing all of the active sessions. +func (s *StateStore) SessionList() (uint64, []*structs.Session, error) { + tx := s.db.Txn(false) + defer tx.Abort() + + // Query all of the active sessions + sessions, err := tx.Get("sessions", "id") + if err != nil { + return 0, nil, fmt.Errorf("failed session lookup: %s", err) + } + + // Go over the sessions and create a slice of them + var result []*structs.Session + var lindex uint64 + for session := sessions.Next(); session != nil; session = sessions.Next() { + sess := session.(*structs.Session) + + // Compute the highest index + if sess.ModifyIndex > lindex { + lindex = sess.ModifyIndex + } + + // Add the session to the result + result = append(result, sess) + } + + return lindex, result, nil +} diff --git a/consul/state/state_store_test.go b/consul/state/state_store_test.go index d6b2c3edd5..37b03c25c3 100644 --- a/consul/state/state_store_test.go +++ b/consul/state/state_store_test.go @@ -1274,3 +1274,48 @@ func TestStateStore_SessionCreate(t *testing.T) { t.Fatalf("expected %#v, got: %#v", expectCheck, actual) } } + +func TestStateStore_ListSessions(t *testing.T) { + s := testStateStore(t) + + // Register some nodes + testRegisterNode(t, s, 1, "node1") + testRegisterNode(t, s, 2, "node2") + testRegisterNode(t, s, 3, "node3") + + // Create some sessions in the state store + sessions := []*structs.Session{ + &structs.Session{ + ID: "session1", + Node: "node1", + Behavior: structs.SessionKeysDelete, + }, + &structs.Session{ + ID: "session2", + Node: "node2", + Behavior: structs.SessionKeysRelease, + }, + &structs.Session{ + ID: "session3", + Node: "node3", + Behavior: structs.SessionKeysDelete, + }, + } + for i, session := range sessions { + if err := s.SessionCreate(uint64(4+i), session); err != nil { + t.Fatalf("err: %s", err) + } + } + + // List out all of the sessions + idx, sessionList, err := s.SessionList() + if err != nil { + t.Fatalf("err: %s", err) + } + if idx != 6 { + t.Fatalf("bad index: %d", idx) + } + if !reflect.DeepEqual(sessionList, sessions) { + t.Fatalf("bad: %#v", sessions) + } +}