mirror of
https://github.com/featurebasedb/featurebase.git
synced 2026-10-12 22:07:59 +00:00
In this commit, the Directive is mocked; it doesn't actually reach out to a controller. Limits key translation to only those partitions (per index) specified in the Directive. Attempting to create or find a key (or ID) for a partition which is not handled by this node will result in an error; translation requests are no longer forwarded to other nodes. Limits import into only those shards specified, per index, by the Directive. Attempting to import into a shard which is not handled by this node will result in an error. Stub out /directive endpoint The `applyDirective()` method still needs to be implemented. Update mds references to use the new /mds/types structure In mds, we moved the shared types to mds/types. FeatureBase needs to reference those instead. This also bumps the mds version in go.mod. Implement the Add/Remove Index part of Holder.ApplyDirective() This adds functionality to `Holder.ApplyDirective()` which adds or removes indexes (tables) based on those provided in the Directive. Still to be implemented here: shards and partitions. WIP: remove client from Batch Move Batch into its own package: batch Also, in order to avoid import loops, this introduces packages: /batch/types /client/types Reorganize the Importer-related code Moved the Importer interface to package: batch Move the "pilosa client" implementation of the Importer interface to package: client Modify batch.NewBatch to take an Importer (not client) This commit modifies the batch.NewBatch() function to use a functinal option on Batch to inject an Importer into the Batch. Prior to this, NewBatch() took a pointer to a client, which was a little too restrictive. Now, MDS can implement an Importer which uses information from MDS to determine to which node(s) the import calls should be directed. Add client.SetAuthToken() method to satisfy SchemaManager interface Update ApplyDirective logic to include fields. This needs more work, but it was enough to get a basic test passing. Move Transaction type into /types package. Add interface check on batch.Importer no-op implementation Updated ApplyDirective to create all currently support Field types There are still the following TODOs: - [ ] impolement field options (ex: decimal scale, int min/max, etc). - [ ] `time` fields Added support for Decimal.Scale in ApplyDirective Update mds dependency Add /health endpoint Update to use dax (dax/mds) instead of mds. After moving the mds repository into the dax repository as a sub-package, this commit changes everything in FeatureBase to use the dax repo instead of the now abandoned mds repo. Introduce and implment the WriteLogger interfaces. This adds both a `WriteLogReader` and `WriteLogWriter` interface. They are both implemented by the implementation: `fileWriteLogger`. The `fileWriteLogger` uses the dax/writelogger API to append log messages to files on disk. Add WriteLogWriter.ImportRoaring method to interface This commit adds the `ImportRoaring` method to the `WriteLogWriter` interface. Still to implement are the `Import` and `ImportValue` methods. Reorganize the ApplyDirective code The primary goal was to cache the incoming Directive on the Holder prior to applying all of the changes in the directive (i.e. loading data from the WriteLogger) because applying those changes often validated against the accepted state of the node. Implement all of the WriteLogger read/write methods Implement the HTTP WriteLogger implementation WIP: Introduce shard.Version. Implement snapshotter. Add HTTP Snapshotter implementation This also recofigures server to use the HTTPSnapshotter instead of the FileSnapshotter. Implement snapshotter: TableKeys Implement snapshotter: FieldKeys Dependency dance last of the dependency dance Add support for prototype This adds the Makefile targets to build the docker container and push it to ECR. SQL3 changes which break with dax changes Missed TODO: implement FieldVersion version to WriteLogger Address bug causing missing TranslateStores to error Originally, we tried to limit the TranslateStores which get allocated to only those for which the node is responsible. This works when adding a new table. But if a table already exists, there's no logic to start missing TranslateStores. This reverts back to the old FeatureBase logic which brutishly allocates a TranslateStore for every partition, even if one is not needed. We need to address this by allowing the ApplyDirective logic to initialize TranslateStores when they don't yet exist. Move the ImportRoaringShardRequest type to the types package Since the ImportRoaringShardRequest object is part of the Importer interface, we need to move it to a non-root (i.e. pilosa) package. All the other interface types are either concrete types or part of a sub-package (such as roaring). We do this to prevent an implementer of the interface from having to import the entire pilosa package and risk circular imports. buncha changes to support latest dax stuff Move dax related types to /dax sub-package This commit moves all the common "dax" types into the /dax sub-package. The idea is to ensure that featurebase does not import dax at all. It's ok if dax imports featurebase. In the future, we might need to split the dax sub-package (common data types used by muliple molecula data-plan services) into it's own repo. Add type: dax.Schema This isn't currently being used; I started to use is as a replacement for pilosa_client.Schema, but then deferred that. But we'll need to do it eventually, so it doesn't hurt to have this type in place. Export RowIDs.Merge() method for use in orchestrator. Add CreateSQL method to dax.Table type The CreateSQL() method will return the "CREATE TABLE" statement required to create the dax.Table. Comment out confusing writelogger log message. We need to revisit this, but for now, this log message is confusing. Also, rename daxSharder to versionStore. Remove hard-coded AWS account Implement more FieldOptions such as Epoch Some of the FieldOption logic was stubbed out in the dax package. This commit fills that out more; specifically, it adds the dax.Field.Options.Epoch parameter. export stuff needed for TopK in orchestrator export ValCount stuff to implement Percentile in orchestrator export more stuff to support less code in orchestrator, shared objs Port dax repo over to featurebase/dax (run all as sub-services) This commit does ALOT. Sorry. It introduces a `featurebase dax` sub-command which can be configured to run the various dax services as sub-services within the same process, or individually as the lone service in process. It also changes all the URL paths to be prefixed with the service name. So for example, instead of calling localhost:8080/status, you would now call localhost:8080/featurebase/status. Also, note that all services provide a /health endpoint to confirm they are running in process. Clean up integration tests. Remove PILOSA_ config prefix. Remove duplicate clients (mistake from porting dax to featurebase) Rename sub-service "featurebase" to "computer" In the places where we have hard-coded the sub-service name into a URI path, I've tried to tag the line with a comment containing: `// #SERVICEPATHPREFIX` Update copilot manifest files to reference "computer" Port dax/README.md from dax repository Separate (toml) Queryer Config from Injections We needed to separate the toml config from the configuration required to inject sub-services into the Queryer. I'm not sure this is the best solution, but it's *a* solution. So here we are. Clean up (i.e. remove) the queryer "implementations" package Remove old test file Run WriteLogger and Snapshotter as local sub-services. Prior to this commit, the writelogger and snapshotter services only worked when run as separate services. This allows them to be run in the same process as all the other dax services. There is still some naming issues that we should address, but it's functional for now. Clean up (i.e. organize) the intra-service interfaces. Implement alpha Director for local messages from MDS to Computer Prior to this commit, messages from MDS to the computer service were still going over http. This commit introduces an interface implementation which registers the local computer command, and use that command's API to directly reference methods used by the Director. Clean up a few more interface names Add Queryer OpenAPI document. Update copilot manifests to reflect latest changes Add OpenAPI documents for WriteLogger and Snapshotter Add OpenAPI document for MDS service Add OpenAPI document for Computer service Consolidate errors to use fb/errors package. This commit is a first pass at trying to ensure that all of the DAX code uses: "github.com/molecula/featurebase/v3/errors" This package is a wrapper for "github.com/pkg/errors", so going forward we want to avoid importing that package. The only method which isn't backward-compatible is `New()`; the New() method in the featurebase/errors package takes an errors.Code. If this becomes a problem, we could change this by reverting New() and then introducing something like NewCoded(). But for now I think it might actually discourage someone from just creating a New() error without thinking about how it should be coded. Introduce VersionStore interface Move the existing VersionStore code to the `inmem` package as the in-memory implementation of the new dax.VersionStore interface. Introduce NodeService interface With this, the Controller can maintain a registry of nodes by using this NodeService interface as opposed to an in-memory map of nodes on the Controller struct. This also adds an inmem implementation of the NodeService interface. Introduce controller.Balancer interface This moves the existing balancer package to controller/naive package. The idea is to allow us to add a different Balancer implementation in the future. Introduce DirectiveVersion interface This commit also includes *A LOT* of refactoring to use dax.Worker and dax.Job types everywhere instead of strings. Introduce Schemar interface The previous `Schemar` struct was moved to the `schemar/inmem` package, and `Schemar` is now an interface implemented by that inmem package. Remove unused type `nUnit` Add boltdb implementation of VersionStore interface. This removed the previous sqlite implementation; we decided not to use sqlite for now (as a basic, local disk implementation) because it requires CGO. -------------------------------------------- No longer applicable: Add sqlite implementation of VersionStore interface. This commit implements the VersionStore interface using sqlite. Sqlite requires CGO, so this may not be something we want to include, but it's implemented here to get a feel for how an external implementation might be used; the next step will be to determine how the user configured FeatureBase to run using sqlite as a backing store for services like MDS. Add boltdb implementation of NodeService and DirectiveVersion interfaces. Add boltdb implementation of naive Balancer interfaces. This includes the two interfaces defined in `naive/balancer.go`: - WorkerJobService - FreeJobService Add boltdb implementation of Schemar interface. clean up a linter issue Thread context.Context through all the interfaces. Some of the interface implementations are going to use context, so we need to make that part of the interface. The boltdb implementations, for example, take a context. This is probably so we can do things like cancel or timeout operations. Update interfaces to return error; remove `panic(err)` everywhere. Down-rev grpc version to 1.38.0 Later versions (after 1.42.0?) cause MustRunCluster.Close() in tests to deadlock. This commit also adds an `isComputeNode` feature flag around some of the write log and shard/partition check functionality so that it doesn't run under normal conditions (this is excercised by running the sql3 tests for example). Add MDS_Persistence test to cover meta data persistence This adds a basic test which configures the MDS container to use boltdb as its persistence storage, saved on a docker volume. Then, the mds container is stopped/replaced, and we confirm that the data stored on the volume is availble to the new MDS container. Fix a few things after rebase with sql-experiment branch The lastest version of sql-experiment contains a fairly significan refactor of the way query iteration works. This commit adjusts for those changes. pull dax IDK changes in to FB IDK (#2177) * pull dax IDK changes in to FB IDK * Move docker-related IDK build stuff to featurebase root Building the docker image required the root level go.mod and vendor directory. This change moves the make targets to the root level Makefile, and the Dockerfiles now copy the root level vendor directory (and everything else in the root for that matter). * Fix batch- and client-related tests * InitializePoller on MDS restart/replacement Prior to this change, if MDS was restarted, its internal poller (which maintains an in-memory list of nodes to poll) is empty. This is bad, because it doesn't know about nodes that it should be polling. This change fixes that. Upon MDS startup, it intializes the poller with the list of nodes that MDS keeps in persistent storage (currently: boltdb). * Add EFS volume to MDS Copilot manifest This allows us to use MDS's persistent storage (via boltdb) in the Copilot demo by saving metadata in a boltdb file on EFS. * Thread logger.Logger through all dax components * Revert some of the breaking changes from DAX development. When we first started prototyping DAX, we made changes to the featurebase core code which would have broken the existing featurebase functionality. This commit reverts some of those changes. Anywhere that we need to modify core featurebase functionilty, we put it behind some kind of feature flag. This flag is typically determined by whether the running node is a "compute" node (i.e. DAX.COMPUTER.RUN = true). Co-authored-by: Travis Turner <travis@molecula.com> add packaging for DAX need cgo for datagen build bind to 0.0.0.0, pass GOOS and GOARCH explicitly not sure if the explicit GOOS/GOARCH is actually necessary... Get INSERT INTO (aka ingest) working through SQL3 This commit does a few things which I'll try do describe here. - Introduces a Qctx interface. The existing Qcx is an implementation of this interface, and can be used exactly how it has been. But this allows us to abstract away the notion of Qcx in the Queryer (which is handling SQL3) until we're ready to address that. As an example, the Qcx has a notion of a featurebase Holder, but that doesn't make sense when we're at the Queryer layer. For now, the Qctx used in the Queryer is a no-op. - Adds a ComputeAPI interface implementation for the Queryer. This is effectively the Import() and ImportValues() methods used for ingest. The logic here handles the incoming ImportRequest by first doing any necessary column and row translation for the entire request, then it splits the records by shard, and generates a new ImportRequest per shard with only the shard-appropriate records. - Changes the mds.Importer to take an MDS interface implementation (which can be an mds client) instead of an mdsAddress. This allows us to use a localy MDS implementation rather than assuming we need a client to make calls over a network. Add queryer.Importer interface to handle ingest via SQL (#2203) * Add queryer.Importer interface to handle ingest via SQL This is meant to support ingest through SQL when the queryer and the compute services are running in the same process, or when they are on seperate processes and need to talk via http client. * remove datagen from RPM was originally added as a convenience to generate test data, but is unused and annoying because datagen doesn't easily cross-compile due to cgo * add marshalUnmarshal to controller to avoid passing pointers passing pointers across API boundaries can cause unpredictable things in local vs remote configurations. Co-authored-by: Matthew Jaffee <jaffee@pilosa.com> "fix" a few issues with wrong default partition numbers these still need to be properly fixed and actually get the correct data from MDS go mod tidy Introduce TableQualifier (OrganizationID/DatabaseID) (#2220) * add check in ApplyDirective that version is increasing fix TestAPIDirective to make version always increasing * fix docker image build and break out dax test in CI We have to run the DAX integration tests separately as they call out to Docker, and so it isn't easy to run them in a Docker container as the other tests do. So we run them directly on the CI runner which has Docker and Go installed. We also explicitly exclude these tests from running during the other tests. Also my editor was automatically reformatting some comments badly which is why I added the "data" thing in those two places * add timeout to poller * give Poller a default Logger apparently we can NPE sometimes, seen in CI: https://gitlab.com/molecula/featurebase/-/jobs/3028286364 * bunch of testing fixes, mostly IDK/DAX related make MDS error if sendDirectives errors, don't just log. sendDirectives can error if computer nodes disagree about the validity of a schema (for example), in which case it might need to get deleted and user notified somehow. very messy, needs more thought. re-introduce old env prefix to maintain compatibility with master branch make self-contained dax container for IDK testing build IDK images from source (now that all the source is available since it's in the same repo) catch errors in DoExtractQuery in idktest.go fix IDK bug where prefix path was hardcoded in all cases rather than only when useMDS was true fix TestBatchTargetMDS... needed to add field options and catch error when creating table. also needed an _id field * fix env prefix in tests * WIP getting tests to pass, wanna see CI * don't error if we get a zero version directive and we don't have a directive yet * cleanup debugging junk * "fix" future.rename thing, run IDK tests * Introduce TableQualifier (OrganizationID/DatabaseID) This commit introduces a lot of new types (in dax/table.go) related to TableQualifer (which is made up of OrganizationID and DatabaseID), as well as things like TableID and TableKey. For the most part, we try to thread a QualifiedTableID through the entirety of DAX. There are some places (for example in the Balancers, which are just aware of string keys) which use a string TableKey (tbl__org__db__tableid). * Remove some debugging comments * Add Org/DB support to CLI. This commit adds support for special commands: SET SET ORG acme SET DB db1 USE db1 * remove ".pulled" from IDK Makefile I don't think we need it any more as most things can be built locally. I think it was only there to refresh the FeatureBase images that were tagged as master, but we don't need to do that any more. * Change DAX json tags to kebab-case (i.e. hyphenated) This commit also renames some struct arguments to more accurately reflect their type: for example, renaming `Table` to `TableKey` when the type is TableKey. * Return DAX TableName in SHOW TABLES (instead of Index.Name) There are cases where SchemaAPI is used to return DAX friendly table names (as opposed to featurebase index names, which are DAX TableKey). This is an attempt to do that. With that said, it's not ideal because anything could call those API methods and expect the other type. * Fix a bug which wasn't completely dropping a table. When using boltdb as a backend, DROP TABLE wasn't removing the reverse-lookup key for the table in boltdb. * Remove idk/testenv/certs which got accidentally committed. also update .gitignore to include those. * Fix IDK ingest tests to be TableQualifier aware. * Add example Table types to dax/table.com godoc. * ignore idk.Main fields for flags, upgrade commandeer * go mod tidy * Fix DAX integration tests: ingester using wrong ENV VARs We change from ORGANIZATION_ID to ORG_ID and from DATABASE_ID to DB_ID * Clarify things around idk (docker) tests * Stop running TestKafkaSourceIntegration with t.Parallel() This test can't be run in parallel as it's currently written. Doing so allows for interleaving of messages to the same kafka topic between tests. I didn't attempt to modify the test so it could be run in parallel. That could be done, but left for someone more ambitious. Co-authored-by: Matthew Jaffee <jaffee@pilosa.com> Require Directive.Version be a non-zero value. (#2227) Because the directive cached on the holder is not a pointer, its default version is 0. In order to avoid having to compare against that, we just require that Directive.Version start at 1. General, non-invasive code cleanup and comment adjustment. Move ImportRoaringShardRequest out of the types package Early on in the DAX development, I moved ImportRoaringShardRequest into a types package. There must have been some import loop going on, but since that is not longer the case, it's safe to move this back into the core featurebase (er... pilosa) package. Move Transaction struct back into the pilosa package (from types) Revert some name changes (cli -> client) Add DAX Handler CloseTimeout This was implemented in htt_handler.go, but it had been commented out in the DAX handler. This just uncomments that and finishes the implementation. Remove Qcx from queryer.Importer interface This sets us up to revert the Qctx interface that was initially introduced to allow us to abstract away the need for a Qcx when calling the ComputeAPI from a remote service (i.e. the queryer). Add some go-doc comments and remove unused code. Move SchemaManager setup from datagen to idk.Main (#2233) The set for idk.SchemaManager (for dax implementations) was previously in datagen. This may have been because of some import loop problem during development, but that's no longer an issue. The setup for this should be in idk.Main so anything using that can leverage the MDS-specific SchemaManager setup. Fix issues around nil TxFactory First, don't return a nil. Rather return a new *TxFactory (with no holder). Second, don't call `f.holder` in the testhook outside of checking if `f.holder` is nil. Wrap all bare errors Make service prefixes constants Instead of having `"computer"` throughout the code, use instead a constant: `dax.ServicePrefixComputer`. MDS skip errors when sending empty directives also add in the docker-login and ecr-push changes for serverless DAX Fix the logic in Directive.IsEmpty() (#2236) Update the cached value for Index.translatePartitions In the case where a node already knows about an index, but its assignment of partitions for that index changes (for example, when another node goes down and the node in question is now responsible for more partitions than it previously was), then we need to update the cached value of Index.translatePartitions because that's used in translation checks. minor fixes for IDK-related bugs WIP: tokenize CLI to access cloud FB CLI cloud support with automatic token refresh Also adds support for a GET command which allows making HTTP GET queries to cloud CP which can be handy for debugging stuff. E.g. GET /v2/databases buncha little fixes working on writelogger stuff fix writelogger/snapshotter setup bugs implement writelogging for importRoaringShard add debug endpoint to MDS use shard transactional endpoint in MDS datagen add debugging to API related to writelogger revert handleroption change clean up big PR remove "GET" command from CLI for making arbitrary HTTP request to cloud control plane (was a messy hack and not that useful) remove json tags from FB objects where we had to duplicate the object elsewhere due to import loops and weren't actually json encoding it unexport handlerOption which was exported to try to avoid doing certain things if we're in DAX mode, but I didn't end up merging that code. remove (hopefully) unecessary extra call to api.indexField fix some formatting, unexport some vars, godoc, etc oops, fix build failure Update FeatureBase CLI to support a standard deployment The standard deployment uses a different endpoint and request payload. This commit tries to detect is the standard deployment is being used, and if so, it uses a standard-specific FBQueryer. It also modifies the auto-detection logic to try standard featurebase and dax ports in the case where a port was not provided. MDS API refactor (#2259) * MDS API refactor table IDs are exposed but only created server side also cleaned up dax Makefile * clean up review feedback Co-authored-by: Travis Turner <travis@pilosa.com> * remove TablesByName * rip out inmem implementations and use boltdb everywhere * remove inmem balancer, create bolt tempfile by default on startup * WIP on snapshot table impl and test * Minor comment and code layout adjustments. This commit also adds the `Equals` method to `QualifiedTableID` for equality comparisons. It's no longer safe to compare struct (two structs might still be equal even if one of the structs doesn't have a `Name` value. * Use a unique docker network for each dax test Ocassionally we would see some test failures due to a network already existing. This shouldn't happen, but to avoid that, this commit generates a unique name for each sub test (which gets deleted at the end of every test). * Fix one instance of NewQualifiedTableID losing Name We should probably check the other instances and see if Name is getting lost. * simplify unique network stuff and fix api directive tests * Remove TableIDRequest and TableIDResponse types for /table-id (#2267) For the mds/table-id http requests, just use dax.QualifiedTableID as both the request and response types. * remove lattice from dax, no error on node re-reg, dax docker-compose * various updates * WIP: mds-refactor branch review * no-op on SnapshotTableKeys if table is not keyed * Makefile helpers * add doWeCare so controller doesn't fail unnecessarily * clean up table creation (#2272) * Strip underscores from TableID stub name * fix boltdb versionstore tests: generate unique, sorted tables * fix controller test related to reregistering a node * JobSet -> generic Set Co-authored-by: Travis Turner <travis@pilosa.com> Co-authored-by: Travis Turner <travis@molecula.com> Cleanup after rebase on master The latest rebase on master entailed all the client/batch changes as well as some of the qcx refactoring. It made for a hairy rebase. This commit fixes some of the tests that were failing after that rebase. Fix batch/client import loop missed during rebase (#2280) It's not surprising that `batch` can't import `client`. It was doing that here (importing an error type from the `client` package). What is surprising is that it's okay for `batch_test.go` to import `client` even though `batch_test.go` is an internal test and therefore part of the `batch` package. different boltDB's for schemar/controller, explicit balancers nice helpers for dax docker-compose, make build really fast build FB binary outside of docker, then create Docker image with its working dir in an empty subdirectory so it doesn't send a GB of context to the daemon. error on unassigned jobs and use client with timeout fix CR feedback deregister batch of nodes also make removal faster via director dial timeout implement WorkersForJobPrefix so orchestrator doesn't make up shards also fix some godocs and remove unused method Run sub-tasks of a Directive concurrently in a worker pool. (#2275) * Run sub-tasks of a Directive concurrently in a worker pool. This allows the compute node to concurrently load shapshot and writelog data concurrently, instead of one keyset/partition/shard at a time. It introduces a config parameter called `DirectiveWorkerPoolSize`. * code review cleanup * Use unique container names in DAX integration tests We were seeing "container already exists" errors in CI, so just to be safe, this commit constructs a unique container name for every container in the DAX integration test run. Stub in SystemAPI to Queryer (note: will not work if used) This just makes is so that dax can compile. Actually implementing system-table functionality for dax will take some planning. Tlt/dax merge prep (#2282) * Remove copilot directory * Remove Dockerfile-datagen-long * Remove orphaned RegisterNodeRequest This type is not defined in the dax/mds/http package. * implement TIMEQUANTUM and TTL in Table.Field type * Remove the "service" misdirection in queryer/writelogger/snapshotter. We had originally used an additional layer, er.. package, for a "service". The main distinction was that the Config differed in that it was internal, unlike the Config that we need to provide for the top-level server config (i.e. toml). Having that additional layer just to support a different Config seemed premature at best. So I'm removing it. * Remove dax docker containers no longer used in tests Since we run everything as "featurebase", we don't have multiple container types anymore. * Some minor comment updates * Remove nfpm stuff related to dax * Fix linter issues Fix "duplicate" issues raised by sonarcloud. run docker components of dax integration tests with coverage trying to get dax integration coverage add coverate volume mounts throughout dax integration tests add a lock, tweak dax Makefile, remote flag on query handler remove some unused code convert batch tests to use clustertests to get coverage maybe fix clustertests more authclustertests fixes, test is failing locally but also seems to have been silently failing in CI prior to these changes... let's see if it's still silent fix some lint to kick CI just re-running the job wasn't working... strange behavior remove RetryLogic test and pipe which don't work RetryLogic test removed due to etcd changes. Seebs thinks we shouldn't test this here. Pipe was being ignored since we're no longer using "bash -c" to execute the command. If we need to generate that output file we'll either have to reintroduce bash -c and set -o pipefail so that it actually fails properly, or figure out some other solution. shooting into the dark... first cut at bulk node registration remove unused stuff from batch tests, set coverpkg to ../... batch registration timeout and fix tests disable most tests and don't run fb background batch test debuggin!!!!!!!!! and then he tried this.... Implement importer (for INSERT INTO) in the Queryer Prior to this, we we passing a nil value in for the importer to the planner.NewExecutionPlanner in the Queryer. This meant that INSERT INTO statements didn't work. Now they should. It uses the importer that we build for IDK in /idk/mds/importer.go, and wrapps that with a type that can determine if the provided string "index" is of the form indexName or TableKey. turn off debug mode, fix log saving Run sql3 test definitions in a dax integration test There are currently 22 tests which are not passing. They are skipped in the "skips" slice. WIP, not working, pql queries to tests Add TableQualifier to PQL query logic in the Queryer Add more PQL tests to the keyed table Allow instant node registration if registration-batch-timeout=0 When running dax services in process, we don't want to wait 3s for the compute node to register; we know it's there because it's in the same process. Fixes related to IncludesColumn PQL test. Tests for ConstRow and FieldValue cleanup add UnionRows and Options, better error reporting on bad queries delete unused schemar client.go, clean up unused in batch test CI move test timeouts into more reasonable territory apparently this had already been done, but got merge-stommped at some point move dax bolt test helpers into dax package Add computer CheckIn routine (#2296) * Add computer CheckIn routine This adds a background routine which sends a "check-in" request to MDS every <interval>. This is to address the case where the poller has removed a computer node from the node list (due to a network fault, for example), but the node is still healthy and becomes available again. In that case, the node needs to "check-in" to tell MDS it is still there. MDS will likely send the node a new directive with Method=reset telling the node to delete all of its data an apply the latest directive. * Don't send directives to Deregistered (i.e. removed) nodes We have an issue where we're locking on sendDirective in the controller, and when the node is unavailable, the send hangs and never releases the lock. This is a temporary fix for that until we address the real problem. Fix .gitlab-ci.yml after rebase fix some indentation shenanigans
798 lines
26 KiB
Go
798 lines
26 KiB
Go
// Copyright 2021 Molecula Corp. All rights reserved.
|
|
package server
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"io"
|
|
"log"
|
|
"net"
|
|
"net/url"
|
|
"os"
|
|
"path/filepath"
|
|
"runtime"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/molecula/featurebase/v3/authz"
|
|
petcd "github.com/molecula/featurebase/v3/etcd"
|
|
rbfcfg "github.com/molecula/featurebase/v3/rbf/cfg"
|
|
"github.com/molecula/featurebase/v3/storage"
|
|
"github.com/molecula/featurebase/v3/toml"
|
|
"github.com/pkg/errors"
|
|
)
|
|
|
|
const (
|
|
defaultBindPort = "10101"
|
|
defaultBindGRPCPort = "20101"
|
|
defaultDiagnosticsInterval = 1 * time.Hour
|
|
|
|
namespacePilosa = "pilosa"
|
|
namespaceFeaturebase = "featurebase"
|
|
)
|
|
|
|
// TLSConfig contains TLS configuration
|
|
type TLSConfig struct {
|
|
// CertificatePath contains the path to the certificate (.crt or .pem file)
|
|
CertificatePath string `toml:"certificate"`
|
|
// CertificateKeyPath contains the path to the certificate key (.key file)
|
|
CertificateKeyPath string `toml:"key"`
|
|
// CACertPath is the path to a CA certificate (.crt or .pem file)
|
|
CACertPath string `toml:"ca-certificate"`
|
|
// SkipVerify disables verification of server certificates when connecting to another Pilosa node
|
|
SkipVerify bool `toml:"skip-verify"`
|
|
// EnableClientVerification enables verification of client TLS certificates (Mutual TLS)
|
|
EnableClientVerification bool `toml:"enable-client-verification"`
|
|
}
|
|
|
|
// Config represents the configuration for the command.
|
|
type Config struct {
|
|
// Name a unique name for this node in the cluster.
|
|
Name string `toml:"name"`
|
|
|
|
// MDSAddress is the location at which this node should register itself and
|
|
// retrieve its instructions. For example, after registring, the MDS service
|
|
// might tell this node that it is responsible for specific shards for a
|
|
// particular index.
|
|
MDSAddress string `toml:"mds-address"`
|
|
|
|
// WriteLogger is the location at which this node should read/write change
|
|
// logs.
|
|
WriteLogger string `toml:"write-logger"`
|
|
|
|
// Snapshotter is the location at which this node should read/write
|
|
// snapshots.
|
|
Snapshotter string `toml:"snapshotter"`
|
|
|
|
// DataDir is the directory where Pilosa stores both indexed data and
|
|
// running state such as cluster topology information.
|
|
DataDir string `toml:"data-dir"`
|
|
|
|
// Bind is the host:port on which Pilosa will listen.
|
|
Bind string `toml:"bind"`
|
|
|
|
// BindGRPC is the host:port on which Pilosa will bind for gRPC.
|
|
BindGRPC string `toml:"bind-grpc"`
|
|
|
|
// Listener is an already-bound listener to use for http.
|
|
//Listener *net.TCPListener
|
|
Listener net.Listener
|
|
|
|
// GRPCListener is an already-bound listener to use for gRPC.
|
|
// This is for use by test infrastructure, where it's useful to
|
|
// be able to dynamically generate the bindings by actually binding
|
|
// to :0, and avoid "address already in use" errors.
|
|
GRPCListener *net.TCPListener
|
|
|
|
// Advertise is the address advertised by the server to other nodes
|
|
// in the cluster. It should be reachable by all other nodes and should
|
|
// route to an interface that Bind is listening on.
|
|
Advertise string `toml:"advertise"`
|
|
|
|
// AdvertiseGRPC is the address advertised by the server to other nodes
|
|
// in the cluster. It should be reachable by all other nodes and should
|
|
// route to an interface that BindGRPC is listening on.
|
|
AdvertiseGRPC string `toml:"advertise-grpc"`
|
|
|
|
// MaxWritesPerRequest limits the number of mutating commands that can be in
|
|
// a single request to the server. This includes Set, Clear, ClearRow, Store, and SetBit.
|
|
MaxWritesPerRequest int `toml:"max-writes-per-request"`
|
|
|
|
// LogPath configures where Pilosa will write logs.
|
|
LogPath string `toml:"log-path"`
|
|
|
|
// Verbose toggles verbose logging which can be useful for debugging.
|
|
Verbose bool `toml:"verbose"`
|
|
|
|
// HTTP Handler options
|
|
Handler struct {
|
|
// CORS Allowed Origins
|
|
AllowedOrigins []string `toml:"allowed-origins"`
|
|
} `toml:"handler"`
|
|
|
|
// MaxMapCount puts an in-process limit on the number of mmaps. After this
|
|
// is exhausted, Pilosa will fall back to reading the file into memory
|
|
// normally.
|
|
MaxMapCount uint64 `toml:"max-map-count"`
|
|
|
|
// MaxFileCount puts a soft, in-process limit on the number of open fragment
|
|
// files. Once this limit is passed, Pilosa will only keep files open while
|
|
// actively working with them, and will close them afterward. This has a
|
|
// negative effect on performance for workloads which make small appends to
|
|
// lots of fragments.
|
|
MaxFileCount uint64 `toml:"max-file-count"`
|
|
|
|
// TLS
|
|
TLS TLSConfig `toml:"tls"`
|
|
|
|
// WorkerPoolSize controls how many goroutines are created for
|
|
// processing queries. Defaults to runtime.NumCPU(). It is
|
|
// intentionally not defined as a flag... only exposed here so
|
|
// that we can limit the size while running tests in CI so we
|
|
// don't exhaust the goroutine limit.
|
|
WorkerPoolSize int `toml:"-"`
|
|
|
|
// ImportWorkerPoolSize controls how many goroutines are created for
|
|
// processing importRoaring jobs. Defaults to runtime.NumCPU(). It is
|
|
// intentionally not defined as a flag... only exposed here so
|
|
// that we can limit the size while running tests in CI so we
|
|
// don't exhaust the goroutine limit.
|
|
ImportWorkerPoolSize int `toml:"-"`
|
|
|
|
// DirectiveWorkerPoolSize controls how many goroutines are created for
|
|
// processing a Directive (i.e. concurrently loading key/partition/shard
|
|
// data from shapshotter and writelogger) on a compute node. Defaults to
|
|
// runtime.NumCPU().
|
|
DirectiveWorkerPoolSize int `toml:"-"`
|
|
|
|
// Limits the total amount of memory to be used by Extract() & SELECT queries.
|
|
MaxQueryMemory int64 `toml:"max-query-memory"`
|
|
|
|
Cluster struct {
|
|
ReplicaN int `toml:"replicas"`
|
|
Name string `toml:"name"`
|
|
// This LongQueryTime is deprecated but still exists for backward compatibility
|
|
LongQueryTime toml.Duration `toml:"long-query-time"`
|
|
PartitionToNodeAssignment string `toml:"partition-to-node-assignment"`
|
|
} `toml:"cluster"`
|
|
|
|
// Etcd config is based on embedded etcd.
|
|
Etcd petcd.Options `toml:"etcd"`
|
|
|
|
LongQueryTime toml.Duration `toml:"long-query-time"`
|
|
|
|
Translation struct {
|
|
MapSize int `toml:"map-size"`
|
|
// DEPRECATED: Translation config supports translation store replication.
|
|
PrimaryURL string `toml:"primary-url"`
|
|
} `toml:"translation"`
|
|
|
|
// AntiEntropy config is now deprecated
|
|
AntiEntropy struct {
|
|
Interval toml.Duration `toml:"interval"`
|
|
} `toml:"anti-entropy"`
|
|
|
|
Metric struct {
|
|
// Service can be statsd, prometheus, expvar, or none.
|
|
Service string `toml:"service"`
|
|
// Host tells the statsd client where to write.
|
|
Host string `toml:"host"`
|
|
PollInterval toml.Duration `toml:"poll-interval"`
|
|
// Diagnostics toggles sending some limited diagnostic information to
|
|
// Pilosa's developers.
|
|
Diagnostics bool `toml:"diagnostics"`
|
|
} `toml:"metric"`
|
|
|
|
Tracing struct {
|
|
// SamplerType is the type of sampler to use.
|
|
SamplerType string `toml:"sampler-type"`
|
|
// SamplerParam is the parameter passed to the tracing sampler.
|
|
// Its meaning is dependent on the type of sampler.
|
|
SamplerParam float64 `toml:"sampler-param"`
|
|
// AgentHostPort is the host:port of the local agent.
|
|
AgentHostPort string `toml:"agent-host-port"`
|
|
} `toml:"tracing"`
|
|
|
|
Profile struct {
|
|
// BlockRate is passed directly to runtime.SetBlockProfileRate
|
|
BlockRate int `toml:"block-rate"`
|
|
// MutexFraction is passed directly to runtime.SetMutexProfileFraction
|
|
MutexFraction int `toml:"mutex-fraction"`
|
|
} `toml:"profile"`
|
|
|
|
SQL struct {
|
|
// EndpointEnabled enables the /sql endpoint.
|
|
EndpointEnabled bool `toml:"endpoint-enabled"`
|
|
} `toml:"sql"`
|
|
|
|
// CheckInTimeout is the amount of time between compute node check-ins to
|
|
// MDS.
|
|
CheckInInterval time.Duration `toml:"check-in-interval"`
|
|
|
|
// Storage.Backend determines which Tx implementation the holder/Index will
|
|
// use; one of the available transactional-storage engines. Choices are
|
|
// listed in the string constants below. Should be one of "roaring" or
|
|
// "rbf".
|
|
Storage *storage.Config `toml:"storage"`
|
|
|
|
// RBFConfig defines all externally configurable RBF flags.
|
|
RBFConfig *rbfcfg.Config `toml:"rbf"`
|
|
|
|
// QueryHistoryLength sets the maximum number of queries that are maintained
|
|
// for the /query-history endpoint. This parameter is per-node, and the
|
|
// result combines the history from all nodes.
|
|
QueryHistoryLength int `toml:"query-history-length"`
|
|
|
|
// LookupDBDSN is an external database to connect to for `ExternalLookup` queries.
|
|
LookupDBDSN string `toml:"lookup-db-dsn"`
|
|
|
|
// Future flags are used to represent features or functionality which is not
|
|
// yet the default behavior, but will be in a future release.
|
|
Future struct {
|
|
// Rename, if true, will outwardly present the name of the application
|
|
// as FeatureBase instead of Pilosa.
|
|
Rename bool `toml:"rename"`
|
|
} `toml:"future"`
|
|
|
|
DataDog struct {
|
|
Enable bool `toml:"enable"`
|
|
Service string `toml:"service"`
|
|
Env string `toml:"env"`
|
|
Version string `toml:"version"`
|
|
Tags string `toml:"tags"`
|
|
CPUProfile bool `toml:"cpu-profile"`
|
|
MutexProfile bool `toml:"mutex-profile"`
|
|
GoroutineProfile bool `toml:"goroutine-profile"`
|
|
BlockProfile bool `toml:"block-profile"`
|
|
HeapProfile bool `toml:"heap-profile"`
|
|
} `toml:"datadog"`
|
|
|
|
Auth Auth
|
|
}
|
|
|
|
type Auth struct {
|
|
// Enable AuthZ/AuthN for featurebase server
|
|
Enable bool `toml:"enable"`
|
|
|
|
ClientId string `toml:"client-id"`
|
|
ClientSecret string `toml:"client-secret"`
|
|
AuthorizeURL string `toml:"authorize-url"`
|
|
TokenURL string `toml:"token-url"`
|
|
GroupEndpointURL string `toml:"group-endpoint-url"`
|
|
RedirectBaseURL string `toml:"redirect-base-url"`
|
|
LogoutURL string `toml:"logout-url"`
|
|
Scopes []string `toml:"scopes"`
|
|
SecretKey string `toml:"secret-key"`
|
|
PermissionsFile string `toml:"permissions"`
|
|
QueryLogPath string `toml:"query-log-path"`
|
|
ConfiguredIPs []string `toml:"configured-ips"`
|
|
}
|
|
|
|
// Namespace returns the namespace to use based on the Future flag.
|
|
func (c *Config) Namespace() string {
|
|
if c.Future.Rename {
|
|
return namespaceFeaturebase
|
|
}
|
|
return namespacePilosa
|
|
}
|
|
|
|
// MustValidate checks that all ports in a Config are unique and not zero.
|
|
// We disallow zero because the tests need to be using from the pre-allocated
|
|
// block of ports maintained by the pilosa/test/port port-mapper.
|
|
func (c *Config) MustValidate() {
|
|
err := c.validate()
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
}
|
|
|
|
func (c *Config) validate() error {
|
|
hostPort := []string{
|
|
"Bind", c.Bind, // :10101
|
|
"BindGRPC", c.BindGRPC, // :20101
|
|
"Advertise", c.Advertise, // on hp = 'http://localhost:63002'
|
|
"AdvertiseGRPC", c.AdvertiseGRPC, // on hp = 'http://localhost:63003'
|
|
"Etcd.LClientURL", c.Etcd.LClientURL, // on hp = ':14000'
|
|
"Etcd.AClientURL", c.Etcd.AClientURL, // ""
|
|
"Etcd.LPeerURL", c.Etcd.LPeerURL, // ":"
|
|
"Etcd.APeerURL", c.Etcd.APeerURL, // ""
|
|
"Etcd.ClusterURL", c.Etcd.ClusterURL,
|
|
}
|
|
|
|
ports := make(map[int]bool)
|
|
n := len(hostPort)
|
|
for i := 0; i < n; i += 2 {
|
|
name := hostPort[i]
|
|
hp := hostPort[i+1]
|
|
if hp == "" {
|
|
continue
|
|
}
|
|
if name == "Advertise" && (hp == "" || hp == ":") {
|
|
continue
|
|
}
|
|
if name == "AdvertiseGRPC" && (hp == "" || hp == ":") {
|
|
continue
|
|
}
|
|
|
|
hp = strings.TrimPrefix(hp, "http://")
|
|
hp = strings.TrimPrefix(hp, "https://")
|
|
splt := strings.Split(hp, ":")
|
|
if len(splt) != 2 {
|
|
return fmt.Errorf("'%v' host:port '%v' did not have a colon; all='%#v'", name, hp, hostPort)
|
|
}
|
|
portstring := splt[1]
|
|
port, err := strconv.Atoi(portstring)
|
|
if err != nil {
|
|
return fmt.Errorf("on '%v', could not convert '%v' to int in '%v': '%v'", name, portstring, hp, err)
|
|
}
|
|
if port == 0 {
|
|
return fmt.Errorf("name '%v': zero port found, not allowed. '%v'. all ='%#v'", name, hp, hostPort)
|
|
}
|
|
if ports[port] {
|
|
return fmt.Errorf("name '%v': duplicate port found, not allowed. '%v' with port %v. all ='%#v'", name, hp, port, hostPort)
|
|
}
|
|
ports[port] = true
|
|
}
|
|
return nil
|
|
}
|
|
|
|
const (
|
|
PartitionToNodeJmp string = "jmp-hash"
|
|
PartitionToNodeModulus string = "modulus"
|
|
)
|
|
|
|
// NewConfig returns an instance of Config with default options.
|
|
func NewConfig() *Config {
|
|
c := &Config{
|
|
Name: "pilosa0",
|
|
DataDir: "~/.pilosa",
|
|
Bind: ":" + defaultBindPort,
|
|
BindGRPC: ":" + defaultBindGRPCPort,
|
|
MaxWritesPerRequest: 5000,
|
|
|
|
// We default these Max File/Map counts very high. This is basically a
|
|
// backwards compatibility thing where we don't want to cause different
|
|
// behavior for those who had previously set their system limits high,
|
|
// and weren't experiencing any bad behavior. Ideally you want these set
|
|
// a bit below your system limits.
|
|
MaxMapCount: 1000000,
|
|
MaxFileCount: 1000000,
|
|
|
|
TLS: TLSConfig{},
|
|
|
|
WorkerPoolSize: runtime.NumCPU(),
|
|
ImportWorkerPoolSize: runtime.NumCPU(),
|
|
|
|
DirectiveWorkerPoolSize: runtime.NumCPU(),
|
|
|
|
Storage: storage.NewDefaultConfig(),
|
|
RBFConfig: rbfcfg.NewDefaultConfig(),
|
|
|
|
QueryHistoryLength: 100,
|
|
|
|
LongQueryTime: toml.Duration(-time.Minute),
|
|
|
|
CheckInInterval: 5 * time.Second,
|
|
}
|
|
|
|
// Cluster config.
|
|
c.Cluster.Name = "cluster0"
|
|
c.Cluster.ReplicaN = 1
|
|
c.Cluster.LongQueryTime = toml.Duration(-time.Minute) // TODO remove this once cluster.longQueryTime is fully deprecated
|
|
c.Cluster.PartitionToNodeAssignment = PartitionToNodeJmp
|
|
|
|
// AntiEntropy config.
|
|
c.AntiEntropy.Interval = toml.Duration(0)
|
|
|
|
// Metric config.
|
|
c.Metric.Service = "none"
|
|
c.Metric.PollInterval = toml.Duration(0 * time.Minute)
|
|
c.Metric.Diagnostics = false
|
|
|
|
// Tracing config.
|
|
c.Tracing.SamplerType = "off"
|
|
c.Tracing.SamplerParam = 0.001
|
|
|
|
c.Profile.BlockRate = 10000000 // 1 sample per 10 ms
|
|
c.Profile.MutexFraction = 100 // 1% sampling
|
|
|
|
c.SQL.EndpointEnabled = false
|
|
|
|
c.Etcd.AClientURL = ""
|
|
c.Etcd.LClientURL = "http://localhost:10301"
|
|
c.Etcd.APeerURL = ""
|
|
c.Etcd.LPeerURL = "http://localhost:10401"
|
|
c.Etcd.Dir = ""
|
|
c.Etcd.Name = ""
|
|
c.Etcd.ClusterName = ""
|
|
c.Etcd.InitCluster = c.Name + "=" + c.Etcd.LPeerURL
|
|
c.Etcd.HeartbeatTTL = 5
|
|
|
|
c.Etcd.TrustedCAFile = ""
|
|
c.Etcd.ClientCertFile = ""
|
|
c.Etcd.ClientKeyFile = ""
|
|
c.Etcd.PeerCertFile = ""
|
|
c.Etcd.PeerKeyFile = ""
|
|
|
|
// Future flags.
|
|
c.Future.Rename = false
|
|
|
|
return c
|
|
}
|
|
|
|
// validateAddrs controls the address fields in the Config object
|
|
// and fills in any blanks.
|
|
// The addresses fields must be guaranteed by the caller to either be
|
|
// completely empty, or have both a host part and a port part
|
|
// separated by a colon. In the latter case either can be empty to
|
|
// indicate it's left unspecified.
|
|
func (c *Config) validateAddrs(ctx context.Context) error {
|
|
// Validate the advertise address.
|
|
advScheme, advHost, advPort, err := validateAdvertiseAddr(ctx, c.Advertise, c.Bind, defaultBindPort)
|
|
if err != nil {
|
|
return errors.Wrapf(err, "validating advertise address")
|
|
}
|
|
c.Advertise = schemeHostPortString(advScheme, advHost, advPort)
|
|
|
|
// Validate the listen address.
|
|
listenScheme, listenHost, listenPort, err := validateListenAddr(ctx, c.Bind, defaultBindPort)
|
|
if err != nil {
|
|
return errors.Wrap(err, "validating listen address")
|
|
}
|
|
c.Bind = schemeHostPortString(listenScheme, listenHost, listenPort)
|
|
|
|
// Validate the gRPC advertise address.
|
|
_, grpcAdvHost, grpcAdvPort, err := validateAdvertiseAddr(ctx, c.AdvertiseGRPC, c.BindGRPC, defaultBindGRPCPort)
|
|
if err != nil {
|
|
return errors.Wrapf(err, "validating grpc advertise address")
|
|
}
|
|
c.AdvertiseGRPC = schemeHostPortString("grpc", grpcAdvHost, grpcAdvPort)
|
|
|
|
// Validate the gRPC listen address.
|
|
_, grpcListenHost, grpcListenPort, err := validateListenAddr(ctx, c.BindGRPC, defaultBindGRPCPort)
|
|
if err != nil {
|
|
return errors.Wrap(err, "validating grpc listen address")
|
|
}
|
|
c.BindGRPC = schemeHostPortString("grpc", grpcListenHost, grpcListenPort)
|
|
|
|
return nil
|
|
}
|
|
|
|
// validateAdvertiseAddr validates and normalizes an address accessible
|
|
// Ensures that if the "host" part is empty, it gets filled in with
|
|
// the configured listen address if any, otherwise it makes a best
|
|
// guess at the outbound IP address.
|
|
// Returns scheme, host, port as strings.
|
|
func validateAdvertiseAddr(ctx context.Context, advAddr, listenAddr, defaultPort string) (string, string, string, error) {
|
|
listenScheme, listenHost, listenPort, err := splitAddr(listenAddr, defaultPort)
|
|
if err != nil {
|
|
return "", "", "", errors.Wrap(err, "getting listen address")
|
|
}
|
|
|
|
advScheme, advHostPort := splitScheme(advAddr)
|
|
advHost, advPort := "", ""
|
|
if advHostPort != "" {
|
|
var err error
|
|
advHost, advPort, err = net.SplitHostPort(advHostPort)
|
|
if err != nil {
|
|
return "", "", "", errors.Wrapf(err, "splitting host port: %s", advHostPort)
|
|
}
|
|
}
|
|
// If no advertise scheme was specified, use the one from
|
|
// the listen address.
|
|
if advScheme == "" {
|
|
advScheme = listenScheme
|
|
}
|
|
// If there was no port number, reuse the one from the listen
|
|
// address.
|
|
if advPort == "" || advPort == "0" {
|
|
advPort = listenPort
|
|
}
|
|
// Resolve non-numeric to numeric.
|
|
portNumber, err := net.DefaultResolver.LookupPort(ctx, "tcp", advPort)
|
|
if err != nil {
|
|
return "", "", "", errors.Wrapf(err, "looking up non-numeric port: %v", advPort)
|
|
}
|
|
advPort = strconv.Itoa(portNumber)
|
|
|
|
// If the advertise host is empty, then we have two cases.
|
|
if advHost == "" {
|
|
if listenHost == "0.0.0.0" {
|
|
advHost = outboundIP().String()
|
|
} else {
|
|
advHost = listenHost
|
|
}
|
|
}
|
|
return advScheme, advHost, advPort, nil
|
|
}
|
|
|
|
// outboundIP gets the preferred outbound ip of this machine.
|
|
func outboundIP() net.IP {
|
|
// This is not actually making a connection to 8.8.8.8.
|
|
// net.Dial() selects the IP address that would be used
|
|
// if an actual connection to 8.8.8.8 were made, so this
|
|
// choice of address is just meant to ensure that an
|
|
// external address is returned (as opposed to a local
|
|
// address like 127.0.0.1).
|
|
conn, err := net.Dial("udp", "8.8.8.8:80")
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
defer conn.Close()
|
|
|
|
localAddr := conn.LocalAddr().(*net.UDPAddr)
|
|
|
|
return localAddr.IP
|
|
}
|
|
|
|
// validateListenAddr validates and normalizes an address suitable for
|
|
// use with net.Listen(). This accepts an empty "host" part to signify
|
|
// the default (localhost) should be used. Rresolves host names to IP
|
|
// addresses.
|
|
// Returns scheme, host, port as strings.
|
|
func validateListenAddr(ctx context.Context, addr, defaultPort string) (string, string, string, error) {
|
|
scheme, host, port, err := splitAddr(addr, defaultPort)
|
|
if err != nil {
|
|
return "", "", "", errors.Wrap(err, "getting listen address")
|
|
}
|
|
rHost, rPort, err := resolveAddr(ctx, host, port)
|
|
if err != nil {
|
|
return "", "", "", errors.Wrap(err, "resolving address")
|
|
}
|
|
return scheme, rHost, rPort, nil
|
|
}
|
|
|
|
// splitScheme returns two strings: the scheme and the hostPort.
|
|
func splitScheme(addr string) (string, string) {
|
|
parts := strings.SplitN(addr, "://", 2)
|
|
if len(parts) == 1 {
|
|
return "", addr
|
|
}
|
|
return parts[0], parts[1]
|
|
}
|
|
|
|
func schemeHostPortString(scheme, host, port string) string {
|
|
var s string
|
|
if scheme != "" {
|
|
s += fmt.Sprintf("%s://", scheme)
|
|
}
|
|
return s + net.JoinHostPort(host, port)
|
|
}
|
|
|
|
// splitAddr returns scheme, host, port as strings.
|
|
func splitAddr(addr string, defaultPort string) (string, string, string, error) {
|
|
scheme, hostPort := splitScheme(addr)
|
|
host, port := "", ""
|
|
if hostPort != "" {
|
|
var err error
|
|
host, port, err = net.SplitHostPort(hostPort)
|
|
if err != nil {
|
|
return "", "", "", errors.Wrapf(err, "splitting host port: %s", hostPort)
|
|
}
|
|
}
|
|
// It's not ideal to have a default here, but the alterative
|
|
// results in a port of 0, which causes Pilosa to listen on
|
|
// a random port.
|
|
if port == "" {
|
|
port = defaultPort
|
|
}
|
|
return scheme, host, port, nil
|
|
}
|
|
|
|
// resolveAddr resolves non-numeric addresses to numeric (IP, port) addresses.
|
|
func resolveAddr(ctx context.Context, host, port string) (string, string, error) {
|
|
resolver := net.DefaultResolver
|
|
|
|
// Resolve the port number. This may translate service names
|
|
// e.g. "postgresql" to a numeric value.
|
|
portNumber, err := resolver.LookupPort(ctx, "tcp", port)
|
|
if err != nil {
|
|
return "", "", errors.Wrapf(err, "resolving up port: %v", port)
|
|
}
|
|
port = strconv.Itoa(portNumber)
|
|
|
|
// Resolve the address.
|
|
if host == "" || host == "localhost" {
|
|
return host, port, nil
|
|
}
|
|
|
|
addr, err := lookupAddr(ctx, resolver, host)
|
|
if err != nil {
|
|
return "", "", errors.Wrap(err, "looking up address")
|
|
}
|
|
return addr, port, nil
|
|
}
|
|
|
|
// lookupAddr resolves the given address/host to an IP address. If
|
|
// multiple addresses are resolved, it returns the first IPv4 address
|
|
// available if there is one, otherwise the first address.
|
|
func lookupAddr(ctx context.Context, resolver *net.Resolver, host string) (string, error) {
|
|
// Resolve the IP address or hostname to an IP address.
|
|
addrs, err := resolver.LookupIPAddr(ctx, host)
|
|
if err != nil {
|
|
return "", errors.Wrap(err, "looking up IP addresses")
|
|
}
|
|
if len(addrs) == 0 {
|
|
return "", fmt.Errorf("cannot resolve %q to an address", host)
|
|
}
|
|
|
|
// LookupIPAddr() can return a mix of IPv6 and IPv4
|
|
// addresses. Return the first IPv4 address if possible.
|
|
for _, addr := range addrs {
|
|
if ip := addr.IP.To4(); ip != nil {
|
|
return ip.String(), nil
|
|
}
|
|
}
|
|
|
|
// No IPv4 address, return the first resolved address instead.
|
|
return addrs[0].String(), nil
|
|
}
|
|
|
|
func (c *Config) ValidateAuth() (errors []error) {
|
|
if !c.Auth.Enable {
|
|
return
|
|
}
|
|
authConfig := []struct {
|
|
name string
|
|
val string
|
|
}{
|
|
{name: "ClientId", val: c.Auth.ClientId},
|
|
{name: "ClientSecret", val: c.Auth.ClientSecret},
|
|
{name: "AuthorizeURL", val: c.Auth.AuthorizeURL},
|
|
{name: "TokenURL", val: c.Auth.TokenURL},
|
|
{name: "GroupEndpointURL", val: c.Auth.GroupEndpointURL},
|
|
{name: "RedirectBaseURL", val: c.Auth.RedirectBaseURL},
|
|
{name: "LogoutURL", val: c.Auth.LogoutURL},
|
|
{name: "SecretKey", val: c.Auth.SecretKey},
|
|
}
|
|
|
|
for _, configOpt := range authConfig {
|
|
name := configOpt.name
|
|
value := configOpt.val
|
|
if value == "" {
|
|
errors = append(errors, fmt.Errorf("empty string for auth config %s", name))
|
|
continue
|
|
}
|
|
|
|
if name == "SecretKey" {
|
|
if len(value) != 64 {
|
|
errors = append(errors, fmt.Errorf("invalid key length for %s. exp %d, got %d", name, 64, len(value)))
|
|
}
|
|
}
|
|
|
|
if strings.Contains(name, "URL") {
|
|
_, err := url.ParseRequestURI(value)
|
|
if err != nil {
|
|
errors = append(errors, fmt.Errorf("invalid URL for auth config %s: %s", name, err))
|
|
continue
|
|
}
|
|
}
|
|
}
|
|
|
|
if len(c.Auth.Scopes) == 0 {
|
|
errors = append(errors, fmt.Errorf("must provide scope for authentication with IdP - for access and refresh token"))
|
|
}
|
|
|
|
if len(c.Auth.ConfiguredIPs) > 0 {
|
|
for _, IP := range c.Auth.ConfiguredIPs {
|
|
if strings.Contains(IP, ":") {
|
|
errors = append(errors, fmt.Errorf("port is not allowed in IP %v for auth.configured-ips", IP))
|
|
continue
|
|
}
|
|
if IP == "" {
|
|
errors = append(errors, fmt.Errorf("empty string for auth.configured-ips"))
|
|
continue
|
|
}
|
|
if strings.Contains(IP, "localhost") {
|
|
errors = append(errors, fmt.Errorf("%v is not a valid IP for auth.configured-ips, DNS names are not allowed", IP))
|
|
continue
|
|
}
|
|
if strings.EqualFold(IP, "0.0.0.0") {
|
|
errors = append(errors, fmt.Errorf("%v is not a valid IP for auth.configured-ips", IP))
|
|
continue
|
|
}
|
|
// validate CIDR addresses
|
|
if strings.Contains(IP, "/") {
|
|
if _, _, err := net.ParseCIDR(IP); err != nil {
|
|
errors = append(errors, fmt.Errorf("%v is not a valid IP for auth.configured-ips: %v", IP, err))
|
|
continue
|
|
}
|
|
continue
|
|
}
|
|
// validate IP
|
|
if net.ParseIP(IP) == nil {
|
|
errors = append(errors, fmt.Errorf("%v is not a valid IP for auth.configured-ips", IP))
|
|
continue
|
|
}
|
|
}
|
|
}
|
|
return errors
|
|
}
|
|
|
|
func (c *Config) ValidatePermissions(permsFile io.Reader) (errors []error) {
|
|
var p authz.GroupPermissions
|
|
if err := p.ReadPermissionsFile(permsFile); err != nil {
|
|
return append(errors, err)
|
|
}
|
|
|
|
if len(p.Permissions) == 0 {
|
|
return append(errors, fmt.Errorf("no group permissions found in permissions file: %s", c.Auth.PermissionsFile))
|
|
}
|
|
|
|
for groupId, indexPerm := range p.Permissions {
|
|
if groupId == "" {
|
|
errors = append(errors, fmt.Errorf("empty string for group id in permissions file %s", c.Auth.PermissionsFile))
|
|
continue
|
|
}
|
|
|
|
for index, perm := range indexPerm {
|
|
if index == "" {
|
|
errors = append(errors, fmt.Errorf("empty string for index for group id %s in permissions file %s ", groupId, c.Auth.PermissionsFile))
|
|
continue
|
|
}
|
|
|
|
if perm == "" {
|
|
errors = append(errors, fmt.Errorf("empty string for permission for group id %s and index %s in permissions file %s", groupId, index, c.Auth.PermissionsFile))
|
|
continue
|
|
}
|
|
|
|
if !((perm == "write") || (perm == "read")) {
|
|
errors = append(errors, fmt.Errorf("not a valid permission %s for group id %s and index %s in permissions file %s; expected permissions are read or write", perm, groupId, index, c.Auth.PermissionsFile))
|
|
continue
|
|
}
|
|
}
|
|
}
|
|
|
|
if p.Admin == "" {
|
|
errors = append(errors, fmt.Errorf("empty string for admin in permissions file: %s", c.Auth.PermissionsFile))
|
|
}
|
|
|
|
return errors
|
|
}
|
|
|
|
func (c *Config) ValidatePermissionsFile() (err error) {
|
|
if c.Auth.PermissionsFile == "" {
|
|
return fmt.Errorf("empty string for auth config permissions file")
|
|
}
|
|
|
|
fileExt := filepath.Ext(c.Auth.PermissionsFile)
|
|
if (fileExt != ".yaml") && (fileExt != ".yml") {
|
|
return fmt.Errorf("invalid file extension for auth config permissions file: %s", c.Auth.PermissionsFile)
|
|
}
|
|
return
|
|
}
|
|
|
|
func (c *Config) MustValidateAuth() {
|
|
errorsAuth := c.ValidateAuth()
|
|
if len(errorsAuth) > 0 {
|
|
for _, e := range errorsAuth {
|
|
log.Println(e)
|
|
}
|
|
}
|
|
|
|
var errorsPerm []error
|
|
errorsPermFile := c.ValidatePermissionsFile()
|
|
if errorsPermFile == nil {
|
|
permsFile, err := os.Open(c.Auth.PermissionsFile)
|
|
if err != nil {
|
|
log.Println(err)
|
|
}
|
|
|
|
defer permsFile.Close()
|
|
|
|
errorsPerm = c.ValidatePermissions(permsFile)
|
|
if len(errorsPerm) > 0 {
|
|
for _, e := range errorsPerm {
|
|
log.Println(e)
|
|
}
|
|
}
|
|
|
|
} else {
|
|
log.Println(errorsPermFile)
|
|
}
|
|
|
|
if len(errorsAuth) > 0 || len(errorsPerm) > 0 || errorsPermFile != nil {
|
|
log.Fatal(fmt.Errorf("there were errors validating authN/authZ config and/or permissions"))
|
|
}
|
|
}
|