Documentation
¶
Index ¶
- Constants
- Variables
- func GenerateUpdatePos(uid int, pos mysql.Position, timeUpdated int64, txTimestamp int64) string
- func GenerateUpdateTime(uid int, timeUpdated int64) (string, error)
- func MessageTruncate(msg string) string
- type Applier
- type ApplierKafka
- func (k *ApplierKafka) ApplyBegin() error
- func (k *ApplierKafka) ApplyCommit() error
- func (k *ApplierKafka) ApplyDDL() error
- func (k *ApplierKafka) ApplyField() error
- func (k *ApplierKafka) ApplyGtid() error
- func (k *ApplierKafka) ApplyHeartbeat() error
- func (k *ApplierKafka) ApplyOther() error
- func (k *ApplierKafka) ApplyRawGtid(ctx context.Context, gtid string) error
- func (k *ApplierKafka) ApplyRow() error
- func (k *ApplierKafka) ApplyStmt() error
- type ApplierMysql
- func (m *ApplierMysql) ApplyBegin() error
- func (m *ApplierMysql) ApplyCommit() error
- func (m *ApplierMysql) ApplyDDL() error
- func (m *ApplierMysql) ApplyField() error
- func (m *ApplierMysql) ApplyGtid() error
- func (m *ApplierMysql) ApplyHeartbeat() error
- func (m *ApplierMysql) ApplyOther() error
- func (m *ApplierMysql) ApplyRawGtid(ctx context.Context, gtid string) error
- func (m *ApplierMysql) ApplyRow() error
- func (m *ApplierMysql) ApplyStmt() error
- type BinlogConnection
- func (bc *BinlogConnection) Close()
- func (bc *BinlogConnection) StartBinlogDumpFromCurrent(ctx context.Context) (mysql.Position, <-chan mysql.BinlogEvent, <-chan error, error)
- func (bc *BinlogConnection) StartBinlogDumpFromPosition(ctx context.Context, startPos mysql.Position) (<-chan mysql.BinlogEvent, <-chan error, error)
- func (bc *BinlogConnection) SwitchOffMasterArg() error
- type ColExpr
- type DBClient
- func (c *DBClient) Begin() error
- func (c *DBClient) Close()
- func (c *DBClient) Commit() error
- func (c *DBClient) Connect() error
- func (c *DBClient) CreateState(source *mysql.ConnParams, dest *mysql.ConnParams, kafkaParams *KafkaParams, ...) (int, error)
- func (c *DBClient) DBName() string
- func (c *DBClient) DeleteTask(ctx context.Context, id int) error
- func (c *DBClient) EndDDL()
- func (c *DBClient) Execute(query string) (*sqltypes.Result, error)
- func (c *DBClient) ExecuteFetch(query string, maxrows int) (*sqltypes.Result, error)
- func (c *DBClient) ExecuteWithRetry(ctx context.Context, query string) (*sqltypes.Result, error)
- func (c *DBClient) GetTask(ctx context.Context, id int) (*sqltypes.Result, error)
- func (c *DBClient) ListLocalTaskIds(addr string) (*sqltypes.Result, error)
- func (c *DBClient) ListLocalTasks(ctx context.Context, addr string) (*sqltypes.Result, error)
- func (c *DBClient) ListTasks(ctx context.Context, perPage, page int) (*sqltypes.Result, error)
- func (c *DBClient) ReadCopyStats(uid int) (int64, error)
- func (c *DBClient) ReadStats(uid int) (mysql.Position, string, bool, error)
- func (c *DBClient) Retry() (*sqltypes.Result, error)
- func (c *DBClient) Rollback() error
- func (c *DBClient) SetMessage(id int, message string) error
- func (c *DBClient) SetNextGtid(ctx context.Context, gtid string) error
- func (c *DBClient) SetState(id int, state, message string) error
- type Filter
- type IDPool
- type KafkaMessage
- type KafkaMessageMaxwell
- type KafkaParams
- type Opcode
- type Plan
- type PrimaryKeyInfo
- type Replicator
- type ReplicatorMode
- type ReplicatorPlan
- type Stats
- type StatsHistoryRecord
- type Table
- type TablePlan
- type TopicMode
Constants ¶
const ( BlplQuery = "Query" BlplTransaction = "Transaction" ReplicationInit = "Init" ReplicationCopying = "Copying" BlpStopped = "Stopped" BlpRunning = "Running" BlpError = "Error" )
const ( PartitionModeColumn = "column" PartitionModeTable = "table" PartitionModePrimaryKey = "primary_key" )
const ( ProducerPartitionByFallbackTable = "table" ProducerPartitionByFallbackPrimaryKey = "primary_key" DefaultProducerPartitionByFallbackTable = ProducerPartitionByFallbackTable )
const ( DestTypeMysql = "mysql" DestTypeKafka = "kafka" SbmPhaseReplay = "replay" SbmPhaseStream = "stream" EventTypeGTID = "gtid" EventTypeXID = "xid" EventTypeQuery = "query" EventTypeTableMap = "tablemap" EventTypeRows = "rows" )
const ( // Equal is used to filter an integer column on a specific value Equal = Opcode(iota) )
const ExcludeStr = "exclude"
ExcludeStr is the filter value for excluding tables that match a rule. TODO(sougou): support this on vstreamer side also.
Variables ¶
var BatchPacketSize = flag.Int("rowstream_packet_size", 250000, "Suggested packet size for Copy Table streamer. This is used only as a recommendation. The actual packet size may be more or less than this amount.")
var HeartbeatTime = 900 * time.Millisecond
HeartbeatTime is set to slightly below 1s, compared to idleTimeout set by player at slightly above 1s. This minimizes conflicts between the two timeouts.
var PacketSize = flag.Int("stream_packet_size", 25, "Suggested packet size for Replication streamer. This is used only as a recommendation. The actual packet size may be more or less than this amount.")
NOTE 经测试,一个包约为250 Bytes左右,kafka类型的可调大,mysql类型的应尽可能调小 FIXME 当前先调小PacketSize,后续增加ap类业务的commit event
Functions ¶
func GenerateUpdatePos ¶
func MessageTruncate ¶
Types ¶
type ApplierKafka ¶
type ApplierKafka struct {
// contains filtered or unexported fields
}
func (*ApplierKafka) ApplyBegin ¶
func (k *ApplierKafka) ApplyBegin() error
func (*ApplierKafka) ApplyCommit ¶
func (k *ApplierKafka) ApplyCommit() error
func (*ApplierKafka) ApplyDDL ¶
func (k *ApplierKafka) ApplyDDL() error
func (*ApplierKafka) ApplyField ¶
func (k *ApplierKafka) ApplyField() error
func (*ApplierKafka) ApplyGtid ¶
func (k *ApplierKafka) ApplyGtid() error
func (*ApplierKafka) ApplyHeartbeat ¶
func (k *ApplierKafka) ApplyHeartbeat() error
func (*ApplierKafka) ApplyOther ¶
func (k *ApplierKafka) ApplyOther() error
func (*ApplierKafka) ApplyRawGtid ¶
func (k *ApplierKafka) ApplyRawGtid(ctx context.Context, gtid string) error
func (*ApplierKafka) ApplyRow ¶
func (k *ApplierKafka) ApplyRow() error
func (*ApplierKafka) ApplyStmt ¶
func (k *ApplierKafka) ApplyStmt() error
type ApplierMysql ¶
type ApplierMysql struct {
// contains filtered or unexported fields
}
func (*ApplierMysql) ApplyBegin ¶
func (m *ApplierMysql) ApplyBegin() error
func (*ApplierMysql) ApplyCommit ¶
func (m *ApplierMysql) ApplyCommit() error
func (*ApplierMysql) ApplyDDL ¶
func (m *ApplierMysql) ApplyDDL() error
func (*ApplierMysql) ApplyField ¶
func (m *ApplierMysql) ApplyField() error
func (*ApplierMysql) ApplyGtid ¶
func (m *ApplierMysql) ApplyGtid() error
func (*ApplierMysql) ApplyHeartbeat ¶
func (m *ApplierMysql) ApplyHeartbeat() error
func (*ApplierMysql) ApplyOther ¶
func (m *ApplierMysql) ApplyOther() error
func (*ApplierMysql) ApplyRawGtid ¶
func (m *ApplierMysql) ApplyRawGtid(ctx context.Context, gtid string) error
func (*ApplierMysql) ApplyRow ¶
func (m *ApplierMysql) ApplyRow() error
func (*ApplierMysql) ApplyStmt ¶
func (m *ApplierMysql) ApplyStmt() error
type BinlogConnection ¶
func NewBinlogConnection ¶
func NewBinlogConnection(cp *mysql.ConnParams) (*BinlogConnection, error)
func (*BinlogConnection) Close ¶
func (bc *BinlogConnection) Close()
func (*BinlogConnection) StartBinlogDumpFromCurrent ¶
func (bc *BinlogConnection) StartBinlogDumpFromCurrent(ctx context.Context) (mysql.Position, <-chan mysql.BinlogEvent, <-chan error, error)
func (*BinlogConnection) StartBinlogDumpFromPosition ¶
func (bc *BinlogConnection) StartBinlogDumpFromPosition(ctx context.Context, startPos mysql.Position) (<-chan mysql.BinlogEvent, <-chan error, error)
func (*BinlogConnection) SwitchOffMasterArg ¶
func (bc *BinlogConnection) SwitchOffMasterArg() error
type ColExpr ¶
type ColExpr struct {
// ColNum specifies the source column value.
ColNum int
Field *proto.Field
FixedValue sqltypes.Value
}
ColExpr represents a column expression.
type DBClient ¶
type DBClient struct {
InTransaction bool
// contains filtered or unexported fields
}
DBClient is a wrapper on DBClient. It allows us to retry a failed transactions on lock errors.
func NewDBClient ¶
func NewDBClient(params *mysql.ConnParams, stats *Stats) *DBClient
func (*DBClient) CreateState ¶
func (c *DBClient) CreateState(source *mysql.ConnParams, dest *mysql.ConnParams, kafkaParams *KafkaParams, filter *proto.Filter, serviceAddr string, rl *vo.RateLimit) (int, error)
func (*DBClient) ExecuteFetch ¶
func (*DBClient) ExecuteWithRetry ¶
func (*DBClient) ListLocalTaskIds ¶
func (*DBClient) ListLocalTasks ¶
func (*DBClient) SetNextGtid ¶
type IDPool ¶
IDPool is used to ensure that the set of IDs in use concurrently never contains any duplicates. The IDs start at 1 and increase without bound, but will never be larger than the peak number of concurrent uses.
IDPool's Get() and Put() methods can be used concurrently.
type KafkaMessage ¶
type KafkaMessage struct {
Table string `json:"table"`
Database string `json:"database"`
Gtid string `json:"gtid,omitempty"`
ExecuteTime int64 `json:"es"`
Ts int64 `json:"ts"`
PkNames []string `json:"pkNames"`
Sql string `json:"sql"`
IsDDL bool `json:"isDdl"`
Type string `json:"type"`
Data []map[string]interface{} `json:"data"`
Old []map[string]interface{} `json:"old,omitempty"`
}
type KafkaMessageMaxwell ¶
type KafkaParams ¶
type Plan ¶
type Plan struct {
Table *Table
// ColExprs is the list of column expressions to be sent
// in the stream.
ColExprs []ColExpr
// Filters is the list of filters to be applied to the columns
// of the table.
Filters []Filter
}
Plan represents the plan for a table.
type PrimaryKeyInfo ¶
type PrimaryKeyInfo struct {
Index int64 // base 1
Name string
CharSet string
Collation string
DataType string
ColumnType string
}
PrimaryKeyInfo is used to store charset and collation for primary keys where applicable
type Replicator ¶
type Replicator struct {
Id int
State string
Message string
// contains filtered or unexported fields
}
Replicator provides the core logic to start vreplication streams
func LoadFromDB ¶
func LoadFromDB(id int, stats *Stats, serviceAddr string) (*Replicator, error)
func NewReplicator ¶
func NewReplicator(source *mysql.ConnParams, dest *mysql.ConnParams, kafkaParams *KafkaParams, filter *proto.Filter, rl *vo.RateLimit, stats *Stats, incrementalMode bool, serviceAddr string) (*Replicator, error)
newReplicator creates a new Replicator. The valid fields from the source are: Keyspce, Shard, Filter, ExternalMySql. The Filter consists of Rules. Each Rule has a Match and an (inner) Filter field. The Match can be a table name or, if it begins with a "/", a wildcard. The Filter can be empty: get all rows and columns. The Filter can be a keyrange, like "-80": get all rows that are within the keyrange. The Filter can be a select expression. Examples.
"select * from t", same as an empty Filter,
"select * from t where in_keyrange('-80')", same as "-80",
"select * from t where in_keyrange(col1, 'hash', '-80')",
"select col1, col2 from t where...",
"select col1, keyspace_id() as ksid from t where...",
"select id, count(*), sum(price) from t group by id".
Only "in_keyrange" expressions are supported in the where clause.
The select expressions can be any valid non-aggregate expressions,
or count(*), or sum(col).
If the target column name does not match the source expression, an
alias like "a+b as targetcol" must be used.
More advanced constructs can be used. Please see the table plan builder
documentation for more info.
func (*Replicator) Done ¶
func (r *Replicator) Done() chan struct{}
func (*Replicator) Replicate ¶
func (r *Replicator) Replicate(ctx context.Context) error
Replicate starts a replication stream. It can be in one of three phases: 1. Init: If a request is issued with no starting position, we assume that the contents of the tables must be copied first. During this phase, the list of tables to be copied is inserted into the copy_state table. A successful insert gets us out of this phase. 2. Copy: If the copy_state table has rows, then we are in this phase. During this phase, we repeatedly invoke copyNext until all the tables are copied. After each table is successfully copied, it's removed from the copy_state table. We exit this phase when there are no rows left in copy_state. 3. Replicate: In this phase, we replicate binlog events indefinitely, unless a stop position was requested. This phase differs from the Init phase because there is a replication position. If a request had a starting position, then we go directly into phase 3. During these phases, the state of replication is reported as 'Init', 'Copying', or 'Running'. They all mean the same thing. The difference in the phases depends on the criteria defined above. The different states reported are mainly informational. The 'Stopped' state is, however, honored. All phases share the same plan building framework. We leverage the fact the row representation of a read (during copy) and a binlog event are identical. However, there are some subtle differences, explained in the plan builder code.
type ReplicatorMode ¶
type ReplicatorMode uint8
const ( ModeOLAP ReplicatorMode = iota ModeOLTP ModeBoth )
type ReplicatorPlan ¶
type ReplicatorPlan struct {
VStreamFilter *proto.Filter
TargetTables map[string]map[string]*TablePlan
TablePlans map[string]map[string]*TablePlan
PKInfoMap map[string]map[string][]*PrimaryKeyInfo
}
ReplicatorPlan is the execution plan for the replicator. It contains plans for all the tables it's replicating. Every phase of vreplication builds its own instance of the ReplicatorPlan. This is because the plan depends on copyState, which changes on every iteration. The table plans within ReplicatorPlan will not be fully populated because all the information is not available initially. For simplicity, the ReplicatorPlan is immutable. Once we get the field info for a table from the stream response, we'll have all the necessary info to build the final plan. At that time, buildExecutionPlan is invoked, which will make a copy of the TablePlan from ReplicatorPlan, and fill the rest of the members, leaving the original plan unchanged. The constructor is buildReplicatorPlan in table_plan_builder.go
func (*ReplicatorPlan) MarshalJSON ¶
func (rp *ReplicatorPlan) MarshalJSON() ([]byte, error)
MarshalJSON performs a custom JSON Marshalling.
type Stats ¶
type Stats struct {
// Stats about the player, keys used are BlplQuery and BlplTransaction
Timings *stats.MultiTimings
SecondsBehindMaster *stats.GaugesWithSingleLabel
History *history.History
State sync2.AtomicString
PhaseTimings *stats.Timings
QueryTimings *stats.MultiTimings
StreamRowCount *stats.Counter
CopyRowCount *stats.Counter
CopyLoopCount *stats.Counter
ErrorCounts *stats.CountersWithMultiLabels
RelayLogLength *stats.Gauge
EventsCount *stats.CountersWithSingleLabel
// contains filtered or unexported fields
}
func (*Stats) LastPosition ¶
LastPosition gets the last replication position.
func (*Stats) MessageHistory ¶
MessageHistory gets all the messages, we store 3 at a time
func (*Stats) RecordHeartbeat ¶
RecordHeartbeat updates the time the last heartbeat from vstreamer was seen
func (*Stats) SetLastPosition ¶
SetLastPosition sets the last replication position.
type StatsHistoryRecord ¶
type TablePlan ¶
type TablePlan struct {
// Dbname, TargetName, SendRule will always be initialized.
Dbname string
TargetName string
TargetDbname string
DbTopic string
TbTopic string
PartitionColumnIndex []int
ExcludeColumnMap map[string]struct{}
SendRule *proto.Rule
// Lastpk will be initialized if it was specified, and
// will be used for building the final plan after field info
// is received.
Lastpk *sqltypes.Result
// BulkInsertFront, BulkInsertValues and BulkInsertOnDup are used
// by vcopier. These three parts are combined to build bulk insert
// statements. This is functionally equivalent to generating
// multiple statements using the "Insert" construct, but much more
// efficient for the copy phase.
BulkInsertFront *sqlparser.ParsedQuery
BulkInsertValues *sqlparser.ParsedQuery
BulkInsertOnDup *sqlparser.ParsedQuery
// Insert, Update and Delete are used by vplayer.
// If the plan is an insertIgnore type, then Insert
// and Update contain 'insert ignore' statements and
// Delete is nil.
Insert *sqlparser.ParsedQuery
Update *sqlparser.ParsedQuery
Delete *sqlparser.ParsedQuery
Fields []*proto.Field
// PKReferences is used to check if an event changed
// a primary key column (row move).
PKReferences []string
}
TablePlan is the execution plan for a table within a replicator. If the column names are not known at the time of plan building (like select *), then only TargetName, SendRule and Lastpk are initialized. When the stream returns the field info, those are used as column names to build the final plan. Lastpk comes from copyState. If it's set, then the generated plans are significantly different because any events that fall beyond Lastpk must be excluded. If column names were known upfront, then all fields of TablePlan are built except for Fields. This member is populated only after the field info is received from the stream. The ParsedQuery objects assume that a map of before and after values will be built based on the streaming rows. Before image values will be prefixed with a "b_", and after image values will be prefixed with a "a_". The TablePlan structure is used during all the phases of vreplication: catchup, copy, fastforward, or regular replication.
func (*TablePlan) MarshalJSON ¶
MarshalJSON performs a custom JSON Marshalling.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
dts
command
|
|
|
Package sqltypes implements interfaces and types that represent SQL values.
|
Package sqltypes implements interfaces and types that represent SQL values. |
|
Package stats is a wrapper for expvar.
|
Package stats is a wrapper for expvar. |
|
Package util ResourcePool provides functionality to manage and reuse resources like connections.
|
Package util ResourcePool provides functionality to manage and reuse resources like connections. |
|
history
Package history implements a circular buffer with adjacent-item deduplication.
|
Package history implements a circular buffer with adjacent-item deduplication. |
|
sync2
Package sync2 provides extra functionality along the same lines as sync.
|
Package sync2 provides extra functionality along the same lines as sync. |
|
timer
Package timer provides various enhanced timer functions.
|
Package timer provides various enhanced timer functions. |