src/org/sonews/daemon/NNTPDaemon.java
changeset 35 ed84c8bdd87b
parent 15 f2293e8566f5
child 37 74139325d305
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/src/org/sonews/daemon/NNTPDaemon.java	Sun Aug 29 17:28:58 2010 +0200
     1.3 @@ -0,0 +1,197 @@
     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.config.Config;
    1.25 +import org.sonews.Main;
    1.26 +import org.sonews.util.Log;
    1.27 +import java.io.IOException;
    1.28 +import java.net.BindException;
    1.29 +import java.net.InetSocketAddress;
    1.30 +import java.net.ServerSocket;
    1.31 +import java.nio.channels.CancelledKeyException;
    1.32 +import java.nio.channels.ClosedChannelException;
    1.33 +import java.nio.channels.SelectionKey;
    1.34 +import java.nio.channels.Selector;
    1.35 +import java.nio.channels.ServerSocketChannel;
    1.36 +import java.nio.channels.SocketChannel;
    1.37 +
    1.38 +/**
    1.39 + * NNTP daemon using SelectableChannels.
    1.40 + * @author Christian Lins
    1.41 + * @since sonews/0.5.0
    1.42 + */
    1.43 +public final class NNTPDaemon extends AbstractDaemon
    1.44 +{
    1.45 +
    1.46 +  public static final Object RegisterGate = new Object();
    1.47 +  
    1.48 +  private static NNTPDaemon instance = null;
    1.49 +  
    1.50 +  public static synchronized NNTPDaemon createInstance(int port)
    1.51 +  {
    1.52 +    if(instance == null)
    1.53 +    {
    1.54 +      instance = new NNTPDaemon(port);
    1.55 +      return instance;
    1.56 +    }
    1.57 +    else
    1.58 +    {
    1.59 +      throw new RuntimeException("NNTPDaemon.createInstance() called twice");
    1.60 +    }
    1.61 +  }
    1.62 +  
    1.63 +  private int port;
    1.64 +  
    1.65 +  private NNTPDaemon(final int port)
    1.66 +  {
    1.67 +    Log.get().info("Server listening on port " + port);
    1.68 +    this.port = port;
    1.69 +  }
    1.70 +
    1.71 +  @Override
    1.72 +  public void run()
    1.73 +  {
    1.74 +    try
    1.75 +    {
    1.76 +      // Create a Selector that handles the SocketChannel multiplexing
    1.77 +      final Selector readSelector  = Selector.open();
    1.78 +      final Selector writeSelector = Selector.open();
    1.79 +      
    1.80 +      // Start working threads
    1.81 +      final int workerThreads = Runtime.getRuntime().availableProcessors() * 4;
    1.82 +      ConnectionWorker[] cworkers = new ConnectionWorker[workerThreads];
    1.83 +      for(int n = 0; n < workerThreads; n++)
    1.84 +      {
    1.85 +        cworkers[n] = new ConnectionWorker();
    1.86 +        cworkers[n].start();
    1.87 +      }
    1.88 +      
    1.89 +      ChannelWriter.getInstance().setSelector(writeSelector);
    1.90 +      ChannelReader.getInstance().setSelector(readSelector);
    1.91 +      ChannelWriter.getInstance().start();
    1.92 +      ChannelReader.getInstance().start();
    1.93 +      
    1.94 +      final ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
    1.95 +      serverSocketChannel.configureBlocking(true);  // Set to blocking mode
    1.96 +      
    1.97 +      // Configure ServerSocket; bind to socket...
    1.98 +      final ServerSocket serverSocket = serverSocketChannel.socket();
    1.99 +      serverSocket.bind(new InetSocketAddress(this.port));
   1.100 +      
   1.101 +      while(isRunning())
   1.102 +      {
   1.103 +        SocketChannel socketChannel;
   1.104 +        
   1.105 +        try
   1.106 +        {
   1.107 +          // As we set the server socket channel to blocking mode the accept()
   1.108 +          // method will block.
   1.109 +          socketChannel = serverSocketChannel.accept();
   1.110 +          socketChannel.configureBlocking(false);
   1.111 +          assert socketChannel.isConnected();
   1.112 +          assert socketChannel.finishConnect();
   1.113 +        }
   1.114 +        catch(IOException ex)
   1.115 +        {
   1.116 +          // Under heavy load an IOException "Too many open files may
   1.117 +          // be thrown. It most cases we should slow down the connection
   1.118 +          // accepting, to give the worker threads some time to process work.
   1.119 +          Log.get().severe("IOException while accepting connection: " + ex.getMessage());
   1.120 +          Log.get().info("Connection accepting sleeping for seconds...");
   1.121 +          Thread.sleep(5000); // 5 seconds
   1.122 +          continue;
   1.123 +        }
   1.124 +        
   1.125 +        final NNTPConnection conn;
   1.126 +        try
   1.127 +        {
   1.128 +          conn = new NNTPConnection(socketChannel);
   1.129 +          Connections.getInstance().add(conn);
   1.130 +        }
   1.131 +        catch(IOException ex)
   1.132 +        {
   1.133 +          Log.get().warning(ex.toString());
   1.134 +          socketChannel.close();
   1.135 +          continue;
   1.136 +        }
   1.137 +        
   1.138 +        try
   1.139 +        {
   1.140 +          SelectionKey selKeyWrite =
   1.141 +            registerSelector(writeSelector, socketChannel, SelectionKey.OP_WRITE);
   1.142 +          registerSelector(readSelector, socketChannel, SelectionKey.OP_READ);
   1.143 +          
   1.144 +          Log.get().info("Connected: " + socketChannel.socket().getRemoteSocketAddress());
   1.145 +
   1.146 +          // Set write selection key and send hello to client
   1.147 +          conn.setWriteSelectionKey(selKeyWrite);
   1.148 +          conn.println("200 " + Config.inst().get(Config.HOSTNAME, "localhost")
   1.149 +              + " " + Main.VERSION + " news server ready - (posting ok).");
   1.150 +        }
   1.151 +        catch(CancelledKeyException cke)
   1.152 +        {
   1.153 +          Log.get().warning("CancelledKeyException " + cke.getMessage() + " was thrown: "
   1.154 +            + socketChannel.socket());
   1.155 +        }
   1.156 +        catch(ClosedChannelException cce)
   1.157 +        {
   1.158 +          Log.get().warning("ClosedChannelException " + cce.getMessage() + " was thrown: "
   1.159 +            + socketChannel.socket());
   1.160 +        }
   1.161 +      }
   1.162 +    }
   1.163 +    catch(BindException ex)
   1.164 +    {
   1.165 +      // Could not bind to socket; this is a fatal problem; so perform shutdown
   1.166 +      ex.printStackTrace();
   1.167 +      System.exit(1);
   1.168 +    }
   1.169 +    catch(IOException ex)
   1.170 +    {
   1.171 +      ex.printStackTrace();
   1.172 +    }
   1.173 +    catch(Exception ex)
   1.174 +    {
   1.175 +      ex.printStackTrace();
   1.176 +    }
   1.177 +  }
   1.178 +  
   1.179 +  public static SelectionKey registerSelector(final Selector selector,
   1.180 +    final SocketChannel channel, final int op)
   1.181 +    throws CancelledKeyException, ClosedChannelException
   1.182 +  {
   1.183 +    // Register the selector at the channel, so that it will be notified
   1.184 +    // on the socket's events
   1.185 +    synchronized(RegisterGate)
   1.186 +    {
   1.187 +      // Wakeup the currently blocking reader/writer thread; we have locked
   1.188 +      // the RegisterGate to prevent the awakened thread to block again
   1.189 +      selector.wakeup();
   1.190 +      
   1.191 +      // Lock the selector to prevent the waiting worker threads going into
   1.192 +      // selector.select() which would block the selector.
   1.193 +      synchronized (selector)
   1.194 +      {
   1.195 +        return channel.register(selector, op, null);
   1.196 +      }
   1.197 +    }
   1.198 +  }
   1.199 +  
   1.200 +}