Derek解读Bytom源码-启动与停止
作者:Derek
简介
Github地址:https://github.com/Bytom/bytom
Gitee地址:https://gitee.com/BytomBlockchain/bytom
本章介绍bytom代码启动、节点初始化、及停止的过程
作者使用MacOS操作系统,其他平台也大同小异
Golang Version: 1.8
预备工作
编译安装
详细步骤见官方 bytom install
设置debug日志输出
开启debug输出文件、函数、行号等详细信息
export BYTOM_DEBUG=debug
初始化并启动bytomd
初始化
./bytomd init --chain_id testnet
bytomd目前支持两种网络,这里我们使用测试网
mainnet:主网
testnet:测试网
启动bytomd
./bytomd node --mining --prof_laddr=":8011"
--prof_laddr=":8080" // 开启pprof输出性能指标
访问:http://127.0.0.1:8080/debug/pprof/
bytomd init初始化
入口函数
** cmd/bytomd/main.go **
func init() {
log.SetFormatter(&log.TextFormatter{FullTimestamp: true, DisableColors: true})
// If environment variable BYTOM_DEBUG is not empty,
// then add the hook to logrus and set the log level to DEBUG
if os.Getenv("BYTOM_DEBUG") != "" {
log.AddHook(ContextHook{})
log.SetLevel(log.DebugLevel)
}
}
func main() {
cmd := cli.PrepareBaseCmd(commands.RootCmd, "TM", os.ExpandEnv(config.DefaultDataDir()))
cmd.Execute()
}
init函数会在main执行之前做初始化操作,可以看到init中bytomd加载BYTOM_DEBUG变量来设置debug日志输出
command cli传参初始化
bytomd的cli解析使用cobra库
** cmd/bytomd/commands **
- cmd/bytomd/commands/root.go
初始化--root传参。bytomd存储配置、keystore、数据的root目录。在MacOS下,默认路径是~/Library/Bytom/ - cmd/bytomd/commands/init.go
初始化--chain_id传参。选择网络类型,在启动bytomd时我们选择了testnet也就是测试网络 - cmd/bytomd/commands/version.go
初始化version传参 - cmd/bytomd/commands/run_node.go
初始化node节点运行时所需要的传参
初始化默认配置
用户传参只有一部分参数,那节点所需的其他参数需要从默认配置中加载。
** cmd/bytomd/commands/root.go **
var (
config = cfg.DefaultConfig()
)
在root.go中有一个config全局变量加载了node所需的所有默认参数
// Default configurable parameters.
func DefaultConfig() *Config {
return &Config{
BaseConfig: DefaultBaseConfig(), // node基础相关配置
P2P: DefaultP2PConfig(), // p2p网络相关配置
Wallet: DefaultWalletConfig(), // 钱包相关配置
Auth: DefaultRPCAuthConfig(), // 验证相关配置
Web: DefaultWebConfig(), // web相关配置
}
}
后面的文章会一一介绍每个配置的作用
bytomd 守护进程启动与退出
** cmd/bytomd/commands/run_node.go **
func runNode(cmd *cobra.Command, args []string) error {
// Create & start node
n := node.NewNode(config)
if _, err := n.Start(); err != nil {
return fmt.Errorf("Failed to start node: %v", err)
} else {
log.WithField("nodeInfo", n.SyncManager().Switch().NodeInfo()).Info("Started node")
}
// Trap signal, run forever.
n.RunForever()
return nil
}
runNode函数有三步操作:
node.NewNode:初始化node运行环境
n.Start:启动node
n.RunForever:监听退出信号,收到ctrl+c操作则退出node。在linux中守进程一般监听SIGTERM信号(ctrl+c)作为退出守护进程的信号
初始化node运行环境
在bytomd中有五个db数据库存储在--root参数下的data目录
- accesstoken.db // 存储token相关信息(钱包访问控制权限)
- trusthistory.db // 存储p2p网络同步相关信息
- txdb.db // 存储交易相关信息
- txfeeds.db //
- wallet.db // 存储钱包相关信息
** node/node.go **
func NewNode(config *cfg.Config) *Node {
ctx := context.Background()
initActiveNetParams(config)
// Get store 初始化txdb数据库
txDB := dbm.NewDB("txdb", config.DBBackend, config.DBDir())
store := leveldb.NewStore(txDB)
// 初始化accesstoken数据库
tokenDB := dbm.NewDB("accesstoken", config.DBBackend, config.DBDir())
accessTokens := accesstoken.NewStore(tokenDB)
// 初始化event事件调度器,也叫任务调度器。一个任务可以被多次调用
// Make event switch
eventSwitch := types.NewEventSwitch()
_, err := eventSwitch.Start()
if err != nil {
cmn.Exit(cmn.Fmt("Failed to start switch: %v", err))
}
// 初始化交易池
txPool := protocol.NewTxPool()
chain, err := protocol.NewChain(store, txPool)
if err != nil {
cmn.Exit(cmn.Fmt("Failed to create chain structure: %v", err))
}
var accounts *account.Manager = nil
var assets *asset.Registry = nil
var wallet *w.Wallet = nil
var txFeed *txfeed.Tracker = nil
// 初始化txfeeds数据库
txFeedDB := dbm.NewDB("txfeeds", config.DBBackend, config.DBDir())
txFeed = txfeed.NewTracker(txFeedDB, chain)
if err = txFeed.Prepare(ctx); err != nil {
log.WithField("error", err).Error("start txfeed")
return nil
}
// 初始化keystore
hsm, err := pseudohsm.New(config.KeysDir())
if err != nil {
cmn.Exit(cmn.Fmt("initialize HSM failed: %v", err))
}
// 初始化钱包,默认wallet是开启状态
if !config.Wallet.Disable {
walletDB := dbm.NewDB("wallet", config.DBBackend, config.DBDir())
accounts = account.NewManager(walletDB, chain)
assets = asset.NewRegistry(walletDB, chain)
wallet, err = w.NewWallet(walletDB, accounts, assets, hsm, chain)
if err != nil {
log.WithField("error", err).Error("init NewWallet")
}
// Clean up expired UTXO reservations periodically.
go accounts.ExpireReservations(ctx, expireReservationsPeriod)
}
newBlockCh := make(chan *bc.Hash, maxNewBlockChSize)
// 初始化网络节点同步管理
syncManager, _ := netsync.NewSyncManager(config, chain, txPool, newBlockCh)
// 初始化pprof,pprof用于输出性能指标,需要制定--prof_laddr参数来开启,在文章开头我们已经开启该功能
// run the profile server
profileHost := config.ProfListenAddress
if profileHost != "" {
// Profiling bytomd programs.see (https://blog.golang.org/profiling-go-programs)
// go tool pprof http://profileHose/debug/pprof/heap
go func() {
http.ListenAndServe(profileHost, nil)
}()
}
// 初始化节点,填充节点所需的所有参数环境
node := &Node{
config: config,
syncManager: syncManager,
evsw: eventSwitch,
accessTokens: accessTokens,
wallet: wallet,
chain: chain,
txfeed: txFeed,
miningEnable: config.Mining,
}
// 初始化挖矿
node.cpuMiner = cpuminer.NewCPUMiner(chain, accounts, txPool, newBlockCh)
node.miningPool = miningpool.NewMiningPool(chain, accounts, txPool, newBlockCh)
node.BaseService = *cmn.NewBaseService(nil, "Node", node)
return node
}
目前bytomd只支持cpu挖矿,所以在代码中只有cpuminer的初始化信息
启动node
** node/node.go **
// Lanch web broser or not
func lanchWebBroser() {
log.Info("Launching System Browser with :", webAddress)
if err := browser.Open(webAddress); err != nil {
log.Error(err.Error())
return
}
}
func (n *Node) initAndstartApiServer() {
n.api = api.NewAPI(n.syncManager, n.wallet, n.txfeed, n.cpuMiner, n.miningPool, n.chain, n.config, n.accessTokens)
listenAddr := env.String("LISTEN", n.config.ApiAddress)
env.Parse()
n.api.StartServer(*listenAddr)
}
func (n *Node) OnStart() error {
if n.miningEnable {
n.cpuMiner.Start()
}
n.syncManager.Start()
n.initAndstartApiServer()
if !n.config.Web.Closed {
lanchWebBroser()
}
return nil
}
OnStart() 启动node进程如下:
- 启动挖矿功能
- 启动p2p网络同步
- 启动http协议的apiserver服务
- 打开浏览器访问bytond的交易页面
停止node
bytomd在启动时执行了n.RunForever()函数,该函数是由tendermint框架启动了监听信号的功能:
** vendor/github.com/tendermint/tmlibs/common/os.go **
func TrapSignal(cb func()) {
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
go func() {
for sig := range c {
fmt.Printf("captured %v, exiting...\n", sig)
if cb != nil {
cb()
}
os.Exit(1)
}
}()
select {}
}
TrapSignal函数监听了SIGTERM信号,bytomd才能成为不退出的守护进程。只有当触发了ctrl+c或kill bytomd_pid才能终止bytomd进程退出。退出时bytomd执行如下操作
** node/node.go **
func (n *Node) OnStop() {
n.BaseService.OnStop()
if n.miningEnable {
n.cpuMiner.Stop()
}
n.syncManager.Stop()
log.Info("Stopping Node")
// TODO: gracefully disconnect from peers.
}
bytomd会将挖矿功能停止,p2p网络停止等操作。
Derek解读Bytom源码-启动与停止的更多相关文章
- Derek解读Bytom源码-持久化存储LevelDB
作者:Derek 简介 Github地址:https://github.com/Bytom/bytom Gitee地址:https://gitee.com/BytomBlockchain/bytom ...
- Derek解读Bytom源码-创世区块
作者:Derek 简介 Github地址:https://github.com/Bytom/bytom Gitee地址:https://gitee.com/BytomBlockchain/bytom ...
- Derek解读Bytom源码-Api Server接口服务
作者:Derek 简介 Github地址:https://github.com/Bytom/bytom Gitee地址:https://gitee.com/BytomBlockchain/bytom ...
- Derek解读Bytom源码-孤块管理
作者:Derek 简介 Github地址:https://github.com/Bytom/bytom Gitee地址:https://gitee.com/BytomBlockchain/bytom ...
- Derek解读Bytom源码-P2P网络 地址簿
作者:Derek 简介 Github地址:https://github.com/Bytom/bytom Gitee地址:https://gitee.com/BytomBlockchain/bytom ...
- Derek解读Bytom源码-protobuf生成比原核心代码
作者:Derek 简介 Github地址:https://github.com/Bytom/bytom Gitee地址:https://gitee.com/BytomBlockchain/bytom ...
- Derek解读Bytom源码-P2P网络 upnp端口映射
作者:Derek 简介 Github地址:https://github.com/Bytom/bytom Gitee地址:https://gitee.com/BytomBlockchain/bytom ...
- RxJava系列6(从微观角度解读RxJava源码)
RxJava系列1(简介) RxJava系列2(基本概念及使用介绍) RxJava系列3(转换操作符) RxJava系列4(过滤操作符) RxJava系列5(组合操作符) RxJava系列6(从微观角 ...
- 入口开始,解读Vue源码(一)-- 造物创世
Why? 网上现有的Vue源码解析文章一搜一大批,但是为什么我还要去做这样的事情呢?因为觉得纸上得来终觉浅,绝知此事要躬行. 然后平时的项目也主要是Vue,在使用Vue的过程中,也对其一些约定产生了一 ...
随机推荐
- DBUtils (30)
DBUtils是java编程中的数据库操作实用工具,小巧简单实用. DBUtils封装了对JDBC的操作,简化了JDBC操作,可以少写代码. Dbutils三个核心功能介绍 一. QueryRunn ...
- 【转载】selenium与自动化测试成神之路
Python selenium —— selenium与自动化测试成神之路 置顶 2016年09月17日 00:33:04 阅读数:43886 Python selenium —— selenium与 ...
- golang学习笔记15 golang用strings.Split切割字符串
golang用strings.Split切割字符串 kv := strings.Split(authString, " ") if len(kv) != 2 || kv[0] != ...
- Caterpillar sis service information training and software
Cat et sis caterpillar heavy duty truck diagnostics repair. Training demonstration allows.cat electr ...
- Hadoop HA方案调研
原文成文于去年(2012.7.30),已然过去了一年,很多信息也许已经过时,不保证正确,与Hadoop学习笔记系列一样仅为留做提醒. ----- 针对现有的所有Hadoop HA方案进行调研,以时间为 ...
- 大数据学习路线:Zookeeper集群管理与选举
大数据技术的学习,逐渐成为很多程序员的必修课,因为趋势也是因为自己的职业生涯.在各个技术社区分享交流成为很多人学习的方式,今天很荣幸给我们分享一些大数据基础知识,大家可以一起学习! 1.集群机器监控 ...
- Caused by: java.net.BindException: Address already in use: bind
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'brandService ...
- php的serialize()函数和unserialize()函数
适用情境:serialize()返回字符串,此字符串包含了表示value的字节流,可以存储于任何地方.这有利于存储或传递 PHP 的值,同时不丢失其类型和结构.比较有用的地方就是将数据存入数据库或记录 ...
- Java axis2.jar包详解及缺少jar包错误分析
Java axis2.jar包详解及缺少jar包错误分析 一.最小开发jar集 axis2 开发最小jar包集: activation-1.1.jar axiom-api-1.2.13.jar ax ...
- 爬虫的基本操作 requests / BeautifulSoup 的使用
爬虫的基本操作 爬虫基础知识 什么是爬虫? 在最开始,还没有诞生Google和百度等一系列搜索引擎的公司的时候,人们进入一些公司的网站只能通过在浏览器地址栏输入网址的方式访问,如同在很早之前前手机不流 ...