From 8b0ac7d9c5891c4a2671eda365738670038bf902 Mon Sep 17 00:00:00 2001 From: Mitchell Hashimoto Date: Wed, 28 Feb 2018 09:53:21 -0800 Subject: [PATCH] agent/consul/state: list intentions --- agent/consul/state/intention.go | 22 ++++++++++ agent/consul/state/intention_test.go | 63 ++++++++++++++++++++++++++++ 2 files changed, 85 insertions(+) diff --git a/agent/consul/state/intention.go b/agent/consul/state/intention.go index 040761e2c..844a1a509 100644 --- a/agent/consul/state/intention.go +++ b/agent/consul/state/intention.go @@ -67,6 +67,28 @@ func init() { 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. func (s *Store) IntentionSet(idx uint64, ixn *structs.Intention) error { tx := s.db.Txn(true) diff --git a/agent/consul/state/intention_test.go b/agent/consul/state/intention_test.go index 1c168c3bc..e4794bba7 100644 --- a/agent/consul/state/intention_test.go +++ b/agent/consul/state/intention_test.go @@ -120,3 +120,66 @@ func TestStore_IntentionSet_emptyId(t *testing.T) { 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) + } +}