public void server_should_become_follower_if_receives_greater_term_in_append_entries_response_message() { var appendEntriesResponse = new AppendEntriesResponse(20, false, Guid.NewGuid(), Guid.NewGuid()); var sendHeartbeat = new SendHeartbeat(); var remoteServers = new List <ServerInCluster> { new ServerInCluster(Guid.NewGuid()), new ServerInCluster(Guid.NewGuid()), new ServerInCluster(Guid.NewGuid()), new ServerInCluster(Guid.NewGuid()), new ServerInCluster(Guid.NewGuid()), }; var requestVoteResponses = remoteServers.Select(x => Task.FromResult(new RequestVoteResponse(0, true, x.Id, remoteServers[0].Id))).ToList(); this.Given(x => GivenTheFollowingRemoteServers(remoteServers)) .And(x => GivenANewServer()) .And(x => x.TheResponseIs(appendEntriesResponse)) .And(x => x.TheResponseIs(requestVoteResponses)) .And(x => ServerReceives(new BecomeCandidate(Guid.Empty))) .When(x => ServerReceives(sendHeartbeat)) .Then(x => ThenTheCurrentTermIs(20)) .And(x => TheServerIsAFollower()) .BDDfy(); }
public void Receive(SendHeartbeat sendHeartbeat) { if (State is Leader) { var remoteServers = GetRemoteServers(); var tasks = new Task <AppendEntriesResponse> [remoteServers.Count]; for (int i = 0; i < tasks.Length; i++) { var lastLogIndex = Log.Count > 0 ? Log.Count - 1 : 0; var lastLogTerm = lastLogIndex > 0 ? Log[lastLogIndex].Term : 0; var appendEntries = new AppendEntries(CurrentTerm, Id, lastLogIndex, lastLogTerm, null, CommitIndex, remoteServers[i].Id); tasks[i] = _messageBus.Send(appendEntries); } Task.WaitAll(tasks); foreach (var task in tasks) { if (task.Result.Term > CurrentTerm) { BecomeFollowerAndMatchTerm(task.Result.Term, task.Result.FollowerId); } } _messageBus.Publish(new SendToSelf(new SendHeartbeat())); } }
public void Initialize() { tagList = new List <string>(); string dllPath = Path.Combine(Config.PeripheralAbsolutePath, PeripheralManager.Dir, dll); if (!File.Exists(dllPath)) { dllPath = Path.Combine(Config.PeripheralAbsolutePath, PeripheralManager.Dir, "RFIDLib", dll); } intPtr = Win32ApiInvoker.LoadLibrary(dllPath); log.InfoFormat("LoadLibrary: dllPath = {0}, ptr = {1}", dllPath, intPtr); uint idcoed = Win32ApiInvoker.GetLastError(); IntPtr api = Win32ApiInvoker.GetProcAddress(intPtr, "OpenDevice"); openDevice = (OpenDevice)Marshal.GetDelegateForFunctionPointer(api, typeof(OpenDevice)); api = Win32ApiInvoker.GetProcAddress(intPtr, "OneFindTags"); oneFindTags = (OneFindTags)Marshal.GetDelegateForFunctionPointer(api, typeof(OneFindTags)); api = Win32ApiInvoker.GetProcAddress(intPtr, "GetHardwareVersionNumber"); getHardwareVersionNumber = (GetHardwareVersionNumber)Marshal.GetDelegateForFunctionPointer(api, typeof(GetHardwareVersionNumber)); api = Win32ApiInvoker.GetProcAddress(intPtr, "GetFirmwareVersion"); getFirmwareVersion = (GetFirmwareVersion)Marshal.GetDelegateForFunctionPointer(api, typeof(GetFirmwareVersion)); api = Win32ApiInvoker.GetProcAddress(intPtr, "GetUniqueID"); getUniqueID = (GetUniqueID)Marshal.GetDelegateForFunctionPointer(api, typeof(GetUniqueID)); api = Win32ApiInvoker.GetProcAddress(intPtr, "SendHeartbeat"); sendHeartbeat = (SendHeartbeat)Marshal.GetDelegateForFunctionPointer(api, typeof(SendHeartbeat)); api = Win32ApiInvoker.GetProcAddress(intPtr, "ConstantFindTags"); constantFindTags = (ConstantFindTags)Marshal.GetDelegateForFunctionPointer(api, typeof(ConstantFindTags)); api = Win32ApiInvoker.GetProcAddress(intPtr, "StopFindTags"); stopFindTags = (StopFindTags)Marshal.GetDelegateForFunctionPointer(api, typeof(StopFindTags)); api = Win32ApiInvoker.GetProcAddress(intPtr, "OnlyRead"); onlyRead = (OnlyRead)Marshal.GetDelegateForFunctionPointer(api, typeof(OnlyRead)); int ret = openDevice(); if (0 == ret) { list = new List <string>(); } else { } }
static private void ReadOp(IAsyncResult ares) { if (_skListener == null) { return; } string text = String.Empty; IPEndPoint ipRemoteEp = new IPEndPoint(IPAddress.Any, 0); EndPoint epRemote = (EndPoint)ipRemoteEp; try { if (_skListener.EndReceiveFrom(ares, ref epRemote) > 0) { HeartBeat hb = HeartBeat.CreateHeartBeat((byte[])ares.AsyncState); ipRemoteEp = (IPEndPoint)epRemote; SendHeartbeat message = new SendHeartbeat(hb); message.SenderType = HeartbeatSenderType.SenderUdp; message.Port = ipRemoteEp.Port; message.IpAddress = ipRemoteEp.Address.ToString(); // Enviar Heartbeat MessageBus.Send(message); } // Continuar lectura buffer = new byte[bufferSize]; if (_skListener != null) { _skListener.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref epRemote, new AsyncCallback(ReadOp), buffer); } } catch (Exception) { // Ignorar excepciones y continuar la lectura //System.Windows.Forms.MessageBox.Show(ex.Message); //throw; } }
static public void StartPipeServe(string name) { _pipeServer = new NamedPipeServerStream(name, PipeDirection.In, maxConn, PipeTransmissionMode.Message, PipeOptions.Asynchronous, bufferSize, bufferSize); int numBytes = 0; keepLoop = true; while (keepLoop) { string message = String.Empty; buffer = new byte[bufferSize]; _pipeServer.WaitForConnection(); do { numBytes = _pipeServer.Read(buffer, 0, bufferSize); //Console.WriteLine("LEidos: " + numBytes.ToString()); } while (numBytes != 0); HeartBeat hb = HeartBeat.CreateHeartBeat(buffer); message = string.Format("Cliente: {0} Pipe: {1} TS: {2} Serial: {3}", hb.ClientID, name, hb.Timestamp, hb.Serial); Console.WriteLine(message); _pipeServer.Disconnect(); SendHeartbeat hbMessage = new SendHeartbeat(hb); hbMessage.SenderType = HeartbeatSenderType.SenderPipe; hbMessage.PipeName = name; // Enviar Heartbeat MessageBus.Send(hbMessage); } }
private void ServerReceives(SendHeartbeat sendHeartbeat) { _server.Receive(sendHeartbeat); }
// Entrada de Heartbeats. public void ReceiveHB(SendHeartbeat req) { ReceiveHearbeat(req); }
/// <summary> /// /// </summary> /// <param name="req"></param> internal void ReceiveHearbeat(SendHeartbeat req) { string message; HeartBeat hb = req.Data; // Obteniendo datos del emisor string senderIP = string.Empty; string senderPipe = string.Empty; int senderPort = 0; // Temp. Usar if para separar dos posibles senders hasta ahora. Si se incrementan, cambiar por switch.. if (req.SenderType == HeartbeatSenderType.SenderUdp) { senderIP = req.IpAddress; senderPort = req.Port; } if (req.SenderType == HeartbeatSenderType.SenderPipe) { senderPipe = req.PipeName; } ClientData client = null; // Chequear ClientID. // Chequear primero si hb.id es null if (null == hb.ClientID) { // usar puerto // TODO Separar chequeos en dependencia de tipo de emisor if (_clientList.ContainsPort(senderPort)) { client = _clientList.GetClient(senderPort); } } else { // usar ID if (_clientList.ContainsId(hb.ClientID)) { client = _clientList.GetClient(hb.ClientID); } } if (client == null) { // Para Debug y advertencia message = string.Format(ClassName + ": Cliente NO REGISTRADO. IP: {0} Port: {1} Client: {2} Text: {3} Serial: {4}.", senderIP, senderPort, hb.ClientID, hb.Timestamp, hb.Serial); Builder.Output(message, TraceEventType.Warning); // Debug return; //ToDo Al terminar depuracion implementar log y notificacion throw new Exception("Cliente no registrado."); } // DEBUG Output Hb recibido string nombre = client.Name; string id = hb.ClientID ?? "No establecida"; string serial = hb.Serial ?? "No establecido"; message = string.Format(ClassName + ": Recibe Cliente: {0} con Id {1} IP: {2} Puerto: {3} TS: {4} Serial: {5}.", nombre, id, senderIP, senderPort, hb.Timestamp, serial); Builder.Output(message, TraceEventType.Verbose); // Realizando comprobacion de puerto si el cliente lo especifica. Se puede comprobar la IP, pero no esta // incorporada en los datos del cliente. if (client.IdType == ClientIdType.KeyByUdpPort) { if (client.Port != senderPort) { //TODO implementar notificacion. message = string.Format(ClassName + ": Cliente {0} tiene configurado puerto UDP: {1} pero transmite por el {2}.", client.Name, client.Port, senderPort); Builder.Output(message, TraceEventType.Warning); } } client.HeartBeat = string.IsNullOrEmpty(hb.Serial) ? hb.Timestamp : hb.Timestamp + "\t" + hb.Serial; if (client.Status == ClientStatus.Inicial) { ClientMoveToWorkList(client); } if (client.Status == ClientStatus.Reiniciado) { ClientRecoverToWorkList(client); } if (client.Status == ClientStatus.Muerto) { ClientRecoverFromDeadToWorkList(client); } }