diff --git a/consul/state/schema.go b/consul/state/schema.go new file mode 100644 index 000000000..8aa920a4c --- /dev/null +++ b/consul/state/schema.go @@ -0,0 +1,54 @@ +package state + +import ( + "fmt" + + "github.com/hashicorp/go-memdb" +) + +// schemaFn is an interface function used to create and return +// new memdb schema structs for constructing an in-memory db. +type schemaFn func() *memdb.TableSchema + +// stateStoreSchema is used to return the combined schema for +// the state store. +func stateStoreSchema() *memdb.DBSchema { + // Create the root DB schema + db := &memdb.DBSchema{ + Tables: make(map[string]*memdb.TableSchema), + } + + // Collect the needed schemas + schemas := []schemaFn{ + indexTableSchema, + } + + // Add the tables to the root schema + for _, fn := range schemas { + schema := fn() + if _, ok := db.Tables[schema.Name]; ok { + panic(fmt.Sprintf("duplicate table name: %s", schema.Name)) + } + db.Tables[schema.Name] = schema + } + return db +} + +// indexTableSchema returns a new table schema used for +// tracking various indexes for the Raft log. +func indexTableSchema() *memdb.TableSchema { + return &memdb.TableSchema{ + Name: "index", + Indexes: map[string]*memdb.IndexSchema{ + "id": &memdb.IndexSchema{ + Name: "id", + AllowMissing: false, + Unique: true, + Indexer: &memdb.StringFieldIndex{ + Field: "Key", + Lowercase: true, + }, + }, + }, + } +} diff --git a/consul/state/state_store.go b/consul/state/state_store.go new file mode 100644 index 000000000..c242f672a --- /dev/null +++ b/consul/state/state_store.go @@ -0,0 +1,34 @@ +package state + +import ( + "fmt" + "io" + "log" + + "github.com/hashicorp/go-memdb" +) + +type StateStore struct { + logger *log.Logger + db *memdb.MemDB +} + +type IndexEntry struct { + Key string + Value uint64 +} + +func NewStateStore(logOutput io.Writer) (*StateStore, error) { + // Create the in-memory DB + db, err := memdb.NewMemDB(stateStoreSchema()) + if err != nil { + return nil, fmt.Errorf("Failed setting up state store: %s", err) + } + + // Create and return the state store + s := &StateStore{ + logger: log.New(logOutput, "", log.LstdFlags), + db: db, + } + return s, nil +}