当前位置:网站首页>Etcd database source code analysis -- rawnode simple package
Etcd database source code analysis -- rawnode simple package
2022-07-05 13:48:00 【Tertium FATUM】
stay etcd 3.6.0 Not before rawnode modular , What's happening now rawnode.go just raft Simple packaging of modules , And will raft.Node run What needs to be saved in each cycle of the collaboration raft The previous hard and soft state of prevSoftSt and prevHardSt Save to rawnode In the structure . The following for rawnode Definition of structure :
// RawNode is a thread-unsafe Node. The methods of this struct correspond to the methods of Node and are described more fully there.
type RawNode struct {
raft *raft
prevSoftSt *SoftState
prevHardSt pb.HardState
}
rawnode The interfaces provided are as follows , Functions in bold will be called by other modules , From these interface functions, we can see that as raft What interfaces should be provided for module encapsulation :
NewRawNode Instantiate RawNode. Information about the initial state of the boot , see also Bootstrap(); This replaces the former “peers” Parameters ( Have the same behavior ). however , It is recommended that applications do not call bootstrap , Instead, set the first index to be greater than 1 And will need ConfState Memory stored as its initial state to manually guide its state . This part can be seen node.go Medium startNode and RestartNode function .
// NewRawNode instantiates a RawNode from the given configuration. See Bootstrap() for bootstrapping an initial state; this replaces the former 'peers' argument to this method (with identical behavior). However, It is recommended that instead of calling Bootstrap, applications bootstrap their state manually by setting up a Storage that has a first index > 1 and which stores the desired ConfState as its InitialState.
func NewRawNode(config *Config) (*RawNode, error) {
r := newRaft(config)
rn := &RawNode{
raft: r, }
rn.prevSoftSt = r.softState()
rn.prevHardSt = r.hardState()
return rn, nil
}
Tick Advance the internal logic clock by one Tick, You can see ETCD Database source code analysis —— from raftNode Of start Function talking about the article, see the principle of logical clock call chain .
func (rn *RawNode) Tick() {
rn.raft.tick() } // Tick advances the internal logical clock by a single tick.
acceptReady: When RawNode The user of decided to continue processing Ready when , call acceptReady. Before this call and Ready() Between calls of , Nothing can be changed RawNode The state of .
// acceptReady is called when the consumer of the RawNode has decided to go
// ahead and handle a Ready. Nothing must alter the state of the RawNode between
// this call and the prior call to Ready().
func (rn *RawNode) acceptReady(rd Ready) {
if rd.SoftState != nil {
rn.prevSoftSt = rd.SoftState }
if len(rd.ReadStates) != 0 {
rn.raft.readStates = nil }
rn.raft.msgs = nil
}
readyWithoutAccept return Ready example . This is a read-only operation , That is, there is no obligation to be ready .
// readyWithoutAccept returns a Ready. This is a read-only operation, i.e. there
// is no obligation that the Ready must be handled.
func (rn *RawNode) readyWithoutAccept() Ready {
return newReady(rn.raft, rn.prevSoftSt, rn.prevHardSt)
}
HasReady stay RawNode The user needs to check whether there is any readiness to call when suspended . The check logic in this method should be the same as Ready.containsUpdates() Agreement .
// HasReady called when RawNode user need to check if any Ready pending.
// Checking logic in this method should be consistent with Ready.containsUpdates().
func (rn *RawNode) HasReady() bool {
r := rn.raft
if !r.softState().equal(rn.prevSoftSt) {
return true }
if hardSt := r.hardState(); !IsEmptyHardState(hardSt) && !isHardStateEqual(hardSt, rn.prevHardSt) {
return true }
if r.raftLog.hasPendingSnapshot() {
return true }
if len(r.msgs) > 0 || len(r.raftLog.unstableEntries()) > 0 || r.raftLog.hasNextEnts() {
return true }
if len(r.readStates) != 0 {
return true }
return false
}
Advance notice RawNode The application has applied and saved the progress in the final ready result .
// Advance notifies the RawNode that the application has applied and saved progress in the
// last Ready results.
func (rn *RawNode) Advance(rd Ready) {
if !IsEmptyHardState(rd.HardState) {
rn.prevHardSt = rd.HardState }
rn.raft.advance(rd)
}
TickQuiesced Advance the internal logic clock by one tick , Without performing any other state machine processing . When known Raft When all peers in the group are in the same state , Callers can avoid periodic heartbeats and elections . The expected usage is based on the group is “ Activities ” still “ static ” Periodically call Tick or tickquiesed. Warning : Be very careful when using this method , Because it will destroy Raft State machine . You should probably use Tick.
// TickQuiesced advances the internal logical clock by a single tick without
// performing any other state machine processing. It allows the caller to avoid
// periodic heartbeats and elections when all of the peers in a Raft group are
// known to be at the same state. Expected usage is to periodically invoke Tick
// or TickQuiesced depending on whether the group is "active" or "quiesced".
//
// WARNING: Be very careful about using this method as it subverts the Raft
// state machine. You should probably be using Tick instead.
func (rn *RawNode) TickQuiesced() {
rn.raft.electionElapsed++ }
Campaign This leads to this RawNode Transition to candidate state .
// Campaign causes this RawNode to transition to candidate state.
func (rn *RawNode) Campaign() error {
return rn.raft.Step(pb.Message{
Type: pb.MsgHup, }) }
Propose Attach data to the raft log .
// Propose proposes data be appended to the raft log.
func (rn *RawNode) Propose(data []byte) error {
return rn.raft.Step(pb.Message{
Type: pb.MsgProp,From: rn.raft.id,Entries: []pb.Entry{
{
Data: data},}}) }
ProposeConfChange Propose configuration changes .
// ProposeConfChange proposes a config change. See (Node).ProposeConfChange for details.
func (rn *RawNode) ProposeConfChange(cc pb.ConfChangeI) error {
m, err := confChangeToMsg(cc)
if err != nil {
return err }
return rn.raft.Step(m)
}
ApplyConfChange Apply configuration changes to local nodes . The application must call this option when applying configuration changes , Unless it decides to reject configuration changes , under these circumstances , Do not call .
// ApplyConfChange applies a config change to the local node. The app must call
// this when it applies a configuration change, except when it decides to reject
// the configuration change, in which case no call must take place.
func (rn *RawNode) ApplyConfChange(cc pb.ConfChangeI) *pb.ConfState {
cs := rn.raft.applyConfChange(cc.AsV2())
return &cs
}
Step Use the given message to advance the state machine .
// Step advances the state machine using the given message.
func (rn *RawNode) Step(m pb.Message) error {
// ignore unexpected local messages receiving over network
if IsLocalMsg(m.Type) {
return ErrStepLocalMsg }
if pr := rn.raft.prs.Progress[m.From]; pr != nil || !IsResponseMsg(m.Type) {
return rn.raft.Step(m) }
return ErrStepPeerNotFound
}
ReportUnreachable The given node cannot be accessed when the report was last sent .ReportSnapshot Report the status of snapshots sent .TransferLeader Try to transfer leadership to a given assignee .ReadIndex Request to read the status . The read state will be set to ready . The read state has a read index . Once the process of the application exceeds reading the index , Then any linearizable read request issued before the read request can be safely processed . The read state will be connected to the same rctx.
// ReportUnreachable reports the given node is not reachable for the last send.
func (rn *RawNode) ReportUnreachable(id uint64) {
_ = rn.raft.Step(pb.Message{
Type: pb.MsgUnreachable, From: id}) }
// ReportSnapshot reports the status of the sent snapshot.
func (rn *RawNode) ReportSnapshot(id uint64, status SnapshotStatus) {
rej := status == SnapshotFailure
_ = rn.raft.Step(pb.Message{
Type: pb.MsgSnapStatus, From: id, Reject: rej})
}
// TransferLeader tries to transfer leadership to the given transferee.
func (rn *RawNode) TransferLeader(transferee uint64) {
_ = rn.raft.Step(pb.Message{
Type: pb.MsgTransferLeader, From: transferee}) }
// ReadIndex requests a read state. The read state will be set in ready.
// Read State has a read index. Once the application advances further than the read
// index, any linearizable read requests issued before the read request can be
// processed safely. The read state will have the same rctx attached.
func (rn *RawNode) ReadIndex(rctx []byte) {
_ = rn.raft.Step(pb.Message{
Type: pb.MsgReadIndex, Entries: []pb.Entry{
{
Data: rctx}}}) }
Ready Return the unfinished work that the application needs to process . This includes attaching and applying items or snapshots 、 Update hard status and send messages . Back to Ready() Must handle , And then through Advance() Send back .
// Ready returns the outstanding work that the application needs to handle. This
// includes appending and applying entries or a snapshot, updating the HardState,
// and sending messages. The returned Ready() *must* be handled and subsequently
// passed back via Advance().
func (rn *RawNode) Ready() Ready {
rd := rn.readyWithoutAccept()
rn.acceptReady(rd)
return rd
}
Status Returns the current state of a given group . This will be allocated , see also BasicStatus and WithProgress To get more friendly allocation options .BasicStatus return BasicStatus. It is worth noting that , This does not include a progress chart ; see also WithProgress, Know how to check without assignment .
// Status returns the current status of the given group. This allocates, see
// BasicStatus and WithProgress for allocation-friendlier choices.
func (rn *RawNode) Status() Status {
status := getStatus(rn.raft)
return status
}
// BasicStatus returns a BasicStatus. Notably this does not contain the
// Progress map; see WithProgress for an allocation-free way to inspect it.
func (rn *RawNode) BasicStatus() BasicStatus {
return getBasicStatus(rn.raft) }
WithProgress It's a helper , Used to reflect on the progress of this node and its peers .
type ProgressType byte // ProgressType indicates the type of replica a Progress corresponds to.
const (
ProgressTypePeer ProgressType = iota // ProgressTypePeer accompanies a Progress for a regular peer replica.
ProgressTypeLearner // ProgressTypeLearner accompanies a Progress for a learner replica.
)
// WithProgress is a helper to introspect the Progress for this node and its peers.
func (rn *RawNode) WithProgress(visitor func(id uint64, typ ProgressType, pr tracker.Progress)) {
rn.raft.prs.Visit(func(id uint64, pr *tracker.Progress) {
typ := ProgressTypePeer
if pr.IsLearner {
typ = ProgressTypeLearner
}
p := *pr
p.Inflights = nil
visitor(id, typ, p)
})
}
边栏推荐
- redis6事务和锁机制
- Log4j utilization correlation
- Can and can FD
- 几款分布式数据库的对比
- Aikesheng sqle audit tool successfully completed the evaluation of "SQL quality management platform grading ability" of the Academy of communications and communications
- [MySQL usage Script] catch all MySQL time and date types and related operation functions (3)
- Intranet penetration tool NetApp
- Wechat app payment callback processing method PHP logging method, notes. 2020/5/26
- 通讯录(链表实现)
- Matlab paper chart standard format output (dry goods)
猜你喜欢

RK3566添加LED

STM32 reverse entry

ZABBIX monitoring

Flutter 3.0更新后如何应用到小程序开发中

Assembly language - Beginner's introduction

The real king of caching, Google guava is just a brother
![[daily question] 1200 Minimum absolute difference](/img/2f/9214df63f6d5fafa1f7247c4529643.png)
[daily question] 1200 Minimum absolute difference

Intranet penetration tool NetApp

MySQL - database query - sort query, paging query

运筹说 第68期|2022年最新影响因子正式发布 快看管科领域期刊的变化
随机推荐
Intranet penetration tool NetApp
2022司钻(钻井)考试题库及模拟考试
Win10——轻量级小工具
Aspx simple user login
Operational research 68 | the latest impact factors in 2022 were officially released. Changes in journals in the field of rapid care
About the problem and solution of 403 error in wampserver
【公开课预告】:视频质量评价基础与实践
stm32逆向入门
个人组件 - 消息提示
ETCD数据库源码分析——rawnode简单封装
[public class preview]: basis and practice of video quality evaluation
Log4j utilization correlation
嵌入式软件架构设计-消息交互
Prefix, infix, suffix expression "recommended collection"
49. Grouping of alphabetic ectopic words: give you a string array, please combine the alphabetic ectopic words together. You can return a list of results in any order. An alphabetic ectopic word is a
What happened to the communication industry in the first half of this year?
私有地址有那些
Liar report query collection network PHP source code
今年上半年,通信行业发生了哪些事?
【MySQL 使用秘籍】一網打盡 MySQL 時間和日期類型與相關操作函數(三)