..

ipfs-cluster中实例化hashicopr/raft

通过上篇的了解,ipfs-cluster中的 raft 使用了 hashicorp/raft 的实现。 这里看一下实例化。

1、NewConsensus 入口,使用到了 libp2praft。

func NewConsensus(
	host host.Host,
	cfg *Config,
	store ds.Datastore,
	staging bool, // this peer must not be bootstrapped if no state exists
) (*Consensus, error) {
	consensus := libp2praft.NewOpLog(state, baseOp)
	raft, err := newRaftWrapper(host, cfg, consensus.FSM(), staging)
	if err != nil {
		logger.Error("error creating raft: ", err)
		return nil, err
	}
	actor := libp2praft.NewActor(raft.raft)
	consensus.SetActor(actor)

	ctx, cancel := context.WithCancel(context.Background())

	cc := &Consensus{
		ctx:       ctx,
		cancel:    cancel,
		config:    cfg,
		host:      host,
		consensus: consensus,
		actor:     actor,
		baseOp:    baseOp,
		raft:      raft,
		rpcReady:  make(chan struct{}, 1),
		readyCh:   make(chan struct{}, 1),
	}
}

2、通过 hraft.NewRaft 创建 raft 实例

// newRaftWrapper creates a Raft instance and initializes
// everything leaving it ready to use. Note, that Bootstrap() should be called
// to make sure the raft instance is usable.
func newRaftWrapper(
	host host.Host,
	cfg *Config,
	fsm hraft.FSM,
	staging bool,
) (*raftWrapper, error) {

	raftW := &raftWrapper{}
	raftW.config = cfg
	raftW.host = host
	raftW.staging = staging
	// Set correct LocalID
	cfg.RaftConfig.LocalID = hraft.ServerID(peer.Encode(host.ID()))

	logger.Debug("creating Raft")
	raftW.raft, err = hraft.NewRaft(
		cfg.RaftConfig,
		fsm,
		raftW.logStore,
		raftW.stableStore,
		raftW.snapshotStore,
		raftW.transport,
	)

	raftW.ctx, raftW.cancel = context.WithCancel(context.Background())
	go raftW.observePeers()

	return raftW, nil
}

Nothing