agent/consul/state: list intentions

This commit is contained in:
Mitchell Hashimoto 2018-02-28 09:53:21 -08:00
parent cc8a6f7f15
commit 9639bfb1be
No known key found for this signature in database
GPG Key ID: 744E147AA52F5B0A
2 changed files with 85 additions and 0 deletions

View File

@ -67,6 +67,28 @@ func init() {
registerSchema(intentionsTableSchema) registerSchema(intentionsTableSchema)
} }
// Intentions returns the list of all intentions.
func (s *Store) Intentions(ws memdb.WatchSet) (uint64, structs.Intentions, error) {
tx := s.db.Txn(false)
defer tx.Abort()
// Get the index
idx := maxIndexTxn(tx, intentionsTableName)
// Get all intentions
iter, err := tx.Get(intentionsTableName, "id")
if err != nil {
return 0, nil, fmt.Errorf("failed intention lookup: %s", err)
}
ws.Add(iter.WatchCh())
var results structs.Intentions
for ixn := iter.Next(); ixn != nil; ixn = iter.Next() {
results = append(results, ixn.(*structs.Intention))
}
return idx, results, nil
}
// IntentionSet creates or updates an intention. // IntentionSet creates or updates an intention.
func (s *Store) IntentionSet(idx uint64, ixn *structs.Intention) error { func (s *Store) IntentionSet(idx uint64, ixn *structs.Intention) error {
tx := s.db.Txn(true) tx := s.db.Txn(true)

View File

@ -120,3 +120,66 @@ func TestStore_IntentionSet_emptyId(t *testing.T) {
t.Fatalf("bad") t.Fatalf("bad")
} }
} }
func TestStore_IntentionsList(t *testing.T) {
s := testStateStore(t)
// Querying with no results returns nil.
ws := memdb.NewWatchSet()
idx, res, err := s.Intentions(ws)
if idx != 0 || res != nil || err != nil {
t.Fatalf("expected (0, nil, nil), got: (%d, %#v, %#v)", idx, res, err)
}
// Create some intentions
ixns := structs.Intentions{
&structs.Intention{
ID: testUUID(),
},
&structs.Intention{
ID: testUUID(),
},
}
// Force deterministic sort order
ixns[0].ID = "a" + ixns[0].ID[1:]
ixns[1].ID = "b" + ixns[1].ID[1:]
// Create
for i, ixn := range ixns {
if err := s.IntentionSet(uint64(1+i), ixn); err != nil {
t.Fatalf("err: %s", err)
}
}
if !watchFired(ws) {
t.Fatalf("bad")
}
// Read it back and verify.
expected := structs.Intentions{
&structs.Intention{
ID: ixns[0].ID,
RaftIndex: structs.RaftIndex{
CreateIndex: 1,
ModifyIndex: 1,
},
},
&structs.Intention{
ID: ixns[1].ID,
RaftIndex: structs.RaftIndex{
CreateIndex: 2,
ModifyIndex: 2,
},
},
}
idx, actual, err := s.Intentions(nil)
if err != nil {
t.Fatalf("err: %s", err)
}
if idx != 2 {
t.Fatalf("bad index: %d", idx)
}
if !reflect.DeepEqual(actual, expected) {
t.Fatalf("bad: %v", actual)
}
}