Documentation
¶
Overview ¶
Package importer imports a CSV or native artifact written by data export into a cluster: it checks the artifact, compares its schema with the target, decides which units and sources to push and renders that decision.
Index ¶
- Constants
- func ApplyRowCheck(p *Plan, rc *RowCheck, batchBytes uint64)
- func AwaitSchema(ctx context.Context, conn *grpc.ClientConn, ...) error
- func CheckResume(sources config.Sources, opts *config.Import) error
- func ComparePlans(a, b *Plan) []string
- func CumulativeTTL(ro *commonv1.ResourceOpts, stage string) (time.Duration, error)
- func NonEmptyFromPlan(groups []string, frames []*transferv1.UnitFrame, unreachable []string) map[string]NonEmptyState
- func PrepareForWrite(m proto.Message) proto.Message
- func ProgressPath(opts config.Import) string
- func Render(w io.Writer, format string, p *Plan) error
- func VerifySelectors(entries []Entry) []*transferv1.Selector
- func WorkerCount(parallelism int, entries []Entry) (int, string)
- func WriteSchema(ctx context.Context, conn *grpc.ClientConn, writes []SchemaAction, ...) (*schemav1.AwaitSchemaAppliedRequest, error)
- type Artifact
- type BadRow
- type CountKey
- type Counts
- type DiffClass
- type Disposition
- type Entry
- type Env
- type FieldDiff
- type Flags
- type Header
- type InflightView
- type Inputs
- type ItemView
- type MultiSourceDecision
- type NonEmptyState
- type Plan
- type PlannedItemView
- type ProgressView
- type PushKey
- type PushOptions
- type PushResult
- type Rejection
- type ResourceKey
- type Result
- type ResumedProgress
- type RouteKey
- type RowCheck
- type RowCountView
- type RowPos
- type SchemaAction
- type SchemaDiff
- type SchemaOptions
- type Schemas
- type Selection
- type SourceDecision
- type SourceInput
- type TargetState
- type VerifyOptions
- type VerifyReport
- type WorkItem
- func (w *WorkItem) CatalogName() string
- func (w *WorkItem) DisplayRange() (lo, hi int64)
- func (w *WorkItem) Key() string
- func (w *WorkItem) Rows() uint64
- func (w *WorkItem) SourceInputs() []SourceInput
- func (w *WorkItem) TimeRange() (lo, hi int64)
- func (w *WorkItem) WithSources(nodes []string) WorkItem
- type WorkItemKind
- type WorkSource
Constants ¶
const ( GateSchema = "SCHEMA" GateTTL = "TTL" GateCoverage = "COVERAGE" // GateRoute refuses a work item whose target route cannot be written to. GateRoute = "ROUTE" // GateRows refuses a work item with rows the liaison would refuse. GateRows = "ROWS" )
The gates that reject a work item.
const ( // GateTopology refuses a native work item whose target shard number or segment interval // differs from the source's. GateTopology = "TOPOLOGY" // GateTimezone refuses a native work item whose target data nodes run in another time zone // than the source node, which would cut segments at other boundaries. GateTimezone = "TZ" // GateVersion refuses a native work item whose segment file format the target data nodes // cannot read. GateVersion = "VERSION" // GateIndexRule refuses a native work item of a group whose index rule has another id on // the target: the index files key the stored tag values by the rule id, so they would be // unreadable there. GateIndexRule = "INDEX_RULE" )
The gates only a native artifact passes through: its part files are placed as they are, so the target must lay data out exactly as the source did and be able to read the files.
const ( // ReasonGap: the source covers time no earlier choice covers. ReasonGap = "gap" // ReasonSubset: one chosen source covers the source's time and the counts agree. ReasonSubset = "subset" // ReasonCountSpread: covered by a chosen source whose row count differs too much; pushed too. ReasonCountSpread = "count-spread" // ReasonNoSingleCovering: covered only by several chosen sources together; pushed too. ReasonNoSingleCovering = "no-single-covering" // ReasonEmpty: the source has no rows or no parts. ReasonEmpty = "empty" // ReasonUnusableRange: some part has no usable time range, so every source is pushed. ReasonUnusableRange = "unusable-range" // ReasonAllSources: --all-sources pushes every source. ReasonAllSources = "all-sources" )
The reasons of a source decision.
const ( // ProgressFileName is the default progress file of an import, below its artifact directory; // --checkpoint names another path, such as one per target cluster. ProgressFileName = ".import-progress.json" )
Variables ¶
This section is empty.
Functions ¶
func ApplyRowCheck ¶
ApplyRowCheck records rc in the plan: the work items with failing rows move to Rejected (gate ROWS) with the first failing rows and the totals as gate details, rows larger than --write-batch-bytes give one warning, and so does a --write-batch-bytes whose full batches the liaison's default receive limit refuses.
func AwaitSchema ¶
func AwaitSchema(ctx context.Context, conn *grpc.ClientConn, req *schemav1.AwaitSchemaAppliedRequest, timeout time.Duration) error
AwaitSchema blocks until every key of req is applied on every node (SchemaBarrierService), or timeout elapses: a timeout or failure is a runtime error (exit 3) naming the laggards. The keys are awaited in requests of at most awaitSchemaMaxKeys keys that share timeout.
func CheckResume ¶
CheckResume refuses, before anything is contacted, a --checkpoint that cannot be a progress file: a directory, such as the artifact directory itself, a file of the artifact, which --restart would move aside, or a name that ends in that of a side file ("-plan.json", "-cursor.json"). Every failure is a usage error (exit 1). A schema-only import uses no progress file and is not checked.
func ComparePlans ¶
ComparePlans lists how b differs from a in what is pushed where and what the gates refuse; the schema dispositions are not compared, since a CREATE becomes OK once written. An entry whose route was unknown (a group the import creates or overwrites, routed only once written) prints copies=? nodes=?, which match any copies and nodes of the same entry in the other plan.
func CumulativeTTL ¶
CumulativeTTL is the retention of a group's stage the way a data node of that stage resolves it (pub.ResolveStageResourceOpts): the group ttl plus the ttl of every lifecycle stage up to and including the named one, matched case-insensitively. The default stage ("" or "hot" without a stage of that name) has the group ttl only. A stage the group lacks is an error.
func NonEmptyFromPlan ¶
func NonEmptyFromPlan(groups []string, frames []*transferv1.UnitFrame, unreachable []string) map[string]NonEmptyState
NonEmptyFromPlan derives the NonEmptyState of groups from a Plan of them: a group is non-empty when any of its shards reports total_count or parts_count above zero, its segment level reports documents, or a property shard reports documents. Every group is unknown when some node was unreachable, since that node's data is not counted.
func PrepareForWrite ¶
PrepareForWrite returns a copy of a schema resource without updated_at, created_at and Metadata.{create_revision, mod_revision}, so the registry stamps them anew; Metadata.id is kept, except an index rule's: it keys the rule's indexed fields, so the registry keeps the target's id on an update and derives it from group and name on a create.
func ProgressPath ¶
ProgressPath is the progress file of an import: --checkpoint, or ProgressFileName below the artifact directory.
func Render ¶
Render writes the plan as json, yaml or, for any other format, a table; RunImport validates the format. The output depends only on the plan, so a dry run and the real run print the same bytes.
func VerifySelectors ¶
func VerifySelectors(entries []Entry) []*transferv1.Selector
VerifySelectors narrows a Plan to the groups the entries import.
func WorkerCount ¶
WorkerCount is the effective number of push workers for entries: max is the number of distinct target data nodes of the entries, an explicit count is kept; either is clamped to the number of work items. The reason explains the value for the operator.
func WriteSchema ¶
func WriteSchema(ctx context.Context, conn *grpc.ClientConn, writes []SchemaAction, art *Schemas, keepIndexRuleIDs bool, ) (*schemav1.AwaitSchemaAppliedRequest, error)
WriteSchema creates or updates every resource of writes, in their (dependency) order, and returns the barrier request that waits for all of them, at the revision the registry answered, plus the _top_n_result of every measure group it creates when the artifact has one in that group (the target creates it asynchronously). A resource created by someone else since the comparison makes Create fail with ALREADY_EXISTS; that and every other failure is a runtime error (exit 3): earlier resources stay written. With keepIndexRuleIDs, an index rule is created with the artifact's id instead of one the target assigns: native index files key their stored fields by the rule id.
Types ¶
type Artifact ¶
type Artifact struct {
Manifest *manifest.Manifest
Schemas
Dir string
// Warnings are the schema fields this importer does not know, found by a strict decode.
Warnings []string
}
Artifact is an opened, checked CSV or native artifact with its decoded schema.
func OpenArtifact ¶
OpenArtifact reads and checks the artifact at dir: manifest.json must exist, the format must be csv or native and artifactVersion at most manifest.ArtifactVersion; every schema file must exist with the registered size and CRC-32, and every data file with the registered size and, when verifyData is set, CRC-32; the containers of a native artifact must open as complete volume sets with the registered entry counts, and with verifyData every volume is verified whole, member checksums included. Any failure is a preflight rejection. An artifact exported without its schema knows only its groups, from the manifest; its CSV columns are read with the target's schema. The schema files are decoded strictly first, so unknown fields become warnings, then leniently. A canceled ctx stops the checksum pass and maps to the exit code of the cancellation.
type BadRow ¶
type BadRow struct {
Item string `json:"item"`
File string `json:"file"`
Reason string `json:"reason"`
Record uint64 `json:"record"`
}
BadRow is a row the liaison would refuse.
type CountKey ¶
type CountKey struct {
Group string
Stage string
Node string
Catalog commonv1.Catalog
Shard uint32
}
CountKey keys a count of the target: one node's shard of a (catalog, group, stage). Stage is the lower-case stage ("hot" for the default) and "" for property; Shard is 0 for the segment-level (index-mode) documents.
type Counts ¶
type Counts struct {
// Shards are the rows (total_count) of every segment, keyed by segment suffix.
Shards map[CountKey]map[string]int64
// Segments are the segment-level (index-mode) documents of every segment.
Segments map[CountKey]map[string]int64
// Properties are the documents of every property group, summed over its shards and nodes;
// they include superseded revisions and tombstones. Only known when PropertiesCounted is set
// (not by a baseline recorded before they were counted).
Properties map[string]int64
// Unreachable are the nodes the Plan could not count.
Unreachable []string
// Answered are the nodes the Plan counted; nil when not known (a baseline recorded without
// it). A node in neither list was not asked: the liaison does not know it.
Answered []string
PropertiesCounted bool
}
Counts is what a Plan of the imported groups counted on the target.
func CountsFromPlan ¶
func CountsFromPlan(result *cluster.PlanResult) *Counts
CountsFromPlan folds a Plan's frames into Counts.
func Snapshot ¶
func Snapshot(ctx context.Context, conn *grpc.ClientConn, selectors []*transferv1.Selector) (*Counts, error)
Snapshot counts the given groups on the target with one Plan without a session.
type DiffClass ¶
type DiffClass string
DiffClass classifies a field difference.
type Disposition ¶
type Disposition string
Disposition is what the import does with one schema resource.
const ( DispositionOK Disposition = "OK" DispositionCreate Disposition = "CREATE" DispositionConflict Disposition = "CONFLICT" DispositionIgnore Disposition = "IGNORE" DispositionOverwrite Disposition = "OVERWRITE" DispositionInvalid Disposition = "INVALID" DispositionMissing Disposition = "MISSING" )
The schema dispositions.
func (Disposition) Blocking ¶
func (d Disposition) Blocking() bool
Blocking reports whether the disposition refuses the whole import.
type Entry ¶
type Entry struct {
// TargetStage is the lower-case stage the rows go to; "" for property.
TargetStage string `json:"targetStage"`
// TargetNodes are the distinct data nodes of the target route, sorted.
TargetNodes []string `json:"targetNodes"`
// Item holds only the chosen sources.
Item WorkItem `json:"item"`
Copies uint32 `json:"copies"`
// TTLExpired marks an item the TTL gate would reject and --force-ttl let through.
TTLExpired bool `json:"ttlExpired,omitempty"`
}
Entry is a work item the import pushes. Its JSON form adds the key and rows of the item.
func (Entry) MarshalJSON ¶
MarshalJSON renders the entry with the key and rows of its item.
type Env ¶
type Env struct {
// Log receives the information, warnings, progress and a verify report that passes, Out the
// plan; with a table output both are stdout, with json or yaml Log is stderr and Out stays the
// rendering. Err receives what explains a failure before its error, such as the work items an
// interrupted push left and a verify report that fails or was interrupted (stderr), Log when
// nil.
Log io.Writer
Out io.Writer
Err io.Writer
// Hints receives the lines about the connection and the settings in use (info, parallelism,
// rate limits), Log when nil: a structured rendering of the plan leaves them out.
Hints io.Writer
Cluster *cluster.Info
Liaisons *cluster.Liaisons
// Hook, when set, is called after every acknowledged batch (see PushOptions.Hook).
Hook func(event string)
// Now is the reference time of the TTL gate; nil uses time.Now.
Now func() time.Time
// Terminal reports the size of the terminal Log is, nil when it is not one: the push then
// redraws a live line per group in place.
Terminal func() (width, height int)
// Confirm asks the operator a yes/no question; nil when stdin is not a terminal or none of the
// streams it can ask on is, and a progress file then needs --resume. The question goes to Log's
// stream when that is a terminal (stdout, or stderr with json or yaml output); otherwise to
// stderr when that is one, after the lines written so far are shown there too.
Confirm func(ctx context.Context, question string) bool
// DuplicationSource names where resumeDuplicationPolicy was set, for the messages: the flag,
// the plan file, the variable or "default"; "" is taken as the flag.
DuplicationSource string
// VerifyExplicit records that --verify was given on the command line: only then is a finished
// import verified again. plan.yaml and BYDBCTL_IMPORT_VERIFY set a default, not a request.
VerifyExplicit bool
// ResumeFromEnv records that --resume came from BYDBCTL_IMPORT_RESUME, not the flag: it
// resumes a progress file without asking when there is one, and starts a fresh import when
// there is none, where the flag exits 1.
ResumeFromEnv bool
}
Env is what RunImport works with besides the settings: where it prints, what the preflight learned and the liaison connections.
type FieldDiff ¶
type FieldDiff struct {
Path string `json:"path"`
Class DiffClass `json:"class"`
Artifact string `json:"artifact"`
Target string `json:"target"`
}
FieldDiff is one differing field of a resource.
func DiffFields ¶
DiffFields lists the differing fields of two resources of a kind, ignoring updated_at, created_at, Metadata.{id, create_revision, mod_revision} and unknown fields, each with its class. artifact and target must be of the same message type.
type Flags ¶
type Flags struct {
ForceTTL bool
AllSources bool
StrictCoverage bool
// SchemaOnly writes the schema only, so the data gates refuse nothing.
SchemaOnly bool
}
Flags are the command flags that change the decision.
type Header ¶
type Header struct {
Endpoint string `json:"endpoint"`
Input string `json:"input"`
Format string `json:"format"`
ExportedAt string `json:"exportedAt"`
ArtifactVersion int `json:"artifactVersion"`
DataNodes int `json:"dataNodes"`
Standalone bool `json:"standalone"`
}
Header describes the target and the artifact.
type InflightView ¶
type InflightView struct {
Key string
Rows uint64
// Part tells a part from the other payloads.
Part bool
}
InflightView is a native payload sent and not answered.
type Inputs ¶
type Inputs struct {
// Now is the reference time of the TTL gate; it never shows in the output.
Now time.Time
Artifact *Artifact
// Target is the predicted target (PredictState): groups to be created carry the artifact's spec.
Target *TargetState
// Endpoint names the liaison for the header, e.g. "liaison-dst:17912 (ROLE_LIAISON)".
Endpoint string
// TargetIndexRuleIDs are the ids of the index rules the target holds before the schema
// write; a native import needs the artifact's ids.
TargetIndexRuleIDs map[ResourceKey]uint32
Actions []SchemaAction
Flags Flags
}
Inputs is everything Decide reads.
type ItemView ¶
type ItemView struct {
// SentWindow is how many rows of a started CSV item were sent after its cursor and not
// acknowledged: they may have landed.
SentWindow uint64
Complete bool
// Started tells a CSV item with a cursor that is not complete.
Started bool
}
ItemView is the progress of one work item.
type MultiSourceDecision ¶
type MultiSourceDecision struct {
Key string `json:"key"`
Decisions []SourceDecision `json:"decisions"`
}
MultiSourceDecision is the source selection of a work item with more than one non-empty source.
type NonEmptyState ¶
type NonEmptyState struct {
// Reason explains an unknown state, e.g. "Plan is not available" or "unreachable nodes [a]".
Reason string
// Known is false when the Plan failed or some node was unreachable: an overwrite of the group then needs --force.
Known bool
// NonEmpty is true when any shard reports rows or parts, or any segment or property shard documents.
NonEmpty bool
}
NonEmptyState tells whether a target group holds data, from an ExportService.Plan of it.
type Plan ¶
type Plan struct {
// Resumed is what the progress file records of an earlier run, nil without one; the text
// rendering says what is left of it, the json and yaml renderings show it.
Resumed *ResumedProgress `json:"resumed,omitempty"`
Entries []Entry `json:"entries"`
Rejected []Rejection `json:"rejected"`
MultiSource []MultiSourceDecision `json:"multiSource"`
Schema []SchemaAction `json:"schema"`
// GateDetails explain the work items the gates refuse or let through expired, one line each;
// the schema gate needs none, the schema says why.
GateDetails []string `json:"gateDetails"`
Warnings []string `json:"warnings"`
// Errors are artifact defects that keep the work items from being built; any refuses the import.
Errors []string `json:"errors,omitempty"`
// Blockers are target problems that refuse the whole import, e.g. a liaison without ImportService.
Blockers []string `json:"blockers,omitempty"`
// RowCheck is the result of the read-only row precheck; nil when it did not run.
RowCheck *RowCheck `json:"rowCheck,omitempty"`
Header Header `json:"header"`
// SchemaOnly marks a --schema-only import: only a blocking schema action or an artifact error refuses it.
SchemaOnly bool `json:"schemaOnly,omitempty"`
// contains filtered or unexported fields
}
Plan is the decision of an import: what is pushed where, what is refused and why.
func Decide ¶
Decide is the pure decision of an import. It builds the work items of the artifact, rejects those the schema gate or the TTL gate refuses, selects the sources of the rest and maps each to its target stage, copies and nodes. Output is sorted, so identical inputs give an identical plan whatever the time.
func (*Plan) Refused ¶
Refused reports whether the import must stop before writing anything: a blocking schema action, an artifact error, or, unless only the schema is imported, a target blocker, a rejection by one of the refusingGates, or every work item rejected.
func (*Plan) SchemaBlocked ¶
SchemaBlocked reports whether any schema action refuses the import.
type PlannedItemView ¶
PlannedItemView is a work item as the first run planned it.
type ProgressView ¶
type ProgressView struct {
// FinishedAt is when a run pushed the last work item, nil before.
FinishedAt *time.Time
// Done is the progress of every work item that has any, by work item key.
Done map[string]ItemView
// Inflight is the native payload each worker sent and has no answer for yet.
Inflight map[string]InflightView
// Plan is the plan of the plan side file, none before it is written.
Plan []PlannedItemView
// Pushed are the rows every run put into the target, Duplicates those pushed again that may
// have landed already.
Pushed []RowCountView
Duplicates []RowCountView
// Liaisons and TargetNodes are the target the progress file was written for.
Liaisons []string
TargetNodes []string
}
ProgressView is a read-only view of an import progress file and its side files as a resume reads them, without checking them against an invocation: for tests and checks.
func ReadProgress ¶
func ReadProgress(path string) (*ProgressView, error)
ReadProgress reads the progress file at path with its plan and cursor side files the way a resume does (the cursors of a cursor side file not older than the progress file replace those of the items not complete, and its pushed counts the progress file's), but does not compare its bindings with any target. A missing progress file is an error that wraps os.ErrNotExist, and one a resume refuses as unusable is an error too.
type PushKey ¶
type PushKey struct {
Kind WorkItemKind
// contains filtered or unexported fields
}
PushKey groups the acknowledged rows of the work items of one kind sent to one (catalog, group, target stage); the stage is "" for property.
type PushOptions ¶
type PushOptions struct {
// Log receives warnings and retry notes; Err the work items done and not done of a push that
// fails, Log when nil.
Log io.Writer
Err io.Writer
// Hook, when set, is called on the worker goroutine after every acknowledged batch with
// "batch <work item key> seq=<n> rows=<r>".
Hook func(event string)
// Progress, when set, shows the progress per (catalog, group, target stage).
Progress *output.Progress
// Import holds the batch, rate, retry and parallelism settings; math.MaxInt parallelism
// means max.
config.Import
// contains filtered or unexported fields
}
PushOptions configure Push.
type PushResult ¶
type PushResult struct {
// Rows are the acknowledged rows per key.
Rows map[PushKey]uint64
// Done lists the keys of the work items whose every batch was acknowledged.
Done []string
}
PushResult is what Push sent.
func Push ¶
func Push(ctx context.Context, liaisons []*cluster.Liaison, art *Artifact, target *Schemas, entries []Entry, opts PushOptions) (*PushResult, error)
Push sends the rows of every entry to the liaisons with a pool of workers. Worker i uses liaison i % L and lazily opens one ImportRows stream per (catalog, group, target stage), reused across its work items. After the first exchange of a stream, a worker keeps up to two batches sent and not yet acknowledged on it: it builds and sends the next batch while the liaison works on the previous ones, so a worker holds at most twice --write-batch-bytes of rows. A work item is done once every one of its batches is acknowledged. Only the first exchange of a stream is retried: UNAVAILABLE and load-protection RESOURCE_EXHAUSTED move to the next liaison, SCHEMA_NOT_FOUND (a schema not live yet) waits; each with a back-off within --send-retry-timeout. Any later error ends the import: every worker is canceled and the error, an exit-3 ExitError, lists the work items done and not done. target is the target schema the rows are assembled for.
func PushParts ¶
func PushParts(ctx context.Context, liaisons []*cluster.Liaison, art *Artifact, entries []Entry, opts PushOptions) (*PushResult, error)
PushParts imports the entries of a native artifact: it reads the part files out of the containers of every chosen source and relays them through ImportParts, one payload per part (with its trace secondary index parts), per series index, per element index and per property shard. The series indexes of every segment go first, in a round of their own, so that no part is queryable before the index that names its series; parts, element indexes and property shards follow. Within a round a pool of workers pushes the entries, worker i through liaison i % L. A payload that some target nodes failed is pushed again to those nodes only, up to partRetryAttempts times; one that still misses a node fails the import (exit 3), which lists the work items done and not done. The rows of the parts that landed are counted per (catalog, group, target stage) for verify.
type Rejection ¶
type Rejection struct {
Gate string `json:"gate"`
Reason string `json:"reason"`
TargetStage string `json:"targetStage"`
TargetNodes []string `json:"targetNodes"`
Item WorkItem `json:"item"`
}
Rejection is a work item a gate refused. Its JSON form adds the key and rows of the item.
func (Rejection) MarshalJSON ¶
MarshalJSON renders the rejection with the key and rows of its item.
type ResourceKey ¶
ResourceKey identifies a group-scoped schema resource.
type Result ¶
type Result struct {
// Plan is the plan decided before anything was written, with every work item; the plan
// printed leaves out the items a progress file records as complete.
Plan *Plan
// Recheck is the plan re-decided after the schema write; nil when not reached.
Recheck *Plan
Push *PushResult
Verify *VerifyReport
// PlanChanges are the differences between Plan and Recheck.
PlanChanges []string
// SchemaWrites counts the resources created or updated.
SchemaWrites int
}
Result is what RunImport did; fields after the failing phase stay empty.
func RunImport ¶
RunImport imports the artifact at opts.Input: it checks the artifact, compares the schema with the target, asks Targets, decides and prints the plan. A dry run stops there (exit 0, or 2 when the import would be refused). A real run then writes the schema in dependency order and waits until every node applied it, re-decides and prints what changed (--abort-on-plan-change stops with exit 5), pushes the rows and, with --verify, reconciles the target's counts (exit 4 on a mismatch). Errors before the schema write keep the exit code of their cause (2 for a refusal: nothing was written); errors from the schema write on are exit 3, except a verify failure (4), a plan change (5), a resume refused by a plan that differs from the recorded one (6) and a resume halted by resumeDuplicationPolicy block (7). Once the progress file exists, an exit 3 names it: the same command resumes. Every error is an exitcode.ExitError.
type ResumedProgress ¶
type ResumedProgress struct {
FinishedAt *time.Time `json:"finishedAt,omitempty"`
Path string `json:"path"`
Done int `json:"done"`
Total int `json:"total"`
}
ResumedProgress is what a progress file records: its path, the work items of the plan it records as done, and when the import finished, if it did.
type RouteKey ¶
RouteKey keys a route by group and lower-case target stage ("hot" for the default stage).
func NewRouteKey ¶
NewRouteKey returns the key of a group's stage, lower-casing the stage and mapping "" to "hot".
type RowCheck ¶
type RowCheck struct {
// Bad lists the first rowCheckExamples failing rows by file and record.
Bad []BadRow `json:"bad"`
// BadItems counts the failing rows per work item key.
BadItems map[string]uint64 `json:"badItems"`
// Largest is the largest row.
Largest RowPos `json:"largest"`
// LargestOverBatch is the largest row over --write-batch-bytes, sent in a batch of its own.
LargestOverBatch RowPos `json:"largestOverBatch"`
Rows uint64 `json:"rows"`
BadRows uint64 `json:"badRows"`
OverBatchRows uint64 `json:"overBatchRows"`
Items int `json:"items"`
}
RowCheck is the result of the read-only row precheck of the planned work items.
func CheckRows ¶
func CheckRows(ctx context.Context, art *Artifact, target *Schemas, entries []Entry, batchBytes uint64) (*RowCheck, error)
CheckRows reads every row of every entry, read-only, and assembles it with the row builder of the push for the target schema (the predicted one before the schema write), then applies the checks the liaison applies before writing: a row the liaison would refuse, or too large for its default receive limit, is bad. It records the largest row and the rows over batchBytes. Work items are checked several at a time. An artifact that cannot be laid out is an error; a context error is returned as is.
type RowCountView ¶
RowCountView is a number of rows of one (catalog, group, stage, kind); the catalog is its name, such as "stream".
type RowPos ¶
type RowPos struct {
File string `json:"file"`
Record uint64 `json:"record"`
Bytes int `json:"bytes"`
}
RowPos is a row of the artifact and its size as sent.
type SchemaAction ¶
type SchemaAction struct {
// Spec is the artifact's resource; nil for nothing to write.
Spec proto.Message `json:"-"`
Kind string `json:"kind"`
Group string `json:"group"`
Name string `json:"name,omitempty"`
Disposition Disposition `json:"disposition"`
Reason string `json:"reason,omitempty"`
// Match is the rule match selecting this resource, pasteable into plan.yaml.
Match string `json:"match,omitempty"`
Diffs []FieldDiff `json:"diffs,omitempty"`
// Notes list the per-column consequences of writing the rows under the target schema, for
// an IGNORE or a resource the import does not apply.
Notes []string `json:"notes,omitempty"`
}
SchemaAction is the disposition of one schema resource of the artifact.
func (*SchemaAction) ID ¶
func (a *SchemaAction) ID() string
ID renders the resource as <kind>/<group>[/<name>].
type SchemaDiff ¶
type SchemaDiff struct {
// Actions are in dependency order, then group and name.
Actions []SchemaAction
}
SchemaDiff is the result of DiffSchemas.
func DiffSchemas ¶
func DiffSchemas(art *Schemas, target *TargetState, opts SchemaOptions) *SchemaDiff
DiffSchemas compares every artifact resource with the target and decides its disposition. measure/<group>/_top_n_result is left out of the comparison on both sides: the target creates it with its group, so it is OK, or a CONFLICT when its columns differ from the target's. art is the artifact's schema; target the target's.
func (*SchemaDiff) Writes ¶
func (d *SchemaDiff) Writes() []SchemaAction
Writes returns the CREATE and OVERWRITE actions in dependency order, each Spec cleared by PrepareForWrite.
type SchemaOptions ¶
type SchemaOptions struct {
// Default is the policy (config.ConflictPolicy*) of resources no rule matches; empty means error.
Default string
// Rules override Default for the resources they match, the first match winning.
Rules []config.ConflictRule
// IncludeSchema false compares nothing: a resource the target lacks is MISSING. It is
// false for an artifact exported without its schema.
IncludeSchema bool
// Force lets an overwrite change a group that holds data.
Force bool
}
SchemaOptions configure DiffSchemas.
type Schemas ¶
type Schemas struct {
Groups map[string]*commonv1.Group
Streams map[ResourceKey]*databasev1.Stream
Measures map[ResourceKey]*databasev1.Measure
Traces map[ResourceKey]*databasev1.Trace
Properties map[ResourceKey]*databasev1.Property
IndexRules map[ResourceKey]*databasev1.IndexRule
IndexRuleBindings map[ResourceKey]*databasev1.IndexRuleBinding
TopNs map[ResourceKey]*databasev1.TopNAggregation
}
Schemas holds schema resources: groups by name, every other kind by group and name.
type Selection ¶
type Selection struct {
// Chosen are the nodes to push, in node order.
Chosen []string
// Decisions has one entry per input source, in node order.
Decisions []SourceDecision
// Warnings explain the sources pushed although another source covers them.
Warnings []string
}
Selection is the result of SelectSources.
func AllSources ¶
func AllSources(sources []SourceInput) Selection
AllSources chooses every non-empty source, for --all-sources.
func SelectSources ¶
func SelectSources(catalog commonv1.Catalog, sources []SourceInput) Selection
SelectSources picks the sources of a shard to push. Empty sources are dropped; the rest are sorted by (coverage length, rows, node name) descending and chosen greedily while they cover time the chosen ones do not; a skipped source is pushed too when no single chosen source covers it, or, for stream and trace, when its row count differs from the smallest single covering source by more than 5% and 64 rows. A stream or trace gap source that also overlaps the chosen sources is warned about. A part without a usable time range makes every non-empty source chosen.
type SourceDecision ¶
type SourceDecision struct {
Node string `json:"node"`
// Reason is one of the Reason* constants.
Reason string `json:"reason"`
// Ref is the chosen source a subset or count-spread source was compared with.
Ref string `json:"ref,omitempty"`
Chosen bool `json:"chosen"`
}
SourceDecision is the verdict on one source.
type SourceInput ¶
SourceInput is one source node's copy of a shard.
type TargetState ¶
type TargetState struct {
Schemas
// Routes are the primary liaison's Targets answers keyed by (group, lower-case stage): the
// stage a route reports and, when it differs (a fallback to hot), the stage that was asked for.
Routes map[RouteKey]*transferv1.TargetsResponse
// RouteIssues explain, by the (group, stage) asked for, why a route cannot be written to:
// a routing error, inactive nodes, a group being deleted, or liaisons that disagree.
RouteIssues map[RouteKey]string
// Blockers are target problems that refuse the whole import, e.g. a liaison without ImportService.
Blockers []string
// Notes are warnings found while collecting, e.g. nodes lagging behind the schema revision.
Notes []string
// Info are remarks for the log only, e.g. a skipped barrier probe.
Info []string
// NonEmptyGroups is keyed by group name; a missing group counts as unknown (fail closed).
NonEmptyGroups map[string]NonEmptyState
DataNodes []*databasev1.Node
Standalone bool
}
TargetState is everything the importer read from the target cluster: its schema, the routes of the (group, stage) pairs the import touches, its data nodes and which groups hold data. The runtime fills it; DiffSchemas and Decide only read it.
func Collect ¶
func Collect(ctx context.Context, liaisons []*cluster.Liaison, info *cluster.Info, art *Artifact, opts SchemaOptions) (*TargetState, error)
Collect reads, read-only, everything the import decides on from the target cluster through the liaisons, the first of which is the primary: the schema of every artifact group the target has (all eight kinds); the Targets routes of the (group, stage) pairs the artifact's work items touch in groups the import leaves as they are, asked of every liaison, and the problems of those routes (RouteIssues, Blockers); for every group a resource of which would be overwritten, whether it holds data (a Plan of those groups; a failed Plan leaves them unknown, so overwriting them needs --force); and whether every node has applied the target's current schema revision (a best-effort barrier probe whose laggards become Notes).
func NewTargetState ¶
func NewTargetState() *TargetState
NewTargetState returns a TargetState with every map allocated.
func PredictState ¶
func PredictState(target *TargetState, actions []SchemaAction) *TargetState
PredictState returns the target as it will be once the actions are applied: created and overwritten resources take the artifact's spec, a created group is known to be empty and every measure group without a _top_n_result gets the one the target creates with it. Routes and the collected issues are copied as they are.
type VerifyOptions ¶
type VerifyOptions struct {
// Log receives the poll notes and the report.
Log io.Writer
// Progress, on a terminal, shows what verify waits for in a live line instead of a note
// per poll.
Progress *output.Progress
// Tolerance are the rows a resumed import pushed again although they may have landed
// already, per stream key.
Tolerance map[streamKey]*verifyTolerance
// Sampled are the trace groups whose sampling pipeline may drop spans in merges: their row
// counts cannot be compared, so they are checked partially.
Sampled map[string]bool
// Timeout is --verify-timeout.
Timeout time.Duration
}
VerifyOptions configure Verify.
type VerifyReport ¶
type VerifyReport struct {
Incomplete []string
Mismatches []string
Warnings []string
// Partial are the trace (group, stage)s checked partially because they sample spans in
// merges, so their row counts do not keep every row sent: only the routes, some growth on
// the target nodes and no more growth than the rows sent × copies are checked.
Partial []string
// Elapsed is how long verify took.
Elapsed time.Duration
// contains filtered or unexported fields
}
VerifyReport is the outcome of --verify: checks that could not complete and count mismatches, either of which fails the import (exit 4), and warnings.
func Verify ¶
func Verify(ctx context.Context, conn *grpc.ClientConn, pre *Counts, plan *Plan, routes map[RouteKey]*transferv1.TargetsResponse, pushed map[PushKey]uint64, opts VerifyOptions, ) *VerifyReport
Verify polls a Plan of the imported groups until the counts reconcile with what was sent or the timeout elapses, then reports in three categories. Stream and trace shards must grow by the same amount on exactly their target nodes and sum to the rows sent; measures must first settle across two polls at least a flush interval apart, then grow, by no more than rows × copies, on every target node of a shard that grew; index-mode measures and properties are only reported. Polls are verifyPollInterval (the 5s flush interval) apart, and every poll that does not end the check logs a waiting line. The target must not take other writes meanwhile.
func (*VerifyReport) Failed ¶
func (r *VerifyReport) Failed() bool
Failed reports whether verification fails the import.
func (*VerifyReport) Render ¶
func (r *VerifyReport) Render(w io.Writer)
Render writes the conclusion of the report and every problem it found.
type WorkItem ¶
type WorkItem struct {
Group string `json:"group"`
// Stage is the source stage from the manifest; "" for property.
Stage string `json:"stage"`
Segment string `json:"segment,omitempty"`
// SegmentVersion is the file format version of the source segment; "" for property.
SegmentVersion string `json:"-"`
// Shards are the shards of the unit a segment item's index covers, in any source.
Shards []uint32 `json:"-"`
// Sources are in node name order.
Sources []WorkSource `json:"sources"`
// RowsMinTimestamp and RowsMaxTimestamp are the time range of the unit's rows as the export
// recorded it (manifest unit), shown for a segment item instead of the segment bounds its
// sources carry; 0 when the export recorded none.
RowsMinTimestamp int64 `json:"-"`
RowsMaxTimestamp int64 `json:"-"`
Catalog commonv1.Catalog `json:"-"`
Shard uint32 `json:"shard"`
Kind WorkItemKind `json:"kind"`
// contains filtered or unexported fields
}
WorkItem is the unit of parallel push: a shard of a segment unit, the segment-level files of a segment unit, or a source shard id of a property group.
func BuildWorkItems ¶
BuildWorkItems splits the manifest's units into work items, sorted by key: a segment unit gives one item per shard holding every source's copy of that shard, plus one segment item when any source has segment-level files; a property unit gives one item per source shard id, holding every source's files of that id. The type of an item follows where its files are, not groups[].indexMode, so a group mixing index-mode and regular measures yields both kinds. A segment item's sources span the bounds of their segment, the time range of index-mode rows. Every source of every item is kept: Decide selects among them.
func (*WorkItem) CatalogName ¶
CatalogName is the lower-case catalog name: stream, measure, trace or property.
func (*WorkItem) DisplayRange ¶
DisplayRange is the time range of the item's rows. A segment item's sources carry the segment bounds the push needs, so it reports the unit's recorded range instead, and the segment bounds only when the artifact recorded none (an older export).
func (*WorkItem) Key ¶
Key identifies the item: catalog/group/stage/segment/shard-N, .../segment or property/group/shard-N.
func (*WorkItem) SourceInputs ¶
func (w *WorkItem) SourceInputs() []SourceInput
SourceInputs returns the sources as SelectSources inputs.
func (*WorkItem) TimeRange ¶
TimeRange is the smallest range holding every source's rows; zero when none has a time.
func (*WorkItem) WithSources ¶
WithSources returns a copy of the item holding only the named sources.
type WorkItemKind ¶
type WorkItemKind uint8
WorkItemKind tells which files of a unit a work item pushes.
const ( // ShardItem pushes one shard's files of a segment unit. ShardItem WorkItemKind = iota // SegmentItem pushes the segment-level files of a segment unit: a native segment's series index, // or the index-mode rows of a CSV measure. SegmentItem // PropertyItem pushes one source shard id's files of a property group. PropertyItem )
The work item kinds.
func (WorkItemKind) MarshalText ¶
func (k WorkItemKind) MarshalText() ([]byte, error)
MarshalText renders the kind by name.
func (WorkItemKind) String ¶
func (k WorkItemKind) String() string
String names the kind for json, yaml and messages.
type WorkSource ¶
type WorkSource struct {
// RowCounts are the rows per resource of Files.
RowCounts map[string]uint64 `json:"rowCounts,omitempty"`
Node string `json:"node"`
// Timezone is the IANA time zone of the node at export time.
Timezone string `json:"timezone,omitempty"`
// Files are in artifact path order, which is file sequence order.
Files []manifest.File `json:"files"`
Parts []manifest.Part `json:"-"`
Rows uint64 `json:"rows"`
MinTimestamp int64 `json:"minTimestamp"`
MaxTimestamp int64 `json:"maxTimestamp"`
}
WorkSource is one source node's files of a work item.