forked from pingcap/tidb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreorg.go
243 lines (211 loc) · 6.65 KB
/
reorg.go
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
// Copyright 2015 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// See the License for the specific language governing permissions and
// limitations under the License.
package ddl
import (
"time"
"github.com/juju/errors"
"github.com/ngaut/log"
"github.com/pingcap/tidb/context"
"github.com/pingcap/tidb/kv"
"github.com/pingcap/tidb/meta"
"github.com/pingcap/tidb/model"
"github.com/pingcap/tidb/mysql"
"github.com/pingcap/tidb/terror"
"github.com/pingcap/tidb/util/mock"
)
// newContext gets a context. It is only used for adding column in reorganization state.
func (d *ddl) newContext() context.Context {
c := mock.NewContext()
c.Store = d.store
c.GetSessionVars().SetStatusFlag(mysql.ServerStatusAutocommit, false)
return c
}
const waitReorgTimeout = 10 * time.Second
func (d *ddl) runReorgJob(f func() error) error {
if d.reorgDoneCh == nil {
// start a reorganization job
d.wait.Add(1)
d.reorgDoneCh = make(chan error, 1)
go func() {
defer d.wait.Done()
d.reorgDoneCh <- f()
}()
}
waitTimeout := waitReorgTimeout
// if d.lease is 0, we are using a local storage,
// and we can wait the reorganization to be done here.
// if d.lease > 0, we don't need to wait here because
// we will wait 2 * lease outer and try checking again,
// so we use a very little timeout here.
if d.lease > 0 {
waitTimeout = 1 * time.Millisecond
}
// wait reorganization job done or timeout
select {
case err := <-d.reorgDoneCh:
log.Info("[ddl] run reorg job done")
d.reorgDoneCh = nil
return errors.Trace(err)
case <-d.quitCh:
log.Info("[ddl] run reorg job ddl quit")
// we return errWaitReorgTimeout here too, so that outer loop will break.
return errWaitReorgTimeout
case <-time.After(waitTimeout):
log.Infof("[ddl] run reorg job wait timeout :%v", waitTimeout)
// if timeout, we will return, check the owner and retry to wait job done again.
return errWaitReorgTimeout
}
}
func (d *ddl) isReorgRunnable(txn kv.Transaction, flag JobType) error {
if d.isClosed() {
// worker is closed, can't run reorganization.
return errors.Trace(errInvalidWorker.Gen("worker is closed"))
}
t := meta.NewMeta(txn)
owner, err := d.getJobOwner(t, flag)
if err != nil {
return errors.Trace(err)
}
if owner == nil || owner.OwnerID != d.uuid {
// if no owner, we will try later, so here just return error.
// or another server is owner, return error too.
log.Infof("[ddl] %s job, self id %s owner %s, txnTS:%d", flag, d.uuid, owner, txn.StartTS())
return errors.Trace(errNotOwner)
}
return nil
}
// delKeysWithStartKey deletes keys with start key in a limited number. If limit < 0, deletes all keys.
// It returns the number of rows deleted, next start key and the error.
func (d *ddl) delKeysWithStartKey(prefix, startKey kv.Key, jobType JobType, job *model.Job, limit int) (int, kv.Key, error) {
limitedDel := limit >= 0
var count int
total := job.GetRowCount()
keys := make([]kv.Key, 0, defaultBatchCnt)
for {
if limitedDel && count >= limit {
break
}
batch := defaultBatchCnt
if limitedDel && count+batch > limit {
batch = limit - count
}
startTS := time.Now()
err := kv.RunInNewTxn(d.store, true, func(txn kv.Transaction) error {
if err1 := d.isReorgRunnable(txn, jobType); err1 != nil {
return errors.Trace(err1)
}
iter, err := txn.Seek(startKey)
if err != nil {
return errors.Trace(err)
}
defer iter.Close()
for i := 0; i < batch; i++ {
if iter.Valid() && iter.Key().HasPrefix(prefix) {
keys = append(keys, iter.Key().Clone())
err = iter.Next()
if err != nil {
return errors.Trace(err)
}
} else {
break
}
}
for _, key := range keys {
err := txn.Delete(key)
// must skip ErrNotExist
// if key doesn't exist, skip this error.
if err != nil && !terror.ErrorEqual(err, kv.ErrNotExist) {
return errors.Trace(err)
}
}
count += len(keys)
total += int64(len(keys))
return nil
})
sub := time.Since(startTS).Seconds()
if err != nil {
log.Warnf("[ddl] deleted %d keys failed, take time %v, deleted %d keys in total", len(keys), sub, total)
return 0, startKey, errors.Trace(err)
}
job.SetRowCount(total)
batchHandleDataHistogram.WithLabelValues(batchDelData).Observe(sub)
log.Infof("[ddl] deleted %d keys take time %v, deleted %d keys in total", len(keys), sub, total)
if len(keys) > 0 {
startKey = keys[len(keys)-1]
}
if noMoreKeysToDelete := len(keys) < batch; noMoreKeysToDelete {
break
}
keys = keys[:0]
}
return count, startKey, nil
}
// addDBHistoryInfo adds schema version and schema information that are used for binlog.
// dbInfo is added in the following operations: create database, drop database.
func addDBHistoryInfo(job *model.Job, ver int64, dbInfo *model.DBInfo) {
// TODO: Remove it.
// This is for compatibility with previous version.
job.Args = []interface{}{ver, dbInfo}
if job.BinlogInfo != nil {
job.BinlogInfo.AddDBInfo(ver, dbInfo)
}
}
// addTableHistoryInfo adds schema version and table information that are used for binlog.
// tblInfo is added except for the following operations: create database, drop database.
func addTableHistoryInfo(job *model.Job, ver int64, tblInfo *model.TableInfo) {
// TODO: Remove it.
// This is for compatibility with previous version.
job.Args = []interface{}{ver, tblInfo}
if job.BinlogInfo != nil {
job.BinlogInfo.AddTableInfo(ver, tblInfo)
}
}
type reorgInfo struct {
*model.Job
Handle int64
d *ddl
first bool
}
func (d *ddl) getReorgInfo(t *meta.Meta, job *model.Job) (*reorgInfo, error) {
var err error
info := &reorgInfo{
Job: job,
d: d,
first: job.SnapshotVer == 0,
}
if info.first {
// get the current version for reorganization if we don't have
var ver kv.Version
ver, err = d.store.CurrentVersion()
if err != nil {
return nil, errors.Trace(err)
} else if ver.Ver <= 0 {
return nil, errInvalidStoreVer.Gen("invalid storage current version %d", ver.Ver)
}
job.SnapshotVer = ver.Ver
} else {
info.Handle, err = t.GetDDLReorgHandle(job)
if err != nil {
return nil, errors.Trace(err)
}
}
if info.Handle > 0 {
// we have already handled this handle, so use next
info.Handle++
}
return info, errors.Trace(err)
}
func (r *reorgInfo) UpdateHandle(txn kv.Transaction, handle int64) error {
t := meta.NewMeta(txn)
return errors.Trace(t.UpdateDDLReorgHandle(r.Job, handle))
}