etcd Raft 라이브러리를 사용하여 자체 분산 KV 스토리지 시스템을 구축하는 방법
소개
raftexample은 etcd raft 합의 알고리즘 라이브러리의 사용을 보여주는 etcd에서 제공하는 예제입니다. raftexample은 궁극적으로 REST API를 제공하는 분산 키-값 스토리지 서비스를 구현합니다.
이 글에서는 독자들이 etcd raft 라이브러리 사용 방법과 raft 라이브러리의 구현 로직을 더 잘 이해할 수 있도록 raftexample의 코드를 읽고 분석할 것입니다.
건축학
raftexample의 아키텍처는 매우 간단하며 기본 파일은 다음과 같습니다.
- main.go: raft 모듈, httpapi 모듈 및 kvstore 모듈 간의 상호 작용을 구성하는 역할을 담당합니다.
- raft.go: 제안서 제출, 전송해야 하는 RPC 메시지 수신, 네트워크 전송 수행 등을 포함하여 raft 라이브러리와의 상호 작용을 담당합니다.
- httpapi.go: REST API 제공을 담당하며 사용자 요청의 진입점 역할을 합니다.
- kvstore.go: raft 프로토콜의 상태 머신에 해당하는 커밋된 로그 항목을 지속적으로 저장하는 역할을 담당합니다.
쓰기 요청의 처리 흐름
HTTP PUT 요청을 통해 httpapi 모듈의 ServeHTTP 메소드에 쓰기 요청이 도착합니다.
curl -L http://127.0.0.1:12380/key -XPUT -d value
스위치를 통해 HTTP 요청 방식을 일치시킨 후 PUT 방식 처리 흐름으로 들어갑니다.
- HTTP 요청 본문에서 콘텐츠(즉, 값)를 읽습니다.
- kvstore 모듈의 Propose 메소드를 통해 제안을 구성합니다(키를 키로, 값을 값으로 사용하여 키-값 쌍 추가).
- 반환할 데이터가 없으므로 클라이언트에 204 StatusNoContent로 응답합니다.
Raft 알고리즘 라이브러리에서 제공하는 Propose 방식을 통해 Raft 알고리즘 라이브러리에 제안서를 제출합니다.
제안 내용에는 새 키-값 쌍 추가, 기존 키-값 쌍 업데이트 등이 포함될 수 있습니다.
// httpapi.go v, err := io.ReadAll(r.Body) if err != nil { log.Printf("Failed to read on PUT (%v)\n", err) http.Error(w, "Failed on PUT", http.StatusBadRequest) return } h.store.Propose(key, string(v)) w.WriteHeader(http.StatusNoContent)
다음으로 kvstore 모듈의 Propose 메소드를 살펴보고 Proposal이 어떻게 구성되고 처리되는지 살펴보겠습니다.
Propose 방법에서는 먼저 gob을 사용하여 작성할 키-값 쌍을 인코딩한 다음 인코딩된 콘텐츠를 kvstore 모듈에서 구성한 제안을 raft 모듈로 전송하는 채널인 ProposalC에 전달합니다.
// kvstore.go func (s *kvstore) Propose(k string, v string) { var buf strings.Builder if err := gob.NewEncoder(&buf).Encode(kv{k, v}); err != nil { log.Fatal(err) } s.proposeC <- buf.String() }
kvstore에서 생성되어 ProposalC로 전달된 제안은 Raft 모듈의 ServeChannels 메소드에 의해 수신되고 처리됩니다.
ProposalC가 닫히지 않았음을 확인한 후 Raft 모듈은 Raft 알고리즘 라이브러리에서 제공하는 Propose 메소드를 사용하여 처리하기 위해 Raft 알고리즘 라이브러리에 제안서를 제출합니다.
// raft.go select { case prop, ok := <-rc.proposeC: if !ok { rc.proposeC = nil } else { rc.node.Propose(context.TODO(), []byte(prop)) }
제안서 제출 후 뗏목 알고리즘 프로세스를 따릅니다. 제안은 결국 리더 노드로 전달됩니다(현재 노드가 리더가 아니고 팔로워가 제안을 전달할 수 있도록 허용한 경우, 비활성화ProposalForwarding 구성에 의해 제어됨). 리더는 제안을 뗏목 로그에 로그 항목으로 추가하고 이를 다른 팔로어 노드와 동기화합니다. 커밋된 것으로 간주된 후 상태 머신에 적용되고 결과가 사용자에게 반환됩니다.
그러나 etcd raft 라이브러리 자체는 노드 간 통신, raft 로그 추가, 상태 머신에 적용 등을 처리하지 않으므로 raft 라이브러리는 이러한 작업에 필요한 데이터만 준비합니다. 실제 작업은 당사에서 수행해야 합니다.
따라서 raft 라이브러리에서 이 데이터를 수신하고 해당 유형에 따라 적절하게 처리해야 합니다. Ready 메소드는 처리해야 하는 데이터를 수신할 수 있는 읽기 전용 채널을 반환합니다.
수신된 데이터에는 적용할 스냅샷, 뗏목 로그에 추가할 로그 항목, 네트워크를 통해 전송할 메시지 등 여러 필드가 포함되어 있다는 점에 유의해야 합니다.
쓰기 요청 예시(리더 노드)를 계속 진행하면 해당 데이터를 수신한 후 스냅샷, HardState 및 항목을 지속적으로 저장하여 서버 충돌로 인해 발생한 문제(예: 팔로어가 여러 후보자에게 투표하는 경우)를 처리해야 합니다. HardState와 항목은 함께 문서에 언급된 대로 모든 서버의 영구 상태를 구성합니다. 지속적으로 저장한 후 스냅샷을 적용하고 래프트 로그에 추가할 수 있습니다.
Since we are currently the leader node, the raft library will return MsgApp type messages to us (corresponding to AppendEntries RPC in the paper). We need to send these messages to the follower nodes. Here, we use the rafthttp provided by etcd for node communication and send the messages to follower nodes using the Send method.
// raft.go case rd := <-rc.node.Ready(): if !raft.IsEmptySnap(rd.Snapshot) { rc.saveSnap(rd.Snapshot) } rc.wal.Save(rd.HardState, rd.Entries) if !raft.IsEmptySnap(rd.Snapshot) { rc.raftStorage.ApplySnapshot(rd.Snapshot) rc.publishSnapshot(rd.Snapshot) } rc.raftStorage.Append(rd.Entries) rc.transport.Send(rc.processMessages(rd.Messages)) applyDoneC, ok := rc.publishEntries(rc.entriesToApply(rd.CommittedEntries)) if !ok { rc.stop() return } rc.maybeTriggerSnapshot(applyDoneC) rc.node.Advance()
Next, we use the publishEntries method to apply the committed raft log entries to the state machine. As mentioned earlier, in raftexample, the kvstore module acts as the state machine. In the publishEntries method, we pass the log entries that need to be applied to the state machine to commitC. Similar to the earlier proposeC, commitC is responsible for transmitting the log entries that the raft module has deemed committed to the kvstore module for application to the state machine.
// raft.go rc.commitC <- &commit{data, applyDoneC}
In the readCommits method of the kvstore module, messages read from commitC are gob-decoded to retrieve the original key-value pairs, which are then stored in a map structure within the kvstore module.
// kvstore.go for commit := range commitC { ... for _, data := range commit.data { var dataKv kv dec := gob.NewDecoder(bytes.NewBufferString(data)) if err := dec.Decode(&dataKv); err != nil { log.Fatalf("raftexample: could not decode message (%v)", err) } s.mu.Lock() s.kvStore[dataKv.Key] = dataKv.Val s.mu.Unlock() } close(commit.applyDoneC) }
Returning to the raft module, we use the Advance method to notify the raft library that we have finished processing the data read from the Ready channel and are ready to process the next batch of data.
Earlier, on the leader node, we sent MsgApp type messages to the follower nodes using the Send method. The follower node's rafthttp listens on the corresponding port to receive requests and return responses. Whether it's a request received by a follower node or a response received by a leader node, it will be submitted to the raft library for processing through the Step method.
raftNode implements the Raft interface in rafthttp, and the Process method of the Raft interface is called to handle the received request content (such as MsgApp messages).
// raft.go func (rc *raftNode) Process(ctx context.Context, m raftpb.Message) error { return rc.node.Step(ctx, m) }
The above describes the complete processing flow of a write request in raftexample.
Summary
This concludes the content of this article. By outlining the structure of raftexample and detailing the processing flow of a write request, I hope to help you better understand how to use the etcd raft library to build your own distributed KV storage service.
If there are any mistakes or issues, please feel free to comment or message me directly. Thank you.
References
https://github.com/etcd-io/etcd/tree/main/contrib/raftexample
https://github.com/etcd-io/raft
https://raft.github.io/raft.pdf
위 내용은 etcd Raft 라이브러리를 사용하여 자체 분산 KV 스토리지 시스템을 구축하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

Golang은 성능과 확장 성 측면에서 Python보다 낫습니다. 1) Golang의 컴파일 유형 특성과 효율적인 동시성 모델은 높은 동시성 시나리오에서 잘 수행합니다. 2) 해석 된 언어로서 파이썬은 천천히 실행되지만 Cython과 같은 도구를 통해 성능을 최적화 할 수 있습니다.

Golang은 동시성에서 C보다 낫고 C는 원시 속도에서 Golang보다 낫습니다. 1) Golang은 Goroutine 및 Channel을 통해 효율적인 동시성을 달성하며, 이는 많은 동시 작업을 처리하는 데 적합합니다. 2) C 컴파일러 최적화 및 표준 라이브러리를 통해 하드웨어에 가까운 고성능을 제공하며 극도의 최적화가 필요한 애플리케이션에 적합합니다.

goisidealforbeginnersandsuitableforcloudandnetworkservicesduetoitssimplicity, 효율성, 및 콘크리 론 피처

Golang은 빠른 개발 및 동시 시나리오에 적합하며 C는 극도의 성능 및 저수준 제어가 필요한 시나리오에 적합합니다. 1) Golang은 쓰레기 수집 및 동시성 메커니즘을 통해 성능을 향상시키고, 고전성 웹 서비스 개발에 적합합니다. 2) C는 수동 메모리 관리 및 컴파일러 최적화를 통해 궁극적 인 성능을 달성하며 임베디드 시스템 개발에 적합합니다.

goimpactsdevelopmentpositively throughlyspeed, 효율성 및 단순성.

Golang과 Python은 각각 고유 한 장점이 있습니다. Golang은 고성능 및 동시 프로그래밍에 적합하지만 Python은 데이터 과학 및 웹 개발에 적합합니다. Golang은 동시성 모델과 효율적인 성능으로 유명하며 Python은 간결한 구문 및 풍부한 라이브러리 생태계로 유명합니다.

Golang과 C의 성능 차이는 주로 메모리 관리, 컴파일 최적화 및 런타임 효율에 반영됩니다. 1) Golang의 쓰레기 수집 메커니즘은 편리하지만 성능에 영향을 줄 수 있습니다. 2) C의 수동 메모리 관리 및 컴파일러 최적화는 재귀 컴퓨팅에서 더 효율적입니다.

Golang과 C는 각각 공연 경쟁에서 고유 한 장점을 가지고 있습니다. 1) Golang은 높은 동시성과 빠른 발전에 적합하며 2) C는 더 높은 성능과 세밀한 제어를 제공합니다. 선택은 프로젝트 요구 사항 및 팀 기술 스택을 기반으로해야합니다.
