-
Notifications
You must be signed in to change notification settings - Fork 6.2k
Expand file tree
/
Copy pathsystable_restore.go
More file actions
411 lines (382 loc) · 14.8 KB
/
Copy pathsystable_restore.go
File metadata and controls
411 lines (382 loc) · 14.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
// Copyright 2020 PingCAP, Inc. Licensed under Apache-2.0.
package restore
import (
"context"
"fmt"
"strings"
"github.com/pingcap/errors"
"github.com/pingcap/log"
berrors "github.com/pingcap/tidb/br/pkg/errors"
"github.com/pingcap/tidb/br/pkg/logutil"
"github.com/pingcap/tidb/br/pkg/utils"
"github.com/pingcap/tidb/pkg/bindinfo"
"github.com/pingcap/tidb/pkg/kv"
"github.com/pingcap/tidb/pkg/parser/model"
"github.com/pingcap/tidb/pkg/parser/mysql"
filter "github.com/pingcap/tidb/pkg/util/table-filter"
"go.uber.org/multierr"
"go.uber.org/zap"
)
const (
sysUserTableName = "user"
)
var statsTables = map[string]map[string]struct{}{
"mysql": {
"stats_buckets": {},
"stats_extended": {},
"stats_feedback": {},
"stats_fm_sketch": {},
"stats_histograms": {},
"stats_history": {},
"stats_meta": {},
"stats_meta_history": {},
"stats_table_locked": {},
"stats_top_n": {},
},
}
var unRecoverableTable = map[string]map[string]struct{}{
"mysql": {
// some variables in tidb (e.g. gc_safe_point) cannot be recovered.
"tidb": {},
"global_variables": {},
"column_stats_usage": {},
"capture_plan_baselines_blacklist": {},
// gc info don't need to recover.
"gc_delete_range": {},
"gc_delete_range_done": {},
// replace into view is not supported now
"tidb_mdl_view": {},
},
"sys": {
// replace into view is not supported now
"schema_unused_indexes": {},
},
}
type checkPrivilegeTableRowsCollateCompatibilitySQLPair struct {
upstreamCollateSQL string
downstreamCollateSQL string
columns map[string]struct{}
}
var collateCompatibilityTables = map[string]map[string]checkPrivilegeTableRowsCollateCompatibilitySQLPair{
"mysql": {
"db": {
upstreamCollateSQL: "SELECT COUNT(1) FROM __TiDB_BR_Temporary_mysql.db",
downstreamCollateSQL: "SELECT COUNT(1) FROM (SELECT Host, DB COLLATE utf8mb4_general_ci, User FROM __TiDB_BR_Temporary_mysql.db GROUP BY Host, DB COLLATE utf8mb4_general_ci, User) as a",
columns: map[string]struct{}{"db": {}},
},
"tables_priv": {
upstreamCollateSQL: "SELECT COUNT(1) FROM __TiDB_BR_Temporary_mysql.tables_priv",
downstreamCollateSQL: "SELECT COUNT(1) FROM (SELECT Host, DB COLLATE utf8mb4_general_ci, User, Table_name COLLATE utf8mb4_general_ci FROM __TiDB_BR_Temporary_mysql.tables_priv GROUP BY Host, DB COLLATE utf8mb4_general_ci, User, Table_name COLLATE utf8mb4_general_ci) as a",
columns: map[string]struct{}{"db": {}, "table_name": {}},
},
"columns_priv": {
upstreamCollateSQL: "SELECT COUNT(1) FROM __TiDB_BR_Temporary_mysql.columns_priv",
downstreamCollateSQL: "SELECT COUNT(1) FROM (SELECT Host, DB COLLATE utf8mb4_general_ci, User, Table_name COLLATE utf8mb4_general_ci, Column_name COLLATE utf8mb4_general_ci FROM __TiDB_BR_Temporary_mysql.columns_priv GROUP BY Host, DB COLLATE utf8mb4_general_ci, User, Table_name COLLATE utf8mb4_general_ci, Column_name COLLATE utf8mb4_general_ci) as a",
columns: map[string]struct{}{"db": {}, "table_name": {}, "column_name": {}},
},
},
}
func isUnrecoverableTable(schemaName string, tableName string) bool {
tableMap, ok := unRecoverableTable[schemaName]
if !ok {
return false
}
_, ok = tableMap[tableName]
return ok
}
func isStatsTable(schemaName string, tableName string) bool {
tableMap, ok := statsTables[schemaName]
if !ok {
return false
}
_, ok = tableMap[tableName]
return ok
}
// RestoreSystemSchemas restores the system schema(i.e. the `mysql` schema).
// Detail see https://github.com/pingcap/br/issues/679#issuecomment-762592254.
func (rc *Client) RestoreSystemSchemas(ctx context.Context, f filter.Filter) (rerr error) {
sysDBs := []string{mysql.SystemDB, mysql.SysDB}
for _, sysDB := range sysDBs {
err := rc.restoreSystemSchema(ctx, f, sysDB)
if err != nil {
return err
}
}
return nil
}
// restoreSystemSchema restores a system schema(i.e. the `mysql` or `sys` schema).
// Detail see https://github.com/pingcap/br/issues/679#issuecomment-762592254.
func (rc *Client) restoreSystemSchema(ctx context.Context, f filter.Filter, sysDB string) (rerr error) {
temporaryDB := utils.TemporaryDBName(sysDB)
defer func() {
// Don't clean the temporary database for next restore with checkpoint.
if rerr == nil {
rc.cleanTemporaryDatabase(ctx, sysDB)
}
}()
if !f.MatchSchema(sysDB) || !rc.withSysTable {
log.Debug("system database filtered out", zap.String("database", sysDB))
return nil
}
originDatabase, ok := rc.databases[temporaryDB.O]
if !ok {
log.Info("system database not backed up, skipping", zap.String("database", sysDB))
return nil
}
db, ok := rc.getDatabaseByName(sysDB)
if !ok {
// Or should we create the database here?
log.Warn("target database not exist, aborting", zap.String("database", sysDB))
return nil
}
tablesRestored := make([]string, 0, len(originDatabase.Tables))
for _, table := range originDatabase.Tables {
tableName := table.Info.Name
if f.MatchTable(sysDB, tableName.O) {
if err := rc.replaceTemporaryTableToSystable(ctx, table.Info, db); err != nil {
log.Warn("error during merging temporary tables into system tables",
logutil.ShortError(err),
zap.Stringer("table", tableName),
)
return errors.Annotatef(err, "error during merging temporary tables into system tables, table: %s", tableName)
}
tablesRestored = append(tablesRestored, tableName.L)
}
}
if err := rc.afterSystemTablesReplaced(ctx, sysDB, tablesRestored); err != nil {
return errors.Annotate(err, "error during extra works after system tables replaced")
}
return nil
}
// database is a record of a database.
// For fast querying whether a table exists and the temporary database of it.
type database struct {
ExistingTables map[string]*model.TableInfo
Name model.CIStr
TemporaryName model.CIStr
}
// getDatabaseByName make a record of a database from info schema by its name.
func (rc *Client) getDatabaseByName(name string) (*database, bool) {
infoSchema := rc.dom.InfoSchema()
schema, ok := infoSchema.SchemaByName(model.NewCIStr(name))
if !ok {
return nil, false
}
db := &database{
ExistingTables: map[string]*model.TableInfo{},
Name: model.NewCIStr(name),
TemporaryName: utils.TemporaryDBName(name),
}
for _, t := range schema.Tables {
db.ExistingTables[t.Name.L] = t
}
return db, true
}
// afterSystemTablesReplaced do some extra work for special system tables.
// e.g. after inserting to the table mysql.user, we must execute `FLUSH PRIVILEGES` to allow it take effect.
func (rc *Client) afterSystemTablesReplaced(ctx context.Context, db string, tables []string) error {
if db != mysql.SystemDB {
return nil
}
var err error
for _, table := range tables {
if table == "user" {
if serr := rc.dom.NotifyUpdatePrivilege(); serr != nil {
log.Warn("failed to flush privileges, please manually execute `FLUSH PRIVILEGES`")
err = multierr.Append(err, berrors.ErrUnknown.Wrap(serr).GenWithStack("failed to flush privileges"))
} else {
log.Info("privilege system table restored, please reconnect to make it effective")
}
} else if table == "bind_info" {
if serr := rc.db.se.Execute(ctx, bindinfo.StmtRemoveDuplicatedPseudoBinding); serr != nil {
log.Warn("failed to delete duplicated pseudo binding", zap.Error(serr))
err = multierr.Append(err,
berrors.ErrUnknown.Wrap(serr).GenWithStack("failed to delete duplicated pseudo binding %s", bindinfo.StmtRemoveDuplicatedPseudoBinding))
} else {
log.Info("success to remove duplicated pseudo binding")
}
}
}
return err
}
// replaceTemporaryTableToSystable replaces the temporary table to real system table.
func (rc *Client) replaceTemporaryTableToSystable(ctx context.Context, ti *model.TableInfo, db *database) error {
dbName := db.Name.L
tableName := ti.Name.L
execSQL := func(sql string) error {
// SQLs here only contain table name and database name, seems it is no need to redact them.
if err := rc.db.se.Execute(ctx, sql); err != nil {
log.Warn("failed to execute SQL restore system database",
zap.String("table", tableName),
zap.Stringer("database", db.Name),
zap.String("sql", sql),
zap.Error(err),
)
return berrors.ErrUnknown.Wrap(err).GenWithStack("failed to execute %s", sql)
}
log.Info("successfully restore system database",
zap.String("table", tableName),
zap.Stringer("database", db.Name),
zap.String("sql", sql),
)
return nil
}
// The newly created tables have different table IDs with original tables,
// hence the old statistics are invalid.
//
// TODO:
// 1 ) Rewrite the table IDs via `UPDATE _temporary_mysql.stats_xxx SET table_id = new_table_id WHERE table_id = old_table_id`
// BEFORE replacing into and then execute `rc.statsHandler.Update(rc.dom.InfoSchema())`.
// 1.5 ) (Optional) The UPDATE statement sometimes costs, the whole system tables restore step can be place into the restore pipeline.
// 2 ) Deprecate the origin interface for backing up statistics.
if isStatsTable(dbName, tableName) {
return nil
}
if isUnrecoverableTable(dbName, tableName) {
return nil
}
// Currently, we don't support restore resource group metadata, so we need to
// remove the resource group related metadata in mysql.user.
// TODO: this function should be removed when we support backup and restore
// resource group.
if dbName == mysql.SystemDB && tableName == sysUserTableName {
sql := fmt.Sprintf("UPDATE %s SET User_attributes = JSON_REMOVE(User_attributes, '$.resource_group');",
utils.EncloseDBAndTable(db.TemporaryName.L, sysUserTableName))
if err := execSQL(sql); err != nil {
// FIXME: find a better way to check the error or we should check the version here instead.
if !strings.Contains(err.Error(), "Unknown column 'User_attributes' in 'field list'") {
return err
}
log.Warn("remove resource group meta failed, please ensure target cluster is newer than v6.6.0", logutil.ShortError(err))
}
}
if db.ExistingTables[tableName] != nil {
log.Info("replace into existing table",
zap.String("table", tableName),
zap.Stringer("schema", db.Name))
if rc.privilegeTableRowsCollateCompatibility {
if err := rc.checkPrivilegeTableRowsCollateCompatibility(ctx, dbName, tableName, ti, db.ExistingTables[tableName]); err != nil {
return err
}
}
// target column order may different with source cluster
columnNames := make([]string, 0, len(ti.Columns))
for _, col := range ti.Columns {
columnNames = append(columnNames, utils.EncloseName(col.Name.L))
}
colListStr := strings.Join(columnNames, ",")
replaceIntoSQL := fmt.Sprintf("REPLACE INTO %s(%s) SELECT %s FROM %s;",
utils.EncloseDBAndTable(db.Name.L, tableName),
colListStr, colListStr,
utils.EncloseDBAndTable(db.TemporaryName.L, tableName))
return execSQL(replaceIntoSQL)
}
renameSQL := fmt.Sprintf("RENAME TABLE %s TO %s;",
utils.EncloseDBAndTable(db.TemporaryName.L, tableName),
utils.EncloseDBAndTable(db.Name.L, tableName),
)
return execSQL(renameSQL)
}
func (rc *Client) cleanTemporaryDatabase(ctx context.Context, originDB string) {
database := utils.TemporaryDBName(originDB)
log.Debug("dropping temporary database", zap.Stringer("database", database))
sql := fmt.Sprintf("DROP DATABASE IF EXISTS %s", utils.EncloseName(database.L))
if err := rc.db.se.Execute(ctx, sql); err != nil {
logutil.WarnTerm("failed to drop temporary database, it should be dropped manually",
zap.Stringer("database", database),
logutil.ShortError(err),
)
}
}
func checkSysTableColumnCollateCompatibility(dbNameL, tableNameL, columnNameL, upstreamCollate, downstreamCollate string) bool {
if upstreamCollate != "utf8mb4_bin" || downstreamCollate != "utf8mb4_general_ci" {
return false
}
collateCompatibilityTableMap, exists := collateCompatibilityTables[dbNameL]
if !exists {
return false
}
collateCompatibilityColumnMap, exists := collateCompatibilityTableMap[tableNameL]
if !exists {
return false
}
_, exists = collateCompatibilityColumnMap.columns[columnNameL]
return exists
}
func (rc *Client) checkPrivilegeTableRowsCollateCompatibility(
ctx context.Context,
dbNameL, tableNameL string,
upstreamTable, downstreamTable *model.TableInfo,
) error {
collateCompatibilityTableMap, exists := collateCompatibilityTables[dbNameL]
if !exists {
return nil
}
collateCompatibilityColumnMap, exists := collateCompatibilityTableMap[tableNameL]
if !exists {
return nil
}
colCount := 0
for _, col := range upstreamTable.Columns {
if _, exists := collateCompatibilityColumnMap.columns[col.Name.L]; exists {
if col.GetCollate() != "utf8mb4_bin" && col.GetCollate() != "utf8mb4_general_ci" {
return errors.Annotatef(berrors.ErrRestoreIncompatibleSys,
"incompatible column collate, upstream table %s.%s column %s collate is %s but should be utf8mb4_bin or utf8mb4_general_ci",
dbNameL, tableNameL, col.Name.L, col.GetCollate())
}
colCount += 1
}
}
if colCount != len(collateCompatibilityColumnMap.columns) {
return errors.Annotatef(berrors.ErrRestoreIncompatibleSys,
"incompatible column collate, upstream table %s.%s has only %d compatible columns",
dbNameL, tableNameL, colCount)
}
colCount = 0
for _, col := range downstreamTable.Columns {
if _, exists := collateCompatibilityColumnMap.columns[col.Name.L]; exists {
if col.GetCollate() != "utf8mb4_general_ci" {
return errors.Annotatef(berrors.ErrRestoreIncompatibleSys,
"incompatible column collate, downstream table %s.%s column %s collate is %s but should be utf8mb4_general_ci",
dbNameL, tableNameL, col.Name.L, col.GetCollate())
}
colCount += 1
}
}
if colCount != len(collateCompatibilityColumnMap.columns) {
return errors.Annotatef(berrors.ErrRestoreIncompatibleSys,
"incompatible column collate, downstream table %s.%s has only %d compatible columns",
dbNameL, tableNameL, colCount)
}
ectx := rc.db.se.GetSessionCtx().GetRestrictedSQLExecutor()
rows, _, err := ectx.ExecRestrictedSQL(
kv.WithInternalSourceType(ctx, kv.InternalTxnBR),
nil,
collateCompatibilityColumnMap.upstreamCollateSQL,
)
if err != nil {
return errors.Annotatef(err, "failed to get the count of privilege rows")
}
if len(rows) == 0 {
return errors.Errorf("failed to get the count of privilege rows")
}
upstreamCount := rows[0].GetInt64(0)
rows, _, err = ectx.ExecRestrictedSQL(
kv.WithInternalSourceType(ctx, kv.InternalTxnBR),
nil,
collateCompatibilityColumnMap.downstreamCollateSQL,
)
if err != nil {
return errors.Annotatef(err, "failed to get the count of privilege rows")
}
if len(rows) == 0 {
return errors.Errorf("failed to get the count of privilege rows")
}
downstreamCount := rows[0].GetInt64(0)
if upstreamCount != downstreamCount {
return errors.Annotatef(berrors.ErrRestoreIncompatibleSys,
"there are duplicated privilege rows with collate utf8mb4_general_ci [upstream count %d != downstream count %d]",
upstreamCount, downstreamCount)
}
return nil
}