featurebase/dax/queryer/compute_api.go
Travis Turner a44b622aa0 Introduce ServiceManager and Refactor DAX Integration tests (#2320)
* Introduce ServiceManager and Refactor DAX Integration tests

The ServiceManager provides an interface with which to manage
featurebase (dax) services (mds, queryer, computer). It replaces the
confusing interface implementations in /dax/server/server.go (which
optionally used pointers to in-process objects to satisfy an interface)
with (for now) http implementations. The thought is that even if we're
running all services in-process, we should communicate between services
over http in order to mirror what we would do in a production
environment where the services are running on different nodes.

This batch of commits does quit a lot, most of which is captured here:

- Added `path` support to `dax.Address`. Address is now a string of the form [scheme]://[host]:[port]/[path].
- Added `Holder.directiveApplied` to determine (in tests) if the computer has completed applying the latest directive. This is somewhat temporary until we improve the mds-to-computer logic.
- Removed the "service prefix" code which was prepending client URL paths with the prefix. Instead, the serviceType (mds, queryer, computer[n] is now part of `dax.Address`).
- Removed, from the dax config, the top level `StorageMethod` and `StorageDSN` and now just have `MDS.Config.DataDir`.
- Added `Computer.Config.N` to specify the number of computers to run in-process.
- Moved the `pilosa.MDS` interface to `computer.Registrar`. This is an example of getting the interfaces defined in the right packages.
- Added `SnapshotTable()` method to the mds client (to align with its API).
- Changed `Balancer.AddJob()` to `Balancer.AddJobs()` to support, for example, adding 256 partitions in a single call. Refactored some of the naive Balancer to account for this.
- Added a `Seed` to the top-level config. It's not really useful because of package `crypto/rand`.
- Added an in-memory implementation of the DisCo interface and disabled etcd in a computer service.
- Create sepearte data-dirs for each in-process computer.
- Disabled grpc in dax.
- Modified the sql3 test definition format to support multiple insert steps and separate query results (to align with those steps).

* Changes necessary to get multiple computer instance running in-process

For now the config looks like this:

```
[computer]
run = true
n = 4
```

but we can probably just change that to be something like:

```
[computer]
run = 4
```

*Issues found running multiple "computers" in-process*
- grpc was trying to bind on the same port
  - changed GRPCListener from `*net.TCPListener` to `net.Listener`
  - created a nopListener and set to that for now (i.e. disabled grpc)
- etcd was starting more than once
  - changed dax to use in-memory implementations of the disco interfaces (i.e. stop using etcd)
- IDAllocator (which uses boltdb) was trying to open the `idalloc.db` file more than once
  - realized we have to set separate data-dirs for each holder. that fixed it.

* Port dax integration tests to ManagedCommand

* Modify Balancer-related methods like AddJob to AddJobs

There were (and still are) a lot of places where we were adding on job
at a time, even when we had a long list of jobs to add. This resulted in
every job add (for example adding 1 of 256 shards) taking ~40ms, or over
10s to create a keyed table. One reason was because each job add was
making multiple boltdb transactions.

* Port over more dax integration test stuff

* Add DirectiveApplied to signify that snapshot/writes have loaded.

We use this in tests to avoid using sleeps.
This should be considered temporary; we're going to need a more robust
solution for determining when a computer node is ready to serve complete
data.

* Finish porting dax integration tests

* Improve godocs

* Remove docker-based DAX integration tests.

* go mod tidy

* Move test/managed.go to avoid package conflicts

* Modify IDK integration tests to work with ServiceManager changes

This is really just computer -> computer0
And the MDS DataDir config change.

* cleanup found during review

* echo $CI_COMMIT_REF_SLUG in CI

* remove docker image arg, use build instead

(cherry picked from commit 2843f218bc)
2022-12-12 09:01:20 -08:00

318 lines
9.3 KiB
Go

package queryer
import (
"context"
"time"
featurebase "github.com/molecula/featurebase/v3"
"github.com/molecula/featurebase/v3/dax"
"github.com/molecula/featurebase/v3/dax/mds/controller/partitioner"
"github.com/molecula/featurebase/v3/errors"
)
// Ensure type implements interface.
var _ featurebase.ComputeAPI = &qualifiedComputeAPI{}
type qualifiedComputeAPI struct {
mds MDS
qual dax.TableQualifier
}
func NewQualifiedComputeAPI(qual dax.TableQualifier, mds MDS) *qualifiedComputeAPI {
return &qualifiedComputeAPI{
mds: mds,
qual: qual,
}
}
// importer is used to get the Importer based on the provided address. We used
// to maintain a map of different importers (pointers to computers) running
// in-process, but since getting rid of that logic this method is currently just
// a wrapper around NewComputeImporter. I'm leaving it like this for now in case
// it makes sense for this to become a cache of computer clients.
func (c *qualifiedComputeAPI) importer(addr dax.Address) (Importer, error) {
return NewComputeImporter(addr), nil
}
func (c *qualifiedComputeAPI) Import(ctx context.Context, qcx *featurebase.Qcx, req *featurebase.ImportRequest, opts ...featurebase.ImportOption) error {
// If the request is empty, return early.
if len(req.ColumnKeys) == 0 && len(req.ColumnIDs) == 0 {
return nil
}
// Determine if the columns use string keys or not.
var hasColKeys bool
if len(req.ColumnKeys) > 0 {
hasColKeys = true
if len(req.ColumnIDs) > 0 {
return errors.Errorf("import request has both column ids and keys")
}
}
// Determine if the rows use string keys or not.
var hasRowKeys bool
if len(req.RowKeys) > 0 {
hasRowKeys = true
if len(req.RowIDs) > 0 {
return errors.Errorf("import request has both row ids and keys")
}
}
partitioner := partitioner.NewPartitioner()
reqPerShard := make(map[uint64]*featurebase.ImportRequest)
tkey, err := c.indexToQualifiedTableKey(ctx, req.Index)
if err != nil {
return errors.Wrap(err, "converting index to qualified table key")
}
stkey := string(tkey)
qtid := tkey.QualifiedTableID()
qtbl, err := c.mds.Table(ctx, qtid)
if err != nil {
return errors.Wrapf(err, "getting table for import: %s", req.Index)
}
// Translate column keys.
if hasColKeys {
// Get the partitions (and therefore, nodes) responsible for the keys.
pMap := partitioner.PartitionsForKeys(qtbl.Key(), qtbl.PartitionN, req.ColumnKeys...)
colIDs := make([]uint64, 0, len(req.ColumnKeys))
for pNum := range pMap {
addr, err := c.mds.IngestPartition(ctx, qtid, pNum)
if err != nil {
return errors.Wrapf(err, "getting ingest partition: %d", pNum)
}
importer, err := c.importer(addr)
if err != nil {
return errors.Wrapf(err, "getting importer for address: %s", addr)
}
colKeyMap, err := importer.CreateIndexKeys(ctx, stkey, req.ColumnKeys...)
if err != nil {
return errors.Wrap(err, "creating index keys")
}
for i := range req.ColumnKeys {
colIDs = append(colIDs, colKeyMap[req.ColumnKeys[i]])
}
}
req.ColumnIDs = colIDs
}
// Translate row keys.
if hasRowKeys {
addr, err := c.mds.IngestPartition(ctx, qtid, 0)
if err != nil {
return errors.Wrapf(err, "getting ingest partition: %d", 0)
}
importer, err := c.importer(addr)
if err != nil {
return errors.Wrapf(err, "getting importer for address: %s", addr)
}
rowKeyMap, err := importer.CreateFieldKeys(ctx, stkey, req.Field, req.RowKeys...)
if err != nil {
return errors.Wrap(err, "creating field keys")
}
rowIDs := make([]uint64, len(req.RowKeys))
for i := range req.RowKeys {
rowIDs[i] = rowKeyMap[req.RowKeys[i]]
}
req.RowIDs = rowIDs
}
// Loop over the column ids and split them up by shard.
for ii := range req.ColumnIDs {
// Determine shard.
shard := req.ColumnIDs[ii] / featurebase.ShardWidth
// Get or create the ImportRequest for this shard.
shardedReq, found := reqPerShard[shard]
if !found {
shardedReq = &featurebase.ImportRequest{
Index: stkey,
IndexCreatedAt: req.IndexCreatedAt,
Field: req.Field,
FieldCreatedAt: req.FieldCreatedAt,
Shard: shard,
RowIDs: []uint64{},
ColumnIDs: []uint64{},
RowKeys: []string{},
ColumnKeys: []string{},
Timestamps: []int64{},
Clear: req.Clear,
}
reqPerShard[shard] = shardedReq
}
shardedReq.ColumnIDs = append(shardedReq.ColumnIDs, req.ColumnIDs[ii])
if len(req.RowIDs) > 0 {
shardedReq.RowIDs = append(shardedReq.RowIDs, req.RowIDs[ii])
}
if len(req.Timestamps) > 0 {
shardedReq.Timestamps = append(shardedReq.Timestamps, req.Timestamps[ii])
}
}
// Send each of the sharded ImportRequests to the appropriate compute node.
for shard, req := range reqPerShard {
addr, err := c.mds.IngestShard(ctx, qtid, dax.ShardNum(shard))
if err != nil {
return errors.Wrapf(err, "getting ingest shard: %d", shard)
}
importer, err := c.importer(addr)
if err != nil {
return errors.Wrapf(err, "getting importer for address: %s", addr)
}
importer.Import(ctx, req,
featurebase.OptImportOptionsClear(req.Clear),
featurebase.OptImportOptionsIgnoreKeyCheck(true),
)
}
return nil
}
func (c *qualifiedComputeAPI) ImportValue(ctx context.Context, qcx *featurebase.Qcx, req *featurebase.ImportValueRequest, opts ...featurebase.ImportOption) error {
// If the request is empty, return early.
if len(req.ColumnKeys) == 0 && len(req.ColumnIDs) == 0 {
return nil
}
// Determine if the columns use string keys or not.
var hasColKeys bool
if len(req.ColumnKeys) > 0 {
hasColKeys = true
if len(req.ColumnIDs) > 0 {
return errors.Errorf("import value request has both column ids and keys")
}
}
partitioner := partitioner.NewPartitioner()
reqPerShard := make(map[uint64]*featurebase.ImportValueRequest)
tkey, err := c.indexToQualifiedTableKey(ctx, req.Index)
if err != nil {
return errors.Wrap(err, "converting index to qualified table key")
}
stkey := string(tkey)
qtid := tkey.QualifiedTableID()
qtbl, err := c.mds.Table(ctx, qtid)
if err != nil {
return errors.Wrapf(err, "getting table for importvalue: %s", req.Index)
}
// Translate column keys.
if hasColKeys {
// Get the partitions (and therefore, nodes) responsible for the keys.
pMap := partitioner.PartitionsForKeys(qtbl.Key(), qtbl.PartitionN, req.ColumnKeys...)
colIDs := make([]uint64, 0, len(req.ColumnKeys))
for pNum := range pMap {
addr, err := c.mds.IngestPartition(ctx, qtid, pNum)
if err != nil {
return errors.Wrapf(err, "getting ingest partition: %d", pNum)
}
importer, err := c.importer(addr)
if err != nil {
return errors.Wrapf(err, "getting importer for address: %s", addr)
}
colKeyMap, err := importer.CreateIndexKeys(ctx, stkey, req.ColumnKeys...)
if err != nil {
return errors.Wrap(err, "creating index keys")
}
for i := range req.ColumnKeys {
colIDs = append(colIDs, colKeyMap[req.ColumnKeys[i]])
}
}
req.ColumnIDs = colIDs
}
// Loop over the column ids and split them up by shard.
for ii := range req.ColumnIDs {
// Determine shard.
shard := req.ColumnIDs[ii] / featurebase.ShardWidth
// Get or create the ImportRequest for this shard.
shardedReq, found := reqPerShard[shard]
if !found {
shardedReq = &featurebase.ImportValueRequest{
Index: stkey,
IndexCreatedAt: req.IndexCreatedAt,
Field: req.Field,
FieldCreatedAt: req.FieldCreatedAt,
Shard: shard,
ColumnIDs: []uint64{},
ColumnKeys: []string{},
Values: []int64{},
FloatValues: []float64{},
TimestampValues: []time.Time{},
StringValues: []string{},
Clear: req.Clear,
}
reqPerShard[shard] = shardedReq
}
shardedReq.ColumnIDs = append(shardedReq.ColumnIDs, req.ColumnIDs[ii])
if len(req.Values) > 0 {
shardedReq.Values = append(shardedReq.Values, req.Values[ii])
}
// TODO: The following would populate the other value types, but the
// EncodeImportValues doesn't seem to use this data. So we need to track
// down how this is being used.
//
// if len(req.FloatValues) > 0 {
// shardedReq.FloatValues = append(shardedReq.FloatValues, req.FloatValues[ii])
// }
// if len(req.TimestampValues) > 0 {
// shardedReq.TimestampValues = append(shardedReq.TimestampValues, req.TimestampValues[ii])
// }
// if len(req.StringValues) > 0 {
// shardedReq.StringValues = append(shardedReq.StringValues, req.StringValues[ii])
// }
}
// Send each of the sharded ImportValueRequests to the appropriate compute
// node.
for shard, req := range reqPerShard {
addr, err := c.mds.IngestShard(ctx, qtid, dax.ShardNum(shard))
if err != nil {
return errors.Wrapf(err, "getting ingest shard: %d", shard)
}
importer, err := c.importer(addr)
if err != nil {
return errors.Wrapf(err, "getting importer for address: %s", addr)
}
importer.ImportValue(ctx, req,
featurebase.OptImportOptionsClear(req.Clear),
featurebase.OptImportOptionsIgnoreKeyCheck(true),
)
}
return nil
}
func (c *qualifiedComputeAPI) Txf() *featurebase.TxFactory {
return &featurebase.TxFactory{}
}
func (c *qualifiedComputeAPI) indexToQualifiedTableKey(ctx context.Context, index string) (dax.TableKey, error) {
qtid, err := c.mds.TableID(ctx, c.qual, dax.TableName(index))
if err != nil {
return "", errors.Wrap(err, "converting index to qualified table id")
}
return qtid.Key(), nil
}