Exemplo n.º 1
0
        public LeaderElection(IList<Peer> peers, object lockObject, NetMQContext context, ILogger logger)
        {
            this.peers = peers;
            this.lockObject = lockObject;
            this.context = context;
            this.logger = logger;

            localPeer = this.peers.First(c => c.IsLocal);
        }
Exemplo n.º 2
0
        public void ElectNewMaster(Peer thisPeer, IList<Peer> allPeers)
        {
            if (!thisPeer.IsLocal)
            {
                throw new Exception("ElectNewMaster: thisPeer is not local. Must initiate election message from my list of higher peers.");
            }

            // If there are no higher peers, I am the winner
            if (!thisPeer.HigherPeers.Any())
            {
                IsLeaderProcess = true;
                return;
            }

            // If any higher thisPeer responds to my election message with Ok
            // I stop bothering them since they outrank me
            if (thisPeer.HigherPeers.OrderByDescending(i => i).Any(id => SendElection(allPeers[id])))
            {
                IsLeaderProcess = false;
                return;
            }

            IsLeaderProcess = true;
        }
Exemplo n.º 3
0
        private bool SendElection(Peer peer)
        {
            if (peer.IsLocal)
            {
                throw new Exception("SendElection: peer is local. Cannot send election message to my self.");
            }

            string reply;

            logger.Log($"Sending election message to {peer.ElectionSocket}");

            bool didAnswer;

            using (var client = context.CreateRequestSocket())
            {
                client.Connect(peer.ElectionSocket);

                // Send election message to higher peer
                client.TrySendFrame(TimeSpan.FromMilliseconds(1000), Message.Election);

                // Wait for reply OK/NOK or timeout
                didAnswer = client.TryReceiveFrameString(TimeSpan.FromMilliseconds(1000), out reply);

                client.Close();
            }

            if (didAnswer)
            {
                return reply == Message.Ok;
            }

            return false;
        }