dsmapper

package
v0.0.0-...-7fe318e Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 26, 2024 License: Apache-2.0 Imports: 22 Imported by: 2

Documentation

Overview

Package dsmapper implements a simple Datastore mapper.

It provides a way to apply some function to all datastore entities of some particular kind, in parallel, but with bounded concurrency (to avoid burning through all CPU/Datastore quota at once). This may be useful when examining or mutating large amounts of datastore entities.

It works by splitting the range of keys into N shards, and launching N worker tasks that each sequentially processes a shard assigned to it, slice by slice.

Index

Constants

This section is empty.

Variables

View Source
var Default = Controller{}

Default is a controller initialized by the server module.

View Source
var ErrNoSuchJob = errors.New("no such mapping job", tq.Fatal)

ErrNoSuchJob is returned by GetJob if there's no Job with requested ID.

View Source
var ModuleName = module.RegisterName("go.chromium.org/luci/server/dsmapper")

ModuleName can be used to refer to this module when declaring dependencies.

Functions

func NewModule

func NewModule(opts *ModuleOptions) module.Module

NewModule returns a server module that initializes Default controller.

func NewModuleFromFlags

func NewModuleFromFlags() module.Module

NewModuleFromFlags is a variant of NewModule that initializes options through command line flags.

Calling this function registers flags in flag.CommandLine. They are usually parsed in server.Main(...).

func RegisterFactory

func RegisterFactory(id ID, m Factory)

RegisterFactory adds the given mapper factory to the internal registry.

See Controller.RegisterFactory for details.

Types

type Controller

type Controller struct {
	// MapperQueue is a name of the Cloud Tasks queue to use for mapping jobs.
	//
	// This queue will perform all "heavy" tasks. It should be configured
	// appropriately to allow desired number of shards to run in parallel.
	//
	// For example, if the largest submitted job is expected to have 128 shards,
	// max_concurrent_requests setting of the mapper queue should be at least 128,
	// otherwise some shards will be stalled waiting for others to finish
	// (defeating the purpose of having large number of shards).
	//
	// If empty, "default" is used.
	MapperQueue string

	// ControlQueue is a name of the Cloud Tasks queue to use for control signals.
	//
	// This queue is used very lightly when starting and stopping jobs (roughly
	// 2*Shards tasks overall per job). A default queue.yaml settings for such
	// queue should be sufficient (unless you run a lot of different jobs at
	// once).
	//
	// If empty, "default" is used.
	ControlQueue string
	// contains filtered or unexported fields
}

Controller is responsible for starting, progressing and finishing mapping jobs.

It should be treated as a global singleton object. Having more than one controller in the production application is a bad idea (they'll collide with each other since they use global datastore namespace). It's still useful to instantiate multiple controllers in unit tests.

func (*Controller) AbortJob

func (ctl *Controller) AbortJob(ctx context.Context, id JobID) (job *Job, err error)

AbortJob aborts a job and returns its most recent state.

Silently does nothing if the job is finished or already aborted.

Returns ErrNoSuchJob is there's no such job at all. All other possible errors are transient and they are marked as such.

func (*Controller) GetJob

func (ctl *Controller) GetJob(ctx context.Context, id JobID) (*Job, error)

GetJob fetches a previously launched job given its ID.

Returns ErrNoSuchJob if not found. All other possible errors are transient and they are marked as such.

func (*Controller) Install

func (ctl *Controller) Install(disp *tq.Dispatcher)

Install registers task queue task handlers in the given task queue dispatcher.

This must be done before Controller is used.

There can be at most one Controller installed into an instance of TQ dispatcher. Installing more will cause panics.

If you need multiple different controllers for some reason, create multiple tq.Dispatchers (with different base URLs, so they don't conflict with each other) and install them all into the router.

func (*Controller) LaunchJob

func (ctl *Controller) LaunchJob(ctx context.Context, j *JobConfig) (JobID, error)

LaunchJob launches a new mapping job, returning its ID (that can be used to control it or query its status).

Launches a datastore transaction inside.

func (*Controller) RegisterFactory

func (ctl *Controller) RegisterFactory(id ID, m Factory)

RegisterFactory adds the given mapper factory to the internal registry.

Intended to be used during init() time or early during the process initialization. Panics if a factory with such ID has already been registered.

The mapper ID will be used internally to identify which mapper a job should be using. If a factory disappears while the job is running (e.g. if the service binary is updated and new binary doesn't have the mapper registered anymore), the job ends with a failure.

type Factory

type Factory func(ctx context.Context, j *Job, shardIdx int) (Mapper, error)

Factory knows how to construct instances of Mapper.

Factory is supplied by the users of the library and registered in the controller via RegisterFactory call.

It is used to get a mapper to process a set of pages within a shard. It takes a Job (including its Config and Params) and a shard index, so it can prepare the mapper for processing of this specific shard.

Returning a transient error triggers an eventual retry. Returning a fatal error causes the shard (eventually the entire job) to be marked as failed.

type ID

type ID string

ID identifies a mapper registered in the controller.

It will be passed across processes, so all processes that execute mapper jobs should register same mappers under same IDs.

The safest approach is to keep mapper IDs in the app unique, e.g. do NOT reuse them when adding new mappers or significantly changing existing ones.

type Job

type Job struct {

	// ID is auto-generated unique identifier of the job.
	ID JobID `gae:"$id"`
	// Config is the configuration of this job. Doesn't change once set.
	Config JobConfig `gae:",noindex"`
	// State is used to track job's lifecycle, see the enum.
	State dsmapperpb.State
	// Created is when the job was created, FYI.
	Created time.Time
	// Updated is when the job was last touched, FYI.
	Updated time.Time
	// contains filtered or unexported fields
}

Job is datastore representation of a mapping job (either active or not).

It is a root entity with autogenerated key.

Use Controller and Job methods to work with jobs. Attempting to use datastore API directly results in an undefined behavior.

func (*Job) FetchInfo

func (j *Job) FetchInfo(ctx context.Context) (*dsmapperpb.JobInfo, error)

FetchInfo fetches information about the job (including all shards).

type JobConfig

type JobConfig struct {
	Query      Query  // a query identifying a set of entities
	Mapper     ID     // ID of a registered mapper to apply to entities
	Params     []byte // arbitrary user-provided data to pass to the mapper
	ShardCount int    // number of shards to split the key range into
	PageSize   int    // how many entities to process at once in each shard

	// PagesPerTask is how many pages (each of PageSize entities) to process
	// inside a TQ task.
	//
	// Default is unlimited: process until the deadline.
	PagesPerTask int

	// TaskDuration is how long to run a single mapping TQ task before
	// checkpointing the state and launching the next mapping TQ task.
	//
	// Small values (e.g. 1 min) makes each processing TQ task relatively small,
	// so it doesn't eat a lot of memory, or produces gigantic unreadable logs.
	// It also makes TQ's "Pause queue" button more handy.
	//
	// Default is 1 min.
	TaskDuration time.Duration

	// TrackProgress enables calculating number of entities per shard before
	// launching mappers, and using it to calculate completion ETA.
	//
	// May be VERY slow if processing large amount of entities. Slowness manifests
	// as a delay between job's launch and it actual start of shards processing.
	//
	// Enable only if shards are relatively small (< 100K entities per shard).
	TrackProgress bool
}

JobConfig defines what a new mapping job should do.

It should be supplied by the users of the mapper library.

func (*JobConfig) Validate

func (jc *JobConfig) Validate() error

Validate returns an error of the config is invalid.

Mapper existence is not checked.

type JobID

type JobID int64

JobID identifies a mapping job.

func LaunchJob

func LaunchJob(ctx context.Context, j *JobConfig) (JobID, error)

LaunchJob launches a new mapping job, returning its ID.

See Controller.LaunchJob for details.

type Mapper

type Mapper func(ctx context.Context, keys []*datastore.Key) error

Mapper applies some function to the given slice of entities, given by their keys.

May be called multiple times for same key (thus should be idempotent).

Returning a transient error indicates that the processing of this batch of keys should be retried (even if some keys were processed successfully).

Returning a fatal error causes the entire shard (and eventually the entire job) to be marked as failed. The processing of the failed shard stops right away, but other shards are kept running until completion (or their own failure).

The function is called outside of any transactions, so it can start its own if needed.

type ModuleOptions

type ModuleOptions struct {
	// MapperQueue is a name of the Cloud Tasks queue to use for mapping jobs.
	//
	// This queue will perform all "heavy" tasks. It should be configured
	// appropriately to allow desired number of shards to run in parallel.
	//
	// For example, if the largest submitted job is expected to have 128 shards,
	// max_concurrent_requests setting of the mapper queue should be at least 128,
	// otherwise some shards will be stalled waiting for others to finish
	// (defeating the purpose of having large number of shards).
	//
	// If empty, "default" is used.
	MapperQueue string

	// ControlQueue is a name of the Cloud Tasks queue to use for control signals.
	//
	// This queue is used very lightly when starting and stopping jobs (roughly
	// 2*Shards tasks overall per job). A default queue.yaml settings for such
	// queue should be sufficient (unless you run a lot of different jobs at
	// once).
	//
	// If empty, "default" is used.
	ControlQueue string
}

ModuleOptions contain configuration of the dsmapper server module.

func (*ModuleOptions) Register

func (o *ModuleOptions) Register(f *flag.FlagSet)

Register registers the command line flags.

type Query

type Query struct {
	Kind     string         // entity kind to limit the query, "" for kindless
	Ancestor *datastore.Key // entity group to limit the query to (or nil)
}

Query is a representation of datastore queries supported by the mapper.

A query defines a set of entities the mapper operates on.

This struct can be embedded into entities as is.

func (*Query) ToDatastoreQuery

func (q *Query) ToDatastoreQuery() *datastore.Query

ToDatastoreQuery returns corresponding datastore.Query.

Directories

Path Synopsis
Package dsmapperlite implements an in-process datastore mapper.
Package dsmapperlite implements an in-process datastore mapper.
internal
splitter
Package splitter implements SplitIntoRanges function useful when splitting large datastore queries into a bunch of smaller queries with approximately evenly-sized result sets.
Package splitter implements SplitIntoRanges function useful when splitting large datastore queries into a bunch of smaller queries with approximately evenly-sized result sets.
tasks
Package tasks contains definition of task queue tasks used by the mapper.
Package tasks contains definition of task queue tasks used by the mapper.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL