github.com/aigarnetwork/aigar@v0.0.0-20191115204914-d59a6eb70f8e/ethdb/leveldb/leveldb.go (about) 1 // Copyright 2018 The go-ethereum Authors 2 // Copyright 2019 The go-aigar Authors 3 // This file is part of the go-aigar library. 4 // 5 // The go-aigar library is free software: you can redistribute it and/or modify 6 // it under the terms of the GNU Lesser General Public License as published by 7 // the Free Software Foundation, either version 3 of the License, or 8 // (at your option) any later version. 9 // 10 // The go-aigar library is distributed in the hope that it will be useful, 11 // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 // GNU Lesser General Public License for more details. 14 // 15 // You should have received a copy of the GNU Lesser General Public License 16 // along with the go-aigar library. If not, see <http://www.gnu.org/licenses/>. 17 18 // +build !js 19 20 // Package leveldb implements the key-value database layer based on LevelDB. 21 package leveldb 22 23 import ( 24 "fmt" 25 "strconv" 26 "strings" 27 "sync" 28 "time" 29 30 "github.com/AigarNetwork/aigar/common" 31 "github.com/AigarNetwork/aigar/ethdb" 32 "github.com/AigarNetwork/aigar/log" 33 "github.com/AigarNetwork/aigar/metrics" 34 "github.com/syndtr/goleveldb/leveldb" 35 "github.com/syndtr/goleveldb/leveldb/errors" 36 "github.com/syndtr/goleveldb/leveldb/filter" 37 "github.com/syndtr/goleveldb/leveldb/opt" 38 "github.com/syndtr/goleveldb/leveldb/util" 39 ) 40 41 const ( 42 // degradationWarnInterval specifies how often warning should be printed if the 43 // leveldb database cannot keep up with requested writes. 44 degradationWarnInterval = time.Minute 45 46 // minCache is the minimum amount of memory in megabytes to allocate to leveldb 47 // read and write caching, split half and half. 48 minCache = 16 49 50 // minHandles is the minimum number of files handles to allocate to the open 51 // database files. 52 minHandles = 16 53 54 // metricsGatheringInterval specifies the interval to retrieve leveldb database 55 // compaction, io and pause stats to report to the user. 56 metricsGatheringInterval = 3 * time.Second 57 ) 58 59 // Database is a persistent key-value store. Apart from basic data storage 60 // functionality it also supports batch writes and iterating over the keyspace in 61 // binary-alphabetical order. 62 type Database struct { 63 fn string // filename for reporting 64 db *leveldb.DB // LevelDB instance 65 66 compTimeMeter metrics.Meter // Meter for measuring the total time spent in database compaction 67 compReadMeter metrics.Meter // Meter for measuring the data read during compaction 68 compWriteMeter metrics.Meter // Meter for measuring the data written during compaction 69 writeDelayNMeter metrics.Meter // Meter for measuring the write delay number due to database compaction 70 writeDelayMeter metrics.Meter // Meter for measuring the write delay duration due to database compaction 71 diskSizeGauge metrics.Gauge // Gauge for tracking the size of all the levels in the database 72 diskReadMeter metrics.Meter // Meter for measuring the effective amount of data read 73 diskWriteMeter metrics.Meter // Meter for measuring the effective amount of data written 74 memCompGauge metrics.Gauge // Gauge for tracking the number of memory compaction 75 level0CompGauge metrics.Gauge // Gauge for tracking the number of table compaction in level0 76 nonlevel0CompGauge metrics.Gauge // Gauge for tracking the number of table compaction in non0 level 77 seekCompGauge metrics.Gauge // Gauge for tracking the number of table compaction caused by read opt 78 79 quitLock sync.Mutex // Mutex protecting the quit channel access 80 quitChan chan chan error // Quit channel to stop the metrics collection before closing the database 81 82 log log.Logger // Contextual logger tracking the database path 83 } 84 85 // New returns a wrapped LevelDB object. The namespace is the prefix that the 86 // metrics reporting should use for surfacing internal stats. 87 func New(file string, cache int, handles int, namespace string) (*Database, error) { 88 // Ensure we have some minimal caching and file guarantees 89 if cache < minCache { 90 cache = minCache 91 } 92 if handles < minHandles { 93 handles = minHandles 94 } 95 logger := log.New("database", file) 96 logger.Info("Allocated cache and file handles", "cache", common.StorageSize(cache*1024*1024), "handles", handles) 97 98 // Open the db and recover any potential corruptions 99 db, err := leveldb.OpenFile(file, &opt.Options{ 100 OpenFilesCacheCapacity: handles, 101 BlockCacheCapacity: cache / 2 * opt.MiB, 102 WriteBuffer: cache / 4 * opt.MiB, // Two of these are used internally 103 Filter: filter.NewBloomFilter(10), 104 DisableSeeksCompaction: true, 105 }) 106 if _, corrupted := err.(*errors.ErrCorrupted); corrupted { 107 db, err = leveldb.RecoverFile(file, nil) 108 } 109 if err != nil { 110 return nil, err 111 } 112 // Assemble the wrapper with all the registered metrics 113 ldb := &Database{ 114 fn: file, 115 db: db, 116 log: logger, 117 quitChan: make(chan chan error), 118 } 119 ldb.compTimeMeter = metrics.NewRegisteredMeter(namespace+"compact/time", nil) 120 ldb.compReadMeter = metrics.NewRegisteredMeter(namespace+"compact/input", nil) 121 ldb.compWriteMeter = metrics.NewRegisteredMeter(namespace+"compact/output", nil) 122 ldb.diskSizeGauge = metrics.NewRegisteredGauge(namespace+"disk/size", nil) 123 ldb.diskReadMeter = metrics.NewRegisteredMeter(namespace+"disk/read", nil) 124 ldb.diskWriteMeter = metrics.NewRegisteredMeter(namespace+"disk/write", nil) 125 ldb.writeDelayMeter = metrics.NewRegisteredMeter(namespace+"compact/writedelay/duration", nil) 126 ldb.writeDelayNMeter = metrics.NewRegisteredMeter(namespace+"compact/writedelay/counter", nil) 127 ldb.memCompGauge = metrics.NewRegisteredGauge(namespace+"compact/memory", nil) 128 ldb.level0CompGauge = metrics.NewRegisteredGauge(namespace+"compact/level0", nil) 129 ldb.nonlevel0CompGauge = metrics.NewRegisteredGauge(namespace+"compact/nonlevel0", nil) 130 ldb.seekCompGauge = metrics.NewRegisteredGauge(namespace+"compact/seek", nil) 131 132 // Start up the metrics gathering and return 133 go ldb.meter(metricsGatheringInterval) 134 return ldb, nil 135 } 136 137 // Close stops the metrics collection, flushes any pending data to disk and closes 138 // all io accesses to the underlying key-value store. 139 func (db *Database) Close() error { 140 db.quitLock.Lock() 141 defer db.quitLock.Unlock() 142 143 if db.quitChan != nil { 144 errc := make(chan error) 145 db.quitChan <- errc 146 if err := <-errc; err != nil { 147 db.log.Error("Metrics collection failed", "err", err) 148 } 149 db.quitChan = nil 150 } 151 return db.db.Close() 152 } 153 154 // Has retrieves if a key is present in the key-value store. 155 func (db *Database) Has(key []byte) (bool, error) { 156 return db.db.Has(key, nil) 157 } 158 159 // Get retrieves the given key if it's present in the key-value store. 160 func (db *Database) Get(key []byte) ([]byte, error) { 161 dat, err := db.db.Get(key, nil) 162 if err != nil { 163 return nil, err 164 } 165 return dat, nil 166 } 167 168 // Put inserts the given value into the key-value store. 169 func (db *Database) Put(key []byte, value []byte) error { 170 return db.db.Put(key, value, nil) 171 } 172 173 // Delete removes the key from the key-value store. 174 func (db *Database) Delete(key []byte) error { 175 return db.db.Delete(key, nil) 176 } 177 178 // NewBatch creates a write-only key-value store that buffers changes to its host 179 // database until a final write is called. 180 func (db *Database) NewBatch() ethdb.Batch { 181 return &batch{ 182 db: db.db, 183 b: new(leveldb.Batch), 184 } 185 } 186 187 // NewIterator creates a binary-alphabetical iterator over the entire keyspace 188 // contained within the leveldb database. 189 func (db *Database) NewIterator() ethdb.Iterator { 190 return db.db.NewIterator(new(util.Range), nil) 191 } 192 193 // NewIteratorWithStart creates a binary-alphabetical iterator over a subset of 194 // database content starting at a particular initial key (or after, if it does 195 // not exist). 196 func (db *Database) NewIteratorWithStart(start []byte) ethdb.Iterator { 197 return db.db.NewIterator(&util.Range{Start: start}, nil) 198 } 199 200 // NewIteratorWithPrefix creates a binary-alphabetical iterator over a subset 201 // of database content with a particular key prefix. 202 func (db *Database) NewIteratorWithPrefix(prefix []byte) ethdb.Iterator { 203 return db.db.NewIterator(util.BytesPrefix(prefix), nil) 204 } 205 206 // Stat returns a particular internal stat of the database. 207 func (db *Database) Stat(property string) (string, error) { 208 return db.db.GetProperty(property) 209 } 210 211 // Compact flattens the underlying data store for the given key range. In essence, 212 // deleted and overwritten versions are discarded, and the data is rearranged to 213 // reduce the cost of operations needed to access them. 214 // 215 // A nil start is treated as a key before all keys in the data store; a nil limit 216 // is treated as a key after all keys in the data store. If both is nil then it 217 // will compact entire data store. 218 func (db *Database) Compact(start []byte, limit []byte) error { 219 return db.db.CompactRange(util.Range{Start: start, Limit: limit}) 220 } 221 222 // Path returns the path to the database directory. 223 func (db *Database) Path() string { 224 return db.fn 225 } 226 227 // meter periodically retrieves internal leveldb counters and reports them to 228 // the metrics subsystem. 229 // 230 // This is how a LevelDB stats table looks like (currently): 231 // Compactions 232 // Level | Tables | Size(MB) | Time(sec) | Read(MB) | Write(MB) 233 // -------+------------+---------------+---------------+---------------+--------------- 234 // 0 | 0 | 0.00000 | 1.27969 | 0.00000 | 12.31098 235 // 1 | 85 | 109.27913 | 28.09293 | 213.92493 | 214.26294 236 // 2 | 523 | 1000.37159 | 7.26059 | 66.86342 | 66.77884 237 // 3 | 570 | 1113.18458 | 0.00000 | 0.00000 | 0.00000 238 // 239 // This is how the write delay look like (currently): 240 // DelayN:5 Delay:406.604657ms Paused: false 241 // 242 // This is how the iostats look like (currently): 243 // Read(MB):3895.04860 Write(MB):3654.64712 244 func (db *Database) meter(refresh time.Duration) { 245 // Create the counters to store current and previous compaction values 246 compactions := make([][]float64, 2) 247 for i := 0; i < 2; i++ { 248 compactions[i] = make([]float64, 4) 249 } 250 // Create storage for iostats. 251 var iostats [2]float64 252 253 // Create storage and warning log tracer for write delay. 254 var ( 255 delaystats [2]int64 256 lastWritePaused time.Time 257 ) 258 259 var ( 260 errc chan error 261 merr error 262 ) 263 264 // Iterate ad infinitum and collect the stats 265 for i := 1; errc == nil && merr == nil; i++ { 266 // Retrieve the database stats 267 stats, err := db.db.GetProperty("leveldb.stats") 268 if err != nil { 269 db.log.Error("Failed to read database stats", "err", err) 270 merr = err 271 continue 272 } 273 // Find the compaction table, skip the header 274 lines := strings.Split(stats, "\n") 275 for len(lines) > 0 && strings.TrimSpace(lines[0]) != "Compactions" { 276 lines = lines[1:] 277 } 278 if len(lines) <= 3 { 279 db.log.Error("Compaction leveldbTable not found") 280 merr = errors.New("compaction leveldbTable not found") 281 continue 282 } 283 lines = lines[3:] 284 285 // Iterate over all the leveldbTable rows, and accumulate the entries 286 for j := 0; j < len(compactions[i%2]); j++ { 287 compactions[i%2][j] = 0 288 } 289 for _, line := range lines { 290 parts := strings.Split(line, "|") 291 if len(parts) != 6 { 292 break 293 } 294 for idx, counter := range parts[2:] { 295 value, err := strconv.ParseFloat(strings.TrimSpace(counter), 64) 296 if err != nil { 297 db.log.Error("Compaction entry parsing failed", "err", err) 298 merr = err 299 continue 300 } 301 compactions[i%2][idx] += value 302 } 303 } 304 // Update all the requested meters 305 if db.diskSizeGauge != nil { 306 db.diskSizeGauge.Update(int64(compactions[i%2][0] * 1024 * 1024)) 307 } 308 if db.compTimeMeter != nil { 309 db.compTimeMeter.Mark(int64((compactions[i%2][1] - compactions[(i-1)%2][1]) * 1000 * 1000 * 1000)) 310 } 311 if db.compReadMeter != nil { 312 db.compReadMeter.Mark(int64((compactions[i%2][2] - compactions[(i-1)%2][2]) * 1024 * 1024)) 313 } 314 if db.compWriteMeter != nil { 315 db.compWriteMeter.Mark(int64((compactions[i%2][3] - compactions[(i-1)%2][3]) * 1024 * 1024)) 316 } 317 // Retrieve the write delay statistic 318 writedelay, err := db.db.GetProperty("leveldb.writedelay") 319 if err != nil { 320 db.log.Error("Failed to read database write delay statistic", "err", err) 321 merr = err 322 continue 323 } 324 var ( 325 delayN int64 326 delayDuration string 327 duration time.Duration 328 paused bool 329 ) 330 if n, err := fmt.Sscanf(writedelay, "DelayN:%d Delay:%s Paused:%t", &delayN, &delayDuration, &paused); n != 3 || err != nil { 331 db.log.Error("Write delay statistic not found") 332 merr = err 333 continue 334 } 335 duration, err = time.ParseDuration(delayDuration) 336 if err != nil { 337 db.log.Error("Failed to parse delay duration", "err", err) 338 merr = err 339 continue 340 } 341 if db.writeDelayNMeter != nil { 342 db.writeDelayNMeter.Mark(delayN - delaystats[0]) 343 } 344 if db.writeDelayMeter != nil { 345 db.writeDelayMeter.Mark(duration.Nanoseconds() - delaystats[1]) 346 } 347 // If a warning that db is performing compaction has been displayed, any subsequent 348 // warnings will be withheld for one minute not to overwhelm the user. 349 if paused && delayN-delaystats[0] == 0 && duration.Nanoseconds()-delaystats[1] == 0 && 350 time.Now().After(lastWritePaused.Add(degradationWarnInterval)) { 351 db.log.Warn("Database compacting, degraded performance") 352 lastWritePaused = time.Now() 353 } 354 delaystats[0], delaystats[1] = delayN, duration.Nanoseconds() 355 356 // Retrieve the database iostats. 357 ioStats, err := db.db.GetProperty("leveldb.iostats") 358 if err != nil { 359 db.log.Error("Failed to read database iostats", "err", err) 360 merr = err 361 continue 362 } 363 var nRead, nWrite float64 364 parts := strings.Split(ioStats, " ") 365 if len(parts) < 2 { 366 db.log.Error("Bad syntax of ioStats", "ioStats", ioStats) 367 merr = fmt.Errorf("bad syntax of ioStats %s", ioStats) 368 continue 369 } 370 if n, err := fmt.Sscanf(parts[0], "Read(MB):%f", &nRead); n != 1 || err != nil { 371 db.log.Error("Bad syntax of read entry", "entry", parts[0]) 372 merr = err 373 continue 374 } 375 if n, err := fmt.Sscanf(parts[1], "Write(MB):%f", &nWrite); n != 1 || err != nil { 376 db.log.Error("Bad syntax of write entry", "entry", parts[1]) 377 merr = err 378 continue 379 } 380 if db.diskReadMeter != nil { 381 db.diskReadMeter.Mark(int64((nRead - iostats[0]) * 1024 * 1024)) 382 } 383 if db.diskWriteMeter != nil { 384 db.diskWriteMeter.Mark(int64((nWrite - iostats[1]) * 1024 * 1024)) 385 } 386 iostats[0], iostats[1] = nRead, nWrite 387 388 compCount, err := db.db.GetProperty("leveldb.compcount") 389 if err != nil { 390 db.log.Error("Failed to read database iostats", "err", err) 391 merr = err 392 continue 393 } 394 395 var ( 396 memComp uint32 397 level0Comp uint32 398 nonLevel0Comp uint32 399 seekComp uint32 400 ) 401 if n, err := fmt.Sscanf(compCount, "MemComp:%d Level0Comp:%d NonLevel0Comp:%d SeekComp:%d", &memComp, &level0Comp, &nonLevel0Comp, &seekComp); n != 4 || err != nil { 402 db.log.Error("Compaction count statistic not found") 403 merr = err 404 continue 405 } 406 db.memCompGauge.Update(int64(memComp)) 407 db.level0CompGauge.Update(int64(level0Comp)) 408 db.nonlevel0CompGauge.Update(int64(nonLevel0Comp)) 409 db.seekCompGauge.Update(int64(seekComp)) 410 411 // Sleep a bit, then repeat the stats collection 412 select { 413 case errc = <-db.quitChan: 414 // Quit requesting, stop hammering the database 415 case <-time.After(refresh): 416 // Timeout, gather a new set of stats 417 } 418 } 419 420 if errc == nil { 421 errc = <-db.quitChan 422 } 423 errc <- merr 424 } 425 426 // batch is a write-only leveldb batch that commits changes to its host database 427 // when Write is called. A batch cannot be used concurrently. 428 type batch struct { 429 db *leveldb.DB 430 b *leveldb.Batch 431 size int 432 } 433 434 // Put inserts the given value into the batch for later committing. 435 func (b *batch) Put(key, value []byte) error { 436 b.b.Put(key, value) 437 b.size += len(value) 438 return nil 439 } 440 441 // Delete inserts the a key removal into the batch for later committing. 442 func (b *batch) Delete(key []byte) error { 443 b.b.Delete(key) 444 b.size++ 445 return nil 446 } 447 448 // ValueSize retrieves the amount of data queued up for writing. 449 func (b *batch) ValueSize() int { 450 return b.size 451 } 452 453 // Write flushes any accumulated data to disk. 454 func (b *batch) Write() error { 455 return b.db.Write(b.b, nil) 456 } 457 458 // Reset resets the batch for reuse. 459 func (b *batch) Reset() { 460 b.b.Reset() 461 b.size = 0 462 } 463 464 // Replay replays the batch contents. 465 func (b *batch) Replay(w ethdb.KeyValueWriter) error { 466 return b.b.Replay(&replayer{writer: w}) 467 } 468 469 // replayer is a small wrapper to implement the correct replay methods. 470 type replayer struct { 471 writer ethdb.KeyValueWriter 472 failure error 473 } 474 475 // Put inserts the given value into the key-value data store. 476 func (r *replayer) Put(key, value []byte) { 477 // If the replay already failed, stop executing ops 478 if r.failure != nil { 479 return 480 } 481 r.failure = r.writer.Put(key, value) 482 } 483 484 // Delete removes the key from the key-value data store. 485 func (r *replayer) Delete(key []byte) { 486 // If the replay already failed, stop executing ops 487 if r.failure != nil { 488 return 489 } 490 r.failure = r.writer.Delete(key) 491 }