Search in sources :

Example 1 with DatagramSocket

use of java.net.DatagramSocket in project zookeeper by apache.

the class LeaderElection method lookForLeader.

/**
     * Invoked in QuorumPeer to find or elect a new leader.
     * 
     * @throws InterruptedException
     */
public Vote lookForLeader() throws InterruptedException {
    try {
        self.jmxLeaderElectionBean = new LeaderElectionBean();
        MBeanRegistry.getInstance().register(self.jmxLeaderElectionBean, self.jmxLocalPeerBean);
    } catch (Exception e) {
        LOG.warn("Failed to register with JMX", e);
        self.jmxLeaderElectionBean = null;
    }
    try {
        self.setCurrentVote(new Vote(self.getId(), self.getLastLoggedZxid()));
        // We are going to look for a leader by casting a vote for ourself
        byte[] requestBytes = new byte[4];
        ByteBuffer requestBuffer = ByteBuffer.wrap(requestBytes);
        byte[] responseBytes = new byte[28];
        ByteBuffer responseBuffer = ByteBuffer.wrap(responseBytes);
        /* The current vote for the leader. Initially me! */
        DatagramSocket s = null;
        try {
            s = new DatagramSocket();
            s.setSoTimeout(200);
        } catch (SocketException e1) {
            LOG.error("Socket exception when creating socket for leader election", e1);
            System.exit(4);
        }
        DatagramPacket requestPacket = new DatagramPacket(requestBytes, requestBytes.length);
        DatagramPacket responsePacket = new DatagramPacket(responseBytes, responseBytes.length);
        int xid = epochGen.nextInt();
        while (self.isRunning()) {
            HashMap<InetSocketAddress, Vote> votes = new HashMap<InetSocketAddress, Vote>(self.getVotingView().size());
            requestBuffer.clear();
            requestBuffer.putInt(xid);
            requestPacket.setLength(4);
            HashSet<Long> heardFrom = new HashSet<Long>();
            for (QuorumServer server : self.getVotingView().values()) {
                LOG.info("Server address: " + server.addr);
                try {
                    requestPacket.setSocketAddress(server.addr);
                } catch (IllegalArgumentException e) {
                    // in order to capture this critical detail.
                    throw new IllegalArgumentException("Unable to set socket address on packet, msg:" + e.getMessage() + " with addr:" + server.addr, e);
                }
                try {
                    s.send(requestPacket);
                    responsePacket.setLength(responseBytes.length);
                    s.receive(responsePacket);
                    if (responsePacket.getLength() != responseBytes.length) {
                        LOG.error("Got a short response: " + responsePacket.getLength());
                        continue;
                    }
                    responseBuffer.clear();
                    int recvedXid = responseBuffer.getInt();
                    if (recvedXid != xid) {
                        LOG.error("Got bad xid: expected " + xid + " got " + recvedXid);
                        continue;
                    }
                    long peerId = responseBuffer.getLong();
                    heardFrom.add(peerId);
                    //if(server.id != peerId){
                    Vote vote = new Vote(responseBuffer.getLong(), responseBuffer.getLong());
                    InetSocketAddress addr = (InetSocketAddress) responsePacket.getSocketAddress();
                    votes.put(addr, vote);
                //}
                } catch (IOException e) {
                    LOG.warn("Ignoring exception while looking for leader", e);
                // Errors are okay, since hosts may be
                // down
                }
            }
            ElectionResult result = countVotes(votes, heardFrom);
            // for a dead peer                 
            if (result.numValidVotes == 0) {
                self.setCurrentVote(new Vote(self.getId(), self.getLastLoggedZxid()));
            } else {
                if (result.winner.getId() >= 0) {
                    self.setCurrentVote(result.vote);
                    // To do: this doesn't use a quorum verifier
                    if (result.winningCount > (self.getVotingView().size() / 2)) {
                        self.setCurrentVote(result.winner);
                        s.close();
                        Vote current = self.getCurrentVote();
                        LOG.info("Found leader: my type is: " + self.getLearnerType());
                        /*
                             * We want to make sure we implement the state machine
                             * correctly. If we are a PARTICIPANT, once a leader
                             * is elected we can move either to LEADING or 
                             * FOLLOWING. However if we are an OBSERVER, it is an
                             * error to be elected as a Leader.
                             */
                        if (self.getLearnerType() == LearnerType.OBSERVER) {
                            if (current.getId() == self.getId()) {
                                // This should never happen!
                                LOG.error("OBSERVER elected as leader!");
                                Thread.sleep(100);
                            } else {
                                self.setPeerState(ServerState.OBSERVING);
                                Thread.sleep(100);
                                return current;
                            }
                        } else {
                            self.setPeerState((current.getId() == self.getId()) ? ServerState.LEADING : ServerState.FOLLOWING);
                            if (self.getPeerState() == ServerState.FOLLOWING) {
                                Thread.sleep(100);
                            }
                            return current;
                        }
                    }
                }
            }
            Thread.sleep(1000);
        }
        return null;
    } finally {
        try {
            if (self.jmxLeaderElectionBean != null) {
                MBeanRegistry.getInstance().unregister(self.jmxLeaderElectionBean);
            }
        } catch (Exception e) {
            LOG.warn("Failed to unregister with JMX", e);
        }
        self.jmxLeaderElectionBean = null;
    }
}
Also used : SocketException(java.net.SocketException) Vote(org.apache.zookeeper.server.quorum.Vote) HashMap(java.util.HashMap) InetSocketAddress(java.net.InetSocketAddress) QuorumServer(org.apache.zookeeper.server.quorum.QuorumPeer.QuorumServer) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer) IOException(java.io.IOException) SocketException(java.net.SocketException) DatagramSocket(java.net.DatagramSocket) DatagramPacket(java.net.DatagramPacket) HashSet(java.util.HashSet)

Example 2 with DatagramSocket

use of java.net.DatagramSocket in project zookeeper by apache.

the class QuorumPeer method startLeaderElection.

public synchronized void startLeaderElection() {
    try {
        if (getPeerState() == ServerState.LOOKING) {
            currentVote = new Vote(myid, getLastLoggedZxid(), getCurrentEpoch());
        }
    } catch (IOException e) {
        RuntimeException re = new RuntimeException(e.getMessage());
        re.setStackTrace(e.getStackTrace());
        throw re;
    }
    //}
    if (electionType == 0) {
        try {
            udpSocket = new DatagramSocket(myQuorumAddr.getPort());
            responder = new ResponderThread();
            responder.start();
        } catch (SocketException e) {
            throw new RuntimeException(e);
        }
    }
    this.electionAlg = createElectionAlgorithm(electionType);
}
Also used : SocketException(java.net.SocketException) DatagramSocket(java.net.DatagramSocket) IOException(java.io.IOException)

Example 3 with DatagramSocket

use of java.net.DatagramSocket in project pinot by linkedin.

the class NetUtil method getHostAddress.

/**
   * Get the ip address of local host.
   */
public static String getHostAddress() throws SocketException, UnknownHostException {
    DatagramSocket ds = new DatagramSocket();
    ds.connect(InetAddress.getByName(DUMMY_OUT_IP), 80);
    InetAddress localAddress = ds.getLocalAddress();
    if (localAddress.getHostAddress().equals("0.0.0.0")) {
        localAddress = InetAddress.getLocalHost();
    }
    return localAddress.getHostAddress();
}
Also used : DatagramSocket(java.net.DatagramSocket) InetAddress(java.net.InetAddress)

Example 4 with DatagramSocket

use of java.net.DatagramSocket in project Openfire by igniterealtime.

the class ConferenceReceiver method initLoneReceiverChannel.

private void initLoneReceiverChannel(int loneReceiverPort) {
    if (this.loneReceiverPort != loneReceiverPort && loneReceiverChannel != null) {
        close();
    }
    this.loneReceiverPort = loneReceiverPort;
    try {
        selector = Selector.open();
    } catch (IOException e) {
        Logger.println("Conference receiver failed to open selector " + e.getMessage());
        return;
    }
    if (loneReceiverPort == 0) {
        return;
    }
    Logger.println("Init lone channel using port " + loneReceiverPort);
    try {
        loneReceiverChannel = DatagramChannel.open();
        if (Logger.logLevel >= Logger.LOG_INFO) {
            Logger.println("Opened lone receiver channel " + loneReceiverChannel);
        }
    } catch (IOException e) {
        Logger.println("Conference receiver failed to open DatagramChannel " + " " + e.getMessage());
        return;
    }
    try {
        loneReceiverChannel.configureBlocking(false);
    } catch (IOException e) {
        Logger.println("Conference receiver failed to configureBlocking to false " + e.getMessage());
        return;
    }
    DatagramSocket socket = loneReceiverChannel.socket();
    try {
        socket.setReceiveBufferSize(RtpSocket.MAX_RECEIVE_BUFFER);
    } catch (SocketException e) {
        Logger.println("ConferenceReceiver failed to set receive buffer size " + e.getMessage());
        return;
    }
    try {
        socket.setSoTimeout(0);
    } catch (SocketException e) {
        Logger.println("ConferenceReceiver failed to set timeout " + e.getMessage());
        return;
    }
    InetSocketAddress bridgeAddress = Bridge.getLocalBridgeAddress();
    InetSocketAddress isa = new InetSocketAddress(bridgeAddress.getAddress(), loneReceiverPort);
    try {
        socket.bind(isa);
    } catch (IOException e) {
        Logger.println("Conference receiver unable to bind to " + loneReceiverPort + " " + e.getMessage());
        return;
    }
    try {
        SelectionKey selectionKey = loneReceiverChannel.register(selector, SelectionKey.OP_READ);
    } catch (Exception e) {
        Logger.println("Conference receiver unable to register:  " + e.getMessage());
        return;
    }
    memberCount++;
    Logger.println("Lone Channel uses port " + loneReceiverPort);
}
Also used : SocketException(java.net.SocketException) SelectionKey(java.nio.channels.SelectionKey) DatagramSocket(java.net.DatagramSocket) InetSocketAddress(java.net.InetSocketAddress) IOException(java.io.IOException) IOException(java.io.IOException) SocketException(java.net.SocketException)

Example 5 with DatagramSocket

use of java.net.DatagramSocket in project Openfire by igniterealtime.

the class ConferenceMember method initializeChannel.

private void initializeChannel() throws IOException {
    datagramChannel = conferenceManager.getConferenceReceiver().getChannel(cp);
    if (datagramChannel != null) {
        synchronized (datagramChannel) {
            if (loneRtcpReceiver == null) {
                int rtcpPort = datagramChannel.socket().getLocalPort() + 1;
                Logger.println("Starting lone RtcpReceiver on port " + rtcpPort);
                loneRtcpReceiver = new RtcpReceiver(new DatagramSocket(rtcpPort), true);
            }
            rtcpReceiver = loneRtcpReceiver;
        }
        return;
    }
    /*
	 * We are trying to find a pair of sockets with consecutive port nums.
	 * The first socket must have an even port.
	 *
	 * If we find a socket that we don't like, we have to keep it open
	 * otherwise when we try to find another socket, we may get the same
	 * one as before.
	 *
	 * So we make a list of the bad sockets and close them all
	 * after we're done.
	 */
    ArrayList badChannels = new ArrayList();
    int nextRtpPort = firstRtpPort;
    try {
        while (true) {
            datagramChannel = DatagramChannel.open();
            if (Logger.logLevel >= Logger.LOG_DETAIL) {
                Logger.println("Call " + cp + " Opened datagram channel " + datagramChannel);
            }
            datagramChannel.configureBlocking(false);
            DatagramSocket socket = datagramChannel.socket();
            socket.setReceiveBufferSize(RtpSocket.MAX_RECEIVE_BUFFER);
            socket.setSoTimeout(0);
            InetSocketAddress bridgeAddress = Bridge.getLocalBridgeAddress();
            InetSocketAddress isa = new InetSocketAddress(bridgeAddress.getAddress(), nextRtpPort);
            if (nextRtpPort > 0) {
                nextRtpPort += 2;
                if (lastRtpPort != 0 && (nextRtpPort + 1) > lastRtpPort) {
                    Logger.println("No more RTP ports available, last is " + lastRtpPort);
                    closeBadChannels(badChannels);
                    throw new IOException("No more RTP ports available, last is " + lastRtpPort);
                }
            }
            try {
                socket.bind(isa);
                int localPort = socket.getLocalPort();
                if ((localPort & 1) != 0) {
                    /*
			 * Port is odd, can't use this datagramSocket
			 */
                    if (Logger.logLevel >= Logger.LOG_INFO) {
                        Logger.println("Call " + cp + " skipping DatagramSocket with odd port " + localPort);
                    }
                    badChannels.add(datagramChannel);
                    continue;
                }
                Logger.writeFile("Call " + cp + " RTCP Port " + (localPort + 1));
                rtcpReceiver = new RtcpReceiver(new DatagramSocket(localPort + 1), false);
                break;
            } catch (SocketException e) {
                /*
		     * Couldn't bind, can't use this DatagramSocket.
		     */
                if (Logger.logLevel >= Logger.LOG_INFO) {
                    Logger.println("Call " + cp + " skipping DatagramSocket " + e.getMessage());
                }
                badChannels.add(datagramChannel);
                continue;
            }
        }
    } catch (Exception e) {
        closeBadChannels(badChannels);
        throw new IOException("Call " + cp + " MemberReceiver exception! " + e.getMessage());
    }
    closeBadChannels(badChannels);
    if (Logger.logLevel >= Logger.LOG_INFO) {
        Logger.println("Call " + cp + " port " + datagramChannel.socket().getLocalPort());
    }
}
Also used : SocketException(java.net.SocketException) DatagramSocket(java.net.DatagramSocket) InetSocketAddress(java.net.InetSocketAddress) ArrayList(java.util.ArrayList) RtcpReceiver(com.sun.voip.RtcpReceiver) IOException(java.io.IOException) IOException(java.io.IOException) SocketException(java.net.SocketException) ParseException(java.text.ParseException)

Aggregations

DatagramSocket (java.net.DatagramSocket)451 DatagramPacket (java.net.DatagramPacket)198 IOException (java.io.IOException)171 InetAddress (java.net.InetAddress)92 InetSocketAddress (java.net.InetSocketAddress)91 SocketException (java.net.SocketException)91 Test (org.junit.Test)55 UnknownHostException (java.net.UnknownHostException)46 ServerSocket (java.net.ServerSocket)37 SocketTimeoutException (java.net.SocketTimeoutException)26 InterruptedIOException (java.io.InterruptedIOException)21 DatagramChannel (java.nio.channels.DatagramChannel)21 BindException (java.net.BindException)18 PortUnreachableException (java.net.PortUnreachableException)18 IllegalBlockingModeException (java.nio.channels.IllegalBlockingModeException)17 SocketAddress (java.net.SocketAddress)14 MulticastSocket (java.net.MulticastSocket)13 ArrayList (java.util.ArrayList)11 MockEndpoint (org.apache.camel.component.mock.MockEndpoint)11 ByteBuffer (java.nio.ByteBuffer)10