func (FSR *FileServer) serverFile() { ch, err := FSR.RN.CommitChannel() if err != nil { panic("[Error] No CommitChannel Received") } lastAppliedIndex := 0 for { commitInfo := <-ch if commitInfo.Err != nil { msg, err := decode(commitInfo.Data) if err != nil { panic("[Error] Decode error") } conn, ok := FSR.mapFind(msg.ClientId) if !ok { panic("[Error] Client not found for this msg") } switch commitInfo.Err.Error() { case "ERR_CONTACT_LEADER": ldrHost := getHost(commitInfo.LeaderId) ldrClientPort := getClientPort(commitInfo.LeaderId) reply(conn, &fs.Msg{Kind: 'R', ReDirAddr: ldrHost + ":" + strconv.Itoa(ldrClientPort)}) case "ERR_TRY_LATER": reply(conn, &fs.Msg{Kind: 'T'}) default: panic("[Error] Unknown error - " + commitInfo.Err.Error()) } } else { for i := lastAppliedIndex + 1; i <= commitInfo.Index; i++ { data, err := FSR.RN.Get(i) if err != nil { panic("[Error] Error from FS.RN.Get - " + err.Error()) } msg, err := decode(data) if err != nil { panic("[Error] Decode error") } response := fs.ProcessMsg(msg) conn, ok := FSR.mapFind(msg.ClientId) if ok { if commitInfo.LeaderId != FSR.Id { panic("[Error] Got CommitInfo & Client found, but node is not leader now") } reply(conn, response) } } lastAppliedIndex = max(lastAppliedIndex, commitInfo.Index) } } }
func (FSR *FileServer) serve(clientId int, conn *net.TCPConn) { reader := bufio.NewReader(conn) for { msg, msgerr, fatalerr := fs.GetMsg(reader) if fatalerr != nil || msgerr != nil { reply(conn, &fs.Msg{Kind: 'M'}) FSR.mapDel(clientId) conn.Close() break } if msgerr != nil { if (!reply(conn, &fs.Msg{Kind: 'M'})) { FSR.mapDel(clientId) conn.Close() break } } //fmt.Println("["+strconv.Itoa(FSR.Id)+"] - Msg Kind ", string(msg.Kind)) if msg.Kind == 'r' { response := fs.ProcessMsg(msg) if !reply(conn, response) { FSR.mapDel(clientId) conn.Close() break } } else { msg.ClientId = clientId data, err := encode(msg) if err != nil { reply(conn, &fs.Msg{Kind: 'I'}) FSR.mapDel(clientId) conn.Close() break } err = FSR.RN.Append(data) if err != nil { reply(conn, &fs.Msg{Kind: 'I'}) FSR.mapDel(clientId) conn.Close() break } } } }