org/sonews/daemon/NNTPDaemon.java
changeset 2 1090e2141798
child 3 2fdc9cc89502
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/org/sonews/daemon/NNTPDaemon.java	Wed Jul 01 10:48:22 2009 +0200
     1.3 @@ -0,0 +1,195 @@
     1.4 +/*
     1.5 + *   SONEWS News Server
     1.6 + *   see AUTHORS for the list of contributors
     1.7 + *
     1.8 + *   This program is free software: you can redistribute it and/or modify
     1.9 + *   it under the terms of the GNU General Public License as published by
    1.10 + *   the Free Software Foundation, either version 3 of the License, or
    1.11 + *   (at your option) any later version.
    1.12 + *
    1.13 + *   This program is distributed in the hope that it will be useful,
    1.14 + *   but WITHOUT ANY WARRANTY; without even the implied warranty of
    1.15 + *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    1.16 + *   GNU General Public License for more details.
    1.17 + *
    1.18 + *   You should have received a copy of the GNU General Public License
    1.19 + *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
    1.20 + */
    1.21 +
    1.22 +package org.sonews.daemon;
    1.23 +
    1.24 +import org.sonews.util.Log;
    1.25 +import java.io.IOException;
    1.26 +import java.net.BindException;
    1.27 +import java.net.InetSocketAddress;
    1.28 +import java.net.ServerSocket;
    1.29 +import java.nio.channels.CancelledKeyException;
    1.30 +import java.nio.channels.ClosedChannelException;
    1.31 +import java.nio.channels.SelectionKey;
    1.32 +import java.nio.channels.Selector;
    1.33 +import java.nio.channels.ServerSocketChannel;
    1.34 +import java.nio.channels.SocketChannel;
    1.35 +
    1.36 +/**
    1.37 + * NNTP daemon using SelectableChannels.
    1.38 + * @author Christian Lins
    1.39 + * @since sonews/0.5.0
    1.40 + */
    1.41 +public final class NNTPDaemon extends AbstractDaemon
    1.42 +{
    1.43 +
    1.44 +  public static final Object RegisterGate = new Object();
    1.45 +  
    1.46 +  private static NNTPDaemon instance = null;
    1.47 +  
    1.48 +  public static synchronized NNTPDaemon createInstance(int port)
    1.49 +  {
    1.50 +    if(instance == null)
    1.51 +    {
    1.52 +      instance = new NNTPDaemon(port);
    1.53 +      return instance;
    1.54 +    }
    1.55 +    else
    1.56 +    {
    1.57 +      throw new RuntimeException("NNTPDaemon.createInstance() called twice");
    1.58 +    }
    1.59 +  }
    1.60 +  
    1.61 +  private int port;
    1.62 +  
    1.63 +  private NNTPDaemon(final int port)
    1.64 +  {
    1.65 +    Log.msg("Server listening on port " + port, false);
    1.66 +    this.port = port;
    1.67 +  }
    1.68 +
    1.69 +  @Override
    1.70 +  public void run()
    1.71 +  {
    1.72 +    try
    1.73 +    {
    1.74 +      // Create a Selector that handles the SocketChannel multiplexing
    1.75 +      final Selector readSelector  = Selector.open();
    1.76 +      final Selector writeSelector = Selector.open();
    1.77 +      
    1.78 +      // Start working threads
    1.79 +      final int workerThreads = Runtime.getRuntime().availableProcessors() * 4;
    1.80 +      ConnectionWorker[] cworkers = new ConnectionWorker[workerThreads];
    1.81 +      for(int n = 0; n < workerThreads; n++)
    1.82 +      {
    1.83 +        cworkers[n] = new ConnectionWorker();
    1.84 +        cworkers[n].start();
    1.85 +      }
    1.86 +      
    1.87 +      ChannelWriter.getInstance().setSelector(writeSelector);
    1.88 +      ChannelReader.getInstance().setSelector(readSelector);
    1.89 +      ChannelWriter.getInstance().start();
    1.90 +      ChannelReader.getInstance().start();
    1.91 +      
    1.92 +      final ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
    1.93 +      serverSocketChannel.configureBlocking(true);  // Set to blocking mode
    1.94 +      
    1.95 +      // Configure ServerSocket; bind to socket...
    1.96 +      final ServerSocket serverSocket = serverSocketChannel.socket();
    1.97 +      serverSocket.bind(new InetSocketAddress(this.port));
    1.98 +      
    1.99 +      while(isRunning())
   1.100 +      {
   1.101 +        SocketChannel socketChannel;
   1.102 +        
   1.103 +        try
   1.104 +        {
   1.105 +          // As we set the server socket channel to blocking mode the accept()
   1.106 +          // method will block.
   1.107 +          socketChannel = serverSocketChannel.accept();
   1.108 +          socketChannel.configureBlocking(false);
   1.109 +          assert socketChannel.isConnected();
   1.110 +          assert socketChannel.finishConnect();
   1.111 +        }
   1.112 +        catch(IOException ex)
   1.113 +        {
   1.114 +          // Under heavy load an IOException "Too many open files may
   1.115 +          // be thrown. It most cases we should slow down the connection
   1.116 +          // accepting, to give the worker threads some time to process work.
   1.117 +          Log.msg("IOException while accepting connection: " + ex.getMessage(), false);
   1.118 +          Log.msg("Connection accepting sleeping for seconds...", true);
   1.119 +          Thread.sleep(5000); // 5 seconds
   1.120 +          continue;
   1.121 +        }
   1.122 +        
   1.123 +        final NNTPConnection conn;
   1.124 +        try
   1.125 +        {
   1.126 +          conn = new NNTPConnection(socketChannel);
   1.127 +          Connections.getInstance().add(conn);
   1.128 +        }
   1.129 +        catch(IOException ex)
   1.130 +        {
   1.131 +          Log.msg(ex.getLocalizedMessage(), false);
   1.132 +          socketChannel.close();
   1.133 +          continue;
   1.134 +        }
   1.135 +        
   1.136 +        try
   1.137 +        {
   1.138 +          SelectionKey selKeyWrite =
   1.139 +            registerSelector(writeSelector, socketChannel, SelectionKey.OP_WRITE);
   1.140 +          registerSelector(readSelector, socketChannel, SelectionKey.OP_READ);
   1.141 +          
   1.142 +          Log.msg("Connected: " + socketChannel.socket().getRemoteSocketAddress(), true);
   1.143 +
   1.144 +          // Set write selection key and send hello to client
   1.145 +          conn.setWriteSelectionKey(selKeyWrite);
   1.146 +          conn.println("200 " + Config.getInstance().get(Config.HOSTNAME, "localhost")
   1.147 +              + " " + Main.VERSION + " news server ready - (posting ok).");
   1.148 +        }
   1.149 +        catch(CancelledKeyException cke)
   1.150 +        {
   1.151 +          Log.msg("CancelledKeyException " + cke.getMessage() + " was thrown: " 
   1.152 +            + socketChannel.socket(), false);
   1.153 +        }
   1.154 +        catch(ClosedChannelException cce)
   1.155 +        {
   1.156 +          Log.msg("ClosedChannelException " + cce.getMessage() + " was thrown: " 
   1.157 +            + socketChannel.socket(), false);
   1.158 +        }
   1.159 +      }
   1.160 +    }
   1.161 +    catch(BindException ex)
   1.162 +    {
   1.163 +      // Could not bind to socket; this is a fatal problem; so perform shutdown
   1.164 +      ex.printStackTrace();
   1.165 +      System.exit(1);
   1.166 +    }
   1.167 +    catch(IOException ex)
   1.168 +    {
   1.169 +      ex.printStackTrace();
   1.170 +    }
   1.171 +    catch(Exception ex)
   1.172 +    {
   1.173 +      ex.printStackTrace();
   1.174 +    }
   1.175 +  }
   1.176 +  
   1.177 +  public static SelectionKey registerSelector(final Selector selector,
   1.178 +    final SocketChannel channel, final int op)
   1.179 +    throws CancelledKeyException, ClosedChannelException
   1.180 +  {
   1.181 +    // Register the selector at the channel, so that it will be notified
   1.182 +    // on the socket's events
   1.183 +    synchronized(RegisterGate)
   1.184 +    {
   1.185 +      // Wakeup the currently blocking reader/writer thread; we have locked
   1.186 +      // the RegisterGate to prevent the awakened thread to block again
   1.187 +      selector.wakeup();
   1.188 +      
   1.189 +      // Lock the selector to prevent the waiting worker threads going into
   1.190 +      // selector.select() which would block the selector.
   1.191 +      synchronized (selector)
   1.192 +      {
   1.193 +        return channel.register(selector, op, null);
   1.194 +      }
   1.195 +    }
   1.196 +  }
   1.197 +  
   1.198 +}