/*
 * JBoss, Home of Professional Open Source
 * Copyright 2005, JBoss Inc., and individual contributors as indicated
 * 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.jboss.ha.jndi;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.UndeclaredThrowableException;
import java.util.HashMap;
import java.util.Set;
import java.util.Map;
import java.util.Collections;
import java.net.ServerSocket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.DatagramPacket;
import java.net.Socket;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.rmi.MarshalledObject;

import javax.management.ObjectInstance;
import javax.management.ObjectName;
import javax.management.QueryExp;
import javax.management.Query;

import org.jboss.ha.framework.interfaces.HAPartition;
import org.jboss.ha.framework.server.ClusterPartition;
import org.jboss.ha.framework.server.ClusterPartitionMBean;
import org.jboss.invocation.Invocation;
import org.jboss.invocation.MarshalledInvocation;
import org.jboss.mx.util.MBeanProxy;
import org.jboss.system.ServiceMBeanSupport;
import org.jboss.logging.Logger;
import org.jnp.interfaces.Naming;
import org.jnp.interfaces.NamingContext;

/** Management Bean for the protocol independent HA-JNDI service. This
 * allows the naming service transport layer to be provided by a detached
 * invoker service like JRMPInvokerHA + ProxyFactoryHA.
 *
 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
 * @author <a href="mailto:sacha.labourey@cogito-info.ch">Sacha Labourey</a>
 * @author Scott.Stark@jboss.org
 * @version $Revision: 1.1.2.4 $
 */
public class DetachedHANamingService
   extends ServiceMBeanSupport
   implements DetachedHANamingServiceMBean, Runnable
{
   // Constants -----------------------------------------------------
   
   // Attributes ----------------------------------------------------
   /** The jnp server socket through which the HAJNDI stub is vended */
   protected ServerSocket bootstrapSocket;

   /** The Naming interface server implementation */
   protected HAJNDI theServer;
   /** The mapping from the long method hash to the Naming Method */
   protected Map marshalledInvocationMapping;
   /** The protocol stub returned to clients by the bootstrap lookup */
   protected Naming stub;
   /** The HAPartition used for the state transfer service */
   protected HAPartition partition;
   /** The partition name used to lookup the HAPartition binding */
   protected String partitionName = "DefaultPartition";
   /** The proxy factory service that generates the Naming stub */
   private ObjectName proxyFactory;

   /** The interface to bind to. This is useful for multi-homed hosts
    that want control over which interfaces accept connections.
    */
   protected InetAddress bindAddress;
   /** The bootstrapSocket listen queue depth */
   protected int backlog = 50;
   /** The jnp protocol listening port. The default is 1100, the same as
    the RMI registry default port. */
   protected int port = 1100;

   /** The autodiscovery multicast group */
   protected String adGroupAddress = NamingContext.DEFAULT_DISCOVERY_GROUP_ADDRESS;
   /** The autodiscovery port */
   protected int adGroupPort = NamingContext.DEFAULT_DISCOVERY_GROUP_PORT;
   protected AutomaticDiscovery autoDiscovery = null;

   // Public --------------------------------------------------------

   public DetachedHANamingService()
   {
      // for JMX
   }
   
   /** Expose the Naming service interface mapping as a read-only attribute
    *
    * @jmx:managed-attribute
    *
    * @return A Map<Long hash, Method> of the Naming interface
    */
   public Map getMethodMap()
   {
      return marshalledInvocationMapping;
   }

   public String getPartitionName()
   {
      return partitionName;
   }
   public void setPartitionName(final String partitionName)
   {
      this.partitionName = partitionName;
   }

   public ObjectName getProxyFactoryObjectName()
   {
      return proxyFactory;
   }
   public void setProxyFactoryObjectName(ObjectName proxyFactory)
   {
      this.proxyFactory = proxyFactory;
   }
   public void setPort(int p)
   {
      port = p;
   }
   public int getPort()
   {
      return port;
   }

   public String getBindAddress()
   {
      String address = null;
      if( bindAddress != null )
         address = bindAddress.getHostAddress();
      return address;
   }
   public void setBindAddress (String host) throws java.net.UnknownHostException
   {
      bindAddress = InetAddress.getByName(host);
   }

   public int getBacklog()
   {
      return backlog;
   }
   public void setBacklog(int backlog)
   {
      if( backlog <= 0 )
         backlog = 50;
      this.backlog = backlog;
   }

   public String getAutoDiscoveryAddress() 
   {
      return this.adGroupAddress;
   }
   
   public void setAutoDiscoveryAddress(String adAddress) 
   {
      this.adGroupAddress = adAddress;
   }
   
   public int getAutoDiscoveryGroup() 
   {
      return this.adGroupPort;
   }
   
   public void setAutoDiscoveryGroup(int adGroup) 
   {
      this.adGroupPort = adGroup;
   }

   public void startService(HAPartition haPartition)
      throws Exception
   {
      this.partition = haPartition;
      this.startService ();
   }
   
   protected void createService()
      throws Exception
   {
      boolean debug = log.isDebugEnabled();
      
      if (debug) 
         log.debug("Initializing HAJNDI server on partition: " + partitionName);
      
      partition = findHAPartitionWithName (partitionName);
      // Start HAJNDI service
      theServer = new HAJNDI(partition);
      log.debug("initialize HAJNDI");
      theServer.init();

      // Build the Naming interface method map
      HashMap tmpMap = new HashMap(13);
      Method[] methods = Naming.class.getMethods();
      for(int m = 0; m < methods.length; m ++)
      {
         Method method = methods[m];
         Long hash = new Long(MarshalledInvocation.calculateHash(method));
         tmpMap.put(hash, method);
      }
      marshalledInvocationMapping = Collections.unmodifiableMap(tmpMap);
      
      // share instance for in-vm discovery
      NamingContext.setHANamingServerForPartition (partitionName, theServer);
   }

   protected void startService()
      throws Exception
   {
      log.debug("Obtaining the transport proxy");
      stub = this.getNamingProxy();
      this.theServer.setHAStub(stub);
      log.debug("Starting HAJNDI bootstrap listener");
      if( port >= 0 )
      {
         try
         {
            bootstrapSocket = new ServerSocket(port, backlog, bindAddress);
            // If an anonymous port was specified get the actual port used
            if( port == 0 )
               port = bootstrapSocket.getLocalPort();
            listen();
            log.info("Listening on " + bootstrapSocket.getInetAddress()
               + ":" + bootstrapSocket.getLocalPort());
         }
         catch (IOException e)
         {
            log.error("Could not start on port " + port, e);
         }
      }

      // Automatic Discovery for unconfigured clients
      if( adGroupAddress != null )
      {
         try
         {
            autoDiscovery = new HANamingService.AutomaticDiscovery ();
            autoDiscovery.start ();
         }
         catch(Exception e)
         {
            log.warn("Failed to start AutomaticDiscovery", e);
         }
      }
   }

   protected void stopService() throws Exception
   {
      // un-share instance for in-vm discovery
      NamingContext.removeHANamingServerForPartition (partitionName);

      // Stop listener
      ServerSocket s = bootstrapSocket;
      bootstrapSocket = null;
      if( s != null )
      {
         log.debug("Closing the bootstrap listener");
         s.close();
      }

      // Stop HAJNDI service
      log.debug("Stopping the HAJNDI service");
      theServer.stop ();

      log.debug("Stopping AutomaticDiscovery");
      if( autoDiscovery != null )
         autoDiscovery.stop();
   }

   /** Expose the Naming service via JMX to invokers.
    *
    * @jmx:managed-operation
    *
    * @param invocation    A pointer to the invocation object
    * @return              Return value of method invocation.
    * 
    * @throws Exception    Failed to invoke method.
    */
   public Object invoke(Invocation invocation) throws Exception
   {
      // Set the method hash to Method mapping
      if (invocation instanceof MarshalledInvocation)
      {
         MarshalledInvocation mi = (MarshalledInvocation) invocation;
         mi.setMethodMap(marshalledInvocationMapping);
      }
      // Invoke the Naming method via reflection
      Method method = invocation.getMethod();
      Object[] args = invocation.getArguments();
      Object value = null;
      try
      {
         value = method.invoke(theServer, args);
      }
      catch(InvocationTargetException e)
      {
         Throwable t = e.getTargetException();
         if( t instanceof Exception )
            throw (Exception) t;
         else
            throw new UndeclaredThrowableException(t, method.toString());
      }

      return value;
   }

   // Runnable implementation ---------------------------------------
   public void run()
   {
      Socket socket = null;
      
      // Accept a connection
      try
      {
         socket = bootstrapSocket.accept();
      }
      catch (IOException e)
      {
         if (bootstrapSocket == null)
            return; // Stopped by normal means

         log.error("Naming stopped", e);
         log.info("Restarting naming");
         try
         {
            start();
         }
         catch (Exception ex)
         {
            log.error("Restart failed", ex);
            return;
         }
      }

      // Create a new thread to accept the next connection
      listen();
      
      // Return the naming server stub
      try
      {
         ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
         synchronized(stub)
         {
            out.writeObject(new MarshalledObject(stub));
         }
      }
      catch (IOException ex)
      {
         if (log.isDebugEnabled()) 
         {
            log.debug("Error writing response to " + socket.getInetAddress(), ex);
         }
      }
      finally
      {
         try
         {
            socket.close();
         }
         catch (IOException e)
         {
         }
      }
   }

   // Protected -----------------------------------------------------
   
   protected void listen()
   {
      Thread t = new Thread(this, "HAJNDI-Listener");
      t.start();
   }

   // Protected -----------------------------------------------------
   
   protected HAPartition findHAPartitionWithName (String name) throws Exception
   {
      HAPartition result = null;
      QueryExp exp = Query.and(
                        Query.eq(
                           Query.classattr(),
                           Query.value(ClusterPartition.class.getName ())
                        ),
                        Query.match(
                           Query.attr("PartitionName"),
                           Query.value(name)
                        )
                      );

      Set mbeans = this.getServer ().queryMBeans (null, exp);
      if (mbeans != null && mbeans.size () > 0)
      {
         ObjectInstance inst = (ObjectInstance)(mbeans.iterator ().next ());
         ClusterPartitionMBean cp = (ClusterPartitionMBean) MBeanProxy.get (
                                                      ClusterPartitionMBean.class, 
                                                      inst.getObjectName (),
                                                      this.getServer ());
         result = cp.getHAPartition();
      }
      
      return result;
   }

   /** Get the Naming proxy for the transport. This version looks  up the
    * proxyFactory service Proxy attribute. Subclasses can override this to
    * set the proxy another way.
    * 
    * @return The Naming proxy for the protocol used with the HAJNDI service
    */ 
   protected Naming getNamingProxy() throws Exception
   {
      Naming proxy = (Naming) server.getAttribute(proxyFactory, "Proxy");
      return proxy;
   }

   protected class AutomaticDiscovery
      implements Runnable
   {
      protected Logger log = Logger.getLogger(AutomaticDiscovery.class);

      protected java.net.MulticastSocket socket = null;
      protected byte[] ipAddress = null;
      protected InetAddress group = null;
      protected boolean stopping = false;
      
      public AutomaticDiscovery () throws Exception
      {
      }
      
      public void start () throws Exception
      {
         stopping = false;
         socket = new MulticastSocket (adGroupPort);
         if (bindAddress != null)
            socket.setInterface(bindAddress);

         group = InetAddress.getByName (adGroupAddress);
         socket.joinGroup (group);
         
         String address = getBindAddress();
         /* An INADDR_ANY (0.0.0.0 || null) address is useless as the value
            sent to a remote client so check for this and use the local host
            address instead.
          */
         if (address == null || address.equals("0.0.0.0"))
         {
            address = InetAddress.getLocalHost().getHostAddress();
         }
         ipAddress = (address + ":" + port).getBytes();

         log.info("Listening on " + socket.getInterface() + ":" + socket.getLocalPort()
            + ", group="+adGroupAddress
            + ", HA-JNDI address="+new String(ipAddress)
         );

         listen ();
      }
      
      public void stop()
      {
         try
         {
            stopping = true;
            socket.leaveGroup(group);
            socket.close();
         }
         catch (Exception ex)
         {
            log.error("Stopping AutomaticDiscovery failed", ex);
         }
      }

      public void run ()
      {
         boolean trace = log.isTraceEnabled();
         // Wait for a datagram
         //
         byte[] buf = new byte[256];
         DatagramPacket packet = new DatagramPacket(buf, buf.length);
         try
         {
            if( trace )
               log.trace("HA-JNDI AutomaticDiscovery waiting for queries...");
            socket.receive(packet);
            if( trace )
               log.trace("HA-JNDI AutomaticDiscovery Packet received.");
         } 
         catch (IOException e)
         {
            if (stopping)
               return; // Stopped by normal means

            log.error("Auto-discovery stopped", e);
            log.info("Restarting auto-discovery");
            try
            {
               start ();
            } catch (Exception ex)
            {
               log.error("Restart failed: auto-discovery is now disabled!!!", ex);
               return;
            }
         }
         
         listen ();

         // Return the naming server IP address and port to the client
         //
         try
         {
            // See if the discovery is restricted to a particular parition
            String requestData = new String(packet.getData());
            int colon = requestData.indexOf(':');
            if( colon > 0 )
            {
               // Check the partition name
               String name = requestData.substring(colon + 1);
               name = name.trim();
               if( name.equals(partitionName) == false )
               {
                  log.debug("Ignoring discovery request for partition: "+name);
                  return;
               }
            }
            DatagramPacket p = new DatagramPacket (ipAddress, ipAddress.length, packet.getAddress(), packet.getPort());
            if( trace )
               log.trace("Sending AutomaticDiscovery answer: " + new String(ipAddress));
            socket.send (p);
            if( trace )
               log.trace("AutomaticDiscovery answer sent.");
         }
         catch (IOException ex)
         {
            log.error ("Error writing response", ex);
         }
      }
      
      protected void listen ()
      {
         Thread t = new Thread (this, "HAJNDI-AutomaticDiscovery");
         t.start ();
      }
   }

   // Private -------------------------------------------------------
   
}
