def setupStubs(self): self.srvCnt = len(self.config['servers']) self.servers = {} self.channels = {} for srv in self.config['servers']: addr = f"{srv['ip']}:{srv['port']}" self.channels[addr] = grpc.insecure_channel(addr) self.servers[addr] = rnpg.raftnodeStub(self.channels[addr])
def requestVote(srvId, results): try: with self.getChannel(srvId) as channel: stub = rnpg.raftnodeStub(channel) resp = stub.requestVote(rnp.requestVoteRequest( term=self.currentTerm, candidateId=self.id, lastLogIndex=len(self.log), lastLogTerm=self.log[-1].term, CMReq=True, srvId=self.id), timeout=10) results[srvId] = resp except Exception as e: results[srvId] = e
def getAppendEntryLatency(self, req, ctx): srvId = random.choice(list(set(range(self.srvCnt)) - {self.id})) with self.getChannel(srvId) as channel: stub = rnpg.raftnodeStub(channel) start = time.time() resp = stub.appendEntries(rnp.appendEntriesRequest( term=self.currentTerm, leaderId=self.id, prevLogIndex=self.nextIndex[srvId] - 1, prevLogTerm=self.log[self.nextIndex[srvId] - 1].term, entries=req.entries, leaderCommit=self.commitIndex, CMReq=True, srvId=self.id), timeout=0.1) return rnp.getAppendEntryLatencyResponse(time=str(time.time() - start))
def appendEntries(srvId, results): try: entries = [ rnp.Entry(term=x.term, key=x.key, value=x.value) for x in self.log[self.nextIndex[srvId]:] ] with self.getChannel(srvId) as channel: stub = rnpg.raftnodeStub(channel) resp = stub.appendEntries(rnp.appendEntriesRequest( term=self.currentTerm, leaderId=self.id, prevLogIndex=self.nextIndex[srvId] - 1, prevLogTerm=self.log[self.nextIndex[srvId] - 1].term, entries=entries, leaderCommit=self.commitIndex, CMReq=True, srvId=self.id), timeout=10) results[srvId] = resp except Exception as e: results[srvId] = e
def setupStubs(self): self.servers = [None] * self.srvCnt for i, srv in enumerate(self.config['servers']): if i != self.id: channel = grpc.insecure_channel(f"{srv['ip']}:{srv['port']}") self.servers[i] = rnpg.raftnodeStub(channel)