Go-ethereum 源码解析之 go-ethereum/ethdb/database.go

Go-ethereum 源码解析之 go-ethereum/ethdb/database.go


Source code

// Copyright 2017 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.


Appendix A. 总体批注

实现了底层数据库 LevelDB 的抽象层 LDBDatabase,用于生产环境。

ethdb.LDBDatabase 实现了接口 ethdb.Database,并且将实际的操作转发给 LevelDB 的接口。同时,基于 metrics.Meter 测试各操作的性能。

ethdb.ldbBatch 在 ethdb.LDBDatabase 的基础上提供了批处理能力。

暂时不深入与性能相关的实现 metrics.Meter。


Appendix B. 详细批注

1. const

  • writePauseWarningThrottler = 1 * time.Minute: ??? 性能相关指标

2. var

  • var OpenFileLimit = 64: ??? LevelDB 一次能打开的文件数量上限?

3. type LDBDatabase struct

数据结构 LDBDatabase 实现了接口 ethdb.Database,并且将实际的操作转发给 LevelDB 的接口。同时,基于 metrics.Meter 测试各操作的性能。

  • fn string: 文件名。??? 干什么的文件名呢?

  • db *leveldb.DB: LevelDB 实例

  • compTimeMeter metrics.Meter // Meter for measuring the total time spent in database compaction

  • compReadMeter metrics.Meter // Meter for measuring the data read during compaction

  • compWriteMeter metrics.Meter // Meter for measuring the data written during compaction

  • writeDelayNMeter metrics.Meter // Meter for measuring the write delay number due to database compaction

  • writeDelayMeter metrics.Meter // Meter for measuring the write delay duration due to database compaction

  • diskReadMeter metrics.Meter // Meter for measuring the effective amount of data read

  • diskWriteMeter metrics.Meter // Meter for measuring the effective amount of data written

  • quitLock sync.Mutex // Mutex protecting the quit channel access

  • quitChan chan chan error // Quit channel to stop the metrics collection before closing the database

  • log log.Logger // Contextual logger tracking the database path

3.1 func NewLDBDatabase(file string, cache int, handles int) (*LDBDatabase, error)

构造函数 NewLDBDatabase() 创建 LDBDatabase 的一个实例,该实例是 LevelDB 的包装器。

参数:

  • file string: 文件名
  • cache int: ??? 缓存?
  • handles int: ??? 处理器?

返回值:

  • LDBDatabase 实例
  • 出错返回错误消息 error,否则返回 nil

主要实现:

  • 构建日志器 logger

    • logger := log.New("database", file)
  • 调整 cache,确保其最小值为 16

  • 调整 handles,确保其最小值为 16

  • 输出日志信息:logger.Info("Allocated cache and file handles", "cache", cache, "handles", handles)

  • 打开 LevelDB,并从可能的错误恢复

    • db, err := leveldb.OpenFile(file, ...)
    • corrupted := err.(*errors.ErrCorrupted)
    • db, err = leveldb.RecoverFile(file, nil)
  • 如果 err 不为 nil,则直接退出

    • return nil, err
  • 构建 LDBDatabase 的实例并返回

    • return &LDBDatabase{fn: file, db: db, log: logger}, nil

注意,这里并没有初始化任何性能计时器。

3.2 func (db *LDBDatabase) Path() string

方法 Path() 返回数据库目录的路径。

3.3 func (db *LDBDatabase) Put(key []byte, value []byte) error

方法 Put() 实现了接口 ethdb.Putter 和接口 ethdb.Database,将 key & value 写入数据库。

参数:

  • key []byte: key
  • value []byte: value

返回值:

  • 出错返回错误消息 error,否则返回 nil

主要实现:

  • 转发给 LevelDB 的方法 Put()
    • return db.db.Put(key, value, nil)

3.4 func (db *LDBDatabase) Has(key []byte) (bool, error)

方法 Has() 实现了接口 ethdb.Database,查询给定的 key 是否存在于数据库。

参数:

  • key []byte: key

返回值:

  • 存在返回 true,否则返回 false
  • 出错返回错误消息 error,否则返回 nil

主要实现:

  • 转发给 LevelDB 的方法 Has()
    • return db.db.Has(key, nil)

3.5 func (db *LDBDatabase) Get(key []byte) ([]byte, error)

方法 Get() 实现了接口 ethdb.Database,从数据库中获取给定 key 对应的 value。

参数:

  • key []byte: key

返回值:

  • 存在返回 key 对应的 value
  • 出错返回错误消息 error,否则返回 nil

主要实现:

  • 转发给 LevelDB 的方法 Get()
    • dat, err := db.db.Get(key, nil)

3.6 func (db *LDBDatabase) Delete(key []byte) error

方法 Delete() 实现了接口 ethdb.Database,从数据库中删除指定的 key。

参数:

  • key []byte: key

返回值:

  • 出错返回错误消息 error,否则返回 nil

主要实现:

  • 转发给 LevelDB 的方法 Delete()
    • return db.db.Delete(key, nil)

3.7 func (db *LDBDatabase) NewIterator() iterator.Iterator

方法 NewIterator() 返回 LevelDB 的迭代器 iterator.Iterator。

返回值:

  • LevelDB 的迭代器 iterator.Iterator

主要实现:

  • return db.db.NewIterator(nil, nil)

3.8 func (db *LDBDatabase) NewIteratorWithPrefix(prefix []byte) iterator.Iterator

方法 NewIteratorWithPrefix() 返回 LevelDB 的迭代器 iterator.Iterator,这个迭代器指向具有指定前缀的数据库子集。

参数:

  • prefix []byte: 前缀

返回值:

  • LevelDB 的迭代器 iterator.Iterator

主要实现:

  • return db.db.NewIterator(util.BytesPrefix(prefix), nil)

3.9 func (db *LDBDatabase) Close()

方法 Close() 实现了接口 ethdb.Database。

主要实现:

  • ??? 停止性能指标器
  • 将实际的关闭操作转发给 LevelDB 的方法 Close()
    • err := db.db.Close()
    • 如果 err == nil
      • db.log.Info("Database closed")
    • 否则
      • db.log.Error("Failed to close database", "err", err)

3.10 func (db *LDBDatabase) LDB() *leveldb.DB

方法 LDB() 返回 LDBDatabase 中的底层 LevelDB 数据库。

返回值:

  • LDBDatabase 中的底层 LevelDB 数据库。

主要实现:

  • return db.db

3.11 func (db *LDBDatabase) Meter(prefix string)

性能指标相关内容,暂时不关注。

3.12 func (db *LDBDatabase) meter(refresh time.Duration)

性能指标相关内容,暂时不关注。

3.13 func (db *LDBDatabase) NewBatch() Batch

方法 NewBatch() 返回批处理器。

返回值:

  • 批处理器 ldbBatch

主要实现:

  • return &ldbBatch{db: db.db, b: new(leveldb.Batch)}

4. type ldbBatch struct

数据结构 ldbBatch 在 LevelDB 的基础上提供批处理能力。

  • db *leveldb.DB: 底层的 LevelDB
  • b *leveldb.Batch: LevelDB 的批处理器
  • size int: 字节数

4.1 func (b *ldbBatch) Put(key, value []byte) error

方法 Put() 实现了接口 ethdb.Putter 和接口 ethdb.Batch,将 key & value 写入数据库。

参数:

  • key []byte: key
  • value []byte: value

返回值:

  • 出错返回错误消息 error,否则返回 nil

主要实现:

  • 转发给 leveldb.Batch 的方法 Put()
    • b.b.Put(key, value)
  • 更新字节数
    • b.size += len(value)

4.2 func (b *ldbBatch) Delete(key []byte) error

方法 Delete() 实现了接口 ethdb.Deleter 和接口 ethdb.Batch,从数据库中删除指定的 key。

参数:

  • key []byte: key

返回值:

  • 出错返回错误消息 error,否则返回 nil

主要实现:

  • 转发给 leveldb.Batch 的方法 Delete()
    • b.b.Delete(key)
  • 更新字节数
    • b.size += 1

4.3 func (b *ldbBatch) Write() error

方法 Write() 实现了接口 ethdb.Batch,将批量数据一次性写入数据库。

返回值:

  • 出错返回错误消息 error,否则返回 nil

主要实现:

  • return b.db.Write(b.b, nil)

4.4 func (b *ldbBatch) ValueSize() int

方法 ValueSize() 实现了接口 ethdb.Batch,返回批量字节数。

返回值:

  • 批量字节数

主要实现:

  • return b.size

4.5 func (b *ldbBatch) Reset()

方法 Reset() 实现了接口 ethdb.Batch,重置数据库。

主要实现:

  • 转发给 leveldb.Batch 的方法 Reset()
    • b.b.Reset()
  • 更新字节数
    • b.size = 0

5. type table struct

数据结构 table 封装了数据库 Database,描述 Database 中的 key 具有相同的前缀 prefix。

  • db Database: 数据库
  • prefix string: 前缀

5.1 func NewTable(db Database, prefix string) Database

构造函数 NewTable() 创建数据库,同时数据库中的 key 具有相同的前缀 prefix。

参数:

  • db Database: 数据库
  • prefix string: 前缀

返回值:

  • 数据库

主要实现:

  • return &table{db: db, prefix: prefix,}

5.2 func (dt *table) Put(key []byte, value []byte) error

方法 Put() 实现了接口 ethdb.Putter 和接口 ethdb.Database。

参数:

  • key []byte: key
  • value []byte: value

返回值:

  • 出错返回错误消息 error,否则返回 nil

主要实现:

  • 给 key 加上前缀 prefix,同时转发给 Database 的方法 Put()
    • dt.db.Put(append([]byte(dt.prefix), key...), value)

5.3 func (dt *table) Has(key []byte) (bool, error)

方法 Has() 实现了接口 ethdb.Database。

参数:

  • key []byte: key

返回值:

  • 存在返回 true,否则返回 false
  • 出错返回错误消息 error,否则返回 nil

主要实现:

  • 给 key 加上前缀 prefix,同时转发给 Database 的方法 Has()
    • dt.db.Has(append([]byte(dt.prefix), key...))

5.4 func (dt *table) Get(key []byte) ([]byte, error)

方法 Get() 实现了接口 ethdb.Database。

参数:

  • key []byte: key

返回值:

  • 存在返回 key 对应的 value
  • 出错返回错误消息 error,否则返回 nil

主要实现:

  • 给 key 加上前缀 prefix,同时转发给 Database 的方法 Get()
    • dt.db.Get(append([]byte(dt.prefix), key...))

5.5 func (dt *table) Delete(key []byte) error

方法 Delete() 实现了接口 ethdb.Deleter 和接口 ethdb.Database。

参数:

  • key []byte: key

返回值:

  • 出错返回错误消息 error,否则返回 nil

主要实现:

  • 给 key 加上前缀 prefix,同时转发给 Database 的方法 Delete()
    • dt.db.Delete(append([]byte(dt.prefix), key...))

5.6 func (dt *table) Close()

方法 Close() 不执行任何操作。注意,这里并不会关闭底层数据库。

5.7 func (dt *table) NewBatch() Batch

方法 NewBatch() 返回具有批处理能力的 ethdb.table。

返回值:

  • 具有批处理能力的 ethdb.tableBatch

主要实现:

  • return &tableBatch{dt.db.NewBatch(), dt.prefix}

6. type tableBatch struct

数据结构 tableBatch 封装了数据库 Database,描述 Database 中的 key 具有相同的前缀 prefix。同时,提供批处理能力。

  • batch Batch: 批处理
  • prefix string: 前缀

6.1 func NewTableBatch(db Database, prefix string) Batch

构造函数 NewTableBatch() 创建具有批处理能力的数据库,同时数据库中的 key 具有相同的前缀 prefix。

参数:

  • db Database: 数据库
  • prefix string: 前缀

返回值:

  • 具有批处理能力数据库

主要实现:

  • return &tableBatch{db.NewBatch(), prefix}

6.2 func (tb *tableBatch) Put(key, value []byte) error

方法 Put() 实现了接口 ethdb.Putter 和接口 ethdb.Batch,将 key & value 插入数据库。

参数:

  • key []byte: key
  • value []byte: value

返回值:

  • 出错返回错误消息 error,否则返回 nil

主要实现:

  • 给 key 加上前缀 prefix,同时转发给 ethdb.Batch 的方法 Put()
    • return tb.batch.Put(append([]byte(tb.prefix), key...), value)

6.3 func (tb *tableBatch) Delete(key []byte) error

方法 Delete() 实现了接口 ethdb.Deleter 和接口 ethdb.Batch,从数据库中删除给定的 key。

参数:

  • key []byte: key

返回值:

  • 出错返回错误消息 error,否则返回 nil

主要实现:

  • 给 key 加上前缀 prefix,同时转发给 ethdb.Batch 的方法 Delete()
    • return tb.batch.Delete(append([]byte(tb.prefix), key...))

6.4 func (tb *tableBatch) Write() error

方法 Write() 实现了接口 ethdb.Batch,将批处理数据一次性写入数据库。

返回值:

  • 出错返回错误消息 error,否则返回 nil

主要实现:

  • 转发给 ethdb.Batch 的方法 Write()
    • return tb.batch.Write()

6.5 func (tb *tableBatch) ValueSize() int

方法 ValueSize() 实现了接口 ethdb.Batch,返回批处理数据的字节数。

返回值:

  • 批处理数据字节数

主要实现:

  • 转发给 ethdb.Batch 的方法 ValueSize()
    • return tb.batch.ValueSize()

6.6 func (tb *tableBatch) Reset()

方法 Reset() 实现了接口 ethdb.Batch,清空批处理数据。

主要实现:

  • 转发给 ethdb.Batch 的方法 Reset()
    • tb.batch.Reset()

Reference

  1. https://github.com/ethereum/go-ethereum/blob/master/ethdb/database.go

Contributor

  1. Windstamp, https://github.com/windstamp
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,319评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,801评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,567评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,156评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,019评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,090评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,500评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,192评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,474评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,566评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,338评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,212评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,572评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,890评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,169评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,478评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,661评论 2 335

推荐阅读更多精彩内容