Skip to content

Commit 9d25f34

Browse files
authored
core: track and improve tx indexing/unindexing (#21331)
* core: add background indexer to waitgroup * core: make indexer stopable * core/rawdb: add unit tests * core/rawdb: fix lint * core/rawdb: fix tests * core/rawdb: fix linter
1 parent 6e71371 commit 9d25f34

3 files changed

Lines changed: 217 additions & 66 deletions

File tree

‎core/blockchain.go‎

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -345,6 +345,8 @@ func NewBlockChain(db ethdb.Database, cacheConfig *CacheConfig, chainConfig *par
345345
go bc.update()
346346
if txLookupLimit != nil {
347347
bc.txLookupLimit = *txLookupLimit
348+
349+
bc.wg.Add(1)
348350
go bc.maintainTxIndex(txIndexBlock)
349351
}
350352
// If periodic cache journal is required, spin it up.
@@ -2230,6 +2232,8 @@ func (bc *BlockChain) update() {
22302232
// sync, Geth will automatically construct the missing indices and delete
22312233
// the extra indices.
22322234
func (bc *BlockChain) maintainTxIndex(ancients uint64) {
2235+
defer bc.wg.Done()
2236+
22332237
// Before starting the actual maintenance, we need to handle a special case,
22342238
// where user might init Geth with an external ancient database. If so, we
22352239
// need to reindex all necessary transactions before starting to process any
@@ -2239,7 +2243,7 @@ func (bc *BlockChain) maintainTxIndex(ancients uint64) {
22392243
if bc.txLookupLimit != 0 && ancients > bc.txLookupLimit {
22402244
from = ancients - bc.txLookupLimit
22412245
}
2242-
rawdb.IndexTransactions(bc.db, from, ancients)
2246+
rawdb.IndexTransactions(bc.db, from, ancients, bc.quit)
22432247
}
22442248
// indexBlocks reindexes or unindexes transactions depending on user configuration
22452249
indexBlocks := func(tail *uint64, head uint64, done chan struct{}) {
@@ -2253,24 +2257,24 @@ func (bc *BlockChain) maintainTxIndex(ancients uint64) {
22532257
rawdb.WriteTxIndexTail(bc.db, 0)
22542258
} else {
22552259
// Prune all stale tx indices and record the tx index tail
2256-
rawdb.UnindexTransactions(bc.db, 0, head-bc.txLookupLimit+1)
2260+
rawdb.UnindexTransactions(bc.db, 0, head-bc.txLookupLimit+1, bc.quit)
22572261
}
22582262
return
22592263
}
22602264
// If a previous indexing existed, make sure that we fill in any missing entries
22612265
if bc.txLookupLimit == 0 || head < bc.txLookupLimit {
22622266
if *tail > 0 {
2263-
rawdb.IndexTransactions(bc.db, 0, *tail)
2267+
rawdb.IndexTransactions(bc.db, 0, *tail, bc.quit)
22642268
}
22652269
return
22662270
}
22672271
// Update the transaction index to the new chain state
22682272
if head-bc.txLookupLimit+1 < *tail {
22692273
// Reindex a part of missing indices and rewind index tail to HEAD-limit
2270-
rawdb.IndexTransactions(bc.db, head-bc.txLookupLimit+1, *tail)
2274+
rawdb.IndexTransactions(bc.db, head-bc.txLookupLimit+1, *tail, bc.quit)
22712275
} else {
22722276
// Unindex a part of stale indices and forward index tail to HEAD-limit
2273-
rawdb.UnindexTransactions(bc.db, *tail, head-bc.txLookupLimit+1)
2277+
rawdb.UnindexTransactions(bc.db, *tail, head-bc.txLookupLimit+1, bc.quit)
22742278
}
22752279
}
22762280
// Any reindexing done, start listening to chain events and moving the index window
@@ -2294,6 +2298,10 @@ func (bc *BlockChain) maintainTxIndex(ancients uint64) {
22942298
case <-done:
22952299
done = nil
22962300
case <-bc.quit:
2301+
if done != nil {
2302+
log.Info("Waiting background transaction indexer to exit")
2303+
<-done
2304+
}
22972305
return
22982306
}
22992307
}

‎core/rawdb/chain_iterator.go‎

Lines changed: 120 additions & 60 deletions
Original file line numberDiff line numberDiff line change
@@ -84,15 +84,17 @@ type blockTxHashes struct {
8484
}
8585

8686
// iterateTransactions iterates over all transactions in the (canon) block
87-
// number(s) given, and yields the hashes on a channel
88-
func iterateTransactions(db ethdb.Database, from uint64, to uint64, reverse bool) (chan *blockTxHashes, chan struct{}) {
87+
// number(s) given, and yields the hashes on a channel. If there is a signal
88+
// received from interrupt channel, the iteration will be aborted and result
89+
// channel will be closed.
90+
func iterateTransactions(db ethdb.Database, from uint64, to uint64, reverse bool, interrupt chan struct{}) chan *blockTxHashes {
8991
// One thread sequentially reads data from db
9092
type numberRlp struct {
9193
number uint64
9294
rlp rlp.RawValue
9395
}
9496
if to == from {
95-
return nil, nil
97+
return nil
9698
}
9799
threads := to - from
98100
if cpus := runtime.NumCPU(); threads > uint64(cpus) {
@@ -101,7 +103,6 @@ func iterateTransactions(db ethdb.Database, from uint64, to uint64, reverse bool
101103
var (
102104
rlpCh = make(chan *numberRlp, threads*2) // we send raw rlp over this channel
103105
hashesCh = make(chan *blockTxHashes, threads*2) // send hashes over hashesCh
104-
abortCh = make(chan struct{})
105106
)
106107
// lookup runs in one instance
107108
lookup := func() {
@@ -115,7 +116,7 @@ func iterateTransactions(db ethdb.Database, from uint64, to uint64, reverse bool
115116
// Feed the block to the aggregator, or abort on interrupt
116117
select {
117118
case rlpCh <- &numberRlp{n, data}:
118-
case <-abortCh:
119+
case <-interrupt:
119120
return
120121
}
121122
if reverse {
@@ -168,7 +169,7 @@ func iterateTransactions(db ethdb.Database, from uint64, to uint64, reverse bool
168169
// Feed the block to the aggregator, or abort on interrupt
169170
select {
170171
case hashesCh <- result:
171-
case <-abortCh:
172+
case <-interrupt:
172173
return
173174
}
174175
}
@@ -177,34 +178,35 @@ func iterateTransactions(db ethdb.Database, from uint64, to uint64, reverse bool
177178
for i := 0; i < int(threads); i++ {
178179
go process()
179180
}
180-
return hashesCh, abortCh
181+
return hashesCh
181182
}
182183

183-
// IndexTransactions creates txlookup indices of the specified block range.
184+
// indexTransactions creates txlookup indices of the specified block range.
184185
//
185186
// This function iterates canonical chain in reverse order, it has one main advantage:
186187
// We can write tx index tail flag periodically even without the whole indexing
187188
// procedure is finished. So that we can resume indexing procedure next time quickly.
188-
func IndexTransactions(db ethdb.Database, from uint64, to uint64) {
189+
//
190+
// There is a passed channel, the whole procedure will be interrupted if any
191+
// signal received.
192+
func indexTransactions(db ethdb.Database, from uint64, to uint64, interrupt chan struct{}, hook func(uint64) bool) {
189193
// short circuit for invalid range
190194
if from >= to {
191195
return
192196
}
193197
var (
194-
hashesCh, abortCh = iterateTransactions(db, from, to, true)
195-
batch = db.NewBatch()
196-
start = time.Now()
197-
logged = start.Add(-7 * time.Second)
198-
// Since we iterate in reverse, we expect the first number to come
198+
hashesCh = iterateTransactions(db, from, to, true, interrupt)
199+
batch = db.NewBatch()
200+
start = time.Now()
201+
logged = start.Add(-7 * time.Second)
202+
// Since we iterate in reverse, we expect the first number to come
199203
// in to be [to-1]. Therefore, setting lastNum to means that the
200204
// prqueue gap-evaluation will work correctly
201205
lastNum = to
202206
queue = prque.New(nil)
203207
// for stats reporting
204208
blocks, txs = 0, 0
205209
)
206-
defer close(abortCh)
207-
208210
for chanDelivery := range hashesCh {
209211
// Push the delivery into the queue and process contiguous ranges.
210212
// Since we iterate in reverse, so lower numbers have lower prio, and
@@ -215,6 +217,10 @@ func IndexTransactions(db ethdb.Database, from uint64, to uint64) {
215217
if _, priority := queue.Peek(); priority != int64(lastNum-1) {
216218
break
217219
}
220+
// For testing
221+
if hook != nil && !hook(lastNum-1) {
222+
break
223+
}
218224
// Next block available, pop it off and index it
219225
delivery := queue.PopItem().(*blockTxHashes)
220226
lastNum = delivery.number
@@ -223,8 +229,7 @@ func IndexTransactions(db ethdb.Database, from uint64, to uint64) {
223229
txs += len(delivery.hashes)
224230
// If enough data was accumulated in memory or we're at the last block, dump to disk
225231
if batch.ValueSize() > ethdb.IdealBatchSize {
226-
// Also write the tail there
227-
WriteTxIndexTail(batch, lastNum)
232+
WriteTxIndexTail(batch, lastNum) // Also write the tail here
228233
if err := batch.Write(); err != nil {
229234
log.Crit("Failed writing batch to db", "error", err)
230235
return
@@ -238,67 +243,122 @@ func IndexTransactions(db ethdb.Database, from uint64, to uint64) {
238243
}
239244
}
240245
}
241-
if lastNum < to {
242-
WriteTxIndexTail(batch, lastNum)
243-
// No need to write the batch if we never entered the loop above...
246+
// If there exists uncommitted data, flush them.
247+
if batch.ValueSize() > 0 {
248+
WriteTxIndexTail(batch, lastNum) // Also write the tail there
244249
if err := batch.Write(); err != nil {
245250
log.Crit("Failed writing batch to db", "error", err)
246251
return
247252
}
248253
}
249-
log.Info("Indexed transactions", "blocks", blocks, "txs", txs, "tail", lastNum, "elapsed", common.PrettyDuration(time.Since(start)))
254+
select {
255+
case <-interrupt:
256+
log.Debug("Transaction indexing interrupted", "blocks", blocks, "txs", txs, "tail", lastNum, "elapsed", common.PrettyDuration(time.Since(start)))
257+
default:
258+
log.Info("Indexed transactions", "blocks", blocks, "txs", txs, "tail", lastNum, "elapsed", common.PrettyDuration(time.Since(start)))
259+
}
250260
}
251261

252-
// UnindexTransactions removes txlookup indices of the specified block range.
253-
func UnindexTransactions(db ethdb.Database, from uint64, to uint64) {
262+
// IndexTransactions creates txlookup indices of the specified block range.
263+
//
264+
// This function iterates canonical chain in reverse order, it has one main advantage:
265+
// We can write tx index tail flag periodically even without the whole indexing
266+
// procedure is finished. So that we can resume indexing procedure next time quickly.
267+
//
268+
// There is a passed channel, the whole procedure will be interrupted if any
269+
// signal received.
270+
func IndexTransactions(db ethdb.Database, from uint64, to uint64, interrupt chan struct{}) {
271+
indexTransactions(db, from, to, interrupt, nil)
272+
}
273+
274+
// indexTransactionsForTesting is the internal debug version with an additional hook.
275+
func indexTransactionsForTesting(db ethdb.Database, from uint64, to uint64, interrupt chan struct{}, hook func(uint64) bool) {
276+
indexTransactions(db, from, to, interrupt, hook)
277+
}
278+
279+
// unindexTransactions removes txlookup indices of the specified block range.
280+
//
281+
// There is a passed channel, the whole procedure will be interrupted if any
282+
// signal received.
283+
func unindexTransactions(db ethdb.Database, from uint64, to uint64, interrupt chan struct{}, hook func(uint64) bool) {
254284
// short circuit for invalid range
255285
if from >= to {
256286
return
257287
}
258-
// Write flag first and then unindex the transaction indices. Some indices
259-
// will be left in the database if crash happens but it's fine.
260-
WriteTxIndexTail(db, to)
261-
// If only one block is unindexed, do it directly
262-
//if from+1 == to {
263-
// data := ReadCanonicalBodyRLP(db, uint64(from))
264-
// DeleteTxLookupEntries(db, ReadBlock(db, ReadCanonicalHash(db, from), from))
265-
// log.Info("Unindexed transactions", "blocks", 1, "tail", to)
266-
// return
267-
//}
268-
// TODO @holiman, add this back (if we want it)
269288
var (
270-
hashesCh, abortCh = iterateTransactions(db, from, to, false)
271-
batch = db.NewBatch()
272-
start = time.Now()
273-
logged = start.Add(-7 * time.Second)
289+
hashesCh = iterateTransactions(db, from, to, false, interrupt)
290+
batch = db.NewBatch()
291+
start = time.Now()
292+
logged = start.Add(-7 * time.Second)
293+
// we expect the first number to come in to be [from]. Therefore, setting
294+
// nextNum to from means that the prqueue gap-evaluation will work correctly
295+
nextNum = from
296+
queue = prque.New(nil)
297+
// for stats reporting
298+
blocks, txs = 0, 0
274299
)
275-
defer close(abortCh)
276300
// Otherwise spin up the concurrent iterator and unindexer
277-
blocks, txs := 0, 0
278301
for delivery := range hashesCh {
279-
DeleteTxLookupEntries(batch, delivery.hashes)
280-
txs += len(delivery.hashes)
281-
blocks++
302+
// Push the delivery into the queue and process contiguous ranges.
303+
queue.Push(delivery, -int64(delivery.number))
304+
for !queue.Empty() {
305+
// If the next available item is gapped, return
306+
if _, priority := queue.Peek(); -priority != int64(nextNum) {
307+
break
308+
}
309+
// For testing
310+
if hook != nil && !hook(nextNum) {
311+
break
312+
}
313+
delivery := queue.PopItem().(*blockTxHashes)
314+
nextNum = delivery.number + 1
315+
DeleteTxLookupEntries(batch, delivery.hashes)
316+
txs += len(delivery.hashes)
317+
blocks++
282318

283-
// If enough data was accumulated in memory or we're at the last block, dump to disk
284-
// A batch counts the size of deletion as '1', so we need to flush more
285-
// often than that.
286-
if blocks%1000 == 0 {
287-
if err := batch.Write(); err != nil {
288-
log.Crit("Failed writing batch to db", "error", err)
289-
return
319+
// If enough data was accumulated in memory or we're at the last block, dump to disk
320+
// A batch counts the size of deletion as '1', so we need to flush more
321+
// often than that.
322+
if blocks%1000 == 0 {
323+
WriteTxIndexTail(batch, nextNum)
324+
if err := batch.Write(); err != nil {
325+
log.Crit("Failed writing batch to db", "error", err)
326+
return
327+
}
328+
batch.Reset()
329+
}
330+
// If we've spent too much time already, notify the user of what we're doing
331+
if time.Since(logged) > 8*time.Second {
332+
log.Info("Unindexing transactions", "blocks", blocks, "txs", txs, "total", to-from, "elapsed", common.PrettyDuration(time.Since(start)))
333+
logged = time.Now()
290334
}
291-
batch.Reset()
292335
}
293-
// If we've spent too much time already, notify the user of what we're doing
294-
if time.Since(logged) > 8*time.Second {
295-
log.Info("Unindexing transactions", "blocks", blocks, "txs", txs, "total", to-from, "elapsed", common.PrettyDuration(time.Since(start)))
296-
logged = time.Now()
336+
}
337+
// Commit the last batch if there exists uncommitted data
338+
if batch.ValueSize() > 0 {
339+
WriteTxIndexTail(batch, nextNum)
340+
if err := batch.Write(); err != nil {
341+
log.Crit("Failed writing batch to db", "error", err)
342+
return
297343
}
298344
}
299-
if err := batch.Write(); err != nil {
300-
log.Crit("Failed writing batch to db", "error", err)
301-
return
345+
select {
346+
case <-interrupt:
347+
log.Debug("Transaction unindexing interrupted", "blocks", blocks, "txs", txs, "tail", to, "elapsed", common.PrettyDuration(time.Since(start)))
348+
default:
349+
log.Info("Unindexed transactions", "blocks", blocks, "txs", txs, "tail", to, "elapsed", common.PrettyDuration(time.Since(start)))
302350
}
303-
log.Info("Unindexed transactions", "blocks", blocks, "txs", txs, "tail", to, "elapsed", common.PrettyDuration(time.Since(start)))
351+
}
352+
353+
// UnindexTransactions removes txlookup indices of the specified block range.
354+
//
355+
// There is a passed channel, the whole procedure will be interrupted if any
356+
// signal received.
357+
func UnindexTransactions(db ethdb.Database, from uint64, to uint64, interrupt chan struct{}) {
358+
unindexTransactions(db, from, to, interrupt, nil)
359+
}
360+
361+
// unindexTransactionsForTesting is the internal debug version with an additional hook.
362+
func unindexTransactionsForTesting(db ethdb.Database, from uint64, to uint64, interrupt chan struct{}, hook func(uint64) bool) {
363+
unindexTransactions(db, from, to, interrupt, hook)
304364
}

0 commit comments

Comments
 (0)