Revision: de9b5c011ad8
Author:   Alexandre Mendonça <ammendonca>
Date:     Tue Aug 26 00:49:15 2014 UTC
Log: Issue 59: Stack can wait for a (configurable) period before binding to socket.
Update Issue 59
Status: Fixed
Committed changes to support using a bind delay parameter.
Should be used as:
<Parameters>
  ...
  <BindDelay value="15000" />
  ...
</Parameters>

The value is specified in ms.
Test also committed.

https://code.google.com/p/jdiameter/source/detail?r=de9b5c011ad8

Added:
/testsuite/tests/src/test/java/org/mobicents/diameter/stack/StackConnectDelayTest.java /testsuite/tests/src/test/resources/configurations/jdiameter-server-two-delay.xml
Modified:
/core/jdiameter/impl/src/main/java/org/jdiameter/server/impl/helpers/Parameters.java /core/jdiameter/impl/src/main/java/org/jdiameter/server/impl/helpers/XMLConfiguration.java /core/jdiameter/impl/src/main/java/org/jdiameter/server/impl/io/tcp/NetworkGuard.java
 /core/jdiameter/impl/src/main/resources/META-INF/jdiameter-server.xsd

=======================================
--- /dev/null
+++ /testsuite/tests/src/test/java/org/mobicents/diameter/stack/StackConnectDelayTest.java Tue Aug 26 00:49:15 2014 UTC
@@ -0,0 +1,162 @@
+/*
+ * TeleStax, Open Source Cloud Communications
+ * Copyright 2011-2014, TeleStax Inc. and individual contributors
+ * by the @authors tag.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation; either version 3 of
+ * the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>
+ */
+
+package org.mobicents.diameter.stack;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+import java.io.InputStream;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+
+import org.apache.log4j.Logger;
+import org.jdiameter.api.Answer;
+import org.jdiameter.api.ApplicationId;
+import org.jdiameter.api.Configuration;
+import org.jdiameter.api.DisconnectCause;
+import org.jdiameter.api.InternalException;
+import org.jdiameter.api.Mode;
+import org.jdiameter.api.Network;
+import org.jdiameter.api.NetworkReqListener;
+import org.jdiameter.api.Peer;
+import org.jdiameter.api.PeerState;
+import org.jdiameter.api.PeerTable;
+import org.jdiameter.api.Request;
+import org.jdiameter.client.api.controller.IPeer;
+import org.jdiameter.server.impl.StackImpl;
+import org.junit.Test;
+
+/**
+ *
+ * @author <a href="mailto:[email protected]";> Alexandre Mendonca </a>
+ * @author <a href="mailto:[email protected]";> Bartosz Baranowski </a>
+ */
+public class StackConnectDelayTest {
+
+ private static Logger logger = Logger.getLogger(StackConnectDelayTest.class);
+
+  // 1. start server
+  // 2. start client + wait for connection
+  // 3. stop client, start it again
+  // 4. wait for connection
+
+  @Test
+  public void testFirstPeerFailsSecondSucceeds() throws Exception {
+    StackImpl server = new StackImpl();
+    StackImpl client1 = new StackImpl();
+    StackImpl client2 = new StackImpl();
+    try {
+      String serverConfigName = "jdiameter-server-two-delay.xml";
+      String client1ConfigName = "jdiameter-client-two.xml";
+      String client2ConfigName = "jdiameter-client-two-second.xml";
+
+ InputStream serverConfigInputStream = StackConnectDelayTest.class.getClassLoader().getResourceAsStream("configurations/" + serverConfigName); + InputStream client1ConfigInputStream = StackConnectDelayTest.class.getClassLoader().getResourceAsStream("configurations/" + client1ConfigName); + InputStream client2ConfigInputStream = StackConnectDelayTest.class.getClassLoader().getResourceAsStream("configurations/" + client2ConfigName);
+
+ Configuration serverConfig = new org.jdiameter.server.impl.helpers.XMLConfiguration(serverConfigInputStream); + Configuration client1Config = new org.jdiameter.server.impl.helpers.XMLConfiguration(client1ConfigInputStream); + Configuration client2Config = new org.jdiameter.server.impl.helpers.XMLConfiguration(client2ConfigInputStream);
+
+      server.init(serverConfig);
+      serverConfigInputStream.close();
+      Network network = server.unwrap(Network.class);
+      network.addNetworkReqListener(new NetworkReqListener() {
+
+        public Answer processRequest(Request request) {
+          return null;
+        }
+      }, ApplicationId.createByAccAppId(193, 19302));
+      server.start();
+
+      List<Peer> peers = server.unwrap(PeerTable.class).getPeerTable();
+ assertEquals("Wrong num of connections, initial setup did not succeed. ", 0, peers.size());
+      client1.init(client1Config);
+      client2.init(client2Config);
+      client1ConfigInputStream.close();
+      client2ConfigInputStream.close();
+      network = client1.unwrap(Network.class);
+      network.addNetworkReqListener(new NetworkReqListener() {
+
+        public Answer processRequest(Request request) {
+          return null;
+        }
+      }, ApplicationId.createByAccAppId(193, 19302));
+
+      network = client2.unwrap(Network.class);
+      network.addNetworkReqListener(new NetworkReqListener() {
+
+        public Answer processRequest(Request request) {
+          return null;
+        }
+      }, ApplicationId.createByAccAppId(193, 19302));
+
+      try {
+        client1.start(Mode.ALL_PEERS, 5000, TimeUnit.MILLISECONDS);
+ fail("Client 1 should not be able to connect since server should not be bound.");
+      }
+      catch (InternalException ie) {
+        // expected.
+ assertEquals("Should have thrown a TimeOut InternalException", "TimeOut", ie.getMessage());
+      }
+      finally {
+        try {
+          client1.stop(DisconnectCause.REBOOTING);
+          client1.destroy();
+        }
+        catch (Exception e) {
+          logger.warn("Failed to stop/destroy CLIENT stack.", e);
+        }
+      }
+      client2.start(Mode.ALL_PEERS, 20000, TimeUnit.MILLISECONDS);
+
+      peers = server.unwrap(PeerTable.class).getPeerTable();
+ assertEquals("Wrong num of connections, initial setup did not succeed. ", 1, peers.size());
+      IPeer p = (IPeer) peers.get(0);
+ assertTrue("Peer not connected. State[" + p.getState(PeerState.class) + "]", ((IPeer) peers.get(0)).isConnected()); + assertEquals("Peer has wrong realm.","mobicents.org", p.getRealmName());
+
+
+    }
+    finally {
+      try {
+        client2.stop(DisconnectCause.REBOOTING);
+        client2.destroy();
+      }
+      catch (Exception e) {
+        logger.warn("Failed to stop/destroy CLIENT stack.", e);
+      }
+
+      try {
+        server.stop(DisconnectCause.REBOOTING);
+        server.destroy();
+      }
+      catch (Exception e) {
+        logger.warn("Failed to stop/destroy SERVER stack.", e);
+      }
+    }
+  }
+
+
+  private void _wait() throws InterruptedException {
+    Thread.sleep(5000);
+  }
+}
=======================================
--- /dev/null
+++ /testsuite/tests/src/test/resources/configurations/jdiameter-server-two-delay.xml Tue Aug 26 00:49:15 2014 UTC
@@ -0,0 +1,77 @@
+<?xml version="1.0"?>
+<Configuration xmlns="http://www.jdiameter.org/jdiameter-server";>
+
+  <LocalPeer>
+    <URI value="aaa://127.0.0.2:3868" />
+    <IPAddresses>
+      <IPAddress value="127.0.0.2" />
+    </IPAddresses>
+    <Realm value="mobicents.org" />
+    <VendorID value="193" />
+    <ProductName value="jDiameter" />
+    <FirmwareRevision value="1" />
+    <OverloadMonitor>
+      <Entry index="1" lowThreshold="0.5" highThreshold="0.6">
+        <ApplicationID>
+          <VendorId value="193" />
+          <AuthApplId value="0" />
+          <AcctApplId value="19302" />
+        </ApplicationID>
+      </Entry>
+    </OverloadMonitor>
+  </LocalPeer>
+
+  <Parameters>
+    <AcceptUndefinedPeer value="true" />
+    <DuplicateProtection value="true" />
+    <DuplicateTimer value="240000" />
+    <UseUriAsFqdn value="false" />
+    <QueueSize value="10000" />
+    <MessageTimeOut value="60000" />
+    <StopTimeOut value="10000" />
+    <CeaTimeOut value="10000" />
+    <IacTimeOut value="30000" />
+    <DwaTimeOut value="10000" />
+    <DpaTimeOut value="5000" />
+    <RecTimeOut value="10000" />
+
+    <BindDelay value="15000" />
+
+    <!-- Statistics Logger Configuration -->
+ <Statistics pause="30000" delay="30000" enabled="true" active_records="Concurrent,ScheduledExecService,Network,ScheduledExecService,AppGenRequestPerSecond,NetGenRequestPerSecond,Peer,Peer.local,PeerFSM"/>
+
+    <Concurrent>
+      <Entity name="ThreadGroup" size="64"/> <!-- Common Thread Pool -->
+      <Entity name="ProcessingMessageTimer" size="1"/>
+      <Entity name="DuplicationMessageTimer" size="1"/>
+      <Entity name="RedirectMessageTimer" size="1"/>
+      <Entity name="PeerOverloadTimer" size="1"/>
+      <Entity name="ConnectionTimer" size="1"/>
+      <Entity name="StatisticTimer" size="1"/>
+    </Concurrent>
+    <Dictionary enabled="false" sendLevel="MESSAGE" receiveLevel="OFF" />
+    <!-- To enable clustering uncomment the following lines
+ <SessionDatasource value="org.mobicents.diameter.impl.ha.data.ReplicatedDataSource"/> + <TimerFacility value="org.mobicents.diameter.impl.ha.timer.ReplicatedTimerFacilityImpl"/>
+    -->
+    </Parameters>
+
+  <Network>
+    <Peers>
+ <Peer name="aaa://127.0.0.2:13868" attempt_connect="false" rating="1" />
+    </Peers>
+
+    <Realms>
+ <Realm name="test.mobicents.org" peers="127.0.0.2" local_action="LOCAL" dynamic="false" exp_time="1">
+        <ApplicationID>
+          <VendorId value="193" />
+          <AuthApplId value="0" />
+          <AcctApplId value="19302" />
+        </ApplicationID>
+      </Realm>
+    </Realms>
+  </Network>
+
+  <Extensions />
+
+</Configuration>
=======================================
--- /core/jdiameter/impl/src/main/java/org/jdiameter/server/impl/helpers/Parameters.java Wed May 23 01:48:38 2012 UTC +++ /core/jdiameter/impl/src/main/java/org/jdiameter/server/impl/helpers/Parameters.java Tue Aug 26 00:49:15 2014 UTC
@@ -1,23 +1,43 @@
 /*
- * JBoss, Home of Professional Open Source
- * Copyright 2006, Red Hat, Inc. and individual contributors
- * by the @authors tag. See the copyright.txt in the distribution for a
- * full listing of individual contributors.
+ * TeleStax, Open Source Cloud Communications
+ * Copyright 2011-2014, TeleStax Inc. and individual contributors
+ * by the @authors tag.
  *
- * This is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
+ * This program is free software: you can redistribute it and/or modify
+ * under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation; either version 3 of
  * the License, or (at your option) any later version.
  *
- * This software is distributed in the hope that it will be useful,
+ * This program is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>
+ *
+ * This file incorporates work covered by the following copyright and
+ * permission notice:
+ *
+ *   JBoss, Home of Professional Open Source
+ *   Copyright 2007-2011, Red Hat, Inc. and individual contributors
+ *   by the @authors tag. See the copyright.txt in the distribution for a
+ *   full listing of individual contributors.
+ *
+ *   This is free software; you can redistribute it and/or modify it
+ *   under the terms of the GNU Lesser General Public License as
+ *   published by the Free Software Foundation; either version 2.1 of
+ *   the License, or (at your option) any later version.
+ *
+ *   This software is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ *   Lesser General Public License for more details.
  *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ *   You should have received a copy of the GNU Lesser General Public
+ *   License along with this software; if not, write to the Free
+ *   Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ *   02110-1301 USA, or see the FSF site: http://www.fsf.org.
  */

 package org.jdiameter.server.impl.helpers;
@@ -106,6 +126,11 @@
    */
public static final Parameters NeedClientAuth = new Parameters("NeedClientAuth", Boolean.class);

+  /**
+   * Socket bind delay property
+   */
+ public static final Parameters BindDelay = new Parameters("BindDelay", Long.class, 0L);
+
   /**
    *  RequestTable - specifies parameters of request table.
    */
=======================================
--- /core/jdiameter/impl/src/main/java/org/jdiameter/server/impl/helpers/XMLConfiguration.java Thu Aug 21 23:39:13 2014 UTC +++ /core/jdiameter/impl/src/main/java/org/jdiameter/server/impl/helpers/XMLConfiguration.java Tue Aug 26 00:49:15 2014 UTC
@@ -269,6 +269,7 @@
else if (nodeName.equals("DwaTimeOut")) { add(DwaTimeOut, getLongValue(c.item(i))); } else if (nodeName.equals("DpaTimeOut")) { add(DpaTimeOut, getLongValue(c.item(i))); } else if (nodeName.equals("RecTimeOut")) { add(RecTimeOut, getLongValue(c.item(i))); } + else if (nodeName.equals("BindDelay")) { add(BindDelay, getLongValue(c.item(i))); } else if (nodeName.equals("ThreadPool")) { addThreadPool(c.item(i)); } else if (nodeName.equals("PeerFSMThreadCount")) { add(PeerFSMThreadCount, getIntValue(c.item(i)));} else if (nodeName.equals("Statistics")) { addStatisticLogger(Statistics, c.item(i)); }
=======================================
--- /core/jdiameter/impl/src/main/java/org/jdiameter/server/impl/io/tcp/NetworkGuard.java Thu Jul 10 02:21:30 2014 UTC +++ /core/jdiameter/impl/src/main/java/org/jdiameter/server/impl/io/tcp/NetworkGuard.java Tue Aug 26 00:49:15 2014 UTC
@@ -1,47 +1,50 @@
- /*
-  * TeleStax, Open Source Cloud Communications
-  * Copyright 2011-2014, TeleStax Inc. and individual contributors
-  * by the @authors tag.
-  *
-  * This program is free software: you can redistribute it and/or modify
-  * under the terms of the GNU Affero General Public License as
-  * published by the Free Software Foundation; either version 3 of
-  * the License, or (at your option) any later version.
-  *
-  * This program is distributed in the hope that it will be useful,
-  * but WITHOUT ANY WARRANTY; without even the implied warranty of
-  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-  * GNU Affero General Public License for more details.
-  *
- * You should have received a copy of the GNU Affero General Public License
-  * along with this program.  If not, see <http://www.gnu.org/licenses/>
-  *
-  * This file incorporates work covered by the following copyright and
-  * permission notice:
-  *
-  *   JBoss, Home of Professional Open Source
-  *   Copyright 2007-2011, Red Hat, Inc. and individual contributors
-  *   by the @authors tag. See the copyright.txt in the distribution for a
-  *   full listing of individual contributors.
-  *
-  *   This is free software; you can redistribute it and/or modify it
-  *   under the terms of the GNU Lesser General Public License as
-  *   published by the Free Software Foundation; either version 2.1 of
-  *   the License, or (at your option) any later version.
-  *
-  *   This software is distributed in the hope that it will be useful,
-  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
-  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-  *   Lesser General Public License for more details.
-  *
-  *   You should have received a copy of the GNU Lesser General Public
-  *   License along with this software; if not, write to the Free
-  *   Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
-  *   02110-1301 USA, or see the FSF site: http://www.fsf.org.
-  */
+/*
+ * TeleStax, Open Source Cloud Communications
+ * Copyright 2011-2014, TeleStax Inc. and individual contributors
+ * by the @authors tag.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation; either version 3 of
+ * the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>
+ *
+ * This file incorporates work covered by the following copyright and
+ * permission notice:
+ *
+ *   JBoss, Home of Professional Open Source
+ *   Copyright 2007-2011, Red Hat, Inc. and individual contributors
+ *   by the @authors tag. See the copyright.txt in the distribution for a
+ *   full listing of individual contributors.
+ *
+ *   This is free software; you can redistribute it and/or modify it
+ *   under the terms of the GNU Lesser General Public License as
+ *   published by the Free Software Foundation; either version 2.1 of
+ *   the License, or (at your option) any later version.
+ *
+ *   This software is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ *   Lesser General Public License for more details.
+ *
+ *   You should have received a copy of the GNU Lesser General Public
+ *   License along with this software; if not, write to the Free
+ *   Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ *   02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */

 package org.jdiameter.server.impl.io.tcp;

+
+import static org.jdiameter.server.impl.helpers.Parameters.BindDelay;
+
 import org.jdiameter.client.api.parser.IMessageParser;
 import org.jdiameter.client.impl.transport.tcp.TCPClientConnection;
 import org.jdiameter.common.api.concurrent.DummyConcurrentFactory;
@@ -65,6 +68,9 @@
 import java.util.List;
 import java.util.Set;
 import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;

 /**
  * TCP implementation of {@link org.jdiameter.server.api.io.INetworkGuard}.
@@ -79,6 +85,7 @@
   protected IMessageParser parser;
   protected IConcurrentFactory concurrentFactory;
   protected int port;
+  protected long bindDelay;
protected CopyOnWriteArrayList<INetworkConnectionListener> listeners = new CopyOnWriteArrayList<INetworkConnectionListener>();
   protected boolean isWork = false;
 //  protected Selector selector;
@@ -87,6 +94,7 @@
   //private Thread thread;
   private List<GuardTask> tasks = new ArrayList<GuardTask>();

+
   @Deprecated
public NetworkGuard(InetAddress inetAddress, int port, IMessageParser parser) throws Exception {
     this(inetAddress, port, null, parser, null);
@@ -106,6 +114,8 @@
     this.parser = parser;
this.concurrentFactory = concurrentFactory == null ? new DummyConcurrentFactory() : concurrentFactory;
     //this.thread = this.concurrentFactory.getThread("NetworkGuard", this);
+ this.bindDelay = data.getConfiguration().getLongValue(BindDelay.ordinal(), (Long) BindDelay.defValue());
+
     try {
       for (int addrIdx = 0; addrIdx < inetAddress.length; addrIdx++) {
GuardTask guardTask = new GuardTask(new InetSocketAddress(inetAddress[addrIdx], port));
@@ -155,14 +165,32 @@
     private Selector selector;
     private ServerSocket serverSocket;

-    public GuardTask(InetSocketAddress addr) throws IOException {
+ private final ScheduledExecutorService binder = Executors.newSingleThreadScheduledExecutor();
+
+    public GuardTask(final InetSocketAddress addr) throws IOException {
       selector = Selector.open();
-      ServerSocketChannel ssc = ServerSocketChannel.open();
+      final ServerSocketChannel ssc = ServerSocketChannel.open();
       ssc.configureBlocking(false);
       serverSocket = ssc.socket();
-      serverSocket.bind(addr);
-      ssc.register(selector, SelectionKey.OP_ACCEPT, addr);
-      logger.info("Open server socket {} ", serverSocket);
+
+      if(bindDelay > 0) {
+ logger.info("Socket binding will be delayed by {}ms...", bindDelay);
+      }
+
+      Runnable task = new Runnable() {
+        public void run() {
+          try {
+            serverSocket.bind(addr);
+            logger.debug("Binding after delaying {}ms...", bindDelay);
+            ssc.register(selector, SelectionKey.OP_ACCEPT, addr);
+            logger.info("Open server socket {} ", serverSocket);
+          }
+          catch (IOException e) {
+            throw new RuntimeException(e);
+          }
+        }
+      };
+      binder.schedule(task, bindDelay, TimeUnit.MILLISECONDS);
     }

     public void start() {
=======================================
--- /core/jdiameter/impl/src/main/resources/META-INF/jdiameter-server.xsd Thu Jan 10 02:46:19 2013 UTC +++ /core/jdiameter/impl/src/main/resources/META-INF/jdiameter-server.xsd Tue Aug 26 00:49:15 2014 UTC
@@ -281,6 +281,14 @@
<xsi:attribute name="value" type="xsi:long" use="required"/>
                </xsi:complexType>
             </xsi:element>
+            <xsi:element name="BindDelay" minOccurs="0" maxOccurs="1">
+                <xsi:annotation>
+ <xsi:documentation>Server Socket bind delay in milliseconds.</xsi:documentation>
+                </xsi:annotation>
+                <xsi:complexType>
+ <xsi:attribute name="value" type="xsi:long" use="required"/>
+               </xsi:complexType>
+            </xsi:element>
<xsi:element name="PeerFSMThreadCount" minOccurs="0" maxOccurs="1">
                 <xsi:annotation>
<xsi:documentation>Peer FSM Thread Count.</xsi:documentation>

--

--- You received this message because you are subscribed to the Google Groups "mobicents-commits" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
For more options, visit https://groups.google.com/d/optout.

Reply via email to