github.com/phillinzzz/newBsc@v1.1.6/core/rawdb/freezer.go (about) 1 // Copyright 2019 The go-ethereum Authors 2 // This file is part of the go-ethereum library. 3 // 4 // The go-ethereum library is free software: you can redistribute it and/or modify 5 // it under the terms of the GNU Lesser General Public License as published by 6 // the Free Software Foundation, either version 3 of the License, or 7 // (at your option) any later version. 8 // 9 // The go-ethereum library is distributed in the hope that it will be useful, 10 // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 // GNU Lesser General Public License for more details. 13 // 14 // You should have received a copy of the GNU Lesser General Public License 15 // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. 16 17 package rawdb 18 19 import ( 20 "errors" 21 "fmt" 22 "math" 23 "os" 24 "path/filepath" 25 "sync" 26 "sync/atomic" 27 "time" 28 29 "github.com/phillinzzz/newBsc/common" 30 "github.com/phillinzzz/newBsc/ethdb" 31 "github.com/phillinzzz/newBsc/log" 32 "github.com/phillinzzz/newBsc/metrics" 33 "github.com/phillinzzz/newBsc/params" 34 "github.com/prometheus/tsdb/fileutil" 35 ) 36 37 var ( 38 // errReadOnly is returned if the freezer is opened in read only mode. All the 39 // mutations are disallowed. 40 errReadOnly = errors.New("read only") 41 42 // errUnknownTable is returned if the user attempts to read from a table that is 43 // not tracked by the freezer. 44 errUnknownTable = errors.New("unknown table") 45 46 // errOutOrderInsertion is returned if the user attempts to inject out-of-order 47 // binary blobs into the freezer. 48 errOutOrderInsertion = errors.New("the append operation is out-order") 49 50 // errSymlinkDatadir is returned if the ancient directory specified by user 51 // is a symbolic link. 52 errSymlinkDatadir = errors.New("symbolic link datadir is not supported") 53 ) 54 55 const ( 56 // freezerRecheckInterval is the frequency to check the key-value database for 57 // chain progression that might permit new blocks to be frozen into immutable 58 // storage. 59 freezerRecheckInterval = time.Minute 60 61 // freezerBatchLimit is the maximum number of blocks to freeze in one batch 62 // before doing an fsync and deleting it from the key-value store. 63 freezerBatchLimit = 30000 64 ) 65 66 // freezer is an memory mapped append-only database to store immutable chain data 67 // into flat files: 68 // 69 // - The append only nature ensures that disk writes are minimized. 70 // - The memory mapping ensures we can max out system memory for caching without 71 // reserving it for go-ethereum. This would also reduce the memory requirements 72 // of Geth, and thus also GC overhead. 73 type freezer struct { 74 // WARNING: The `frozen` field is accessed atomically. On 32 bit platforms, only 75 // 64-bit aligned fields can be atomic. The struct is guaranteed to be so aligned, 76 // so take advantage of that (https://golang.org/pkg/sync/atomic/#pkg-note-BUG). 77 frozen uint64 // Number of blocks already frozen 78 threshold uint64 // Number of recent blocks not to freeze (params.FullImmutabilityThreshold apart from tests) 79 80 readonly bool 81 tables map[string]*freezerTable // Data tables for storing everything 82 instanceLock fileutil.Releaser // File-system lock to prevent double opens 83 84 trigger chan chan struct{} // Manual blocking freeze trigger, test determinism 85 86 quit chan struct{} 87 closeOnce sync.Once 88 } 89 90 // newFreezer creates a chain freezer that moves ancient chain data into 91 // append-only flat file containers. 92 func newFreezer(datadir string, namespace string, readonly bool) (*freezer, error) { 93 // Create the initial freezer object 94 var ( 95 readMeter = metrics.NewRegisteredMeter(namespace+"ancient/read", nil) 96 writeMeter = metrics.NewRegisteredMeter(namespace+"ancient/write", nil) 97 sizeGauge = metrics.NewRegisteredGauge(namespace+"ancient/size", nil) 98 ) 99 // Ensure the datadir is not a symbolic link if it exists. 100 if info, err := os.Lstat(datadir); !os.IsNotExist(err) { 101 if info.Mode()&os.ModeSymlink != 0 { 102 log.Warn("Symbolic link ancient database is not supported", "path", datadir) 103 return nil, errSymlinkDatadir 104 } 105 } 106 // Leveldb uses LOCK as the filelock filename. To prevent the 107 // name collision, we use FLOCK as the lock name. 108 lock, _, err := fileutil.Flock(filepath.Join(datadir, "FLOCK")) 109 if err != nil { 110 return nil, err 111 } 112 // Open all the supported data tables 113 freezer := &freezer{ 114 readonly: readonly, 115 threshold: params.FullImmutabilityThreshold, 116 tables: make(map[string]*freezerTable), 117 instanceLock: lock, 118 trigger: make(chan chan struct{}), 119 quit: make(chan struct{}), 120 } 121 for name, disableSnappy := range FreezerNoSnappy { 122 table, err := newTable(datadir, name, readMeter, writeMeter, sizeGauge, disableSnappy) 123 if err != nil { 124 for _, table := range freezer.tables { 125 table.Close() 126 } 127 lock.Release() 128 return nil, err 129 } 130 freezer.tables[name] = table 131 } 132 if err := freezer.repair(); err != nil { 133 for _, table := range freezer.tables { 134 table.Close() 135 } 136 lock.Release() 137 return nil, err 138 } 139 log.Info("Opened ancient database", "database", datadir, "readonly", readonly) 140 return freezer, nil 141 } 142 143 // Close terminates the chain freezer, unmapping all the data files. 144 func (f *freezer) Close() error { 145 var errs []error 146 f.closeOnce.Do(func() { 147 close(f.quit) 148 for _, table := range f.tables { 149 if err := table.Close(); err != nil { 150 errs = append(errs, err) 151 } 152 } 153 if err := f.instanceLock.Release(); err != nil { 154 errs = append(errs, err) 155 } 156 }) 157 if errs != nil { 158 return fmt.Errorf("%v", errs) 159 } 160 return nil 161 } 162 163 // HasAncient returns an indicator whether the specified ancient data exists 164 // in the freezer. 165 func (f *freezer) HasAncient(kind string, number uint64) (bool, error) { 166 if table := f.tables[kind]; table != nil { 167 return table.has(number), nil 168 } 169 return false, nil 170 } 171 172 // Ancient retrieves an ancient binary blob from the append-only immutable files. 173 func (f *freezer) Ancient(kind string, number uint64) ([]byte, error) { 174 if table := f.tables[kind]; table != nil { 175 return table.Retrieve(number) 176 } 177 return nil, errUnknownTable 178 } 179 180 // Ancients returns the length of the frozen items. 181 func (f *freezer) Ancients() (uint64, error) { 182 return atomic.LoadUint64(&f.frozen), nil 183 } 184 185 // AncientSize returns the ancient size of the specified category. 186 func (f *freezer) AncientSize(kind string) (uint64, error) { 187 if table := f.tables[kind]; table != nil { 188 return table.size() 189 } 190 return 0, errUnknownTable 191 } 192 193 // AppendAncient injects all binary blobs belong to block at the end of the 194 // append-only immutable table files. 195 // 196 // Notably, this function is lock free but kind of thread-safe. All out-of-order 197 // injection will be rejected. But if two injections with same number happen at 198 // the same time, we can get into the trouble. 199 func (f *freezer) AppendAncient(number uint64, hash, header, body, receipts, td []byte) (err error) { 200 if f.readonly { 201 return errReadOnly 202 } 203 // Ensure the binary blobs we are appending is continuous with freezer. 204 if atomic.LoadUint64(&f.frozen) != number { 205 return errOutOrderInsertion 206 } 207 // Rollback all inserted data if any insertion below failed to ensure 208 // the tables won't out of sync. 209 defer func() { 210 if err != nil { 211 rerr := f.repair() 212 if rerr != nil { 213 log.Crit("Failed to repair freezer", "err", rerr) 214 } 215 log.Info("Append ancient failed", "number", number, "err", err) 216 } 217 }() 218 // Inject all the components into the relevant data tables 219 if err := f.tables[freezerHashTable].Append(f.frozen, hash[:]); err != nil { 220 log.Error("Failed to append ancient hash", "number", f.frozen, "hash", hash, "err", err) 221 return err 222 } 223 if err := f.tables[freezerHeaderTable].Append(f.frozen, header); err != nil { 224 log.Error("Failed to append ancient header", "number", f.frozen, "hash", hash, "err", err) 225 return err 226 } 227 if err := f.tables[freezerBodiesTable].Append(f.frozen, body); err != nil { 228 log.Error("Failed to append ancient body", "number", f.frozen, "hash", hash, "err", err) 229 return err 230 } 231 if err := f.tables[freezerReceiptTable].Append(f.frozen, receipts); err != nil { 232 log.Error("Failed to append ancient receipts", "number", f.frozen, "hash", hash, "err", err) 233 return err 234 } 235 if err := f.tables[freezerDifficultyTable].Append(f.frozen, td); err != nil { 236 log.Error("Failed to append ancient difficulty", "number", f.frozen, "hash", hash, "err", err) 237 return err 238 } 239 atomic.AddUint64(&f.frozen, 1) // Only modify atomically 240 return nil 241 } 242 243 // TruncateAncients discards any recent data above the provided threshold number. 244 func (f *freezer) TruncateAncients(items uint64) error { 245 if f.readonly { 246 return errReadOnly 247 } 248 if atomic.LoadUint64(&f.frozen) <= items { 249 return nil 250 } 251 for _, table := range f.tables { 252 if err := table.truncate(items); err != nil { 253 return err 254 } 255 } 256 atomic.StoreUint64(&f.frozen, items) 257 return nil 258 } 259 260 // Sync flushes all data tables to disk. 261 func (f *freezer) Sync() error { 262 var errs []error 263 for _, table := range f.tables { 264 if err := table.Sync(); err != nil { 265 errs = append(errs, err) 266 } 267 } 268 if errs != nil { 269 return fmt.Errorf("%v", errs) 270 } 271 return nil 272 } 273 274 // freeze is a background thread that periodically checks the blockchain for any 275 // import progress and moves ancient data from the fast database into the freezer. 276 // 277 // This functionality is deliberately broken off from block importing to avoid 278 // incurring additional data shuffling delays on block propagation. 279 func (f *freezer) freeze(db ethdb.KeyValueStore) { 280 nfdb := &nofreezedb{KeyValueStore: db} 281 282 var ( 283 backoff bool 284 triggered chan struct{} // Used in tests 285 ) 286 for { 287 select { 288 case <-f.quit: 289 log.Info("Freezer shutting down") 290 return 291 default: 292 } 293 if backoff { 294 // If we were doing a manual trigger, notify it 295 if triggered != nil { 296 triggered <- struct{}{} 297 triggered = nil 298 } 299 select { 300 case <-time.NewTimer(freezerRecheckInterval).C: 301 backoff = false 302 case triggered = <-f.trigger: 303 backoff = false 304 case <-f.quit: 305 return 306 } 307 } 308 // Retrieve the freezing threshold. 309 hash := ReadHeadBlockHash(nfdb) 310 if hash == (common.Hash{}) { 311 log.Debug("Current full block hash unavailable") // new chain, empty database 312 backoff = true 313 continue 314 } 315 number := ReadHeaderNumber(nfdb, hash) 316 threshold := atomic.LoadUint64(&f.threshold) 317 318 switch { 319 case number == nil: 320 log.Error("Current full block number unavailable", "hash", hash) 321 backoff = true 322 continue 323 324 case *number < threshold: 325 log.Debug("Current full block not old enough", "number", *number, "hash", hash, "delay", threshold) 326 backoff = true 327 continue 328 329 case *number-threshold <= f.frozen: 330 log.Debug("Ancient blocks frozen already", "number", *number, "hash", hash, "frozen", f.frozen) 331 backoff = true 332 continue 333 } 334 head := ReadHeader(nfdb, hash, *number) 335 if head == nil { 336 log.Error("Current full block unavailable", "number", *number, "hash", hash) 337 backoff = true 338 continue 339 } 340 // Seems we have data ready to be frozen, process in usable batches 341 limit := *number - threshold 342 if limit-f.frozen > freezerBatchLimit { 343 limit = f.frozen + freezerBatchLimit 344 } 345 var ( 346 start = time.Now() 347 first = f.frozen 348 ancients = make([]common.Hash, 0, limit-f.frozen) 349 ) 350 for f.frozen <= limit { 351 // Retrieves all the components of the canonical block 352 hash := ReadCanonicalHash(nfdb, f.frozen) 353 if hash == (common.Hash{}) { 354 log.Error("Canonical hash missing, can't freeze", "number", f.frozen) 355 break 356 } 357 header := ReadHeaderRLP(nfdb, hash, f.frozen) 358 if len(header) == 0 { 359 log.Error("Block header missing, can't freeze", "number", f.frozen, "hash", hash) 360 break 361 } 362 body := ReadBodyRLP(nfdb, hash, f.frozen) 363 if len(body) == 0 { 364 log.Error("Block body missing, can't freeze", "number", f.frozen, "hash", hash) 365 break 366 } 367 receipts := ReadReceiptsRLP(nfdb, hash, f.frozen) 368 if len(receipts) == 0 { 369 log.Error("Block receipts missing, can't freeze", "number", f.frozen, "hash", hash) 370 break 371 } 372 td := ReadTdRLP(nfdb, hash, f.frozen) 373 if len(td) == 0 { 374 log.Error("Total difficulty missing, can't freeze", "number", f.frozen, "hash", hash) 375 break 376 } 377 log.Trace("Deep froze ancient block", "number", f.frozen, "hash", hash) 378 // Inject all the components into the relevant data tables 379 if err := f.AppendAncient(f.frozen, hash[:], header, body, receipts, td); err != nil { 380 break 381 } 382 ancients = append(ancients, hash) 383 } 384 // Batch of blocks have been frozen, flush them before wiping from leveldb 385 if err := f.Sync(); err != nil { 386 log.Crit("Failed to flush frozen tables", "err", err) 387 } 388 // Wipe out all data from the active database 389 batch := db.NewBatch() 390 for i := 0; i < len(ancients); i++ { 391 // Always keep the genesis block in active database 392 if first+uint64(i) != 0 { 393 DeleteBlockWithoutNumber(batch, ancients[i], first+uint64(i)) 394 DeleteCanonicalHash(batch, first+uint64(i)) 395 } 396 } 397 if err := batch.Write(); err != nil { 398 log.Crit("Failed to delete frozen canonical blocks", "err", err) 399 } 400 batch.Reset() 401 402 // Wipe out side chains also and track dangling side chians 403 var dangling []common.Hash 404 for number := first; number < f.frozen; number++ { 405 // Always keep the genesis block in active database 406 if number != 0 { 407 dangling = ReadAllHashes(db, number) 408 for _, hash := range dangling { 409 log.Trace("Deleting side chain", "number", number, "hash", hash) 410 DeleteBlock(batch, hash, number) 411 } 412 } 413 } 414 if err := batch.Write(); err != nil { 415 log.Crit("Failed to delete frozen side blocks", "err", err) 416 } 417 batch.Reset() 418 419 // Step into the future and delete and dangling side chains 420 if f.frozen > 0 { 421 tip := f.frozen 422 for len(dangling) > 0 { 423 drop := make(map[common.Hash]struct{}) 424 for _, hash := range dangling { 425 log.Debug("Dangling parent from freezer", "number", tip-1, "hash", hash) 426 drop[hash] = struct{}{} 427 } 428 children := ReadAllHashes(db, tip) 429 for i := 0; i < len(children); i++ { 430 // Dig up the child and ensure it's dangling 431 child := ReadHeader(nfdb, children[i], tip) 432 if child == nil { 433 log.Error("Missing dangling header", "number", tip, "hash", children[i]) 434 continue 435 } 436 if _, ok := drop[child.ParentHash]; !ok { 437 children = append(children[:i], children[i+1:]...) 438 i-- 439 continue 440 } 441 // Delete all block data associated with the child 442 log.Debug("Deleting dangling block", "number", tip, "hash", children[i], "parent", child.ParentHash) 443 DeleteBlock(batch, children[i], tip) 444 } 445 dangling = children 446 tip++ 447 } 448 if err := batch.Write(); err != nil { 449 log.Crit("Failed to delete dangling side blocks", "err", err) 450 } 451 } 452 // Log something friendly for the user 453 context := []interface{}{ 454 "blocks", f.frozen - first, "elapsed", common.PrettyDuration(time.Since(start)), "number", f.frozen - 1, 455 } 456 if n := len(ancients); n > 0 { 457 context = append(context, []interface{}{"hash", ancients[n-1]}...) 458 } 459 log.Info("Deep froze chain segment", context...) 460 461 // Avoid database thrashing with tiny writes 462 if f.frozen-first < freezerBatchLimit { 463 backoff = true 464 } 465 } 466 } 467 468 // repair truncates all data tables to the same length. 469 func (f *freezer) repair() error { 470 min := uint64(math.MaxUint64) 471 for _, table := range f.tables { 472 items := atomic.LoadUint64(&table.items) 473 if min > items { 474 min = items 475 } 476 } 477 for _, table := range f.tables { 478 if err := table.truncate(min); err != nil { 479 return err 480 } 481 } 482 atomic.StoreUint64(&f.frozen, min) 483 return nil 484 }